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 |
|---|---|---|---|---|---|---|---|---|
// 所在工程:Agebull.EntityModel
// 整理用户:bull2
// 建立时间:2012-08-13 5:35
// 整理时间:2012-08-30 3:13
namespace Agebull.Common.Settings
{
/// <summary>
/// 自定的配置文件
/// </summary>
public class AppliationConfiguration
{
private static readonly ConfigurationSettings _Settings = new ConfigurationSettings() ;
/// <summary>
/// 配置集合
/// </summary>
public static ConfigurationSettings Settings
{
get
{
return _Settings ;
}
}
}
}
| 21.153846 | 95 | 0.541818 | [
"MPL-2.0",
"MPL-2.0-no-copyleft-exception"
] | agebullhu/EntityModel | src/Extend/SystemExtend/Configuration.cs | 614 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace TygaSoft.Model
{
public partial class PackageInfo
{
public string CustomerCode { get; set; }
public string CustomerName { get; set; }
public string ProductCode { get; set; }
public string ProductName { get; set; }
}
}
| 23.4375 | 49 | 0.637333 | [
"MIT"
] | ranran1997/Wms | Src/TygaSoft/Model/PackageInfo.cs | 377 | C# |
namespace BookFast.Data
{
public class Program
{
public static void Main()
{
}
}
} | 13.222222 | 33 | 0.495798 | [
"MIT"
] | dzimchuk/book-fast-api | src/BookFast.Data/Program.cs | 121 | C# |
// ****************************************************************************
// * The MIT License(MIT)
// * Copyright � 2017 Thomas Due
// *
// * 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.
// ****************************************************************************
namespace AgileCards.Common.Models
{
/// <summary>Information about the sorting of a list of jira issues.</summary>
public class SortingInformation
{
/// <summary>Gets or sets the member path.</summary>
public string MemberPath { get; set; }
/// <summary>Gets or sets a value indicating whether this <see cref="SortingInformation"/> is ascending.</summary>
public bool Ascending { get; set; }
}
}
| 50.5 | 122 | 0.638064 | [
"MIT"
] | DoveSoftConsult/AgileCardsPrinting | Source/AgileCards.Common/Models/SortingInformation.cs | 1,830 | 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("WebApplication1")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("WebApplication1")]
[assembly: AssemblyCopyright("Copyright © 2020")]
[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("6a750be1-5f50-4ccc-a1a4-80c16cd17386")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Revision and Build Numbers
// by using the '*' as shown below:
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 37.722222 | 84 | 0.752577 | [
"Apache-2.0"
] | phanductri13/ATDTDM-PDT | WebApplication1/Properties/AssemblyInfo.cs | 1,361 | C# |
using System;
using System.Runtime.InteropServices;
namespace SixtenLabs.SpawnOfVulkan
{
[StructLayout(LayoutKind.Explicit)]
public struct DescriptorSetHandle
{
[FieldOffset(0)]
public IntPtr nativePointer;
public readonly static DescriptorSetHandle Null = new DescriptorSetHandle(IntPtr.Zero);
private DescriptorSetHandle(IntPtr nativePointer)
{
this.nativePointer = nativePointer;
}
}
} | 27.411765 | 95 | 0.695279 | [
"Unlicense"
] | SixtenLabs/SpawnOfVulkan | src/SixtenLabs.SpawnOfVulkan/Handles/DescriptorSetHandle.cs | 468 | 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("helloworld-windows.Windows")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("helloworld-windows.Windows")]
[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)] | 36.862069 | 84 | 0.744621 | [
"Apache-2.0"
] | feedhenry-templates/helloworld-windows | helloworld-windows/helloworld-windows.Windows/Properties/AssemblyInfo.cs | 1,072 | C# |
//----------------------------------------------------------------------
//
// Copyright (c) Microsoft Corporation.
// All rights reserved.
//
// This code is licensed under the MIT License.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files(the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and / or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions :
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using System;
using System.Threading;
using System.Threading.Tasks;
using SafariServices;
using Foundation;
using AuthenticationServices;
using UIKit;
namespace Microsoft.Identity.Core.UI
{
internal abstract class WebviewBase : NSObject, IWebUI, ISFSafariViewControllerDelegate
{
protected static SemaphoreSlim returnedUriReady;
protected static AuthorizationResult authorizationResult;
protected static UIViewController viewController;
protected SFSafariViewController safariViewController;
protected SFAuthenticationSession sfAuthenticationSession;
protected ASWebAuthenticationSession asWebAuthenticationSession;
protected nint taskId = UIApplication.BackgroundTaskInvalid;
protected NSObject didEnterBackgroundNotification;
protected NSObject willEnterForegroundNotification;
public WebviewBase()
{
didEnterBackgroundNotification = NSNotificationCenter.DefaultCenter.AddObserver(UIApplication.DidEnterBackgroundNotification, OnMoveToBackground);
willEnterForegroundNotification = NSNotificationCenter.DefaultCenter.AddObserver(UIApplication.WillEnterForegroundNotification, OnMoveToForeground);
}
public abstract Task<AuthorizationResult> AcquireAuthorizationAsync(Uri authorizationUri, Uri redirectUri,
RequestContext requestContext);
public static bool ContinueAuthentication(string url)
{
if (returnedUriReady == null)
{
return false;
}
viewController.InvokeOnMainThread(() =>
{
authorizationResult = new AuthorizationResult(AuthorizationStatus.Success, url);
returnedUriReady.Release();
});
return true;
}
protected void OnMoveToBackground(NSNotification notification)
{
// After iOS 11.3, it is neccesary to keep a background task running while moving an app to the background
// in order to prevent the system from reclaiming network resources from the app.
// This will prevent authentication from failing while the application is moved to the background while waiting for MFA to finish.
taskId = UIApplication.SharedApplication.BeginBackgroundTask(() =>
{
if (taskId != UIApplication.BackgroundTaskInvalid)
{
UIApplication.SharedApplication.EndBackgroundTask(taskId);
taskId = UIApplication.BackgroundTaskInvalid;
}
});
}
protected void OnMoveToForeground(NSNotification notification)
{
if (taskId != UIApplication.BackgroundTaskInvalid)
{
UIApplication.SharedApplication.EndBackgroundTask(taskId);
taskId = UIApplication.BackgroundTaskInvalid;
}
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
if (didEnterBackgroundNotification != null)
{
didEnterBackgroundNotification.Dispose();
didEnterBackgroundNotification = null;
}
if (willEnterForegroundNotification != null)
{
willEnterForegroundNotification.Dispose();
willEnterForegroundNotification = null;
}
}
}
public abstract void ValidateRedirectUri(Uri redirectUri);
}
}
| 41.305085 | 160 | 0.665367 | [
"MIT"
] | AaronPatterson/azure-activedirectory-library-for-dotnet | src/Microsoft.IdentityModel.Clients.ActiveDirectory/Platforms/iOS/WebviewBase.cs | 4,876 | C# |
using System;
namespace VsjAPI
{
public class WeatherForecast
{
public DateTime Date { get; set; }
public int TemperatureC { get; set; }
public int TemperatureF => 32 + (int)(TemperatureC / 0.5556);
public string Summary { get; set; }
}
}
| 17.9375 | 69 | 0.595819 | [
"MIT"
] | Varanasi-Software-Junction/vsjecommerceapp | VsjAPI/WeatherForecast.cs | 287 | C# |
using CMS.Model.Model;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Globalization;
using System.Linq;
namespace CMS.Service.Helper
{
public static class EnumHelper
{
public static string GetDescription<T>(this T e) where T : IConvertible
{
string description = string.Empty;
Type type = e.GetType();
Array values = Enum.GetValues(type);
foreach (int val in values)
{
if (val == e.ToInt32(CultureInfo.InvariantCulture))
{
var memInfo = type.GetMember(type.GetEnumName(val));
var descriptionAttribute = memInfo[0]
.GetCustomAttributes(typeof(DescriptionAttribute), false)
.FirstOrDefault() as DescriptionAttribute;
if (descriptionAttribute != null)
{
return descriptionAttribute.Description;
}
}
}
return description;
}
public static List<LookupModel> GetEnumLookup(Type type)
{
var list = new List<LookupModel>();
var names = Enum.GetNames(type);
foreach (var name in names)
{
var field = type.GetField(name);
var fds = field.GetCustomAttributes(typeof(DescriptionAttribute), true);
foreach (DescriptionAttribute fd in fds)
{
var model = new LookupModel()
{
Id = (int)field.GetRawConstantValue(),
Name = fd.Description
};
list.Add(model);
}
}
return list;
}
}
}
| 31.982759 | 88 | 0.50027 | [
"Apache-2.0"
] | mehmetakbudak/CMS | CMS.Service/Helper/EnumHelper.cs | 1,857 | C# |
// *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
// *** 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.Cloudflare
{
/// <summary>
/// Provides a Cloudflare Access Application resource. Access Applications
/// are used to restrict access to a whole application using an
/// authorisation gateway managed by Cloudflare.
///
/// ## Example Usage
///
/// ```csharp
/// using Pulumi;
/// using Cloudflare = Pulumi.Cloudflare;
///
/// class MyStack : Stack
/// {
/// public MyStack()
/// {
/// // With CORS configuration
/// var stagingApp = new Cloudflare.AccessApplication("stagingApp", new Cloudflare.AccessApplicationArgs
/// {
/// CorsHeaders =
/// {
/// new Cloudflare.Inputs.AccessApplicationCorsHeaderArgs
/// {
/// AllowCredentials = true,
/// AllowedMethods =
/// {
/// "GET",
/// "POST",
/// "OPTIONS",
/// },
/// AllowedOrigins =
/// {
/// "https://example.com",
/// },
/// MaxAge = 10,
/// },
/// },
/// Domain = "staging.example.com",
/// Name = "staging application",
/// SessionDuration = "24h",
/// Type = "self_hosted",
/// ZoneId = "1d5fdc9e88c8a8c4518b068cd94331fe",
/// });
/// }
///
/// }
/// ```
///
/// ## Import
///
/// Access Applications can be imported using a composite ID formed of account ID and application ID.
///
/// ```sh
/// $ pulumi import cloudflare:index/accessApplication:AccessApplication staging cb029e245cfdd66dc8d2e570d5dd3322/d41d8cd98f00b204e9800998ecf8427e
/// ```
/// </summary>
[CloudflareResourceType("cloudflare:index/accessApplication:AccessApplication")]
public partial class AccessApplication : Pulumi.CustomResource
{
/// <summary>
/// The account to which the access application should be added. Conflicts with `zone_id`.
/// </summary>
[Output("accountId")]
public Output<string> AccountId { get; private set; } = null!;
/// <summary>
/// The identity providers selected for the application.
/// </summary>
[Output("allowedIdps")]
public Output<ImmutableArray<string>> AllowedIdps { get; private set; } = null!;
/// <summary>
/// Application Audience (AUD) Tag of the application
/// </summary>
[Output("aud")]
public Output<string> Aud { get; private set; } = null!;
/// <summary>
/// Option to skip identity provider
/// selection if only one is configured in allowed_idps. Defaults to `false`
/// (disabled).
/// </summary>
[Output("autoRedirectToIdentity")]
public Output<bool?> AutoRedirectToIdentity { get; private set; } = null!;
/// <summary>
/// CORS configuration for the Access Application. See
/// below for reference structure.
/// </summary>
[Output("corsHeaders")]
public Output<ImmutableArray<Outputs.AccessApplicationCorsHeader>> CorsHeaders { get; private set; } = null!;
/// <summary>
/// Option that returns a custom error message when a user is denied access to the application.
/// </summary>
[Output("customDenyMessage")]
public Output<string?> CustomDenyMessage { get; private set; } = null!;
/// <summary>
/// Option that redirects to a custom URL when a user is denied access to the application.
/// </summary>
[Output("customDenyUrl")]
public Output<string?> CustomDenyUrl { get; private set; } = null!;
/// <summary>
/// The complete URL of the asset you wish to put
/// Cloudflare Access in front of. Can include subdomains or paths. Or both.
/// </summary>
[Output("domain")]
public Output<string> Domain { get; private set; } = null!;
/// <summary>
/// Option to provide increased security against compromised authorization tokens and CSRF attacks by requiring an additional "binding" cookie on requests. Defaults to `false`.
/// </summary>
[Output("enableBindingCookie")]
public Output<bool?> EnableBindingCookie { get; private set; } = null!;
/// <summary>
/// Friendly name of the Access Application.
/// </summary>
[Output("name")]
public Output<string> Name { get; private set; } = null!;
/// <summary>
/// How often a user will be forced to
/// re-authorise. Must be in the format `"48h"` or `"2h45m"`.
/// Valid time units are `ns`, `us` (or `µs`), `ms`, `s`, `m`, `h`. Defaults to `24h`.
/// </summary>
[Output("sessionDuration")]
public Output<string?> SessionDuration { get; private set; } = null!;
/// <summary>
/// The application type. Defaults to `self_hosted`. Valid
/// values are `self_hosted`, `ssh`, `vnc`, or `file`.
/// </summary>
[Output("type")]
public Output<string?> Type { get; private set; } = null!;
/// <summary>
/// The DNS zone to which the access application should be added. Conflicts with `account_id`.
/// </summary>
[Output("zoneId")]
public Output<string> ZoneId { get; private set; } = null!;
/// <summary>
/// Create a AccessApplication 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 AccessApplication(string name, AccessApplicationArgs args, CustomResourceOptions? options = null)
: base("cloudflare:index/accessApplication:AccessApplication", name, args ?? new AccessApplicationArgs(), MakeResourceOptions(options, ""))
{
}
private AccessApplication(string name, Input<string> id, AccessApplicationState? state = null, CustomResourceOptions? options = null)
: base("cloudflare:index/accessApplication:AccessApplication", name, state, MakeResourceOptions(options, id))
{
}
private static CustomResourceOptions MakeResourceOptions(CustomResourceOptions? options, Input<string>? id)
{
var defaultOptions = new CustomResourceOptions
{
Version = Utilities.Version,
};
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 AccessApplication 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="state">Any extra arguments used during the lookup.</param>
/// <param name="options">A bag of options that control this resource's behavior</param>
public static AccessApplication Get(string name, Input<string> id, AccessApplicationState? state = null, CustomResourceOptions? options = null)
{
return new AccessApplication(name, id, state, options);
}
}
public sealed class AccessApplicationArgs : Pulumi.ResourceArgs
{
/// <summary>
/// The account to which the access application should be added. Conflicts with `zone_id`.
/// </summary>
[Input("accountId")]
public Input<string>? AccountId { get; set; }
[Input("allowedIdps")]
private InputList<string>? _allowedIdps;
/// <summary>
/// The identity providers selected for the application.
/// </summary>
public InputList<string> AllowedIdps
{
get => _allowedIdps ?? (_allowedIdps = new InputList<string>());
set => _allowedIdps = value;
}
/// <summary>
/// Option to skip identity provider
/// selection if only one is configured in allowed_idps. Defaults to `false`
/// (disabled).
/// </summary>
[Input("autoRedirectToIdentity")]
public Input<bool>? AutoRedirectToIdentity { get; set; }
[Input("corsHeaders")]
private InputList<Inputs.AccessApplicationCorsHeaderArgs>? _corsHeaders;
/// <summary>
/// CORS configuration for the Access Application. See
/// below for reference structure.
/// </summary>
public InputList<Inputs.AccessApplicationCorsHeaderArgs> CorsHeaders
{
get => _corsHeaders ?? (_corsHeaders = new InputList<Inputs.AccessApplicationCorsHeaderArgs>());
set => _corsHeaders = value;
}
/// <summary>
/// Option that returns a custom error message when a user is denied access to the application.
/// </summary>
[Input("customDenyMessage")]
public Input<string>? CustomDenyMessage { get; set; }
/// <summary>
/// Option that redirects to a custom URL when a user is denied access to the application.
/// </summary>
[Input("customDenyUrl")]
public Input<string>? CustomDenyUrl { get; set; }
/// <summary>
/// The complete URL of the asset you wish to put
/// Cloudflare Access in front of. Can include subdomains or paths. Or both.
/// </summary>
[Input("domain", required: true)]
public Input<string> Domain { get; set; } = null!;
/// <summary>
/// Option to provide increased security against compromised authorization tokens and CSRF attacks by requiring an additional "binding" cookie on requests. Defaults to `false`.
/// </summary>
[Input("enableBindingCookie")]
public Input<bool>? EnableBindingCookie { get; set; }
/// <summary>
/// Friendly name of the Access Application.
/// </summary>
[Input("name", required: true)]
public Input<string> Name { get; set; } = null!;
/// <summary>
/// How often a user will be forced to
/// re-authorise. Must be in the format `"48h"` or `"2h45m"`.
/// Valid time units are `ns`, `us` (or `µs`), `ms`, `s`, `m`, `h`. Defaults to `24h`.
/// </summary>
[Input("sessionDuration")]
public Input<string>? SessionDuration { get; set; }
/// <summary>
/// The application type. Defaults to `self_hosted`. Valid
/// values are `self_hosted`, `ssh`, `vnc`, or `file`.
/// </summary>
[Input("type")]
public Input<string>? Type { get; set; }
/// <summary>
/// The DNS zone to which the access application should be added. Conflicts with `account_id`.
/// </summary>
[Input("zoneId")]
public Input<string>? ZoneId { get; set; }
public AccessApplicationArgs()
{
}
}
public sealed class AccessApplicationState : Pulumi.ResourceArgs
{
/// <summary>
/// The account to which the access application should be added. Conflicts with `zone_id`.
/// </summary>
[Input("accountId")]
public Input<string>? AccountId { get; set; }
[Input("allowedIdps")]
private InputList<string>? _allowedIdps;
/// <summary>
/// The identity providers selected for the application.
/// </summary>
public InputList<string> AllowedIdps
{
get => _allowedIdps ?? (_allowedIdps = new InputList<string>());
set => _allowedIdps = value;
}
/// <summary>
/// Application Audience (AUD) Tag of the application
/// </summary>
[Input("aud")]
public Input<string>? Aud { get; set; }
/// <summary>
/// Option to skip identity provider
/// selection if only one is configured in allowed_idps. Defaults to `false`
/// (disabled).
/// </summary>
[Input("autoRedirectToIdentity")]
public Input<bool>? AutoRedirectToIdentity { get; set; }
[Input("corsHeaders")]
private InputList<Inputs.AccessApplicationCorsHeaderGetArgs>? _corsHeaders;
/// <summary>
/// CORS configuration for the Access Application. See
/// below for reference structure.
/// </summary>
public InputList<Inputs.AccessApplicationCorsHeaderGetArgs> CorsHeaders
{
get => _corsHeaders ?? (_corsHeaders = new InputList<Inputs.AccessApplicationCorsHeaderGetArgs>());
set => _corsHeaders = value;
}
/// <summary>
/// Option that returns a custom error message when a user is denied access to the application.
/// </summary>
[Input("customDenyMessage")]
public Input<string>? CustomDenyMessage { get; set; }
/// <summary>
/// Option that redirects to a custom URL when a user is denied access to the application.
/// </summary>
[Input("customDenyUrl")]
public Input<string>? CustomDenyUrl { get; set; }
/// <summary>
/// The complete URL of the asset you wish to put
/// Cloudflare Access in front of. Can include subdomains or paths. Or both.
/// </summary>
[Input("domain")]
public Input<string>? Domain { get; set; }
/// <summary>
/// Option to provide increased security against compromised authorization tokens and CSRF attacks by requiring an additional "binding" cookie on requests. Defaults to `false`.
/// </summary>
[Input("enableBindingCookie")]
public Input<bool>? EnableBindingCookie { get; set; }
/// <summary>
/// Friendly name of the Access Application.
/// </summary>
[Input("name")]
public Input<string>? Name { get; set; }
/// <summary>
/// How often a user will be forced to
/// re-authorise. Must be in the format `"48h"` or `"2h45m"`.
/// Valid time units are `ns`, `us` (or `µs`), `ms`, `s`, `m`, `h`. Defaults to `24h`.
/// </summary>
[Input("sessionDuration")]
public Input<string>? SessionDuration { get; set; }
/// <summary>
/// The application type. Defaults to `self_hosted`. Valid
/// values are `self_hosted`, `ssh`, `vnc`, or `file`.
/// </summary>
[Input("type")]
public Input<string>? Type { get; set; }
/// <summary>
/// The DNS zone to which the access application should be added. Conflicts with `account_id`.
/// </summary>
[Input("zoneId")]
public Input<string>? ZoneId { get; set; }
public AccessApplicationState()
{
}
}
}
| 39.558603 | 184 | 0.573032 | [
"ECL-2.0",
"Apache-2.0"
] | pulumi/pulumi-cloudflare | sdk/dotnet/AccessApplication.cs | 15,866 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
namespace Microsoft.AspNetCore.Connections;
/// <summary>
/// Enumerates the <see cref="FileHandleEndPoint"/> types.
/// </summary>
public enum FileHandleType
{
Auto,
Tcp,
Pipe
}
| 22 | 71 | 0.715152 | [
"MIT"
] | Aezura/aspnetcore | src/Servers/Connections.Abstractions/src/FileHandleType.cs | 330 | C# |
// <auto-generated>
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
// </auto-generated>
namespace Microsoft.Azure.Management.Kusto.Models
{
/// <summary>
/// Defines values for State.
/// </summary>
public static class State
{
public const string Creating = "Creating";
public const string Unavailable = "Unavailable";
public const string Running = "Running";
public const string Deleting = "Deleting";
public const string Deleted = "Deleted";
public const string Stopping = "Stopping";
public const string Stopped = "Stopped";
public const string Starting = "Starting";
}
}
| 32.034483 | 74 | 0.674919 | [
"MIT"
] | AnanyShah/azure-sdk-for-net | src/SDKs/Kusto/Management.Kusto/Generated/Models/State.cs | 929 | C# |
using System.Collections.Generic;
using System.IO;
using Microsoft.AspNet.Builder;
using Nancy;
using Nancy.Owin;
using Nancy.ViewEngines.Razor;
namespace FindReplace
{
public class Startup
{
public void Configure(IApplicationBuilder app)
{
app.UseOwin(x => x.UseNancy());
}
}
public class CustomRootPathProvider : IRootPathProvider
{
public string GetRootPath()
{
return Directory.GetCurrentDirectory();
}
}
public class RazorConfig : IRazorConfiguration
{
public IEnumerable<string> GetAssemblyNames()
{
return null;
}
public IEnumerable<string> GetDefaultNamespaces()
{
return null;
}
public bool AutoIncludeModelNamespace
{
get { return false; }
}
}
}
| 18.261905 | 57 | 0.674055 | [
"MIT"
] | CharlesEwel/find-replace | find-replace/Startup.cs | 767 | C# |
using System.Reflection;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Problem04PrintADeckOf52Cards")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Johnson Controls")]
[assembly: AssemblyProduct("Problem04PrintADeckOf52Cards")]
[assembly: AssemblyCopyright("Copyright © Johnson Controls 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("c4360f70-0e65-4c00-ae7a-5f2e42f56052")]
// 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")]
| 39.5 | 84 | 0.751758 | [
"MIT"
] | atanas-georgiev/TelerikAcademy | 01.CSharp-Part-1/Homework6/Problem04PrintADeckOf52Cards/Properties/AssemblyInfo.cs | 1,425 | C# |
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using PlayFab.Json;
using PlayFab.SharedModels;
using UnityEngine;
#if !UNITY_WSA && !UNITY_WP8
using Ionic.Zlib;
#endif
namespace PlayFab.Internal
{
public class PlayFabWww : IPlayFabHttp
{
private int _pendingWwwMessages = 0;
public bool SessionStarted { get; set; }
public string AuthKey { get; set; }
public void InitializeHttp() { }
public void Update() { }
public void OnDestroy() { }
public void MakeApiCall(CallRequestContainer reqContainer)
{
reqContainer.RequestHeaders["Content-Type"] = "application/json";
#if !UNITY_WSA && !UNITY_WP8 && !UNITY_WEBGL
if (PlayFabSettings.CompressApiData)
{
reqContainer.RequestHeaders["Content-Encoding"] = "GZIP";
reqContainer.RequestHeaders["Accept-Encoding"] = "GZIP";
using (var stream = new MemoryStream())
{
using (var zipstream = new GZipStream(stream, CompressionMode.Compress, CompressionLevel.BestCompression))
{
zipstream.Write(reqContainer.Payload, 0, reqContainer.Payload.Length);
}
reqContainer.Payload = stream.ToArray();
}
}
#endif
//Debug.LogFormat("Posting {0} to Url: {1}", req.Trim(), url);
var www = new WWW(reqContainer.FullUrl, reqContainer.Payload, reqContainer.RequestHeaders);
#if PLAYFAB_REQUEST_TIMING
var stopwatch = System.Diagnostics.Stopwatch.StartNew();
#endif
// Start the www corouting to Post, and get a response or error which is then passed to the callbacks.
Action<string> wwwSuccessCallback = (response) =>
{
try
{
#if PLAYFAB_REQUEST_TIMING
var startTime = DateTime.UtcNow;
#endif
var httpResult = JsonWrapper.DeserializeObject<HttpResponseObject>(response);
if (httpResult.code == 200)
{
// We have a good response from the server
reqContainer.JsonResponse = JsonWrapper.SerializeObject(httpResult.data);
reqContainer.DeserializeResultJson();
reqContainer.ApiResult.Request = reqContainer.ApiRequest;
reqContainer.ApiResult.CustomData = reqContainer.CustomData;
#if !DISABLE_PLAYFABCLIENT_API
var res = reqContainer.ApiResult as ClientModels.LoginResult;
var regRes = reqContainer.ApiResult as ClientModels.RegisterPlayFabUserResult;
if (res != null)
AuthKey = res.SessionTicket;
else if (regRes != null)
AuthKey = regRes.SessionTicket;
if (res != null || regRes != null)
PlayFabDeviceUtil.OnPlayFabLogin(res, regRes);
#endif
try
{
PlayFabHttp.SendEvent(reqContainer.ApiEndpoint, reqContainer.ApiRequest, reqContainer.ApiResult, ApiProcessingEventType.Post);
}
catch (Exception e)
{
Debug.LogException(e);
}
#if PLAYFAB_REQUEST_TIMING
stopwatch.Stop();
var timing = new PlayFabHttp.RequestTiming {
StartTimeUtc = startTime,
ApiEndpoint = reqContainer.ApiEndpoint,
WorkerRequestMs = (int)stopwatch.ElapsedMilliseconds,
MainThreadRequestMs = (int)stopwatch.ElapsedMilliseconds
};
PlayFabHttp.SendRequestTiming(timing);
#endif
try
{
reqContainer.InvokeSuccessCallback();
}
catch (Exception e)
{
Debug.LogException(e);
}
}
else
{
if (reqContainer.ErrorCallback != null)
{
reqContainer.Error = PlayFabHttp.GeneratePlayFabError(response, reqContainer.CustomData);
PlayFabHttp.SendErrorEvent(reqContainer.ApiRequest, reqContainer.Error);
reqContainer.ErrorCallback(reqContainer.Error);
}
}
}
catch (Exception e)
{
Debug.LogException(e);
}
};
Action<string> wwwErrorCallback = (errorCb) =>
{
reqContainer.JsonResponse = errorCb;
if (reqContainer.ErrorCallback != null)
{
reqContainer.Error = PlayFabHttp.GeneratePlayFabError(reqContainer.JsonResponse, reqContainer.CustomData);
PlayFabHttp.SendErrorEvent(reqContainer.ApiRequest, reqContainer.Error);
reqContainer.ErrorCallback(reqContainer.Error);
}
};
PlayFabHttp.instance.StartCoroutine(Post(www, wwwSuccessCallback, wwwErrorCallback));
}
private IEnumerator Post(WWW www, Action<string> wwwSuccessCallback, Action<string> wwwErrorCallback)
{
yield return www;
if (!string.IsNullOrEmpty(www.error))
{
wwwErrorCallback(www.error);
}
else
{
try
{
#if !UNITY_WSA && !UNITY_WP8 && !UNITY_WEBGL
string encoding;
if (www.responseHeaders.TryGetValue("Content-Encoding", out encoding) && encoding.ToLowerInvariant() == "gzip")
{
var stream = new MemoryStream(www.bytes);
using (var gZipStream = new GZipStream(stream, CompressionMode.Decompress, false))
{
var buffer = new byte[4096];
using (var output = new MemoryStream())
{
int read;
while ((read = gZipStream.Read(buffer, 0, buffer.Length)) > 0)
{
output.Write(buffer, 0, read);
}
output.Seek(0, SeekOrigin.Begin);
var streamReader = new StreamReader(output);
var jsonResponse = streamReader.ReadToEnd();
//Debug.Log(jsonResponse);
wwwSuccessCallback(jsonResponse);
}
}
}
else
#endif
{
wwwSuccessCallback(www.text);
}
}
catch (Exception e)
{
wwwErrorCallback("Unhandled error in PlayFabWWW: " + e);
}
}
}
public int GetPendingMessages()
{
return _pendingWwwMessages;
}
}
}
| 39.725389 | 154 | 0.484675 | [
"Apache-2.0"
] | MirrorAndLight/UnicornBattle | BasicIosPush/Assets/PlayFabSdk/Shared/Internal/PlayFabHttp/PlayFabWWW.cs | 7,667 | C# |
namespace AttentyPracticeFrameWork.ApiRoutes
{
public interface IApiRouteAggregate
{
string GetWeatherEntry();
}
} | 19.285714 | 45 | 0.711111 | [
"MIT"
] | lior277/AttentyPractice | AttentyPracticeFrameWork/Internals/DAL/ApiAccsess/ApiRoutes/IApiRouteAggregate.cs | 137 | C# |
/*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the codepipeline-2015-07-09.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.CodePipeline.Model
{
/// <summary>
/// Container for the parameters to the ListPipelines operation.
/// Gets a summary of all of the pipelines associated with your account.
/// </summary>
public partial class ListPipelinesRequest : AmazonCodePipelineRequest
{
private int? _maxResults;
private string _nextToken;
/// <summary>
/// Gets and sets the property MaxResults.
/// <para>
/// The maximum number of pipelines to return in a single call. To retrieve the remaining
/// pipelines, make another call with the returned nextToken value. The minimum value
/// you can specify is 1. The maximum accepted value is 1000.
/// </para>
/// </summary>
[AWSProperty(Min=1, Max=1000)]
public int MaxResults
{
get { return this._maxResults.GetValueOrDefault(); }
set { this._maxResults = value; }
}
// Check to see if MaxResults property is set
internal bool IsSetMaxResults()
{
return this._maxResults.HasValue;
}
/// <summary>
/// Gets and sets the property NextToken.
/// <para>
/// An identifier that was returned from the previous list pipelines call. It can be used
/// to return the next set of pipelines in the list.
/// </para>
/// </summary>
[AWSProperty(Min=1, Max=2048)]
public string NextToken
{
get { return this._nextToken; }
set { this._nextToken = value; }
}
// Check to see if NextToken property is set
internal bool IsSetNextToken()
{
return this._nextToken != null;
}
}
} | 32.402439 | 110 | 0.635303 | [
"Apache-2.0"
] | ChristopherButtars/aws-sdk-net | sdk/src/Services/CodePipeline/Generated/Model/ListPipelinesRequest.cs | 2,657 | C# |
namespace Kaiyuanshe.OpenHackathon.Server.Models
{
/// <summary>
/// decribes a resource list
/// </summary>
public interface IResourceList<T>
{
/// <summary>
/// List of the resources
/// </summary>
T[] value { get; set; }
/// <summary>
/// The URL the client should use to fetch the next page (per server side paging).
/// No more results if it's null or empty.
/// </summary>
string nextLink { get; set; }
}
}
| 26.5 | 91 | 0.520755 | [
"MIT"
] | think-in-universe/open-hackathon | src/open-hackathon-server/Kaiyuanshe.OpenHackathon.Server/Models/IResourceList.cs | 532 | C# |
using System;
using stellar_dotnet_sdk.xdr;
namespace stellar_dotnet_sdk
{
public class MemoId : Memo
{
public MemoId(long id)
{
if (id < 0)
throw new ArgumentException("id must be a positive number");
IdValue = id;
}
public long IdValue { get; }
public override xdr.Memo ToXdr()
{
var memo = new xdr.Memo();
memo.Discriminant = MemoType.Create(MemoType.MemoTypeEnum.MEMO_ID);
var idXdr = new Uint64();
idXdr.InnerValue = IdValue;
memo.Id = idXdr;
return memo;
}
public override bool Equals(Object o)
{
if (this == o) return true;
if (o == null || GetType() != o.GetType()) return false;
MemoId memoId = (MemoId) o;
return IdValue == memoId.IdValue;
}
public override int GetHashCode()
{
return HashCode.Start
.Hash(IdValue);
}
}
} | 26.365854 | 80 | 0.489362 | [
"Apache-2.0"
] | alphapoint/dotnet-stellar-sdk | stellar-dotnet-sdk/MemoId.cs | 1,083 | C# |
namespace StorageManager.Query
{
public class StorageQueryConstantMember : StorageQueryOperand
{
public StorageQueryConstantMember(object value = null)
{
Value = value;
}
public object Value { get; }
public override object Evaluate(object source = null)
{
return Value;
}
public override string ToString()
{
return Value.ToString();
}
}
} | 22.285714 | 65 | 0.561966 | [
"MIT"
] | mcolon/StorageManager | StorageManager/Query/StorageQueryConstant.cs | 468 | C# |
using System;
using System.Collections.Generic;
using Uno.Disposables;
using Uno.UI.Xaml.Core;
using Windows.Foundation;
using Windows.System;
using Windows.UI.Xaml.Automation.Peers;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Markup;
namespace Windows.UI.Xaml.Controls
{
[ContentProperty(Name = "Items")]
public partial class MenuFlyoutSubItem : MenuFlyoutItemBase, ISubMenuOwner
{
// Popup for the MenuFlyoutSubItem
Popup m_tpPopup;
// Presenter for the MenuFlyoutSubItem
Control m_tpPresenter;
// In Threshold, MenuFlyout uses the MenuPopupThemeTransition.
// UNO TODO Transition m_tpMenuPopupThemeTransition = null;
// Event pointer for the Loaded event
// IDisposable m_epLoadedHandler;
// Event pointer for the size changed on the MenuFlyoutSubItem's presenter
IDisposable m_epPresenterSizeChangedHandler;
// Helper to which to delegate cascading menu functionality.
CascadingMenuHelper m_menuHelper;
// Weak reference the parent that owns the menu that this item belongs to.
private WeakReference m_wrParentOwner;
DependencyObjectCollection<MenuFlyoutItemBase> m_tpItems;
public string Text
{
get => (string)this.GetValue(TextProperty);
set => SetValue(TextProperty, value);
}
public IList<MenuFlyoutItemBase> Items => m_tpItems;
public IconElement Icon
{
get => (IconElement)this.GetValue(IconProperty);
set => this.SetValue(IconProperty, value);
}
public static Windows.UI.Xaml.DependencyProperty TextProperty { get; } =
Windows.UI.Xaml.DependencyProperty.Register(
"Text",
typeof(string),
typeof(MenuFlyoutSubItem),
new FrameworkPropertyMetadata(default(string)));
public static Windows.UI.Xaml.DependencyProperty IconProperty { get; } =
Windows.UI.Xaml.DependencyProperty.Register(
"Icon",
typeof(IconElement),
typeof(MenuFlyoutSubItem),
new FrameworkPropertyMetadata(default(IconElement)));
public MenuFlyoutSubItem()
{
#if MFSI_DEBUG
IGNOREHR(DebugTrace(XCP_TRACE_OUTPUT_MSG /*traceType*/, "MFSI[0x%p]: ", this));
#endif // MFSI_DEBUG
PrepareState();
DefaultStyleKey = typeof(MenuFlyoutSubItem);
}
void PrepareState()
{
#if MFSI_DEBUG
IGNOREHR(DebugTrace(XCP_TRACE_OUTPUT_MSG /*traceType*/, "MFSI[0x%p]: PrepareState.", this));
#endif // MFSI_DEBUG
// Create the sub menu items collection and set the owner
m_tpItems = new DependencyObjectCollection<MenuFlyoutItemBase>(this);
m_menuHelper = new CascadingMenuHelper();
m_menuHelper.Initialize(this);
}
void DisconnectFrameworkPeerCore()
{
// Ensure the clean up the items whenever MenuFlyoutSubItem is disconnected
//if (m_tpItems.GetAsCoreDO() != null)
//{
// (Collection_Clear((CCollection*)(m_tpItems.GetAsCoreDO())));
// (Collection_SetOwner((CCollection*)(m_tpItems.GetAsCoreDO()), null));
//}
// (MenuFlyoutSubItemGenerated.DisconnectFrameworkPeerCore());
}
protected override void OnApplyTemplate()
{
#if MFSI_DEBUG
IGNOREHR(DebugTrace(XCP_TRACE_OUTPUT_MSG /*traceType*/, "MFSI[0x%p]: OnApplyTemplate.", this));
#endif // MFSI_DEBUG
m_menuHelper.OnApplyTemplate();
}
// PointerEntered event handler that shows the MenuFlyoutSubItem
// whenever the pointer is over to the
// In case of touch, the MenuFlyoutSubItem will be shown by
// PointerReleased event.
protected override void OnPointerEntered(PointerRoutedEventArgs args)
{
base.OnPointerEntered(args);
#if MFSI_DEBUG
IGNOREHR(DebugTrace(XCP_TRACE_OUTPUT_MSG /*traceType*/, "MFSI[0x%p]: OnPointerEntered.", this));
#endif // MFSI_DEBUG
UpdateParentOwner(null /*parentMenuFlyoutPresenter*/);
m_menuHelper.OnPointerEntered(args);
}
// PointerExited event handler that ensures the close MenuFlyoutSubItem
// whenever the pointer over is out of the current MenuFlyoutSubItem or
// out of the main presenter. If the exited point is on MenuFlyoutSubItem
// or sub presenter position, we want to keep the opened
protected override void OnPointerExited(PointerRoutedEventArgs args)
{
base.OnPointerExited(args);
#if MFSI_DEBUG
IGNOREHR(DebugTrace(XCP_TRACE_OUTPUT_MSG /*traceType*/, "MFSI[0x%p]: OnPointerExited.", this));
#endif // MFSI_DEBUG
bool parentIsSubMenu = false;
MenuFlyoutPresenter parentPresenter = GetParentMenuFlyoutPresenter();
if (parentPresenter != null)
{
parentIsSubMenu = parentPresenter.IsSubPresenter;
}
m_menuHelper.OnPointerExited(args, parentIsSubMenu);
}
// PointerPressed event handler that ensures the pressed state.
protected override void OnPointerPressed(PointerRoutedEventArgs args)
{
base.OnPointerPressed(args);
#if MFSI_DEBUG
IGNOREHR(DebugTrace(XCP_TRACE_OUTPUT_MSG /*traceType*/, "MFSI[0x%p]: OnPointerPressed.", this));
#endif // MFSI_DEBUG
m_menuHelper.OnPointerPressed(args);
}
// PointerReleased event handler that shows MenuFlyoutSubItem in
// case of touch input.
protected override void OnPointerReleased(PointerRoutedEventArgs args)
{
base.OnPointerReleased(args);
#if MFSI_DEBUG
IGNOREHR(DebugTrace(XCP_TRACE_OUTPUT_MSG /*traceType*/, "MFSI[0x%p]: OnPointerReleased.", this));
#endif // MFSI_DEBUG
m_menuHelper.OnPointerReleased(args);
}
protected override void OnGotFocus(RoutedEventArgs args)
{
base.OnGotFocus(args);
#if MFSI_DEBUG
IGNOREHR(DebugTrace(XCP_TRACE_OUTPUT_MSG /*traceType*/, "MFSI[0x%p]: OnGotFocus.", this));
#endif // MFSI_DEBUG
m_menuHelper.OnGotFocus(args);
}
protected override void OnLostFocus(RoutedEventArgs args)
{
base.OnLostFocus(args);
#if MFSI_DEBUG
IGNOREHR(DebugTrace(XCP_TRACE_OUTPUT_MSG /*traceType*/, "MFSI[0x%p]: OnLostFocus.", this));
#endif // MFSI_DEBUG
m_menuHelper.OnLostFocus(args);
}
// KeyDown event handler that handles the keyboard navigation between
// the menu items and shows the MenuFlyoutSubItem in case of hitting
// the enter or right arrow key.
protected override void OnKeyDown(KeyRoutedEventArgs args)
{
base.OnKeyDown(args);
#if MFSI_DEBUG
IGNOREHR(DebugTrace(XCP_TRACE_OUTPUT_MSG /*traceType*/, "MFSI[0x%p]: OnKeyDown.", this));
#endif // MFSI_DEBUG
bool handled = args.Handled;
bool shouldHandleEvent = false;
if (!handled)
{
MenuFlyoutPresenter spParentPresenter = GetParentMenuFlyoutPresenter();
if (spParentPresenter != null)
{
var key = args.Key;
// Navigate each item with the arrow down or up key
if (key == VirtualKey.Down || key == VirtualKey.Up)
{
spParentPresenter.HandleUpOrDownKey(key == VirtualKey.Down);
UpdateVisualState();
// If we handle the event here, it won't get handled in m_menuHelper.OnKeyDown,
// so we'll do that afterwards.
shouldHandleEvent = true;
}
}
}
m_menuHelper.OnKeyDown(args);
args.Handled = shouldHandleEvent;
}
protected override void OnKeyUp(KeyRoutedEventArgs args)
{
base.OnKeyUp(args);
#if MFSI_DEBUG
IGNOREHR(DebugTrace(XCP_TRACE_OUTPUT_MSG /*traceType*/, "MFSI[0x%p]: OnKeyUp.", this));
#endif // MFSI_DEBUG
m_menuHelper.OnKeyUp(args);
}
// Ensure the creating the popup and menu presenter to show the
void EnsurePopupAndPresenter()
{
#if MFSI_DEBUG
IGNOREHR(DebugTrace(XCP_TRACE_OUTPUT_MSG /*traceType*/, "MFSI[0x%p]: EnsurePopupAndPresenter.", this));
#endif // MFSI_DEBUG
if (m_tpPopup == null)
{
MenuFlyoutPresenter spParentMenuFlyoutPresenter = null;
Control spPresenter;
UIElement spPresenterAsUI;
FrameworkElement spPresenterAsFE;
Popup spPopup;
spPopup = new Popup();
spPopup.IsSubMenu = true;
spPopup.IsLightDismissEnabled = false;
spParentMenuFlyoutPresenter = GetParentMenuFlyoutPresenter();
#if false // UNO TODO Windowed Popup is not available
if (spParentMenuFlyoutPresenter != null)
{
spParentMenuFlyout = spParentMenuFlyoutPresenter.GetParentMenuFlyout();
// Set the windowed Popup if the MenuFlyout is set the windowed Popup
if (spParentMenuFlyout && spParentMenuFlyout.IsWindowedPopup())
{
ASSERT((CPopup*)(spPopup as Popup.GetHandle()).DoesPlatformSupportWindowedPopup(DXamlCore.GetCurrent().GetHandle()));
((CPopup*)(spPopup as Popup.GetHandle()).SetIsWindowed());
// Ensure the sub menu is the windowed Popup
ASSERT((CPopup*)(spPopup as Popup.GetHandle()).IsWindowed());
xaml.IXamlRoot xamlRoot = XamlRoot.GetForElementStatic(spParentMenuFlyoutPresenter);
if (xamlRoot)
{
(spPopup as Popup.XamlRoot = xamlRoot);
}
}
}
#endif
spPresenter = CreateSubPresenter();
spPresenterAsUI = spPresenter;
if (spParentMenuFlyoutPresenter != null)
{
int parentDepth = spParentMenuFlyoutPresenter.GetDepth();
(spPresenter as MenuFlyoutPresenter).SetDepth(parentDepth + 1);
}
spPopup.Child = spPresenterAsUI as FrameworkElement;
m_tpPresenter = spPresenter;
m_tpPopup = spPopup;
((ItemsControl)m_tpPresenter).ItemsSource = m_tpItems;
spPresenterAsFE = spPresenter;
spPresenterAsFE.SizeChanged += OnPresenterSizeChanged;
m_epPresenterSizeChangedHandler = Disposable.Create(() => spPresenterAsFE.SizeChanged -= OnPresenterSizeChanged);
m_menuHelper.SetSubMenuPresenter(spPresenter as Control);
}
}
void ForwardPresenterProperties(
MenuFlyout pOwnerMenuFlyout,
MenuFlyoutPresenter pParentMenuFlyoutPresenter,
MenuFlyoutPresenter pSubMenuFlyoutPresenter)
{
Style spStyle;
ElementTheme parentPresenterTheme;
object spDataContext;
FrameworkElement spPopupAsFE;
MenuFlyoutPresenter spSubMenuFlyoutPresenter = pSubMenuFlyoutPresenter;
Control spSubMenuFlyoutPresenterAsControl;
DependencyObject spThisAsDO = this;
global::System.Diagnostics.Debug.Assert(pOwnerMenuFlyout != null && pParentMenuFlyoutPresenter != null && pSubMenuFlyoutPresenter != null);
spSubMenuFlyoutPresenterAsControl = spSubMenuFlyoutPresenter;
// Set the sub presenter style from the MenuFlyout's presenter style
spStyle = pOwnerMenuFlyout.MenuFlyoutPresenterStyle;
if (spStyle != null)
{
((Control)pSubMenuFlyoutPresenter).Style = spStyle;
}
else
{
((Control)pSubMenuFlyoutPresenter).ClearValue(FrameworkElement.StyleProperty);
}
// Set the sub presenter's RequestTheme from the parent presenter's RequestTheme
parentPresenterTheme = pParentMenuFlyoutPresenter.RequestedTheme;
pSubMenuFlyoutPresenter.RequestedTheme = parentPresenterTheme;
// Set the sub presenter's DataContext from the parent presenter's DataContext
spDataContext = pParentMenuFlyoutPresenter.DataContext;
pSubMenuFlyoutPresenter.DataContext = spDataContext;
// Set the sub presenter's FlowDirection from the current sub menu item's FlowDirection
var flowDirection = FlowDirection;
pSubMenuFlyoutPresenter.FlowDirection = flowDirection;
// Set the popup's FlowDirection from the current FlowDirection
spPopupAsFE = m_tpPopup;
spPopupAsFE.FlowDirection = flowDirection;
// Set the sub presenter's Language from the parent presenter's Language
pSubMenuFlyoutPresenter.Language = pParentMenuFlyoutPresenter.Language;
// Set the sub presenter's IsTextScaleFactorEnabledInternal from the parent presenter's IsTextScaleFactorEnabledInternal
var isTextScaleFactorEnabled = pParentMenuFlyoutPresenter.IsTextScaleFactorEnabledInternal;
pSubMenuFlyoutPresenter.IsTextScaleFactorEnabledInternal = isTextScaleFactorEnabled;
ElementSoundMode soundMode = ElementSoundPlayerService.GetEffectiveSoundMode(spThisAsDO as DependencyObject);
(spSubMenuFlyoutPresenterAsControl as Control).ElementSoundMode = soundMode;
}
// Ensure that any currently open MenuFlyoutSubItems are closed
void EnsureCloseExistingSubItems()
{
#if MFSI_DEBUG
IGNOREHR(DebugTrace(XCP_TRACE_OUTPUT_MSG /*traceType*/, "MFSI[0x%p]: EnsureCloseExistingSubItems.", this));
#endif // MFSI_DEBUG
MenuFlyoutPresenter spParentPresenter;
spParentPresenter = GetParentMenuFlyoutPresenter();
if (spParentPresenter != null)
{
IMenuPresenter openedSubPresenter;
openedSubPresenter = (spParentPresenter as IMenuPresenter).SubPresenter;
if (openedSubPresenter != null)
{
ISubMenuOwner subMenuOwner;
subMenuOwner = openedSubPresenter.Owner;
if (subMenuOwner != null && subMenuOwner != this)
{
openedSubPresenter.CloseSubMenu();
}
}
}
}
bool IsOpen => m_tpPopup?.IsOpen ?? false;
Control
CreateSubPresenter()
{
#if MFSI_DEBUG
IGNOREHR(DebugTrace(XCP_TRACE_OUTPUT_MSG /*traceType*/, "MFSI[0x%p]: CreateSubPresenter.", this));
#endif // MFSI_DEBUG
MenuFlyoutPresenter spPresenter = new MenuFlyoutPresenter();
// Specify the sub MenuFlyoutPresenter
(spPresenter as MenuFlyoutPresenter).IsSubPresenter = true;
(spPresenter as IMenuPresenter).Owner = this;
return spPresenter;
}
void UpdateParentOwner(MenuFlyoutPresenter parentMenuFlyoutPresenter)
{
MenuFlyoutPresenter parentPresenter = parentMenuFlyoutPresenter;
if (parentPresenter == null)
{
parentPresenter = GetParentMenuFlyoutPresenter();
}
#if MFSI_DEBUG
IGNOREHR(DebugTrace(XCP_TRACE_OUTPUT_MSG /*traceType*/, "MFSI[0x%p]: UpdateParentOwner - parentPresenter=0x%p.", this, parentPresenter));
#endif // MFSI_DEBUG
if (parentPresenter != null)
{
ISubMenuOwner parentSubMenuOwner;
parentSubMenuOwner = (parentPresenter as IMenuPresenter).Owner;
#if MFSI_DEBUG
IGNOREHR(DebugTrace(XCP_TRACE_OUTPUT_MSG /*traceType*/, "MFSI[0x%p]: UpdateParentOwner - parentSubMenuOwner=0x%p.", this, parentSubMenuOwner));
#endif // MFSI_DEBUG
if (parentSubMenuOwner != null)
{
((ISubMenuOwner)this).ParentOwner = parentSubMenuOwner;
}
}
}
// Set the popup open or close status for MenuFlyoutSubItem and ensure the
// focus to the current presenter.
void SetIsOpen(bool isOpen)
{
bool isOpened = false;
isOpened = m_tpPopup.IsOpen;
#if MFSI_DEBUG
IGNOREHR(DebugTrace(XCP_TRACE_OUTPUT_MSG /*traceType*/, "MFSI[0x%p]: SetIsOpen isOpen=%d, isOpened=%d.", this, isOpen, isOpened));
#endif // MFSI_DEBUG
if (isOpen != isOpened)
{
(m_tpPresenter as IMenuPresenter).Owner = isOpen ? this : null;
MenuFlyoutPresenter parentPresenter;
parentPresenter = GetParentMenuFlyoutPresenter();
if (parentPresenter != null)
{
(parentPresenter as IMenuPresenter).SubPresenter = isOpen ? m_tpPresenter as MenuFlyoutPresenter : null;
IMenu owningMenu;
owningMenu = (parentPresenter as IMenuPresenter).OwningMenu;
if (owningMenu != null)
{
(m_tpPresenter as IMenuPresenter).OwningMenu = isOpen ? owningMenu : null;
}
UpdateParentOwner(parentPresenter);
}
// UNO TODO
//VisualTree* visualTree = VisualTree.GetForElementNoRef(GetHandle());
//if (visualTree)
//{
// // Put the popup on the same VisualTree as this flyout sub item to make sure it shows up in the right place
// (CPopup*)(m_tpPopup as Popup.GetHandle()).SetAssociatedVisualTree(visualTree);
//}
// Set the popup open or close state
m_tpPopup.IsOpen = isOpen;
// Set the focus to the displayed sub menu presenter when MenuFlyoutSubItem is opened and
// set the focus back to the original sub item when the displayed sub menu presenter is closed.
if (isOpen)
{
// Set the focus to the displayed sub menu presenter to navigate the each sub items
m_tpPresenter.Focus(FocusState.Programmatic);
// UNO TODO
// (DependencyObject.SetFocusedElement(
// spPresenterAsDO as DependencyObject,
// xaml.FocusState_Programmatic,
// false /*animateIfBringIntoView*/,
// &focusUpdated));
}
else
{
// Set the focus to the sub menu item
this.Focus(FocusState.Programmatic);
// UNO TODO
//(DependencyObject.SetFocusedElement(
// spThisAsDO as DependencyObject,
// xaml.FocusState_Programmatic,
// false /*animateIfBringIntoView*/,
// &focusUpdated));
}
UpdateVisualState();
}
}
void Open()
{
#if MFSI_DEBUG
IGNOREHR(DebugTrace(XCP_TRACE_OUTPUT_MSG /*traceType*/, "MFSI[0x%p]: Open.", this));
#endif // MFSI_DEBUG
m_menuHelper.OpenSubMenu();
}
void Close()
{
#if MFSI_DEBUG
IGNOREHR(DebugTrace(XCP_TRACE_OUTPUT_MSG /*traceType*/, "MFSI[0x%p]: Close.", this));
#endif // MFSI_DEBUG
m_menuHelper.CloseSubMenu();
}
private protected override void ChangeVisualState(bool bUseTransitions)
{
bool hasToggleMenuItem = false;
bool hasIconMenuItem = false;
bool bIsPopupOpened = false;
MenuFlyoutPresenter spPresenter;
var bIsEnabled = IsEnabled;
var focusState = FocusState;
var shouldBeNarrow = GetShouldBeNarrow();
spPresenter = GetParentMenuFlyoutPresenter();
if (spPresenter != null)
{
hasToggleMenuItem = spPresenter.GetContainsToggleItems();
hasIconMenuItem = spPresenter.GetContainsIconItems();
}
if (m_tpPopup != null)
{
bIsPopupOpened = m_tpPopup.IsOpen;
}
// CommonStates
if (!bIsEnabled)
{
VisualStateManager.GoToState(this, "Disabled", bUseTransitions);
}
else if (bIsPopupOpened)
{
VisualStateManager.GoToState(this, "SubMenuOpened", bUseTransitions);
}
else if (m_menuHelper.IsPressed)
{
VisualStateManager.GoToState(this, "Pressed", bUseTransitions);
}
else if (m_menuHelper.IsPointerOver)
{
VisualStateManager.GoToState(this, "PointerOver", bUseTransitions);
}
else
{
VisualStateManager.GoToState(this, "Normal", bUseTransitions);
}
// FocusStates
if (FocusState.Unfocused != focusState && bIsEnabled)
{
if (FocusState.Pointer == focusState)
{
VisualStateManager.GoToState(this, "PointerFocused", bUseTransitions);
}
else
{
VisualStateManager.GoToState(this, "Focused", bUseTransitions);
}
}
else
{
VisualStateManager.GoToState(this, "Unfocused", bUseTransitions);
}
// CheckPlaceholderStates
if (hasToggleMenuItem && hasIconMenuItem)
{
VisualStateManager.GoToState(this, "CheckAndIconPlaceholder", bUseTransitions);
}
else if (hasToggleMenuItem)
{
VisualStateManager.GoToState(this, "CheckPlaceholder", bUseTransitions);
}
else if (hasIconMenuItem)
{
VisualStateManager.GoToState(this, "IconPlaceholder", bUseTransitions);
}
else
{
VisualStateManager.GoToState(this, "NoPlaceholder", bUseTransitions);
}
// PaddingSizeStates
if (shouldBeNarrow)
{
VisualStateManager.GoToState(this, "NarrowPadding", bUseTransitions);
}
else
{
VisualStateManager.GoToState(this, "DefaultPadding", bUseTransitions);
}
}
// MenuFlyoutSubItem's presenter size changed event handler that
// adjust the sub presenter position to the proper space area
// on the available window rect.
void OnPresenterSizeChanged(
object pSender,
SizeChangedEventArgs args)
{
#if MFSI_DEBUG
IGNOREHR(DebugTrace(XCP_TRACE_OUTPUT_MSG /*traceType*/, "MFSI[0x%p]: OnPresenterSizeChanged.", this));
#endif // MFSI_DEBUG
m_menuHelper.OnPresenterSizeChanged(pSender, args, m_tpPopup as Popup);
#if false // UNO TODO
if (m_tpMenuPopupThemeTransition == null)
{
MenuFlyoutPresenter parentMenuFlyoutPresenter;
parentMenuFlyoutPresenter = GetParentMenuFlyoutPresenter();
// Get how many sub menus deep we are. We need this number to know what kind of Z
// offset to use for displaying elevation. The menus aren't parented in the visual
// hierarchy so that has to be applied with an additional transform.
int depth = 1;
if (parentMenuFlyoutPresenter != null)
{
depth = parentMenuFlyoutPresenter.GetDepth() + 1;
}
Transition spMenuPopupChildTransition;
(MenuFlyout.PreparePopupThemeTransitionsAndShadows((Popup*)(m_tpPopup), 0.67 /* closedRatioConstant */, depth, &spMenuPopupChildTransition));
(spMenuPopupChildTransition as MenuPopupThemeTransition.Direction = xaml_primitives.AnimationDirection_Top);
m_tpMenuPopupThemeTransition = spMenuPopupChildTransition;
}
// Update the OpenedLength property of the ThemeTransition.
double openedLength = (m_tpPresenter as Control).ActualHeight;
(m_tpMenuPopupThemeTransition as MenuPopupThemeTransition).OpenedLength = openedLength;
#endif
}
void ClearStateFlags()
{
#if MFSI_DEBUG
IGNOREHR(DebugTrace(XCP_TRACE_OUTPUT_MSG /*traceType*/, "MFSI[0x%p]: ClearStateFlags.", this));
#endif // MFSI_DEBUG
m_menuHelper.ClearStateFlags();
}
void OnIsEnabledChanged(/*IsEnabledChangedEventArgs* args*/)
{
#if MFSI_DEBUG
IGNOREHR(DebugTrace(XCP_TRACE_OUTPUT_MSG /*traceType*/, "MFSI[0x%p]: OnIsEnabledChanged.", this));
#endif // MFSI_DEBUG
m_menuHelper.OnIsEnabledChanged();
}
void OnVisibilityChanged()
{
#if MFSI_DEBUG
IGNOREHR(DebugTrace(XCP_TRACE_OUTPUT_MSG /*traceType*/, "MFSI[0x%p]: OnVisibilityChanged.", this));
#endif // MFSI_DEBUG
m_menuHelper.OnVisibilityChanged();
}
protected override AutomationPeer OnCreateAutomationPeer()
{
//*ppAutomationPeer = null;
//MenuFlyoutSubItemAutomationPeer spAutomationPeer;
//(ActivationAPI.ActivateAutomationInstance(KnownTypeIndex.MenuFlyoutSubItemAutomationPeer, GetHandle(), spAutomationPeer.GetAddressOf()));
//(spAutomationPeer.Owner = this);
//*ppAutomationPeer = spAutomationPeer.Detach();
return null;
}
string GetPlainText()
{
return Text;
}
bool ISubMenuOwner.IsSubMenuOpen => IsOpen;
ISubMenuOwner ISubMenuOwner.ParentOwner
{
get => m_wrParentOwner?.Target as ISubMenuOwner;
set => m_wrParentOwner = new WeakReference(value);
}
bool ISubMenuOwner.IsSubMenuPositionedAbsolutely => true;
void ISubMenuOwner.PrepareSubMenu()
{
#if MFSI_DEBUG
IGNOREHR(DebugTrace(XCP_TRACE_OUTPUT_MSG /*traceType*/, "MFSI[0x%p]: PrepareSubMenu.", this));
#endif // MFSI_DEBUG
EnsurePopupAndPresenter();
global::System.Diagnostics.Debug.Assert(m_tpPopup != null);
global::System.Diagnostics.Debug.Assert(m_tpPresenter != null);
}
void ISubMenuOwner.OpenSubMenu(Point position)
{
#if MFSI_DEBUG
IGNOREHR(DebugTrace(XCP_TRACE_OUTPUT_MSG /*traceType*/, "MFSI[0x%p]: OpenSubMenu.", this));
#endif // MFSI_DEBUG
EnsurePopupAndPresenter();
EnsureCloseExistingSubItems();
MenuFlyoutPresenter parentMenuFlyoutPresenter;
parentMenuFlyoutPresenter = GetParentMenuFlyoutPresenter();
if (parentMenuFlyoutPresenter != null)
{
IMenu owningMenu;
owningMenu = (parentMenuFlyoutPresenter as IMenuPresenter).OwningMenu;
(m_tpPresenter as IMenuPresenter).OwningMenu = owningMenu;
MenuFlyout parentMenuFlyout;
parentMenuFlyout = parentMenuFlyoutPresenter.GetParentMenuFlyout();
if (parentMenuFlyout != null)
{
// Update the TemplateSettings before it is opened.
(m_tpPresenter as MenuFlyoutPresenter).SetParentMenuFlyout(parentMenuFlyout);
(m_tpPresenter as MenuFlyoutPresenter).UpdateTemplateSettings();
// Forward the parent presenter's properties to the sub presenter
ForwardPresenterProperties(
parentMenuFlyout,
parentMenuFlyoutPresenter,
m_tpPresenter as MenuFlyoutPresenter);
}
}
m_tpPopup.HorizontalOffset = position.X;
m_tpPopup.VerticalOffset = position.Y;
SetIsOpen(true);
}
void ISubMenuOwner.PositionSubMenu(Point position)
{
#if MFSI_DEBUG
IGNOREHR(DebugTrace(XCP_TRACE_OUTPUT_MSG /*traceType*/, "MFSI[0x%p]: PositionSubMenu - (%f, %f).", this, position.X, position.Y));
#endif // MFSI_DEBUG
if (position.X != float.NegativeInfinity)
{
m_tpPopup.HorizontalOffset = position.X;
}
if (position.Y != float.NegativeInfinity)
{
m_tpPopup.VerticalOffset = position.Y;
}
}
void ISubMenuOwner.ClosePeerSubMenus()
{
#if MFSI_DEBUG
IGNOREHR(DebugTrace(XCP_TRACE_OUTPUT_MSG /*traceType*/, "MFSI[0x%p]: ClosePeerSubMenus.", this));
#endif // MFSI_DEBUG
EnsureCloseExistingSubItems();
}
void ISubMenuOwner.CloseSubMenu()
{
#if MFSI_DEBUG
IGNOREHR(DebugTrace(XCP_TRACE_OUTPUT_MSG /*traceType*/, "MFSI[0x%p]: CloseSubMenu.", this));
#endif // MFSI_DEBUG
SetIsOpen(false);
}
void ISubMenuOwner.CloseSubMenuTree()
{
#if MFSI_DEBUG
IGNOREHR(DebugTrace(XCP_TRACE_OUTPUT_MSG /*traceType*/, "MFSI[0x%p]: CloseSubMenuTree.", this));
#endif // MFSI_DEBUG
m_menuHelper.CloseChildSubMenus();
}
void ISubMenuOwner.DelayCloseSubMenu()
{
#if MFSI_DEBUG
IGNOREHR(DebugTrace(XCP_TRACE_OUTPUT_MSG /*traceType*/, "MFSI[0x%p]: DelayCloseSubMenu.", this));
#endif // MFSI_DEBUG
m_menuHelper.DelayCloseSubMenu();
}
void ISubMenuOwner.CancelCloseSubMenu()
{
#if MFSI_DEBUG
IGNOREHR(DebugTrace(XCP_TRACE_OUTPUT_MSG /*traceType*/, "MFSI[0x%p]: CancelCloseSubMenu.", this));
#endif // MFSI_DEBUG
m_menuHelper.CancelCloseSubMenu();
}
void ISubMenuOwner.RaiseAutomationPeerExpandCollapse(bool isOpen)
{
// UNO TODO
//AutomationPeer spAutomationPeer;
//bool isListener = false;
//AutomationPeer.ListenerExistsHelper(xaml_automation_peers.AutomationEvents_PropertyChanged, &isListener);
//if (isListener)
//{
// (GetOrCreateAutomationPeer(&spAutomationPeer));
// if (spAutomationPeer)
// {
// (spAutomationPeer as MenuFlyoutSubItemAutomationPeer.RaiseExpandCollapseAutomationEvent(isOpen));
// }
//}
}
}
}
| 28.79638 | 147 | 0.733697 | [
"Apache-2.0"
] | AbdalaMask/uno | src/Uno.UI/UI/Xaml/Controls/MenuFlyout/MenuFlyoutSubItem.cs | 25,456 | C# |
using System;
namespace Peach.Core
{
/// <summary>
/// Linear Shift Feedback Register
/// Produces a pseudo random sequence of numbers from 1 to (2^N)-1
/// </summary>
public class LSFR
{
private uint value;
private int[] taps;
private int degree;
public LSFR(int degree, uint init, int[] taps)
{
if (degree <= 1 || degree > 32)
throw new ArgumentOutOfRangeException("degree");
foreach (int i in taps)
{
if (i > degree)
throw new ArgumentOutOfRangeException("taps");
}
this.degree = degree;
this.value = init;
this.taps = polynomials[degree];
}
public LSFR(int degree, uint init)
{
if (degree <= 1 || degree > 32)
throw new ArgumentOutOfRangeException("degree");
this.degree = degree;
this.value = init;
this.taps = polynomials[degree];
}
public uint Next()
{
// If the degree is 5, and there are taps at 5, 3
// bit = ((value >> 0) ^ (value >> 2)) & 1
// value = (value >> 1) | (bit << 4)
uint bit = value >> (degree - taps[0]);
for (int i = 1; i < taps.Length; ++i)
bit ^= (value >> (degree - taps[i]));
bit &= 1;
value = (value >> 1) | (bit << (degree - 1));
return value;
}
// http://www.xilinx.com/support/documentation/application_notes/xapp052.pdf
private static int[][] polynomials = {
null,
null,
new int[] { 2, 1 },
new int[] { 3, 2 },
new int[] { 4, 3 },
new int[] { 5, 3 },
new int[] { 6, 5 },
new int[] { 7, 6 },
new int[] { 8, 6, 5, 4 },
new int[] { 9, 5 },
new int[] { 10, 7 },
new int[] { 11, 9 },
new int[] { 12, 6, 4, 1 },
new int[] { 13, 4, 3, 1 },
new int[] { 14, 5, 3, 1 },
new int[] { 15, 14 },
new int[] { 16, 15, 13, 4 },
new int[] { 17, 14 },
new int[] { 18, 11 },
new int[] { 19, 6, 2, 1 },
new int[] { 20, 17 },
new int[] { 21, 19 },
new int[] { 22, 21 },
new int[] { 23, 18 },
new int[] { 24, 23, 22, 17 },
new int[] { 25, 22 },
new int[] { 26, 6, 2, 1 },
new int[] { 27, 5, 2, 1 },
new int[] { 28, 25 },
new int[] { 29, 27 },
new int[] { 30, 6, 4, 1 },
new int[] { 31, 28 },
new int[] { 32, 22, 2, 1 },
};
}
/// <summary>
/// Produces a pseudo random sequence of numbers from [1,max]
/// </summary>
public class SequenceGenerator
{
uint index;
uint value;
uint max;
LSFR generator;
public SequenceGenerator(uint max)
{
if (max == 0)
throw new ArgumentOutOfRangeException("max");
this.max = max;
Init();
}
void Init()
{
this.index = 0;
this.value = 0;
if (max > 1)
this.generator = new LSFR(GetDegree(max), max);
}
int GetDegree(uint value)
{
for (int i = 0; i < 32; ++i)
{
if ((value & 0x80000000) != 0)
return (32 - i);
value <<= 1;
}
return 0;
}
public uint Get(uint index)
{
if (index > max)
throw new ArgumentOutOfRangeException("index");
if (index == max)
{
this.index = index;
value = max;
return value;
}
if (index < this.index)
Init();
for (uint i = this.index; i < index; ++i)
{
do
{
value = generator.Next();
}
while (value > max);
if (i == uint.MaxValue)
break;
}
this.index = index;
return value;
}
public uint Value
{
get
{
return value;
}
}
}
}
| 20.302326 | 79 | 0.49685 | [
"MIT"
] | FXTi/peachfuzz-code | Peach.Core/LSFR.cs | 3,492 | C# |
using MicrosoftResearch.Infer;
using MicrosoftResearch.Infer.Distributions;
using MicrosoftResearch.Infer.Factors;
using MicrosoftResearch.Infer.Maths;
using MicrosoftResearch.Infer.Models;
using MicrosoftResearch.Infer.Utils;
using System;
namespace CrowdsourcingModels
{
/// <summary>
/// The CBCC model class.
/// </summary>
public class CBCC : BCC
{
// Additional ranges
/// <summary>
/// The community range.
/// </summary>
protected Range m;
// Additional variables
/// <summary>
///
/// </summary>
protected VariableArray<int> Community;
/// <summary>
///
/// </summary>
protected VariableArray<Discrete> CommunityInit;
/// <summary>
///
/// </summary>
protected Variable<Vector> CommunityProb;
/// <summary>
///
/// </summary>
protected VariableArray<VariableArray<Vector>, Vector[][]> ScoreMatrix;
/// <summary>
///
/// </summary>
protected VariableArray<VariableArray<Vector>, Vector[][]> CommunityScoreMatrix;
/// <summary>
///
/// </summary>
protected VariableArray<VariableArray<Vector>, Vector[][]> CommunityConfusionMatrix;
/// <summary>
///
/// </summary>
protected Variable<PositiveDefiniteMatrix> NoiseMatrix = Variable.New<PositiveDefiniteMatrix>().Named("NoiseMatrix");
// Additional priors
/// <summary>
///
/// </summary>
protected VariableArray<Discrete> CommunityConstraint;
/// <summary>
///
/// </summary>
protected VariableArray<VariableArray<VectorGaussian>, VectorGaussian[][]> ScoreMatrixConstraint;
/// <summary>
///
/// </summary>
protected VariableArray<VariableArray<VectorGaussian>, VectorGaussian[][]> CommunityScoreMatrixPrior;
/// <summary>
///
/// </summary>
protected Variable<Dirichlet> CommunityProbPrior;
/// <summary>
/// The noise precision that generates the workers score matrix from the communities score matrix.
/// </summary>
public double NoisePrecision
{
get;
set;
}
/// <summary>
/// The number of communities.
/// </summary>
public int CommunityCount
{
get;
protected set;
}
/// <summary>
/// Set the number of communities.
/// </summary>
/// <param name="CommunityCount"></param>
public void SetCommunityCount(int CommunityCount)
{
this.CommunityCount = CommunityCount;
}
/// <summary>
/// The mean vector of the Gaussian distribution generating the community score matrices.
/// </summary>
public Tuple<double, double>[] ScoreMeanParameters
{
get;
set;
}
/// <summary>
/// The precision matrix of the Gaussian distribution generating the community score matrices.
/// </summary>
public double[] ScorePrecisionParameters
{
get;
set;
}
/// <summary>
/// The hyperparameter governing community membership.
/// </summary>
public double CommunityPseudoCount
{
get;
set;
}
/// <summary>
/// The prior for the score matrices.
/// </summary>
public VectorGaussian[][] CommunityScoreMatrixPriorObserved
{
get;
protected set;
}
/// <summary>
/// The prior for community membership.
/// </summary>
public Dirichlet CommunityProbPriorObserved
{
get;
protected set;
}
/// <summary>
/// Creates a CBCC model instance.
/// </summary>
public CBCC()
: base()
{
NoisePrecision = 5;
CommunityCount = 3;
CommunityPseudoCount = 10.0;
ScoreMeanParameters = null;
ScorePrecisionParameters = null;
}
/// <summary>
/// Initializes the CBCC model.
/// </summary>
/// <param name="taskCount">The number of tasks.</param>
/// <param name="labelCount">The number of labels.</param>
public override void CreateModel(int taskCount, int labelCount)
{
CreateModel(taskCount, labelCount, CommunityCount);
}
/// <summary>
/// Initializes the CBCC model with a number of communities.
/// </summary>
/// <param name="taskCount">The number of tasks.</param>
/// <param name="labelCount">The number of labels.</param>
/// <param name="communityCount">The number of communities.</param>
public virtual void CreateModel(int taskCount, int labelCount, int communityCount)
{
Evidence = Variable<bool>.Random(this.EvidencePrior);
var evidenceBlock = Variable.If(Evidence);
CommunityCount = communityCount;
CommunityProbPriorObserved = Dirichlet.Symmetric(communityCount, CommunityPseudoCount);
DefineVariablesAndRanges(taskCount, labelCount);
DefineGenerativeProcess();
DefineInferenceEngine();
evidenceBlock.CloseBlock();
if (ScoreMeanParameters == null)
{
var scoreMatrixPrior = GetScoreMatrixPrior();
CommunityScoreMatrixPriorObserved = Util.ArrayInit(CommunityCount, comm => Util.ArrayInit(labelCount, lab => new VectorGaussian(scoreMatrixPrior[lab])));
}
else
{
CommunityScoreMatrixPriorObserved = Util.ArrayInit(
CommunityCount,
comm => Util.ArrayInit(
labelCount, lab => VectorGaussian.FromMeanAndPrecision(
Vector.FromArray(
Util.ArrayInit(labelCount, lab1 => lab == lab1 ? ScoreMeanParameters[comm].Item1 : ScoreMeanParameters[comm].Item2)),
PositiveDefiniteMatrix.IdentityScaledBy(LabelCount, ScorePrecisionParameters[comm]))));
}
}
/// <summary>
/// Defines the variables and the ranges of CBCC.
/// </summary>
/// <param name="taskCount">The number of tasks.</param>
/// <param name="labelCount">The number of labels.</param>
protected override void DefineVariablesAndRanges(int taskCount, int labelCount)
{
WorkerCount = Variable.New<int>().Named("WorkerCount");
m = new Range(CommunityCount).Named("m");
n = new Range(taskCount).Named("n");
c = new Range(labelCount).Named("c");
k = new Range(WorkerCount).Named("k");
// The tasks for each worker
WorkerTaskCount = Variable.Array<int>(k).Named("WorkerTaskCount");
kn = new Range(WorkerTaskCount[k]).Named("kn");
WorkerTaskIndex = Variable.Array(Variable.Array<int>(kn), k).Named("WorkerTaskIndex");
WorkerTaskIndex.SetValueRange(n);
WorkerLabel = Variable.Array(Variable.Array<int>(kn), k).Named("WorkerLabel");
// The background probability vector
BackgroundLabelProbPrior = Variable.New<Dirichlet>().Named("BackgroundLabelProbPrior");
BackgroundLabelProb = Variable<Vector>.Random(BackgroundLabelProbPrior).Named("BackgroundLabelProb");
BackgroundLabelProb.SetValueRange(c);
// Community membership
CommunityProbPrior = Variable.New<Dirichlet>().Named("CommunityProbPrior");
CommunityProb = Variable<Vector>.Random(CommunityProbPrior).Named("CommunityProb");
CommunityProb.SetValueRange(m);
Community = Variable.Array<int>(k).Attrib(QueryTypes.Marginal).Attrib(QueryTypes.MarginalDividedByPrior).Named("Community");
CommunityConstraint = Variable.Array<Discrete>(k).Named("CommunityConstraint");
Community[k] = Variable.Discrete(CommunityProb).ForEach(k);
Variable.ConstrainEqualRandom(Community[k], CommunityConstraint[k]);
// Initialiser to break symmetry for community membership
CommunityInit = Variable.Array<Discrete>(k).Named("CommunityInit");
Community[k].InitialiseTo(CommunityInit[k]);
// Community parameters
CommunityScoreMatrixPrior = Variable.Array(Variable.Array<VectorGaussian>(c), m).Named("CommunityScoreMatrixPrior");
CommunityScoreMatrix = Variable.Array(Variable.Array<Vector>(c), m).Named("CommunityScoreMatrix");
CommunityScoreMatrix[m][c] = Variable<Vector>.Random(CommunityScoreMatrixPrior[m][c]);
CommunityConfusionMatrix = Variable.Array(Variable.Array<Vector>(c), m).Named("CommunityConfusionMatrix");
CommunityConfusionMatrix[m][c] = Variable.Softmax(CommunityScoreMatrix[m][c]);
CommunityScoreMatrix.SetValueRange(c);
// Parameters for each worker
ScoreMatrix = Variable.Array(Variable.Array<Vector>(c), k).Attrib(QueryTypes.Marginal).Attrib(QueryTypes.MarginalDividedByPrior).Named("ScoreMatrix");
ScoreMatrixConstraint = Variable.Array(Variable.Array<VectorGaussian>(c), k).Named("ScoreMatrixConstraint");
WorkerConfusionMatrix = Variable.Array(Variable.Array<Vector>(c), k).Named("ConfusionMatrix");
// The unobserved 'true' label for each task
TrueLabel = Variable.Array<int>(n).Attrib(QueryTypes.Marginal).Attrib(QueryTypes.MarginalDividedByPrior).Named("Truth");
TrueLabelConstraint = Variable.Array<Discrete>(n).Named("TruthConstraint");
TrueLabel[n] = Variable.Discrete(BackgroundLabelProb).ForEach(n);
Variable.ConstrainEqualRandom(TrueLabel[n], TrueLabelConstraint[n]);
// The labels given by the workers
WorkerLabel = Variable.Array(Variable.Array<int>(kn), k).Named("WorkerLabel");
}
/// <summary>
/// Defines the generative process of CBCC.
/// </summary>
protected override void DefineGenerativeProcess()
{
// The process that generates the worker's label
using (Variable.ForEach(k))
{
using (Variable.Switch(Community[k]))
{
ScoreMatrix[k][c] = Variable.VectorGaussianFromMeanAndPrecision(CommunityScoreMatrix[Community[k]][c], NoiseMatrix);
}
Variable.ConstrainEqualRandom(ScoreMatrix[k][c], ScoreMatrixConstraint[k][c]);
WorkerConfusionMatrix[k][c] = Variable.Softmax(ScoreMatrix[k][c]);
var trueLabel = Variable.Subarray(TrueLabel, WorkerTaskIndex[k]);
trueLabel.SetValueRange(c);
using (Variable.ForEach(kn))
{
using (Variable.Switch(trueLabel[kn]))
{
WorkerLabel[k][kn] = Variable.Discrete(WorkerConfusionMatrix[k][trueLabel[kn]]);
}
}
}
}
/// <summary>
/// Initializes the CBCC inference engine.
/// </summary>
protected override void DefineInferenceEngine()
{
Engine = new InferenceEngine(new VariationalMessagePassing());
Engine.ShowProgress = false;
Engine.Compiler.UseParallelForLoops = true;
Engine.Compiler.GivePriorityTo(typeof(SoftmaxOp_BL06));
Engine.Compiler.WriteSourceFiles = false;
}
/// <summary>
/// Attachs the data to the workers labels.
/// </summary>
/// <param name="taskIndices">The matrix of the task indices (columns) of each worker (rows).</param>
/// <param name="workerLabels">The matrix of the labels (columns) of each worker (rows).</param>
protected override void AttachData(int[][] taskIndices, int[][] workerLabels)
{
AttachData(taskIndices, workerLabels, null, null);
}
/// <summary>
/// Attachs the data to the workers labels and sets the constraints on the community score matrices and
/// the community memberships (used for online training).
/// </summary>
/// <param name="taskIndices">The matrix of the task indices (columns) of each worker (rows).</param>
/// <param name="workerLabels">The matrix of the labels (columns) of each worker (rows).</param>
/// <param name="scoreConstraint">The constraint of the community score matrices.</param>
/// <param name="communityConstraint">The constraint of the workers community membership.</param>
protected void AttachData(int[][] taskIndices, int[][] workerLabels, VectorGaussian[][] scoreConstraint, Discrete[] communityConstraint)
{
int communityCount = m.SizeAsInt;
int workerCount = workerLabels.Length;
int labelCount = c.SizeAsInt;
base.AttachData(taskIndices, workerLabels);
CommunityInit.ObservedValue = Util.ArrayInit(workerCount, worker => Discrete.PointMass(Rand.Int(communityCount), communityCount));
if (scoreConstraint != null)
{
ScoreMatrixConstraint.ObservedValue = scoreConstraint;
}
else
{
ScoreMatrixConstraint.ObservedValue = Util.ArrayInit(workerCount, w => Util.ArrayInit(labelCount, lab => VectorGaussian.Uniform(labelCount)));
}
if (communityConstraint != null)
{
CommunityConstraint.ObservedValue = communityConstraint;
}
else
{
CommunityConstraint.ObservedValue = Util.ArrayInit(workerCount, w => Discrete.Uniform(communityCount));
}
}
/// <summary>
/// Sets the priors of CBCC.
/// </summary>
/// <param name="workerCount">The number of workers.</param>
/// <param name="priors">The priors.</param>
protected override void SetPriors(int workerCount, BCCPosteriors priors)
{
int communityCount = m.SizeAsInt;
int labelCount = c.SizeAsInt;
WorkerCount.ObservedValue = workerCount;
NoiseMatrix.ObservedValue = PositiveDefiniteMatrix.IdentityScaledBy(labelCount, NoisePrecision);
CBCCPosteriors cbccPriors = (CBCCPosteriors)priors;
if (cbccPriors == null || cbccPriors.BackgroundLabelProb == null)
BackgroundLabelProbPrior.ObservedValue = Dirichlet.Uniform(labelCount);
else
BackgroundLabelProbPrior.ObservedValue = cbccPriors.BackgroundLabelProb;
if (cbccPriors == null || cbccPriors.CommunityProb == null)
CommunityProbPrior.ObservedValue = CommunityProbPriorObserved;
else
CommunityProbPrior.ObservedValue = cbccPriors.CommunityProb;
if (cbccPriors == null || cbccPriors.CommunityScoreMatrix == null)
CommunityScoreMatrixPrior.ObservedValue = CommunityScoreMatrixPriorObserved;
else
CommunityScoreMatrixPrior.ObservedValue = cbccPriors.CommunityScoreMatrix;
if (cbccPriors == null || cbccPriors.TrueLabelConstraint == null)
TrueLabelConstraint.ObservedValue = Util.ArrayInit(TaskCount, t => Discrete.Uniform(labelCount));
else
TrueLabelConstraint.ObservedValue = cbccPriors.TrueLabelConstraint;
}
/// <summary>
/// Infers the posteriors of CBCC using the attached data.
/// </summary>
/// <param name="taskIndices">The matrix of the task indices (columns) of each worker (rows).</param>
/// <param name="workerLabels">The matrix of the labels (columns) of each worker (rows).</param>
/// <param name="priors">The priors.</param>
/// <returns></returns>
public override BCCPosteriors Infer(int[][] taskIndices, int[][] workerLabels, BCCPosteriors priors)
{
var cbccPriors = (CBCCPosteriors)priors;
VectorGaussian[][] scoreConstraint = (cbccPriors == null ? null : cbccPriors.WorkerScoreMatrixConstraint);
Discrete[] communityConstraint = (cbccPriors == null ? null : cbccPriors.WorkerCommunityConstraint);
SetPriors(workerLabels.Length, priors);
AttachData(taskIndices, workerLabels, scoreConstraint, communityConstraint);
var result = new CBCCPosteriors();
Engine.NumberOfIterations = NumberOfIterations;
result.Evidence = Engine.Infer<Bernoulli>(Evidence);
result.BackgroundLabelProb = Engine.Infer<Dirichlet>(BackgroundLabelProb);
result.WorkerConfusionMatrix = Engine.Infer<Dirichlet[][]>(WorkerConfusionMatrix);
result.TrueLabel = Engine.Infer<Discrete[]>(TrueLabel);
result.TrueLabelConstraint = Engine.Infer<Discrete[]>(TrueLabel, QueryTypes.MarginalDividedByPrior);
result.CommunityScoreMatrix = Engine.Infer<VectorGaussian[][]>(CommunityScoreMatrix);
result.CommunityConfusionMatrix = Engine.Infer<Dirichlet[][]>(CommunityConfusionMatrix);
result.WorkerScoreMatrixConstraint = Engine.Infer<VectorGaussian[][]>(ScoreMatrix, QueryTypes.MarginalDividedByPrior);
result.CommunityProb = Engine.Infer<Dirichlet>(CommunityProb);
result.Community = Engine.Infer<Discrete[]>(Community);
result.WorkerCommunityConstraint = Engine.Infer<Discrete[]>(Community, QueryTypes.MarginalDividedByPrior);
return result;
}
/// <summary>
/// Returns the community score matrix prior.
/// </summary>
/// <returns>The community score matrix prior.</returns>
private VectorGaussian[] GetScoreMatrixPrior()
{
var dim = new Range(LabelCount);
var mean = Variable.VectorGaussianFromMeanAndPrecision(Vector.Zero(LabelCount), PositiveDefiniteMatrix.IdentityScaledBy(LabelCount, 1));
var prec = Variable.WishartFromShapeAndRate(1.0, PositiveDefiniteMatrix.IdentityScaledBy(LabelCount, 1));
var score = Variable.VectorGaussianFromMeanAndPrecision(mean, prec);
var confusion = Variable.Softmax(score);
confusion.SetValueRange(dim);
var confusionConstraint = Variable.New<Dirichlet>();
Variable.ConstrainEqualRandom(confusion, confusionConstraint);
var engine = new InferenceEngine(new VariationalMessagePassing())
{
ShowProgress = false
};
engine.Compiler.WriteSourceFiles = false;
var scorePrior = new VectorGaussian[LabelCount];
for (int d = 0; d < LabelCount; d++)
{
confusionConstraint.ObservedValue = new Dirichlet(Util.ArrayInit(LabelCount, i => i == d ? (InitialWorkerBelief / (1 - InitialWorkerBelief)) * (LabelCount - 1) : 1.0));
scorePrior[d] = engine.Infer<VectorGaussian>(score);
}
return scorePrior;
}
}
/// <summary>
/// CBCC posterior object.
/// </summary>
[Serializable]
public class CBCCPosteriors : BCCPosteriors
{
/// <summary>
/// The Dirichlet posteriors of the workers community membership.
/// </summary>
public Dirichlet CommunityProb;
/// <summary>
/// The posterior probabilities of the workers community membnerships.
/// </summary>
public Discrete[] Community;
/// <summary>
/// The Dirichlet posteriors of the community confusion matrix.
/// </summary>
public Dirichlet[][] CommunityConfusionMatrix;
/// <summary>
/// The Gaussian posteriors of the community score matrix.
/// </summary>
public VectorGaussian[][] CommunityScoreMatrix;
/// <summary>
/// The Gaussian constraint of the community score matrix (used for online training).
/// </summary>
public VectorGaussian[][] WorkerScoreMatrixConstraint;
/// <summary>
/// Theconstraint of the workers community membership (used for online training).
/// </summary>
public Discrete[] WorkerCommunityConstraint;
}
}
| 42.50924 | 184 | 0.607526 | [
"Apache-2.0"
] | orchidproject/active-crowd-toolkit | CrowdsourcingModels/CBCC.cs | 20,704 | C# |
using Codeuctivity.OpenXmlPowerTools;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Validation;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using Xunit;
namespace Codeuctivity.Tests
{
public class FaTests
{
[Theory]
[InlineData("FA001-00010", "FA/RevTracking/001-DeletedRun.docx")]
[InlineData("FA001-00020", "FA/RevTracking/002-DeletedNumberedParagraphs.docx")]
[InlineData("FA001-00030", "FA/RevTracking/003-DeletedFieldCode.docx")]
[InlineData("FA001-00040", "FA/RevTracking/004-InsertedNumberingProperties.docx")]
[InlineData("FA001-00050", "FA/RevTracking/005-InsertedNumberedParagraph.docx")]
[InlineData("FA001-00060", "FA/RevTracking/006-DeletedTableRow.docx")]
[InlineData("FA001-00070", "FA/RevTracking/007-InsertedTableRow.docx")]
[InlineData("FA001-00080", "FA/RevTracking/008-InsertedFieldCode.docx")]
[InlineData("FA001-00090", "FA/RevTracking/009-InsertedParagraph.docx")]
[InlineData("FA001-00100", "FA/RevTracking/010-InsertedRun.docx")]
[InlineData("FA001-00110", "FA/RevTracking/011-InsertedMathChar.docx")]
[InlineData("FA001-00120", "FA/RevTracking/012-DeletedMathChar.docx")]
[InlineData("FA001-00130", "FA/RevTracking/013-DeletedParagraph.docx")]
[InlineData("FA001-00140", "FA/RevTracking/014-MovedParagraph.docx")]
[InlineData("FA001-00150", "FA/RevTracking/015-InsertedContentControl.docx")]
[InlineData("FA001-00160", "FA/RevTracking/016-DeletedContentControl.docx")]
[InlineData("FA001-00170", "FA/RevTracking/017-NumberingChange.docx")]
[InlineData("FA001-00180", "FA/RevTracking/018-ParagraphPropertiesChange.docx")]
[InlineData("FA001-00190", "FA/RevTracking/019-RunPropertiesChange.docx")]
[InlineData("FA001-00200", "FA/RevTracking/020-SectionPropertiesChange.docx")]
[InlineData("FA001-00210", "FA/RevTracking/021-TableGridChange.docx")]
[InlineData("FA001-00220", "FA/RevTracking/022-TablePropertiesChange.docx")]
[InlineData("FA001-00230", "FA/RevTracking/023-CellPropertiesChange.docx")]
[InlineData("FA001-00240", "FA/RevTracking/024-RowPropertiesChange.docx")]
public void FA001_DocumentsWithRevTracking(string testId, string src)
{
// Load the source document
var sourceDir = new DirectoryInfo("../../../../TestFiles/");
var sourceDocxFi = new FileInfo(Path.Combine(sourceDir.FullName, src));
var wmlSourceDocument = new WmlDocument(sourceDocxFi.FullName);
// Create the dir for the test
var rootTempDir = TestUtil.TempDir;
var thisTestTempDir = new DirectoryInfo(Path.Combine(rootTempDir.FullName, testId));
if (thisTestTempDir.Exists)
{
Assert.True(false, "Duplicate test id: " + testId);
}
else
{
thisTestTempDir.Create();
}
var tempDirFullName = thisTestTempDir.FullName;
// Copy src DOCX to temp directory, for ease of review
var sourceDocxCopiedToDestFileName = new FileInfo(Path.Combine(tempDirFullName, sourceDocxFi.Name));
if (!sourceDocxCopiedToDestFileName.Exists)
{
wmlSourceDocument.SaveAs(sourceDocxCopiedToDestFileName.FullName);
}
var sourceDocxAcceptedCopiedToDestFileName = new FileInfo(Path.Combine(tempDirFullName, sourceDocxFi.Name.ToLower().Replace(".docx", "-accepted.docx")));
var wmlSourceAccepted = RevisionProcessor.AcceptRevisions(wmlSourceDocument);
wmlSourceAccepted.SaveAs(sourceDocxAcceptedCopiedToDestFileName.FullName);
var outFi = new FileInfo(Path.Combine(tempDirFullName, "Output.docx"));
var settings = new FormattingAssemblerSettings();
var assembledWml = FormattingAssembler.AssembleFormatting(wmlSourceDocument, settings);
assembledWml.SaveAs(outFi.FullName);
var outAcceptedFi = new FileInfo(Path.Combine(tempDirFullName, "Output-accepted.docx"));
var assembledAcceptedWml = RevisionProcessor.AcceptRevisions(assembledWml);
assembledAcceptedWml.SaveAs(outAcceptedFi.FullName);
Validate(outFi);
}
private void Validate(FileInfo fi)
{
using var wDoc = WordprocessingDocument.Open(fi.FullName, true);
var v = new OpenXmlValidator();
var errors = v.Validate(wDoc).Where(ve =>
{
var found = s_ExpectedErrors.Any(xe => ve.Description.Contains(xe));
return !found;
});
if (errors.Any())
{
var sb = new StringBuilder();
foreach (var item in errors)
{
sb.Append(item.Description).Append(Environment.NewLine);
}
var s = sb.ToString();
Assert.True(false, s);
}
}
private static readonly List<string> s_ExpectedErrors = new List<string>()
{
"The 'http://schemas.openxmlformats.org/wordprocessingml/2006/main:evenHBand' attribute is not declared.",
"The 'http://schemas.openxmlformats.org/wordprocessingml/2006/main:evenVBand' attribute is not declared.",
"The 'http://schemas.openxmlformats.org/wordprocessingml/2006/main:firstColumn' attribute is not declared.",
"The 'http://schemas.openxmlformats.org/wordprocessingml/2006/main:firstRow' attribute is not declared.",
"The 'http://schemas.openxmlformats.org/wordprocessingml/2006/main:firstRowFirstColumn' attribute is not declared.",
"The 'http://schemas.openxmlformats.org/wordprocessingml/2006/main:firstRowLastColumn' attribute is not declared.",
"The 'http://schemas.openxmlformats.org/wordprocessingml/2006/main:lastColumn' attribute is not declared.",
"The 'http://schemas.openxmlformats.org/wordprocessingml/2006/main:lastRow' attribute is not declared.",
"The 'http://schemas.openxmlformats.org/wordprocessingml/2006/main:lastRowFirstColumn' attribute is not declared.",
"The 'http://schemas.openxmlformats.org/wordprocessingml/2006/main:lastRowLastColumn' attribute is not declared.",
"The 'http://schemas.openxmlformats.org/wordprocessingml/2006/main:noHBand' attribute is not declared.",
"The 'http://schemas.openxmlformats.org/wordprocessingml/2006/main:noVBand' attribute is not declared.",
"The 'http://schemas.openxmlformats.org/wordprocessingml/2006/main:oddHBand' attribute is not declared.",
"The 'http://schemas.openxmlformats.org/wordprocessingml/2006/main:oddVBand' attribute is not declared.",
"The element has unexpected child element 'http://schemas.openxmlformats.org/wordprocessingml/2006/main:updateFields'.",
"The attribute 'http://schemas.openxmlformats.org/wordprocessingml/2006/main:name' has invalid value 'useWord2013TrackBottomHyphenation'. The Enumeration constraint failed.",
"The 'http://schemas.microsoft.com/office/word/2012/wordml:restartNumberingAfterBreak' attribute is not declared.",
"Attribute 'id' should have unique value. Its current value '",
"The 'urn:schemas-microsoft-com:mac:vml:blur' attribute is not declared.",
"Attribute 'http://schemas.openxmlformats.org/wordprocessingml/2006/main:id' should have unique value. Its current value '",
"The element has unexpected child element 'http://schemas.microsoft.com/office/word/2012/wordml:",
"The element has invalid child element 'http://schemas.microsoft.com/office/word/2012/wordml:",
"The 'urn:schemas-microsoft-com:mac:vml:complextextbox' attribute is not declared.",
"http://schemas.microsoft.com/office/word/2010/wordml:",
"http://schemas.microsoft.com/office/word/2008/9/12/wordml:",
"The 'http://schemas.openxmlformats.org/wordprocessingml/2006/main:allStyles' attribute is not declared.",
"The 'http://schemas.openxmlformats.org/wordprocessingml/2006/main:customStyles' attribute is not declared.",
"The element has invalid child element 'http://schemas.openxmlformats.org/wordprocessingml/2006/main:ins'.",
"The element has invalid child element 'http://schemas.openxmlformats.org/wordprocessingml/2006/main:del'.",
};
}
} | 61.671429 | 186 | 0.675817 | [
"MIT"
] | stesee/Open-Xml-PowerTools | OpenXmlPowerTools.Tests/FormattingAssemblerTests.cs | 8,636 | C# |
using System.Collections.Generic;
using System.Linq;
namespace WarOfEmpires.Commands.Empires {
public sealed class BuildSiegeCommand : ICommand {
public string Email { get; }
public List<SiegeWeaponInfo> SiegeWeapons { get; }
public BuildSiegeCommand(string email, IEnumerable<SiegeWeaponInfo> details) {
Email = email;
SiegeWeapons = details.ToList();
}
}
} | 30.357143 | 86 | 0.668235 | [
"MIT"
] | maikelbos0/WarOfEmpires | WarOfEmpires.Commands/Empires/BuildSiegeCommand.cs | 427 | C# |
// Copyright (c) Cratis. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
namespace Cratis.Types.for_ImplementationsOf
{
public interface IAmAnInterface
{
}
}
| 24.7 | 101 | 0.744939 | [
"MIT"
] | Cratis/cratis | Specifications/Fundamentals/Types/for_ImplementationsOf/IAmAnInterface.cs | 249 | C# |
using System;
using System.IO;
using System.Windows.Forms;
using Common;
using DAL;
using Models;
using SolidWorks.Interop.sldworks;
using SolidWorks.Interop.swconst;
namespace SolidWorksHelper
{
public class CMODF555400AutoDrawing : IAutoDrawing
{
readonly CMODF555400Service objCMODF555400Service = new CMODF555400Service();
public void AutoDrawing(SldWorks swApp, ModuleTree tree, string projectPath)
{
//创建项目模型存放地址
string itemPath = $@"{projectPath}\{tree.Item}-{tree.Module}-{tree.CategoryName}";
if (!CommonFunc.CreateProjectPath(itemPath)) return;
//Pack的后缀
string suffix = $@"{tree.Item}-{tree.Module}-{tree.ODPNo.Substring(tree.ODPNo.Length - 6)}";
//判断文件是否存在,如果存在将不执行pack,如果不存在则执行pack
//packango后需要接收打包完成的地址,参数为后缀
string packedAssyPath = $@"{itemPath}\{tree.CategoryName.ToLower()}_{suffix}.sldasm";
if (!File.Exists(packedAssyPath)) packedAssyPath = CommonFunc.PackAndGoFunc(suffix, swApp, tree.ModelPath, itemPath);
//查询参数
CMODF555400 item = (CMODF555400)objCMODF555400Service.GetModelByModuleTreeId(tree.ModuleTreeId.ToString());
swApp.CommandInProgress = true; //告诉SolidWorks,现在是用外部程序调用命令
int warnings = 0;
int errors = 0;
suffix = "_" + suffix;//后缀
ModelDoc2 swModel = default(ModelDoc2);
ModelDoc2 swPart = default(ModelDoc2);
AssemblyDoc swAssy = default(AssemblyDoc);
Component2 swComp;
Feature swFeat = default(Feature);
object configNames = null;
EditPart swEdit = new EditPart();
//打开Pack后的模型
swModel = swApp.OpenDoc6(packedAssyPath, (int)swDocumentTypes_e.swDocASSEMBLY,
(int)swOpenDocOptions_e.swOpenDocOptions_Silent, "", ref errors, ref warnings) as ModelDoc2;
swAssy = swModel as AssemblyDoc;//装配体
//打开装配体后必须重建,使Pack后的零件名都更新到带后缀的状态,否则程序出错
swModel.ForceRebuild3(true);//TopOnly参数设置成true,只重建顶层,不重建零件内部
/*注意SolidWorks单位是m,计算是应当/1000m
* 整形与整形运算得出的结果仍然时整形,1640 / 1000m结果为0,因此必须将其中一个转化成decimal型,使用后缀m就可以了
* (int)不进行四舍五入,Convert.ToInt32会四舍五入
*/
//-----------计算中间值,----------
//新风面板卡扣数量及间距
int frontPanelKaKouNo = (int)((item.Length - 300m) / 450m) + 2;
decimal frontPanelKaKouDis = Convert.ToDecimal((item.Length - 300m) / (frontPanelKaKouNo - 1)) / 1000m;
//新风面板螺丝孔数量及间距
int frontPanelHoleNo = (int)((item.Length - 300m) / 900m) + 2;
decimal frontPanelHoleDis = Convert.ToDecimal((item.Length - 300) / (frontPanelHoleNo - 1)) / 1000m;
//新风CJ孔数量和新风CJ孔第一个CJ距离边缘距离
int frontCjNo = (int)((item.Length - 30m) / 32m) + 1;
decimal frontCjFirstDis = Convert.ToDecimal((item.Length - (frontCjNo - 1) * 32m) / 2) / 1000m;
//Midroof灯板螺丝孔数量及第二个孔距离边缘距离,灯板顶面吊装槽钢螺丝孔位距离
int midRoofHoleNo = (int)((item.Length - 300m) / 400m);
decimal midRoofSecondHoleDis = Convert.ToDecimal((item.Length - (midRoofHoleNo - 1) * 400m) / 2) / 1000m;
decimal midRoofTopHoleDis =
Convert.ToDecimal(item.Deepth - 535m - 360m - 90m -
(int)((item.Deepth - 535m - 360m - 90m - 100m) / 50m) * 50m) / 1000m;
//KSA数量,KSA侧板长度(以全长计算)水洗烟罩KSA在三角板内侧,减去3mm
int ksaNo = (int)((item.Length - 2m) / 498m);
decimal ksaSideLength = Convert.ToDecimal((item.Length - 3m - ksaNo * 498m) / 2) / 1000m;
//MESH侧板长度(除去排风三角板3mm计算)
decimal meshSideLength = Convert.ToDecimal((item.Length - 3m - (int)((item.Length - 2m) / 498m) * 498m) / 2) / 1000m;
//侧板CJ孔整列到烟罩底部
//int sidePanelDownCjNo = (int)((item.Deepth - 95m) / 32m);
//非水洗烟罩KV/UV
//int sidePanelSideCjNo = (int)((item.Deepth - 305m) / 32m);
//水洗烟罩KW/UW
//int sidePanelSideCjNo = (int)((item.Deepth - 380m) / 32m);
//CMOD555400斜侧板CJ孔计算,175为CMOD底部长度,555-400为高度差
int sidePanelDownCjNo = (int)(((decimal)(Math.Sqrt(Math.Pow((double)item.Deepth-175d,2)+ Math.Pow(555d-400d,2))) - 95m) / 32m);
int sidePanelSideCjNo = sidePanelDownCjNo-3;
try
{
//----------Top Level----------
//烟罩深度
swModel.Parameter("D1@Distance80").SystemValue = item.Deepth / 1000m;
//灯板加强筋
if (item.Deepth > 1649m && ((item.LightType == "FSLONG" && item.Length > 1900m) ||
(item.LightType == "FSSHORT" && item.Length > 1500m) || (item.Length > 2000m)))
{
swComp = swAssy.GetComponentByName(CommonFunc.AddSuffix(suffix, "FNHM0006-3"));
swComp.SetSuppression2(2); //2解压缩,0压缩
swComp = swAssy.GetComponentByName(CommonFunc.AddSuffix(suffix, "FNHM0006-2"));
swComp.SetSuppression2(2); //2解压缩,0压缩
swPart = swComp.GetModelDoc2();//打开零件
swPart.Parameter("D2@Base-Flange1").SystemValue = item.Deepth / 1000m - 898m / 1000m;
}
else
{
swComp = swAssy.GetComponentByName(CommonFunc.AddSuffix(suffix, "FNHM0006-3"));
swComp.SetSuppression2(0); //2解压缩,0压缩
swComp = swAssy.GetComponentByName(CommonFunc.AddSuffix(suffix, "FNHM0006-2"));
swComp.SetSuppression2(0); //2解压缩,0压缩
}
//----------新风脖颈----------
swFeat = swAssy.FeatureByName("LocalLPattern3");
if (item.SuNo == 1) swFeat.SetSuppression2(0, 2, configNames); //参数1:1解压,0压缩
else
{
swFeat.SetSuppression2(1, 2, configNames); //参数1:1解压,0压缩
swModel.Parameter("D1@LocalLPattern3").SystemValue = item.SuNo; //D1阵列数量,D3阵列距离
swModel.Parameter("D3@LocalLPattern3").SystemValue = item.SuDis / 1000m; //D1阵列数量,D3阵列距离
}
//----------新风前面板中间加强筋----------
swComp = swAssy.GetComponentByName(CommonFunc.AddSuffix(suffix, "FNHA0030-1"));
if (item.Length > 1599m) swComp.SetSuppression2(2); //2解压缩,0压缩
else swComp.SetSuppression2(0); //2解压缩,0压缩
//----------排风腔----------
swComp = swAssy.GetComponentByName(CommonFunc.AddSuffix(suffix, "FNHE0070-1"));
swPart = swComp.GetModelDoc2();//打开零件3
swPart.Parameter("D2@Base-Flange1").SystemValue = item.Length / 1000m;
swPart.Parameter("D2@Sketch9").SystemValue = midRoofSecondHoleDis;
if (midRoofHoleNo == 1)
{
swFeat = swComp.FeatureByName("LPattern1");
swFeat.SetSuppression2(0, 2, configNames); //参数1:1解压,0压缩
}
else
{
swFeat = swComp.FeatureByName("LPattern1");
swFeat.SetSuppression2(1, 2, configNames); //参数1:1解压,0压缩
swPart.Parameter("D1@LPattern1").SystemValue = midRoofHoleNo;
}
//排风口
//if (item.ExNo == 1)
//{
swFeat = swComp.FeatureByName("EXCOONE");
swFeat.SetSuppression2(1, 2, configNames);
//swFeat = swComp.FeatureByName("EXCOTWO");
//swFeat.SetSuppression2(0, 2, configNames); //参数1:1解压,0压缩
//swPart.Parameter("D4@Sketch11").SystemValue = item.ExRightDis / 1000m;
swPart.Parameter("D2@Sketch4").SystemValue = item.ExLength / 1000m;
swPart.Parameter("D3@Sketch4").SystemValue = item.ExWidth / 1000m;
//}
//else
//{
// swFeat = swComp.FeatureByName("EXCOONE");
// swFeat.SetSuppression2(0, 2, configNames); //参数1:1解压,0压缩
// swFeat = swComp.FeatureByName("EXCOTWO");
// swFeat.SetSuppression2(1, 2, configNames); //参数1:1解压,0压缩
// swPart.Parameter("D5@Sketch12").SystemValue = item.ExRightDis / 1000m;
// swPart.Parameter("D4@Sketch12").SystemValue = item.ExDis / 1000m;
// swPart.Parameter("D1@Sketch12").SystemValue = item.ExLength / 1000m;
// swPart.Parameter("D2@Sketch12").SystemValue = item.ExWidth / 1000m;
//}
//下水口/上排水
if (item.Outlet == "LEFT")
{
swFeat = swComp.FeatureByName("DRAINPIPE-LEFT");
swFeat.SetSuppression2(1, 2, configNames); //参数1:1解压,0压缩
swFeat = swComp.FeatureByName("DRAINPIPE-RIGHT");
swFeat.SetSuppression2(0, 2, configNames); //参数1:1解压,0压缩
swFeat = swComp.FeatureByName("AUTODRAIN LEFT");
swFeat.SetSuppression2(0, 2, configNames); //参数1:1解压,0压缩
swFeat = swComp.FeatureByName("AUTODRAIN RIGHT");
swFeat.SetSuppression2(0, 2, configNames); //参数1:1解压,0压缩
swFeat = swComp.FeatureByName("液位探测器孔");
swFeat.SetSuppression2(0, 2, configNames); //参数1:1解压,0压缩
}
else if (item.Outlet == "RIGHT")
{
swFeat = swComp.FeatureByName("DRAINPIPE-LEFT");
swFeat.SetSuppression2(0, 2, configNames); //参数1:1解压,0压缩
swFeat = swComp.FeatureByName("DRAINPIPE-RIGHT");
swFeat.SetSuppression2(1, 2, configNames); //参数1:1解压,0压缩
swFeat = swComp.FeatureByName("AUTODRAIN LEFT");
swFeat.SetSuppression2(0, 2, configNames); //参数1:1解压,0压缩
swFeat = swComp.FeatureByName("AUTODRAIN RIGHT");
swFeat.SetSuppression2(0, 2, configNames); //参数1:1解压,0压缩
swFeat = swComp.FeatureByName("液位探测器孔");
swFeat.SetSuppression2(0, 2, configNames); //参数1:1解压,0压缩
}
else if (item.Outlet == "UPLEFT")
{
swFeat = swComp.FeatureByName("DRAINPIPE-LEFT");
swFeat.SetSuppression2(0, 2, configNames); //参数1:1解压,0压缩
swFeat = swComp.FeatureByName("DRAINPIPE-RIGHT");
swFeat.SetSuppression2(0, 2, configNames); //参数1:1解压,0压缩
swFeat = swComp.FeatureByName("AUTODRAIN LEFT");
swFeat.SetSuppression2(1, 2, configNames); //参数1:1解压,0压缩
swFeat = swComp.FeatureByName("AUTODRAIN RIGHT");
swFeat.SetSuppression2(0, 2, configNames); //参数1:1解压,0压缩
}
else if (item.Outlet == "UPRIGHT")
{
swFeat = swComp.FeatureByName("DRAINPIPE-LEFT");
swFeat.SetSuppression2(0, 2, configNames); //参数1:1解压,0压缩
swFeat = swComp.FeatureByName("DRAINPIPE-RIGHT");
swFeat.SetSuppression2(0, 2, configNames); //参数1:1解压,0压缩
swFeat = swComp.FeatureByName("AUTODRAIN LEFT");
swFeat.SetSuppression2(0, 2, configNames); //参数1:1解压,0压缩
swFeat = swComp.FeatureByName("AUTODRAIN RIGHT");
swFeat.SetSuppression2(1, 2, configNames); //参数1:1解压,0压缩
}
else
{
swFeat = swComp.FeatureByName("DRAINPIPE-LEFT");
swFeat.SetSuppression2(0, 2, configNames); //参数1:1解压,0压缩
swFeat = swComp.FeatureByName("DRAINPIPE-RIGHT");
swFeat.SetSuppression2(0, 2, configNames); //参数1:1解压,0压缩
swFeat = swComp.FeatureByName("AUTODRAIN LEFT");
swFeat.SetSuppression2(0, 2, configNames); //参数1:1解压,0压缩
swFeat = swComp.FeatureByName("AUTODRAIN RIGHT");
swFeat.SetSuppression2(0, 2, configNames); //参数1:1解压,0压缩
}
//背靠背
if (item.BackToBack == "YES")
{
swFeat = swComp.FeatureByName("BACKTOBACK");
swFeat.SetSuppression2(1, 2, configNames); //参数1:1解压,0压缩
}
else
{
swFeat = swComp.FeatureByName("BACKTOBACK");
swFeat.SetSuppression2(0, 2, configNames); //参数1:1解压,0压缩
}
//进水口
if (item.Inlet == "LEFT")
{
swFeat = swComp.FeatureByName("DRWATER INLET-L");
swFeat.SetSuppression2(1, 2, configNames); //参数1:1解压,0压缩
swFeat = swComp.FeatureByName("DRWATER INLET-R");
swFeat.SetSuppression2(0, 2, configNames); //参数1:1解压,0压缩
}
else if (item.Inlet == "RIGHT")
{
swFeat = swComp.FeatureByName("DRWATER INLET-L");
swFeat.SetSuppression2(0, 2, configNames); //参数1:1解压,0压缩
swFeat = swComp.FeatureByName("DRWATER INLET-R");
swFeat.SetSuppression2(1, 2, configNames); //参数1:1解压,0压缩
}
else
{
swFeat = swComp.FeatureByName("DRWATER INLET-L");
swFeat.SetSuppression2(0, 2, configNames); //参数1:1解压,0压缩
swFeat = swComp.FeatureByName("DRWATER INLET-R");
swFeat.SetSuppression2(0, 2, configNames); //参数1:1解压,0压缩
}
//ANSUL
if (item.ANSUL == "YES")
{
//侧喷
if (item.ANSide == "LEFT")
{
swFeat = swComp.FeatureByName("ANSUL-LEFT");
swFeat.SetSuppression2(1, 2, configNames); //参数1:1解压,0压缩
}
else if (item.ANSide == "RIGHT")
{
swFeat = swComp.FeatureByName("ANSUL-RIGHT");
swFeat.SetSuppression2(1, 2, configNames); //参数1:1解压,0压缩
}
else
{
swFeat = swComp.FeatureByName("ANSUL-LEFT");
swFeat.SetSuppression2(0, 2, configNames); //参数1:1解压,0压缩
swFeat = swComp.FeatureByName("ANSUL-RIGHT");
swFeat.SetSuppression2(0, 2, configNames); //参数1:1解压,0压缩
}
}
//----------排风腔前面板----------
swComp = swAssy.GetComponentByName(CommonFunc.AddSuffix(suffix, "FNHE0071-1"));
swPart = swComp.GetModelDoc2();
swPart.Parameter("D2@Base-Flange1").SystemValue = item.Length / 1000m;
swComp = swAssy.GetComponentByName(CommonFunc.AddSuffix(suffix, "FNHE0074-1"));
swPart = swComp.GetModelDoc2();
swPart.Parameter("D2@Base-Flange1").SystemValue = (item.Length - 7.5m) / 1000m;
swComp = swAssy.GetComponentByName(CommonFunc.AddSuffix(suffix, "FNHE0088-1"));
swPart = swComp.GetModelDoc2();
swPart.Parameter("D2@Base-Flange1").SystemValue = (item.Length - 7.5m) / 1000m;
//----------排风滑门/导轨----------
swComp = swAssy.GetComponentByName(CommonFunc.AddSuffix(suffix, "FNCE0013-2"));
if (item.ExWidth == 300m) swComp.SetSuppression2(0); //2解压缩,0压缩
else swComp.SetSuppression2(2); //2解压缩,0压缩
swComp = swAssy.GetComponentByName(CommonFunc.AddSuffix(suffix, "FNCE0013-1"));
if (item.ExWidth == 300m) swComp.SetSuppression2(0); //2解压缩,0压缩
else
{
swComp.SetSuppression2(2);//2解压缩,0压缩
swPart = swComp.GetModelDoc2();
swPart.Parameter("D1@Sketch1").SystemValue = (item.ExLength / 2 + 10m) / 1000m;
swPart.Parameter("D2@Sketch1").SystemValue = (item.ExWidth + 20m) / 1000m;
}
swComp = swAssy.GetComponentByName(CommonFunc.AddSuffix(suffix, "FNCE0018-2"));
swComp.SetSuppression2(2); //2解压缩,0压缩
swComp = swAssy.GetComponentByName(CommonFunc.AddSuffix(suffix, "FNCE0018-1"));
swComp.SetSuppression2(2);//2解压缩,0压缩
swPart = swComp.GetModelDoc2();
if (item.ExNo == 1) swPart.Parameter("D2@Base-Flange1").SystemValue = (item.ExLength * 2 + 100m) / 1000m;
else swPart.Parameter("D2@Base-Flange1").SystemValue = (item.ExLength * 3 + item.ExDis + 100m) / 1000m;
//----------排风脖颈----------
swComp = swAssy.GetComponentByName(CommonFunc.AddSuffix(suffix, "FNHE0089-1"));
swPart = swComp.GetModelDoc2();
swPart.Parameter("D2@Base-Flange1").SystemValue = item.ExLength / 1000m;
swPart.Parameter("D2@Sketch1").SystemValue = item.ExHeight / 1000m;
//swFeat = swComp.FeatureByName("ANSUL");
//if (item.ANSUL == "YES") swFeat.SetSuppression2(1, 2, configNames); //参数1:1解压,0压缩
//else swFeat.SetSuppression2(0, 2, configNames); //参数1:1解压,0压缩
swComp = swAssy.GetComponentByName(CommonFunc.AddSuffix(suffix, "FNHE0090-1"));
swComp.SetSuppression2(2);//2解压缩,0压缩
swPart = swComp.GetModelDoc2();
swPart.Parameter("D1@Sketch1").SystemValue = (item.ExWidth - 2.5m) / 1000m;
swPart.Parameter("D2@Sketch1").SystemValue = item.ExHeight / 1000m;
//----------排风腔内部零件----------
swComp = swAssy.GetComponentByName(CommonFunc.AddSuffix(suffix, "FNHE0075-1"));
swPart = swComp.GetModelDoc2();
swPart.Parameter("D2@Base-Flange1").SystemValue = (item.Length - 113m) / 2000m;
swComp = swAssy.GetComponentByName(CommonFunc.AddSuffix(suffix, "FNHE0078-1"));
swPart = swComp.GetModelDoc2();
swPart.Parameter("D2@Base-Flange1").SystemValue = (item.Length - 170m) / 2000m;
swComp = swAssy.GetComponentByName(CommonFunc.AddSuffix(suffix, "FNHE0079-1"));
swPart = swComp.GetModelDoc2();
swPart.Parameter("D2@Base-Flange1").SystemValue = (item.Length - 200m) / 2000m;
//----------灯具----------
//日光灯
if (item.LightType == "FSLONG")
{
swComp = swAssy.GetComponentByName(CommonFunc.AddSuffix(suffix, "5201020410-1"));
swComp.SetSuppression2(2); //2解压缩,0压缩
swComp = swAssy.GetComponentByName(CommonFunc.AddSuffix(suffix, "5201020409-1"));
swComp.SetSuppression2(0); //2解压缩,0压缩
}
else if (item.LightType == "FSSHORT")
{
swComp = swAssy.GetComponentByName(CommonFunc.AddSuffix(suffix, "5201020410-1"));
swComp.SetSuppression2(0); //2解压缩,0压缩
swComp = swAssy.GetComponentByName(CommonFunc.AddSuffix(suffix, "5201020409-1"));
swComp.SetSuppression2(2); //2解压缩,0压缩
}
else
{
swComp = swAssy.GetComponentByName(CommonFunc.AddSuffix(suffix, "5201020410-1"));
swComp.SetSuppression2(0); //2解压缩,0压缩
swComp = swAssy.GetComponentByName(CommonFunc.AddSuffix(suffix, "5201020409-1"));
swComp.SetSuppression2(0); //2解压缩,0压缩
}
//----------MiddleRoof灯板----------
swComp = swAssy.GetComponentByName(CommonFunc.AddSuffix(suffix, "FNHM0001-1"));
swEdit.FNHM0001(swComp, "CMOD", item.Length, item.Deepth, 555m, 400m, item.ExRightDis, midRoofTopHoleDis, midRoofSecondHoleDis, midRoofHoleNo, item.LightType, 0, item.LEDSpotNo, item.LEDSpotDis, item.ANSUL, item.ANDropNo, item.ANYDis, item.ANDropDis1, item.ANDropDis2, item.ANDropDis3, item.ANDropDis4, item.ANDropDis5, item.ANDetectorEnd, item.ANDetectorNo, item.ANDetectorDis1, item.ANDetectorDis2, item.ANDetectorDis3, item.ANDetectorDis4, item.ANDetectorDis5, "NO", "NO", item.MARVEL, item.IRNo, item.IRDis1, item.IRDis2, item.IRDis3);
//----------吊装槽钢----------
swComp = swAssy.GetComponentByName(CommonFunc.AddSuffix(suffix, "2900100001-1"));
swPart = swComp.GetModelDoc2();
if (item.ANSUL == "YES") swPart.Parameter("D2@基体-法兰1").SystemValue = (item.Deepth - 250) / 1000m;
else swPart.Parameter("D2@基体-法兰1").SystemValue = (item.Deepth - 100m) / 1000m;
//----------大侧板----------
if (item.SidePanel == "BOTH")
{
//LEFT
//LEFT
swComp = swAssy.GetComponentByName(CommonFunc.AddSuffix(suffix, "FNHS0051-1"));
swComp.SetSuppression2(2); //2解压缩,0压缩
swEdit.FNHS0051(swComp, item.Deepth, 555m,400m,sidePanelSideCjNo, sidePanelDownCjNo);
swComp = swAssy.GetComponentByName(CommonFunc.AddSuffix(suffix, "FNHS0052-1"));
swComp.SetSuppression2(2); //2解压缩,0压缩
swEdit.FNHS0052(swComp, item.Deepth, 555m, 400m);
//RIGHT
swComp = swAssy.GetComponentByName(CommonFunc.AddSuffix(suffix, "FNHS0053-1"));
swComp.SetSuppression2(2); //2解压缩,0压缩
swEdit.FNHS0053(swComp, item.Deepth, 555m, 400m, sidePanelSideCjNo, sidePanelDownCjNo);
swComp = swAssy.GetComponentByName(CommonFunc.AddSuffix(suffix, "FNHS0054-1"));
swComp.SetSuppression2(2); //2解压缩,0压缩
swEdit.FNHS0054(swComp, item.Deepth, 555m, 400m);
}
else if (item.SidePanel == "LEFT")
{
swComp = swAssy.GetComponentByName(CommonFunc.AddSuffix(suffix, "FNHS0053-1"));
swComp.SetSuppression2(0); //2解压缩,0压缩
swComp = swAssy.GetComponentByName(CommonFunc.AddSuffix(suffix, "FNHS0054-1"));
swComp.SetSuppression2(0); //2解压缩,0压缩
swComp = swAssy.GetComponentByName(CommonFunc.AddSuffix(suffix, "FNHS0051-1"));
swComp.SetSuppression2(2); //2解压缩,0压缩
swEdit.FNHS0051(swComp, item.Deepth, 555m, 400m, sidePanelSideCjNo, sidePanelDownCjNo);
swComp = swAssy.GetComponentByName(CommonFunc.AddSuffix(suffix, "FNHS0052-1"));
swComp.SetSuppression2(2); //2解压缩,0压缩
swEdit.FNHS0052(swComp, item.Deepth, 555m, 400m);
}
else if (item.SidePanel == "RIGHT")
{
swComp = swAssy.GetComponentByName(CommonFunc.AddSuffix(suffix, "FNHS0051-1"));
swComp.SetSuppression2(0); //2解压缩,0压缩
swComp = swAssy.GetComponentByName(CommonFunc.AddSuffix(suffix, "FNHS0052-1"));
swComp.SetSuppression2(0); //2解压缩,0压缩
swComp = swAssy.GetComponentByName(CommonFunc.AddSuffix(suffix, "FNHS0053-1"));
swComp.SetSuppression2(2); //2解压缩,0压缩
swEdit.FNHS0053(swComp, item.Deepth, 555m, 400m, sidePanelSideCjNo, sidePanelDownCjNo);
swComp = swAssy.GetComponentByName(CommonFunc.AddSuffix(suffix, "FNHS0054-1"));
swComp.SetSuppression2(2); //2解压缩,0压缩
swEdit.FNHS0054(swComp, item.Deepth, 555m, 400m);
}
else
{
swComp = swAssy.GetComponentByName(CommonFunc.AddSuffix(suffix, "FNHS0051-1"));
swComp.SetSuppression2(0); //2解压缩,0压缩
swComp = swAssy.GetComponentByName(CommonFunc.AddSuffix(suffix, "FNHS0052-1"));
swComp.SetSuppression2(0); //2解压缩,0压缩
swComp = swAssy.GetComponentByName(CommonFunc.AddSuffix(suffix, "FNHS0053-1"));
swComp.SetSuppression2(0); //2解压缩,0压缩
swComp = swAssy.GetComponentByName(CommonFunc.AddSuffix(suffix, "FNHS0054-1"));
swComp.SetSuppression2(0); //2解压缩,0压缩
}
//------------F型新风腔主体----------
swComp = swAssy.GetComponentByName(CommonFunc.AddSuffix(suffix, "FNHA0021-1"));
swEdit.FNHA0021(swComp, item.Length, frontPanelKaKouNo, frontPanelKaKouDis, midRoofSecondHoleDis, midRoofTopHoleDis, midRoofHoleNo, item.SuDis, item.SuNo, item.MARVEL, item.IRNo, item.IRDis1, item.IRDis2, item.IRDis3, item.SidePanel, "KV", "NO");
//----------新风前面板----------
swComp = swAssy.GetComponentByName(CommonFunc.AddSuffix(suffix, "FNHA0027-1"));
swPart = swComp.GetModelDoc2();
swPart.Parameter("D1@草图1").SystemValue = (item.Length - 3m) / 1000m;
swPart.Parameter("D1@阵列(线性)7").SystemValue = frontPanelKaKouNo;
swPart.Parameter("D3@阵列(线性)7").SystemValue = frontPanelKaKouDis;
swPart.Parameter("D1@LPattern1").SystemValue = frontPanelHoleNo;
swPart.Parameter("D3@LPattern1").SystemValue = frontPanelHoleDis;
//----------蜂窝板压条----------
swComp = swAssy.GetComponentByName(CommonFunc.AddSuffix(suffix, "FNHA0029-1"));
swPart = swComp.GetModelDoc2();
swPart.Parameter("D1@草图1").SystemValue = (item.Length - 6m) / 1000m;
swPart.Parameter("D1@LPattern1").SystemValue = frontPanelHoleNo;
swPart.Parameter("D3@LPattern1").SystemValue = frontPanelHoleDis;
//----------镀锌隔板----------
swComp = swAssy.GetComponentByName(CommonFunc.AddSuffix(suffix, "FNHA0022-1"));
swPart = swComp.GetModelDoc2();
swPart.Parameter("D2@Sketch1").SystemValue = (item.Length - 6m) / 1000m;
//MARVEL
//if (item.MARVEL == "YES")
//{
// swFeat = swComp.FeatureByName("IR3FAN");
// swFeat.SetSuppression2(0, 2, configNames); //参数1:1解压,0压缩
// if (item.IRNo > 0)
// {
// swFeat = swComp.FeatureByName("MA1");
// swFeat.SetSuppression2(1, 2, configNames); //参数1:1解压,0压缩
// swPart.Parameter("D1@Sketch2").SystemValue = item.IRDis1 / 1000m;
// }
// if (item.IRNo > 1)
// {
// swFeat = swComp.FeatureByName("MA2");
// swFeat.SetSuppression2(1, 2, configNames); //参数1:1解压,0压缩
// swPart.Parameter("D1@Sketch3").SystemValue = item.IRDis2 / 1000m;
// }
// if (item.IRNo > 2)
// {
// swFeat = swComp.FeatureByName("MA3");
// swFeat.SetSuppression2(1, 2, configNames); //参数1:1解压,0压缩
// swPart.Parameter("D1@Sketch4").SystemValue = item.IRDis3 / 1000m;
// swFeat = swComp.FeatureByName("IR3FAN");
// swFeat.SetSuppression2(1, 2, configNames); //参数1:1解压,0压缩
// }
//}
//else
//{
// swFeat = swComp.FeatureByName("MA1");
// swFeat.SetSuppression2(0, 2, configNames); //参数1:1解压,0压缩
// swFeat = swComp.FeatureByName("MA2");
// swFeat.SetSuppression2(0, 2, configNames); //参数1:1解压,0压缩
// swFeat = swComp.FeatureByName("MA3");
// swFeat.SetSuppression2(0, 2, configNames); //参数1:1解压,0压缩
// swFeat = swComp.FeatureByName("IR3FAN");
// swFeat.SetSuppression2(0, 2, configNames); //参数1:1解压,0压缩
//}
//----------新风滑门导轨----------
swComp = swAssy.GetComponentByName(CommonFunc.AddSuffix(suffix, "FNHA0010-1"));
swPart = swComp.GetModelDoc2();
swPart.Parameter("D2@草图1").SystemValue = (item.Length - 200m) / 1000m;
swComp = swAssy.GetComponentByName(CommonFunc.AddSuffix(suffix, "FNHE0010-1"));
swPart = swComp.GetModelDoc2();
swPart.Parameter("D1@草图1").SystemValue = (item.Length - 200m) / 1000m;
//----------新风底部CJ孔板----------
swComp = swAssy.GetComponentByName(CommonFunc.AddSuffix(suffix, "FNHA0005-1"));
swPart = swComp.GetModelDoc2();
swPart.Parameter("D2@基体-法兰1").SystemValue = item.Length / 1000m;
swPart.Parameter("D1@CJHOLES").SystemValue = frontCjNo;
swPart.Parameter("D10@草图8").SystemValue = frontCjFirstDis;
swPart.Parameter("D1@LPattern1").SystemValue = frontPanelHoleNo;
swPart.Parameter("D3@LPattern1").SystemValue = frontPanelHoleDis;
swFeat = swComp.FeatureByName("BLUETOOTH");
swFeat.SetSuppression2(0, 2, configNames); //参数1:1解压,0压缩
swFeat = swComp.FeatureByName("LOGO");
if (item.LEDlogo == "YES") swFeat.SetSuppression2(1, 2, configNames); //参数1:1解压,0压缩
else swFeat.SetSuppression2(0, 2, configNames); //参数1:1解压,0压缩
//集水翻边
swFeat = swComp.FeatureByName("DRAINCHANNEL-RIGHT");
swFeat.SetSuppression2(0, 2, configNames); //参数1:1解压,0压缩
swFeat = swComp.FeatureByName("DRAINCHANNEL-LEFT");
swFeat.SetSuppression2(0, 2, configNames); //参数1:1解压,0压缩
//----------LOGO----------
swComp = swAssy.GetComponentByName(CommonFunc.AddSuffix(suffix, "2900300005-3"));
if (item.LEDlogo == "YES") swComp.SetSuppression2(2); //2解压缩,0压缩
else swComp.SetSuppression2(0); //2解压缩,0压缩
swComp = swAssy.GetComponentByName(CommonFunc.AddSuffix(suffix, "5201010401-3"));
if (item.LEDlogo == "YES") swComp.SetSuppression2(2); //2解压缩,0压缩
else swComp.SetSuppression2(0); //2解压缩,0压缩
swModel.ForceRebuild3(true);//设置成true,直接更新顶层,速度很快,设置成false,每个零件都会更新,很慢
swModel.Save();//保存,很耗时间
swApp.CloseDoc(packedAssyPath);//关闭,很快
}
catch (Exception ex)
{
throw new Exception(packedAssyPath + "作图过程发生异常,详细:" + ex.Message);
}
finally
{
swApp.CommandInProgress = false; //及时关闭外部命令调用,否则影响SolidWorks的使用
}
}
}
}
| 57.606618 | 555 | 0.53558 | [
"MIT"
] | felixzhu1989/Compass | SolidWorksHelper/HoodAutoDrawing/CMODF555400AutoDrawing.cs | 33,952 | C# |
using AniCharades.Adapters.Interfaces;
using AniCharades.Common.Utils;
namespace AniCharades.Services.Franchise.Relations.Common
{
public class AnyWordMatchesStrategy : IRelationStrategy
{
public bool AreRelated(IEntryInstance firstEntry, IEntryInstance secondEntry)
{
return firstEntry.Title.ContainsAnySharedWord(secondEntry.Title);
}
}
}
| 27.928571 | 85 | 0.741688 | [
"MIT"
] | Forczu/AniCharades | AniCharades.Services/Franchise/Relations/Common/AnyWordMatchesStrategy.cs | 393 | C# |
using UnityEngine;
using UnityEngine.UI;
public class StatusIndicator : MonoBehaviour {
[SerializeField]
private RectTransform healthBarRect;
[SerializeField]
private Text healthText;
private void Start()
{
if (healthBarRect == null) {
Debug.LogError("STATUS INDICATOR: No health bar object referenced!");
}
if (healthText == null)
{
Debug.LogError("STATUS INDICATOR: No health text object referenced!");
}
}
public void SetHealth(int _cur, int _max) // _variables are private and only available in scope of method
{
float _value = (float)_cur / _max;
healthBarRect.localScale = new Vector3(_value, healthBarRect.localScale.y, healthBarRect.localScale.z);
healthText.text = _cur + "/" + _max + " HP";
}
}
| 26.363636 | 112 | 0.616092 | [
"MIT"
] | minhancao/RedCaster | Library/Collab/Base/Assets/Scripts/StatusIndicator.cs | 872 | C# |
using System.Text.Json.Serialization;
namespace Essensoft.AspNetCore.Payment.Alipay.Domain
{
/// <summary>
/// AlipayUserCertifyOpenInitializeModel Data Structure.
/// </summary>
public class AlipayUserCertifyOpenInitializeModel : AlipayObject
{
/// <summary>
/// 认证场景码。入参支持的认证场景码和商户签约的认证场景相关,取值如下: FACE:多因子人脸认证 CERT_PHOTO:多因子证照认证 CERT_PHOTO_FACE :多因子证照和人脸认证 SMART_FACE:多因子快捷认证
/// </summary>
[JsonPropertyName("biz_code")]
public string BizCode { get; set; }
/// <summary>
/// 自定义人脸比对图片的base64编码格式的string字符串
/// </summary>
[JsonPropertyName("face_contrast_picture")]
public string FaceContrastPicture { get; set; }
/// <summary>
/// 需要验证的身份信息(json)字段说明如下: identity_type:身份信息参数类型,必须传入CERT_INFO cert_name:真实姓名,必填 cert_no:证件号码,必填 cert_type:证件类型,必填, 取值如下: IDENTITY_CARD:身份证 HOME_VISIT_PERMIT_HK_MC:港澳通行证 HOME_VISIT_PERMIT_TAIWAN:台湾通行证 RESIDENCE_PERMIT_HK_MC:港澳居住证 RESIDENCE_PERMIT_TAIWAN:台湾居住证
/// </summary>
[JsonPropertyName("identity_param")]
public string IdentityParam { get; set; }
/// <summary>
/// 商户个性化配置,格式为json,详细支持的字段说明为: return_url:需要回跳的目标地址,必填,一般指定为商户业务页面
/// </summary>
[JsonPropertyName("merchant_config")]
public string MerchantConfig { get; set; }
/// <summary>
/// 商户请求的唯一标识,商户要保证其唯一性,值为32位长度的字母数字组合。建议:前面几位字符是商户自定义的简称,中间可以使用一段时间,后段可以使用一个随机或递增序列
/// </summary>
[JsonPropertyName("outer_order_no")]
public string OuterOrderNo { get; set; }
}
}
| 38.780488 | 268 | 0.671069 | [
"MIT"
] | LuohuaRain/payment | src/Essensoft.AspNetCore.Payment.Alipay/Domain/AlipayUserCertifyOpenInitializeModel.cs | 2,192 | C# |
using System;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
using System.Web;
using System.Web.Security;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.Owin;
using Microsoft.Owin.Security.DataProtection;
using Umbraco.Core;
using Umbraco.Core.Configuration;
using Umbraco.Core.Configuration.UmbracoSettings;
using Umbraco.Core.Mapping;
using Umbraco.Core.Models.Identity;
using Umbraco.Core.Security;
using Umbraco.Core.Services;
namespace Umbraco.Web.Security
{
/// <summary>
/// Default back office user manager
/// </summary>
public class BackOfficeUserManager : BackOfficeUserManager<BackOfficeIdentityUser>
{
public const string OwinMarkerKey = "Umbraco.Web.Security.Identity.BackOfficeUserManagerMarker";
public BackOfficeUserManager(IUserStore<BackOfficeIdentityUser, int> store)
: base(store)
{
}
public BackOfficeUserManager(
IUserStore<BackOfficeIdentityUser, int> store,
IdentityFactoryOptions<BackOfficeUserManager> options,
MembershipProviderBase membershipProvider,
IContentSection contentSectionConfig)
: base(store)
{
if (options == null) throw new ArgumentNullException("options");
InitUserManager(this, membershipProvider, contentSectionConfig, options);
}
#region Static Create methods
/// <summary>
/// Creates a BackOfficeUserManager instance with all default options and the default BackOfficeUserManager
/// </summary>
/// <param name="options"></param>
/// <param name="userService"></param>
/// <param name="memberTypeService"></param>
/// <param name="entityService"></param>
/// <param name="externalLoginService"></param>
/// <param name="membershipProvider"></param>
/// <param name="contentSectionConfig"></param>
/// <param name="globalSettings"></param>
/// <returns></returns>
public static BackOfficeUserManager Create(
IdentityFactoryOptions<BackOfficeUserManager> options,
IUserService userService,
IMemberTypeService memberTypeService,
IEntityService entityService,
IExternalLoginService externalLoginService,
MembershipProviderBase membershipProvider,
UmbracoMapper mapper,
IContentSection contentSectionConfig,
IGlobalSettings globalSettings)
{
if (options == null) throw new ArgumentNullException("options");
if (userService == null) throw new ArgumentNullException("userService");
if (memberTypeService == null) throw new ArgumentNullException("memberTypeService");
if (externalLoginService == null) throw new ArgumentNullException("externalLoginService");
var manager = new BackOfficeUserManager(
new BackOfficeUserStore(userService, memberTypeService, entityService, externalLoginService, globalSettings, membershipProvider, mapper));
manager.InitUserManager(manager, membershipProvider, contentSectionConfig, options);
return manager;
}
/// <summary>
/// Creates a BackOfficeUserManager instance with all default options and a custom BackOfficeUserManager instance
/// </summary>
/// <param name="options"></param>
/// <param name="customUserStore"></param>
/// <param name="membershipProvider"></param>
/// <param name="contentSectionConfig"></param>
/// <returns></returns>
public static BackOfficeUserManager Create(
IdentityFactoryOptions<BackOfficeUserManager> options,
BackOfficeUserStore customUserStore,
MembershipProviderBase membershipProvider,
IContentSection contentSectionConfig)
{
var manager = new BackOfficeUserManager(customUserStore, options, membershipProvider, contentSectionConfig);
return manager;
}
#endregion
/// <summary>
/// Initializes the user manager with the correct options
/// </summary>
/// <param name="manager"></param>
/// <param name="membershipProvider"></param>
/// <param name="contentSectionConfig"></param>
/// <param name="options"></param>
/// <returns></returns>
protected void InitUserManager(
BackOfficeUserManager manager,
MembershipProviderBase membershipProvider,
IContentSection contentSectionConfig,
IdentityFactoryOptions<BackOfficeUserManager> options)
{
//NOTE: This method is mostly here for backwards compat
base.InitUserManager(manager, membershipProvider, options.DataProtectionProvider, contentSectionConfig);
}
}
/// <summary>
/// Generic Back office user manager
/// </summary>
public class BackOfficeUserManager<T> : UserManager<T, int>
where T : BackOfficeIdentityUser
{
public BackOfficeUserManager(IUserStore<T, int> store)
: base(store)
{
}
#region What we support do not currently
// TODO: We could support this - but a user claims will mostly just be what is in the auth cookie
public override bool SupportsUserClaim
{
get { return false; }
}
// TODO: Support this
public override bool SupportsQueryableUsers
{
get { return false; }
}
/// <summary>
/// Developers will need to override this to support custom 2 factor auth
/// </summary>
public override bool SupportsUserTwoFactor
{
get { return false; }
}
// TODO: Support this
public override bool SupportsUserPhoneNumber
{
get { return false; }
}
#endregion
public virtual async Task<ClaimsIdentity> GenerateUserIdentityAsync(T user)
{
// NOTE the authenticationType must match the umbraco one
// defined in CookieAuthenticationOptions.AuthenticationType
var userIdentity = await CreateIdentityAsync(user, Core.Constants.Security.BackOfficeAuthenticationType);
return userIdentity;
}
/// <summary>
/// Initializes the user manager with the correct options
/// </summary>
/// <param name="manager"></param>
/// <param name="membershipProvider">
/// The <see cref="MembershipProviderBase"/> for the users called UsersMembershipProvider
/// </param>
/// <param name="dataProtectionProvider"></param>
/// <param name="contentSectionConfig"></param>
/// <returns></returns>
protected void InitUserManager(
BackOfficeUserManager<T> manager,
MembershipProviderBase membershipProvider,
IDataProtectionProvider dataProtectionProvider,
IContentSection contentSectionConfig)
{
// Configure validation logic for usernames
manager.UserValidator = new BackOfficeUserValidator<T>(manager)
{
AllowOnlyAlphanumericUserNames = false,
RequireUniqueEmail = true
};
// Configure validation logic for passwords
manager.PasswordValidator = new MembershipProviderPasswordValidator(membershipProvider);
//use a custom hasher based on our membership provider
manager.PasswordHasher = GetDefaultPasswordHasher(membershipProvider);
if (dataProtectionProvider != null)
{
manager.UserTokenProvider = new DataProtectorTokenProvider<T, int>(dataProtectionProvider.Create("ASP.NET Identity"))
{
TokenLifespan = TimeSpan.FromDays(3)
};
}
manager.UserLockoutEnabledByDefault = true;
manager.MaxFailedAccessAttemptsBeforeLockout = membershipProvider.MaxInvalidPasswordAttempts;
//NOTE: This just needs to be in the future, we currently don't support a lockout timespan, it's either they are locked
// or they are not locked, but this determines what is set on the account lockout date which corresponds to whether they are
// locked out or not.
manager.DefaultAccountLockoutTimeSpan = TimeSpan.FromDays(30);
//custom identity factory for creating the identity object for which we auth against in the back office
manager.ClaimsIdentityFactory = new BackOfficeClaimsIdentityFactory<T>();
manager.EmailService = new EmailService(
contentSectionConfig.NotificationEmailAddress,
new EmailSender());
//NOTE: Not implementing these, if people need custom 2 factor auth, they'll need to implement their own UserStore to support it
//// Register two factor authentication providers. This application uses Phone and Emails as a step of receiving a code for verifying the user
//// You can write your own provider and plug in here.
//manager.RegisterTwoFactorProvider("PhoneCode", new PhoneNumberTokenProvider<ApplicationUser>
//{
// MessageFormat = "Your security code is: {0}"
//});
//manager.RegisterTwoFactorProvider("EmailCode", new EmailTokenProvider<ApplicationUser>
//{
// Subject = "Security Code",
// BodyFormat = "Your security code is: {0}"
//});
//manager.SmsService = new SmsService();
}
/// <summary>
/// Used to validate a user's session
/// </summary>
/// <param name="userId"></param>
/// <param name="sessionId"></param>
/// <returns></returns>
public virtual async Task<bool> ValidateSessionIdAsync(int userId, string sessionId)
{
var userSessionStore = Store as IUserSessionStore<BackOfficeIdentityUser, int>;
//if this is not set, for backwards compat (which would be super rare), we'll just approve it
if (userSessionStore == null)
return true;
return await userSessionStore.ValidateSessionIdAsync(userId, sessionId);
}
/// <summary>
/// This will determine which password hasher to use based on what is defined in config
/// </summary>
/// <returns></returns>
protected virtual IPasswordHasher GetDefaultPasswordHasher(MembershipProviderBase provider)
{
//if the current user membership provider is unknown (this would be rare), then return the default password hasher
if (provider.IsUmbracoUsersProvider() == false)
return new PasswordHasher();
//if the configured provider has legacy features enabled, then return the membership provider password hasher
if (provider.AllowManuallyChangingPassword || provider.DefaultUseLegacyEncoding)
return new MembershipProviderPasswordHasher(provider);
//we can use the user aware password hasher (which will be the default and preferred way)
return new UserAwareMembershipProviderPasswordHasher(provider);
}
/// <summary>
/// Gets/sets the default back office user password checker
/// </summary>
public IBackOfficeUserPasswordChecker BackOfficeUserPasswordChecker { get; set; }
/// <summary>
/// Helper method to generate a password for a user based on the current password validator
/// </summary>
/// <returns></returns>
public string GeneratePassword()
{
var passwordValidator = PasswordValidator as PasswordValidator;
if (passwordValidator == null)
{
var membershipPasswordHasher = PasswordHasher as IMembershipProviderPasswordHasher;
//get the real password validator, this should not be null but in some very rare cases it could be, in which case
//we need to create a default password validator to use since we have no idea what it actually is or what it's rules are
//this is an Edge Case!
passwordValidator = PasswordValidator as PasswordValidator
?? (membershipPasswordHasher != null
? new MembershipProviderPasswordValidator(membershipPasswordHasher.MembershipProvider)
: new PasswordValidator());
}
var password = Membership.GeneratePassword(
passwordValidator.RequiredLength,
passwordValidator.RequireNonLetterOrDigit ? 2 : 0);
var random = new Random();
var passwordChars = password.ToCharArray();
if (passwordValidator.RequireDigit && passwordChars.ContainsAny(Enumerable.Range(48, 58).Select(x => (char)x)))
password += Convert.ToChar(random.Next(48, 58)); // 0-9
if (passwordValidator.RequireLowercase && passwordChars.ContainsAny(Enumerable.Range(97, 123).Select(x => (char)x)))
password += Convert.ToChar(random.Next(97, 123)); // a-z
if (passwordValidator.RequireUppercase && passwordChars.ContainsAny(Enumerable.Range(65, 91).Select(x => (char)x)))
password += Convert.ToChar(random.Next(65, 91)); // A-Z
if (passwordValidator.RequireNonLetterOrDigit && passwordChars.ContainsAny(Enumerable.Range(33, 48).Select(x => (char)x)))
password += Convert.ToChar(random.Next(33, 48)); // symbols !"#$%&'()*+,-./
return password;
}
/// <summary>
/// Override to check the user approval value as well as the user lock out date, by default this only checks the user's locked out date
/// </summary>
/// <param name="userId"></param>
/// <returns></returns>
/// <remarks>
/// In the ASP.NET Identity world, there is only one value for being locked out, in Umbraco we have 2 so when checking this for Umbraco we need to check both values
/// </remarks>
public override async Task<bool> IsLockedOutAsync(int userId)
{
var user = await FindByIdAsync(userId);
if (user == null)
throw new InvalidOperationException("No user found by id " + userId);
if (user.IsApproved == false)
return true;
return await base.IsLockedOutAsync(userId);
}
#region Overrides for password logic
/// <summary>
/// Logic used to validate a username and password
/// </summary>
/// <param name="user"></param>
/// <param name="password"></param>
/// <returns></returns>
/// <remarks>
/// By default this uses the standard ASP.Net Identity approach which is:
/// * Get password store
/// * Call VerifyPasswordAsync with the password store + user + password
/// * Uses the PasswordHasher.VerifyHashedPassword to compare the stored password
///
/// In some cases people want simple custom control over the username/password check, for simplicity
/// sake, developers would like the users to simply validate against an LDAP directory but the user
/// data remains stored inside of Umbraco.
/// See: http://issues.umbraco.org/issue/U4-7032 for the use cases.
///
/// We've allowed this check to be overridden with a simple callback so that developers don't actually
/// have to implement/override this class.
/// </remarks>
public override async Task<bool> CheckPasswordAsync(T user, string password)
{
if (BackOfficeUserPasswordChecker != null)
{
var result = await BackOfficeUserPasswordChecker.CheckPasswordAsync(user, password);
if (user.HasIdentity == false)
{
return false;
}
//if the result indicates to not fallback to the default, then return true if the credentials are valid
if (result != BackOfficeUserPasswordCheckerResult.FallbackToDefaultChecker)
{
return result == BackOfficeUserPasswordCheckerResult.ValidCredentials;
}
}
//we cannot proceed if the user passed in does not have an identity
if (user.HasIdentity == false)
return false;
//use the default behavior
return await base.CheckPasswordAsync(user, password);
}
public override Task<IdentityResult> ResetPasswordAsync(int userId, string token, string newPassword)
{
var result = base.ResetPasswordAsync(userId, token, newPassword);
if (result.Result.Succeeded)
RaisePasswordResetEvent(userId);
return result;
}
/// <summary>
/// This is a special method that will reset the password but will raise the Password Changed event instead of the reset event
/// </summary>
/// <param name="userId"></param>
/// <param name="token"></param>
/// <param name="newPassword"></param>
/// <returns></returns>
/// <remarks>
/// We use this because in the back office the only way an admin can change another user's password without first knowing their password
/// is to generate a token and reset it, however, when we do this we want to track a password change, not a password reset
/// </remarks>
public Task<IdentityResult> ChangePasswordWithResetAsync(int userId, string token, string newPassword)
{
var result = base.ResetPasswordAsync(userId, token, newPassword);
if (result.Result.Succeeded)
RaisePasswordChangedEvent(userId);
return result;
}
public override Task<IdentityResult> ChangePasswordAsync(int userId, string currentPassword, string newPassword)
{
var result = base.ChangePasswordAsync(userId, currentPassword, newPassword);
if (result.Result.Succeeded)
RaisePasswordChangedEvent(userId);
return result;
}
/// <summary>
/// Override to determine how to hash the password
/// </summary>
/// <param name="store"></param>
/// <param name="user"></param>
/// <param name="password"></param>
/// <returns></returns>
protected override async Task<bool> VerifyPasswordAsync(IUserPasswordStore<T, int> store, T user, string password)
{
var userAwarePasswordHasher = PasswordHasher as IUserAwarePasswordHasher<BackOfficeIdentityUser, int>;
if (userAwarePasswordHasher == null)
return await base.VerifyPasswordAsync(store, user, password);
var hash = await store.GetPasswordHashAsync(user);
return userAwarePasswordHasher.VerifyHashedPassword(user, hash, password) != PasswordVerificationResult.Failed;
}
/// <summary>
/// Override to determine how to hash the password
/// </summary>
/// <param name="passwordStore"></param>
/// <param name="user"></param>
/// <param name="newPassword"></param>
/// <returns></returns>
/// <remarks>
/// This method is called anytime the password needs to be hashed for storage (i.e. including when reset password is used)
/// </remarks>
protected override async Task<IdentityResult> UpdatePassword(IUserPasswordStore<T, int> passwordStore, T user, string newPassword)
{
user.LastPasswordChangeDateUtc = DateTime.UtcNow;
var userAwarePasswordHasher = PasswordHasher as IUserAwarePasswordHasher<BackOfficeIdentityUser, int>;
if (userAwarePasswordHasher == null)
return await base.UpdatePassword(passwordStore, user, newPassword);
var result = await PasswordValidator.ValidateAsync(newPassword);
if (result.Succeeded == false)
return result;
await passwordStore.SetPasswordHashAsync(user, userAwarePasswordHasher.HashPassword(user, newPassword));
await UpdateSecurityStampInternal(user);
return IdentityResult.Success;
}
/// <summary>
/// This is copied from the underlying .NET base class since they decided to not expose it
/// </summary>
/// <param name="user"></param>
/// <returns></returns>
private async Task UpdateSecurityStampInternal(BackOfficeIdentityUser user)
{
if (SupportsUserSecurityStamp == false)
return;
await GetSecurityStore().SetSecurityStampAsync(user, NewSecurityStamp());
}
/// <summary>
/// This is copied from the underlying .NET base class since they decided to not expose it
/// </summary>
/// <returns></returns>
private IUserSecurityStampStore<BackOfficeIdentityUser, int> GetSecurityStore()
{
var store = Store as IUserSecurityStampStore<BackOfficeIdentityUser, int>;
if (store == null)
throw new NotSupportedException("The current user store does not implement " + typeof(IUserSecurityStampStore<>));
return store;
}
/// <summary>
/// This is copied from the underlying .NET base class since they decided to not expose it
/// </summary>
/// <returns></returns>
private static string NewSecurityStamp()
{
return Guid.NewGuid().ToString();
}
#endregion
public override async Task<IdentityResult> SetLockoutEndDateAsync(int userId, DateTimeOffset lockoutEnd)
{
var result = await base.SetLockoutEndDateAsync(userId, lockoutEnd);
// The way we unlock is by setting the lockoutEnd date to the current datetime
if (result.Succeeded && lockoutEnd > DateTimeOffset.UtcNow)
{
RaiseAccountLockedEvent(userId);
}
else
{
RaiseAccountUnlockedEvent(userId);
//Resets the login attempt fails back to 0 when unlock is clicked
await ResetAccessFailedCountAsync(userId);
}
return result;
}
public override async Task<IdentityResult> ResetAccessFailedCountAsync(int userId)
{
var lockoutStore = (IUserLockoutStore<BackOfficeIdentityUser, int>)Store;
var user = await FindByIdAsync(userId);
if (user == null)
throw new InvalidOperationException("No user found by user id " + userId);
var accessFailedCount = await GetAccessFailedCountAsync(user.Id);
if (accessFailedCount == 0)
return IdentityResult.Success;
await lockoutStore.ResetAccessFailedCountAsync(user);
//raise the event now that it's reset
RaiseResetAccessFailedCountEvent(userId);
return await UpdateAsync(user);
}
/// <summary>
/// Overrides the Microsoft ASP.NET user management method
/// </summary>
/// <param name="userId"></param>
/// <returns>
/// returns a Async Task<IdentityResult>
/// </returns>
/// <remarks>
/// Doesn't set fail attempts back to 0
/// </remarks>
public override async Task<IdentityResult> AccessFailedAsync(int userId)
{
var lockoutStore = (IUserLockoutStore<BackOfficeIdentityUser, int>)Store;
var user = await FindByIdAsync(userId);
if (user == null)
throw new InvalidOperationException("No user found by user id " + userId);
var count = await lockoutStore.IncrementAccessFailedCountAsync(user);
if (count >= MaxFailedAccessAttemptsBeforeLockout)
{
await lockoutStore.SetLockoutEndDateAsync(user, DateTimeOffset.UtcNow.Add(DefaultAccountLockoutTimeSpan));
//NOTE: in normal aspnet identity this would do set the number of failed attempts back to 0
//here we are persisting the value for the back office
}
var result = await UpdateAsync(user);
//Slightly confusing: this will return a Success if we successfully update the AccessFailed count
if (result.Succeeded)
RaiseLoginFailedEvent(userId);
return result;
}
internal void RaiseAccountLockedEvent(int userId)
{
OnAccountLocked(new IdentityAuditEventArgs(AuditEvent.AccountLocked, GetCurrentRequestIpAddress(), affectedUser: userId));
}
internal void RaiseAccountUnlockedEvent(int userId)
{
OnAccountUnlocked(new IdentityAuditEventArgs(AuditEvent.AccountUnlocked, GetCurrentRequestIpAddress(), affectedUser: userId));
}
internal void RaiseForgotPasswordRequestedEvent(int userId)
{
OnForgotPasswordRequested(new IdentityAuditEventArgs(AuditEvent.ForgotPasswordRequested, GetCurrentRequestIpAddress(), affectedUser: userId));
}
internal void RaiseForgotPasswordChangedSuccessEvent(int userId)
{
OnForgotPasswordChangedSuccess(new IdentityAuditEventArgs(AuditEvent.ForgotPasswordChangedSuccess, GetCurrentRequestIpAddress(), affectedUser: userId));
}
internal void RaiseLoginFailedEvent(int userId)
{
OnLoginFailed(new IdentityAuditEventArgs(AuditEvent.LoginFailed, GetCurrentRequestIpAddress(), affectedUser: userId));
}
internal void RaiseInvalidLoginAttemptEvent(string username)
{
OnLoginFailed(new IdentityAuditEventArgs(AuditEvent.LoginFailed, GetCurrentRequestIpAddress(), username, string.Format("Attempted login for username '{0}' failed", username)));
}
internal void RaiseLoginRequiresVerificationEvent(int userId)
{
OnLoginRequiresVerification(new IdentityAuditEventArgs(AuditEvent.LoginRequiresVerification, GetCurrentRequestIpAddress(), affectedUser: userId));
}
internal void RaiseLoginSuccessEvent(int userId)
{
OnLoginSuccess(new IdentityAuditEventArgs(AuditEvent.LoginSucces, GetCurrentRequestIpAddress(), affectedUser: userId));
}
internal SignOutAuditEventArgs RaiseLogoutSuccessEvent(int userId)
{
var args = new SignOutAuditEventArgs(AuditEvent.LogoutSuccess, GetCurrentRequestIpAddress(), affectedUser: userId);
OnLogoutSuccess(args);
return args;
}
internal void RaisePasswordChangedEvent(int userId)
{
OnPasswordChanged(new IdentityAuditEventArgs(AuditEvent.PasswordChanged, GetCurrentRequestIpAddress(), affectedUser: userId));
}
// TODO: I don't think this is required anymore since from 7.7 we no longer display the reset password checkbox since that didn't make sense.
internal void RaisePasswordResetEvent(int userId)
{
OnPasswordReset(new IdentityAuditEventArgs(AuditEvent.PasswordReset, GetCurrentRequestIpAddress(), affectedUser: userId));
}
internal void RaiseResetAccessFailedCountEvent(int userId)
{
OnResetAccessFailedCount(new IdentityAuditEventArgs(AuditEvent.ResetAccessFailedCount, GetCurrentRequestIpAddress(), affectedUser: userId));
}
internal void RaiseSendingUserInvite(UserInviteEventArgs args) => OnSendingUserInvite(args);
internal bool HasSendingUserInviteEventHandler => SendingUserInvite != null;
// TODO: Not sure why these are not strongly typed events?? They should be in netcore!
public static event EventHandler AccountLocked;
public static event EventHandler AccountUnlocked;
public static event EventHandler ForgotPasswordRequested;
public static event EventHandler ForgotPasswordChangedSuccess;
public static event EventHandler LoginFailed;
public static event EventHandler LoginRequiresVerification;
public static event EventHandler LoginSuccess;
public static event EventHandler LogoutSuccess;
public static event EventHandler PasswordChanged;
public static event EventHandler PasswordReset;
public static event EventHandler ResetAccessFailedCount;
/// <summary>
/// Raised when a user is invited
/// </summary>
public static event EventHandler SendingUserInvite; // this event really has nothing to do with the user manager but was the most convenient place to put it
protected virtual void OnSendingUserInvite(UserInviteEventArgs e) => SendingUserInvite?.Invoke(this, e);
protected virtual void OnAccountLocked(IdentityAuditEventArgs e) => AccountLocked?.Invoke(this, e);
protected virtual void OnAccountUnlocked(IdentityAuditEventArgs e) => AccountUnlocked?.Invoke(this, e);
protected virtual void OnForgotPasswordRequested(IdentityAuditEventArgs e) => ForgotPasswordRequested?.Invoke(this, e);
protected virtual void OnForgotPasswordChangedSuccess(IdentityAuditEventArgs e) => ForgotPasswordChangedSuccess?.Invoke(this, e);
protected virtual void OnLoginFailed(IdentityAuditEventArgs e) => LoginFailed?.Invoke(this, e);
protected virtual void OnLoginRequiresVerification(IdentityAuditEventArgs e) => LoginRequiresVerification?.Invoke(this, e);
protected virtual void OnLoginSuccess(IdentityAuditEventArgs e) => LoginSuccess?.Invoke(this, e);
protected virtual void OnLogoutSuccess(IdentityAuditEventArgs e) => LogoutSuccess?.Invoke(this, e);
protected virtual void OnPasswordChanged(IdentityAuditEventArgs e) => PasswordChanged?.Invoke(this, e);
protected virtual void OnPasswordReset(IdentityAuditEventArgs e) => PasswordReset?.Invoke(this, e);
protected virtual void OnResetAccessFailedCount(IdentityAuditEventArgs e) => ResetAccessFailedCount?.Invoke(this, e);
/// <summary>
/// Returns the current request IP address for logging if there is one
/// </summary>
/// <returns></returns>
protected virtual string GetCurrentRequestIpAddress()
{
// TODO: inject a service to get this value, we should not be relying on the old HttpContext.Current especially in the ASP.NET Identity world.
var httpContext = HttpContext.Current == null ? (HttpContextBase)null : new HttpContextWrapper(HttpContext.Current);
return httpContext.GetCurrentRequestIpAddress();
}
}
}
| 44.870504 | 188 | 0.644348 | [
"MIT"
] | AlphaDelta/Umbraco-CMS | src/Umbraco.Web/Security/BackOfficeUserManager.cs | 31,187 | C# |
// -------------------------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License (MIT). See LICENSE in the repo root for license information.
// -------------------------------------------------------------------------------------------------
namespace Microsoft.Health.Abstractions.Exceptions
{
public class UnsupportedMediaTypeException : MicrosoftHealthException
{
public UnsupportedMediaTypeException(string message)
: base(message)
{
}
}
}
| 38.125 | 101 | 0.47377 | [
"MIT"
] | ECGKit/healthcare-shared-components | src/Microsoft.Health.Abstractions/Exceptions/UnsupportedMediaTypeException.cs | 612 | C# |
/* ====================================================================
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for Additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==================================================================== */
namespace TestCases.SS.UserModel
{
using System;
using NUnit.Framework;
using NPOI.SS;
using NPOI.SS.Util;
using TestCases.SS;
using NPOI.SS.UserModel;
/**
* Tests row Shifting capabilities.
*
* @author Shawn Laubach (slaubach at apache dot com)
* @author Toshiaki Kamoshida (kamoshida.Toshiaki at future dot co dot jp)
*/
[TestFixture]
public class BaseTestSheetShiftRows
{
private ITestDataProvider _testDataProvider;
public BaseTestSheetShiftRows()
{
_testDataProvider = TestCases.HSSF.HSSFITestDataProvider.Instance;
}
protected BaseTestSheetShiftRows(ITestDataProvider TestDataProvider)
{
_testDataProvider = TestDataProvider;
}
/**
* Tests the ShiftRows function. Does three different Shifts.
* After each Shift, Writes the workbook to file and Reads back to
* Check. This ensures that if some Changes code that breaks
* writing or what not, they realize it.
*
* @param sampleName the sample file to Test against
*/
[Test]
public void TestShiftRows()
{
// Read Initial file in
String sampleName = "SimpleMultiCell." + _testDataProvider.StandardFileNameExtension;
IWorkbook wb = _testDataProvider.OpenSampleWorkbook(sampleName);
ISheet s = wb.GetSheetAt(0);
// Shift the second row down 1 and write to temp file
s.ShiftRows(1, 1, 1);
{
Console.WriteLine("Shift the second row down 1");
var msg = string.Format("1a {0}-{1}-{2}-{3}-{4}-{5}", GetRowValue(s, 0), GetRowValue(s, 1), GetRowValue(s, 2), GetRowValue(s, 3), GetRowValue(s, 4), GetRowValue(s, 5));
Console.WriteLine(msg);
}
wb = _testDataProvider.WriteOutAndReadBack(wb);
// Read from temp file and check the number of cells in each
// row (in original file each row was unique)
s = wb.GetSheetAt(0);
{
var msg = string.Format("1b {0}-{1}-{2}-{3}-{4}-{5}", GetRowValue(s, 0), GetRowValue(s, 1), GetRowValue(s, 2), GetRowValue(s, 3), GetRowValue(s, 4), GetRowValue(s, 5));
Console.WriteLine(msg);
}
Assert.AreEqual(s.GetRow(0).PhysicalNumberOfCells, 1);
ConfirmEmptyRow(s, 1);
Assert.AreEqual(s.GetRow(2).PhysicalNumberOfCells, 2);
Assert.AreEqual(s.GetRow(3).PhysicalNumberOfCells, 4);
Assert.AreEqual(s.GetRow(4).PhysicalNumberOfCells, 5);
// Shift rows 1-3 down 3 in the current one. This Tests when
// 1 row is blank. Write to a another temp file
s.ShiftRows(0, 2, 3);
{
Console.WriteLine("Shift rows 1-3 down 3 in the current one");
var msg = string.Format("2a {0}-{1}-{2}-{3}-{4}-{5}", GetRowValue(s, 0), GetRowValue(s, 1), GetRowValue(s, 2), GetRowValue(s, 3), GetRowValue(s, 4), GetRowValue(s, 5));
Console.WriteLine(msg);
}
wb = _testDataProvider.WriteOutAndReadBack(wb);
// Read and ensure things are where they should be
s = wb.GetSheetAt(0);
{
var msg = string.Format("2b {0}-{1}-{2}-{3}-{4}-{5}", GetRowValue(s, 0), GetRowValue(s, 1), GetRowValue(s, 2), GetRowValue(s, 3), GetRowValue(s, 4), GetRowValue(s, 5));
Console.WriteLine(msg);
}
ConfirmEmptyRow(s, 0);
ConfirmEmptyRow(s, 1);
ConfirmEmptyRow(s, 2);
Assert.AreEqual(s.GetRow(3).PhysicalNumberOfCells, 1);
ConfirmEmptyRow(s, 4);
Assert.AreEqual(s.GetRow(5).PhysicalNumberOfCells, 2);
// Read the first file again
wb = _testDataProvider.OpenSampleWorkbook(sampleName);
s = wb.GetSheetAt(0);
// Shift rows 3 and 4 up and write to temp file
s.ShiftRows(2, 3, -2);
{
Console.WriteLine("Shift rows 3 and 4 up");
var msg = string.Format("3a {0}-{1}-{2}-{3}-{4}-{5}", GetRowValue(s, 0), GetRowValue(s, 1), GetRowValue(s, 2), GetRowValue(s, 3), GetRowValue(s, 4), GetRowValue(s, 5));
Console.WriteLine(msg);
}
wb = _testDataProvider.WriteOutAndReadBack(wb);
s = wb.GetSheetAt(0);
{
var msg = string.Format("3b {0}-{1}-{2}-{3}-{4}-{5}", GetRowValue(s, 0), GetRowValue(s, 1), GetRowValue(s, 2), GetRowValue(s, 3), GetRowValue(s, 4), GetRowValue(s, 5));
Console.WriteLine(msg);
}
Assert.AreEqual(s.GetRow(0).PhysicalNumberOfCells, 3);
Assert.AreEqual(s.GetRow(1).PhysicalNumberOfCells, 4);
ConfirmEmptyRow(s, 2);
ConfirmEmptyRow(s, 3);
Assert.AreEqual(s.GetRow(4).PhysicalNumberOfCells, 5);
}
private static string GetRowValue(ISheet s, int rowIx)
{
IRow row = s.GetRow(rowIx);
if (row == null) { return "null"; }
return row.PhysicalNumberOfCells .ToString();
}
private static string GetRowNum(ISheet s, int rowIx)
{
IRow row = s.GetRow(rowIx);
if (row == null) { return "null"; }
return row.RowNum.ToString();
}
private static void ConfirmEmptyRow(ISheet s, int rowIx)
{
IRow row = s.GetRow(rowIx);
Assert.IsTrue(row == null || row.PhysicalNumberOfCells == 0);
}
/**
* Tests when rows are null.
*/
[Test]
public void TestShiftRow()
{
IWorkbook b = _testDataProvider.CreateWorkbook();
ISheet s = b.CreateSheet();
s.CreateRow(0).CreateCell(0).SetCellValue("TEST1");
s.CreateRow(3).CreateCell(0).SetCellValue("TEST2");
s.ShiftRows(0, 4, 1);
}
/**
* Tests when Shifting the first row.
*/
[Test]
public void TestActiveCell()
{
IWorkbook b = _testDataProvider.CreateWorkbook();
ISheet s = b.CreateSheet();
s.CreateRow(0).CreateCell(0).SetCellValue("TEST1");
s.CreateRow(3).CreateCell(0).SetCellValue("TEST2");
s.ShiftRows(0, 4, 1);
}
/**
* When Shifting rows, the page breaks should go with it
*/
[Test]
public void TestShiftRowBreaks()
{ // TODO - enable XSSF Test
IWorkbook b = _testDataProvider.CreateWorkbook();
ISheet s = b.CreateSheet();
IRow row = s.CreateRow(4);
row.CreateCell(0).SetCellValue("test");
s.SetRowBreak(4);
s.ShiftRows(4, 4, 2);
Assert.IsTrue(s.IsRowBroken(6), "Row number 6 should have a pagebreak");
}
[Test]
public void TestShiftWithComments()
{ // TODO - enable XSSF Test
IWorkbook wb = _testDataProvider.OpenSampleWorkbook("comments." + _testDataProvider.StandardFileNameExtension);
ISheet sheet = wb.GetSheet("Sheet1");
Assert.AreEqual(3, sheet.LastRowNum);
// Verify comments are in the position expected
Assert.IsNotNull(sheet.GetCellComment(0, 0));
Assert.IsNull(sheet.GetCellComment(1, 0));
Assert.IsNotNull(sheet.GetCellComment(2, 0));
Assert.IsNotNull(sheet.GetCellComment(3, 0));
String comment1 = sheet.GetCellComment(0, 0).String.String;
Assert.AreEqual(comment1, "comment top row1 (index0)\n");
String comment3 = sheet.GetCellComment(2, 0).String.String;
Assert.AreEqual(comment3, "comment top row3 (index2)\n");
String comment4 = sheet.GetCellComment(3, 0).String.String;
Assert.AreEqual(comment4, "comment top row4 (index3)\n");
// Shifting all but first line down to Test comments Shifting
sheet.ShiftRows(1, sheet.LastRowNum, 1, true, true);
// Test that comments were Shifted as expected
Assert.AreEqual(4, sheet.LastRowNum);
Assert.IsNotNull(sheet.GetCellComment(0, 0));
Assert.IsNull(sheet.GetCellComment(1, 0));
Assert.IsNull(sheet.GetCellComment(2, 0));
Assert.IsNotNull(sheet.GetCellComment(3, 0));
Assert.IsNotNull(sheet.GetCellComment(4, 0));
String comment1_Shifted = sheet.GetCellComment(0, 0).String.String;
Assert.AreEqual(comment1, comment1_Shifted);
String comment3_Shifted = sheet.GetCellComment(3, 0).String.String;
Assert.AreEqual(comment3, comment3_Shifted);
String comment4_Shifted = sheet.GetCellComment(4, 0).String.String;
Assert.AreEqual(comment4, comment4_Shifted);
// Write out and read back in again
// Ensure that the Changes were persisted
wb = _testDataProvider.WriteOutAndReadBack(wb);
sheet = wb.GetSheet("Sheet1");
Assert.AreEqual(4, sheet.LastRowNum);
// Verify comments are in the position expected After the shift
Assert.IsNotNull(sheet.GetCellComment(0, 0));
Assert.IsNull(sheet.GetCellComment(1, 0));
Assert.IsNull(sheet.GetCellComment(2, 0));
Assert.IsNotNull(sheet.GetCellComment(3, 0));
Assert.IsNotNull(sheet.GetCellComment(4, 0));
comment1_Shifted = sheet.GetCellComment(0, 0).String.String;
Assert.AreEqual(comment1, comment1_Shifted);
comment3_Shifted = sheet.GetCellComment(3, 0).String.String;
Assert.AreEqual(comment3, comment3_Shifted);
comment4_Shifted = sheet.GetCellComment(4, 0).String.String;
Assert.AreEqual(comment4, comment4_Shifted);
}
[Test]
public void TestShiftWithNames()
{
IWorkbook wb = _testDataProvider.CreateWorkbook();
ISheet sheet1 = wb.CreateSheet("Sheet1");
wb.CreateSheet("Sheet2");
IRow row = sheet1.CreateRow(0);
row.CreateCell(0).SetCellValue(1.1);
row.CreateCell(1).SetCellValue(2.2);
IName name1 = wb.CreateName();
name1.NameName = (/*setter*/"name1");
name1.RefersToFormula = (/*setter*/"Sheet1!$A$1+Sheet1!$B$1");
IName name2 = wb.CreateName();
name2.NameName = (/*setter*/"name2");
name2.RefersToFormula = (/*setter*/"Sheet1!$A$1");
//refers to A1 but on Sheet2. Should stay unaffected.
IName name3 = wb.CreateName();
name3.NameName = (/*setter*/"name3");
name3.RefersToFormula = (/*setter*/"Sheet2!$A$1");
//The scope of this one is Sheet2. Should stay unaffected.
IName name4 = wb.CreateName();
name4.NameName = (/*setter*/"name4");
name4.RefersToFormula = (/*setter*/"A1");
name4.SheetIndex = (/*setter*/1);
sheet1.ShiftRows(0, 1, 2); //shift down the top row on Sheet1.
name1 = wb.GetNameAt(0);
Assert.AreEqual("Sheet1!$A$3+Sheet1!$B$3", name1.RefersToFormula);
name2 = wb.GetNameAt(1);
Assert.AreEqual("Sheet1!$A$3", name2.RefersToFormula);
//name3 and name4 refer to Sheet2 and should not be affected
name3 = wb.GetNameAt(2);
Assert.AreEqual("Sheet2!$A$1", name3.RefersToFormula);
name4 = wb.GetNameAt(3);
Assert.AreEqual("A1", name4.RefersToFormula);
}
[Test]
public void TestShiftWithMergedRegions()
{
IWorkbook wb = _testDataProvider.CreateWorkbook();
ISheet sheet = wb.CreateSheet();
IRow row = sheet.CreateRow(0);
row.CreateCell(0).SetCellValue(1.1);
row.CreateCell(1).SetCellValue(2.2);
CellRangeAddress region = new CellRangeAddress(0, 0, 0, 2);
Assert.AreEqual("A1:C1", region.FormatAsString());
sheet.AddMergedRegion(region);
sheet.ShiftRows(0, 1, 2);
region = sheet.GetMergedRegion(0);
Assert.AreEqual("A3:C3", region.FormatAsString());
}
/**
* See bug #34023
*/
[Test]
public void TestShiftWithFormulas()
{
IWorkbook wb = _testDataProvider.OpenSampleWorkbook("ForShifting." + _testDataProvider.StandardFileNameExtension);
ISheet sheet = wb.GetSheet("Sheet1");
Assert.AreEqual(20, sheet.LastRowNum);
ConfirmRow(sheet, 0, 1, 171, 1, "ROW(D1)", "100+B1", "COUNT(D1:E1)");
ConfirmRow(sheet, 1, 2, 172, 1, "ROW(D2)", "100+B2", "COUNT(D2:E2)");
ConfirmRow(sheet, 2, 3, 173, 1, "ROW(D3)", "100+B3", "COUNT(D3:E3)");
ConfirmCell(sheet, 6, 1, 271, "200+B1");
ConfirmCell(sheet, 7, 1, 272, "200+B2");
ConfirmCell(sheet, 8, 1, 273, "200+B3");
ConfirmCell(sheet, 14, 0, 0.0, "A12"); // the cell referred to by this formula will be Replaced
// -----------
// Row index 1 -> 11 (row "2" -> row "12")
sheet.ShiftRows(1, 1, 10);
// Now check what sheet looks like After Move
// no Changes on row "1"
ConfirmRow(sheet, 0, 1, 171, 1, "ROW(D1)", "100+B1", "COUNT(D1:E1)");
// row "2" is now empty
ConfirmEmptyRow(sheet, 1);
// Row "2" Moved to row "12", and the formula has been updated.
// note however that the cached formula result (2) has not been updated. (POI differs from Excel here)
ConfirmRow(sheet, 11, 2, 172, 1, "ROW(D12)", "100+B12", "COUNT(D12:E12)");
// no Changes on row "3"
ConfirmRow(sheet, 2, 3, 173, 1, "ROW(D3)", "100+B3", "COUNT(D3:E3)");
ConfirmCell(sheet, 14, 0, 0.0, "#REF!");
// Formulas on rows that weren't Shifted:
ConfirmCell(sheet, 6, 1, 271, "200+B1");
ConfirmCell(sheet, 7, 1, 272, "200+B12"); // this one Moved
ConfirmCell(sheet, 8, 1, 273, "200+B3");
// check formulas on other sheets
ISheet sheet2 = wb.GetSheet("Sheet2");
ConfirmCell(sheet2, 0, 0, 371, "300+Sheet1!B1");
ConfirmCell(sheet2, 1, 0, 372, "300+Sheet1!B12");
ConfirmCell(sheet2, 2, 0, 373, "300+Sheet1!B3");
ConfirmCell(sheet2, 11, 0, 300, "300+Sheet1!#REF!");
// Note - named ranges formulas have not been updated
}
private static void ConfirmRow(ISheet sheet, int rowIx, double valA, double valB, double valC,
String formulaA, String formulaB, String formulaC)
{
ConfirmCell(sheet, rowIx, 4, valA, formulaA);
ConfirmCell(sheet, rowIx, 5, valB, formulaB);
ConfirmCell(sheet, rowIx, 6, valC, formulaC);
}
private static void ConfirmCell(ISheet sheet, int rowIx, int colIx,
double expectedValue, String expectedFormula)
{
ICell cell = sheet.GetRow(rowIx).GetCell(colIx);
Assert.AreEqual(expectedValue, cell.NumericCellValue, 0.0);
Assert.AreEqual(expectedFormula, cell.CellFormula);
}
}
}
| 42.890585 | 185 | 0.556953 | [
"Apache-2.0"
] | sunshinele/npoi | testcases/main/SS/UserModel/BaseTestSheetShiftRows.cs | 16,856 | C# |
// This file is part of Silk.NET.
//
// You may modify and distribute Silk.NET under the terms
// of the MIT license. See the LICENSE file for details.
using System;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
using System.Text;
using Silk.NET.Core;
using Silk.NET.Core.Native;
using Silk.NET.Core.Attributes;
using Silk.NET.Core.Contexts;
using Silk.NET.Core.Loader;
#pragma warning disable 1591
namespace Silk.NET.OpenGL.Legacy.Extensions.ARB
{
public static class ArbTextureCompressionOverloads
{
public static unsafe void CompressedTexImage1D<T0>(this ArbTextureCompression thisApi, [Flow(FlowDirection.In)] ARB target, [Flow(FlowDirection.In)] int level, [Flow(FlowDirection.In)] ARB internalformat, [Flow(FlowDirection.In)] uint width, [Flow(FlowDirection.In)] int border, [Flow(FlowDirection.In)] uint imageSize, [Count(Parameter = "imageSize"), Flow(FlowDirection.In)] ReadOnlySpan<T0> data) where T0 : unmanaged
{
// SpanOverloader
thisApi.CompressedTexImage1D(target, level, internalformat, width, border, imageSize, in data.GetPinnableReference());
}
public static unsafe void CompressedTexImage1D<T0>(this ArbTextureCompression thisApi, [Flow(FlowDirection.In)] ARB target, [Flow(FlowDirection.In)] int level, [Flow(FlowDirection.In)] InternalFormat internalformat, [Flow(FlowDirection.In)] uint width, [Flow(FlowDirection.In)] int border, [Flow(FlowDirection.In)] uint imageSize, [Count(Parameter = "imageSize"), Flow(FlowDirection.In)] ReadOnlySpan<T0> data) where T0 : unmanaged
{
// SpanOverloader
thisApi.CompressedTexImage1D(target, level, internalformat, width, border, imageSize, in data.GetPinnableReference());
}
public static unsafe void CompressedTexImage1D<T0>(this ArbTextureCompression thisApi, [Flow(FlowDirection.In)] TextureTarget target, [Flow(FlowDirection.In)] int level, [Flow(FlowDirection.In)] ARB internalformat, [Flow(FlowDirection.In)] uint width, [Flow(FlowDirection.In)] int border, [Flow(FlowDirection.In)] uint imageSize, [Count(Parameter = "imageSize"), Flow(FlowDirection.In)] ReadOnlySpan<T0> data) where T0 : unmanaged
{
// SpanOverloader
thisApi.CompressedTexImage1D(target, level, internalformat, width, border, imageSize, in data.GetPinnableReference());
}
public static unsafe void CompressedTexImage1D<T0>(this ArbTextureCompression thisApi, [Flow(FlowDirection.In)] TextureTarget target, [Flow(FlowDirection.In)] int level, [Flow(FlowDirection.In)] InternalFormat internalformat, [Flow(FlowDirection.In)] uint width, [Flow(FlowDirection.In)] int border, [Flow(FlowDirection.In)] uint imageSize, [Count(Parameter = "imageSize"), Flow(FlowDirection.In)] ReadOnlySpan<T0> data) where T0 : unmanaged
{
// SpanOverloader
thisApi.CompressedTexImage1D(target, level, internalformat, width, border, imageSize, in data.GetPinnableReference());
}
public static unsafe void CompressedTexImage2D<T0>(this ArbTextureCompression thisApi, [Flow(FlowDirection.In)] ARB target, [Flow(FlowDirection.In)] int level, [Flow(FlowDirection.In)] ARB internalformat, [Flow(FlowDirection.In)] uint width, [Flow(FlowDirection.In)] uint height, [Flow(FlowDirection.In)] int border, [Flow(FlowDirection.In)] uint imageSize, [Count(Parameter = "imageSize"), Flow(FlowDirection.In)] ReadOnlySpan<T0> data) where T0 : unmanaged
{
// SpanOverloader
thisApi.CompressedTexImage2D(target, level, internalformat, width, height, border, imageSize, in data.GetPinnableReference());
}
public static unsafe void CompressedTexImage2D<T0>(this ArbTextureCompression thisApi, [Flow(FlowDirection.In)] ARB target, [Flow(FlowDirection.In)] int level, [Flow(FlowDirection.In)] InternalFormat internalformat, [Flow(FlowDirection.In)] uint width, [Flow(FlowDirection.In)] uint height, [Flow(FlowDirection.In)] int border, [Flow(FlowDirection.In)] uint imageSize, [Count(Parameter = "imageSize"), Flow(FlowDirection.In)] ReadOnlySpan<T0> data) where T0 : unmanaged
{
// SpanOverloader
thisApi.CompressedTexImage2D(target, level, internalformat, width, height, border, imageSize, in data.GetPinnableReference());
}
public static unsafe void CompressedTexImage2D<T0>(this ArbTextureCompression thisApi, [Flow(FlowDirection.In)] TextureTarget target, [Flow(FlowDirection.In)] int level, [Flow(FlowDirection.In)] ARB internalformat, [Flow(FlowDirection.In)] uint width, [Flow(FlowDirection.In)] uint height, [Flow(FlowDirection.In)] int border, [Flow(FlowDirection.In)] uint imageSize, [Count(Parameter = "imageSize"), Flow(FlowDirection.In)] ReadOnlySpan<T0> data) where T0 : unmanaged
{
// SpanOverloader
thisApi.CompressedTexImage2D(target, level, internalformat, width, height, border, imageSize, in data.GetPinnableReference());
}
public static unsafe void CompressedTexImage2D<T0>(this ArbTextureCompression thisApi, [Flow(FlowDirection.In)] TextureTarget target, [Flow(FlowDirection.In)] int level, [Flow(FlowDirection.In)] InternalFormat internalformat, [Flow(FlowDirection.In)] uint width, [Flow(FlowDirection.In)] uint height, [Flow(FlowDirection.In)] int border, [Flow(FlowDirection.In)] uint imageSize, [Count(Parameter = "imageSize"), Flow(FlowDirection.In)] ReadOnlySpan<T0> data) where T0 : unmanaged
{
// SpanOverloader
thisApi.CompressedTexImage2D(target, level, internalformat, width, height, border, imageSize, in data.GetPinnableReference());
}
public static unsafe void CompressedTexImage3D<T0>(this ArbTextureCompression thisApi, [Flow(FlowDirection.In)] ARB target, [Flow(FlowDirection.In)] int level, [Flow(FlowDirection.In)] ARB internalformat, [Flow(FlowDirection.In)] uint width, [Flow(FlowDirection.In)] uint height, [Flow(FlowDirection.In)] uint depth, [Flow(FlowDirection.In)] int border, [Flow(FlowDirection.In)] uint imageSize, [Count(Parameter = "imageSize"), Flow(FlowDirection.In)] ReadOnlySpan<T0> data) where T0 : unmanaged
{
// SpanOverloader
thisApi.CompressedTexImage3D(target, level, internalformat, width, height, depth, border, imageSize, in data.GetPinnableReference());
}
public static unsafe void CompressedTexImage3D<T0>(this ArbTextureCompression thisApi, [Flow(FlowDirection.In)] ARB target, [Flow(FlowDirection.In)] int level, [Flow(FlowDirection.In)] InternalFormat internalformat, [Flow(FlowDirection.In)] uint width, [Flow(FlowDirection.In)] uint height, [Flow(FlowDirection.In)] uint depth, [Flow(FlowDirection.In)] int border, [Flow(FlowDirection.In)] uint imageSize, [Count(Parameter = "imageSize"), Flow(FlowDirection.In)] ReadOnlySpan<T0> data) where T0 : unmanaged
{
// SpanOverloader
thisApi.CompressedTexImage3D(target, level, internalformat, width, height, depth, border, imageSize, in data.GetPinnableReference());
}
public static unsafe void CompressedTexImage3D<T0>(this ArbTextureCompression thisApi, [Flow(FlowDirection.In)] TextureTarget target, [Flow(FlowDirection.In)] int level, [Flow(FlowDirection.In)] ARB internalformat, [Flow(FlowDirection.In)] uint width, [Flow(FlowDirection.In)] uint height, [Flow(FlowDirection.In)] uint depth, [Flow(FlowDirection.In)] int border, [Flow(FlowDirection.In)] uint imageSize, [Count(Parameter = "imageSize"), Flow(FlowDirection.In)] ReadOnlySpan<T0> data) where T0 : unmanaged
{
// SpanOverloader
thisApi.CompressedTexImage3D(target, level, internalformat, width, height, depth, border, imageSize, in data.GetPinnableReference());
}
public static unsafe void CompressedTexImage3D<T0>(this ArbTextureCompression thisApi, [Flow(FlowDirection.In)] TextureTarget target, [Flow(FlowDirection.In)] int level, [Flow(FlowDirection.In)] InternalFormat internalformat, [Flow(FlowDirection.In)] uint width, [Flow(FlowDirection.In)] uint height, [Flow(FlowDirection.In)] uint depth, [Flow(FlowDirection.In)] int border, [Flow(FlowDirection.In)] uint imageSize, [Count(Parameter = "imageSize"), Flow(FlowDirection.In)] ReadOnlySpan<T0> data) where T0 : unmanaged
{
// SpanOverloader
thisApi.CompressedTexImage3D(target, level, internalformat, width, height, depth, border, imageSize, in data.GetPinnableReference());
}
public static unsafe void CompressedTexSubImage1D<T0>(this ArbTextureCompression thisApi, [Flow(FlowDirection.In)] ARB target, [Flow(FlowDirection.In)] int level, [Flow(FlowDirection.In)] int xoffset, [Flow(FlowDirection.In)] uint width, [Flow(FlowDirection.In)] ARB format, [Flow(FlowDirection.In)] uint imageSize, [Count(Parameter = "imageSize"), Flow(FlowDirection.In)] ReadOnlySpan<T0> data) where T0 : unmanaged
{
// SpanOverloader
thisApi.CompressedTexSubImage1D(target, level, xoffset, width, format, imageSize, in data.GetPinnableReference());
}
public static unsafe void CompressedTexSubImage1D<T0>(this ArbTextureCompression thisApi, [Flow(FlowDirection.In)] ARB target, [Flow(FlowDirection.In)] int level, [Flow(FlowDirection.In)] int xoffset, [Flow(FlowDirection.In)] uint width, [Flow(FlowDirection.In)] PixelFormat format, [Flow(FlowDirection.In)] uint imageSize, [Count(Parameter = "imageSize"), Flow(FlowDirection.In)] ReadOnlySpan<T0> data) where T0 : unmanaged
{
// SpanOverloader
thisApi.CompressedTexSubImage1D(target, level, xoffset, width, format, imageSize, in data.GetPinnableReference());
}
public static unsafe void CompressedTexSubImage1D<T0>(this ArbTextureCompression thisApi, [Flow(FlowDirection.In)] TextureTarget target, [Flow(FlowDirection.In)] int level, [Flow(FlowDirection.In)] int xoffset, [Flow(FlowDirection.In)] uint width, [Flow(FlowDirection.In)] ARB format, [Flow(FlowDirection.In)] uint imageSize, [Count(Parameter = "imageSize"), Flow(FlowDirection.In)] ReadOnlySpan<T0> data) where T0 : unmanaged
{
// SpanOverloader
thisApi.CompressedTexSubImage1D(target, level, xoffset, width, format, imageSize, in data.GetPinnableReference());
}
public static unsafe void CompressedTexSubImage1D<T0>(this ArbTextureCompression thisApi, [Flow(FlowDirection.In)] TextureTarget target, [Flow(FlowDirection.In)] int level, [Flow(FlowDirection.In)] int xoffset, [Flow(FlowDirection.In)] uint width, [Flow(FlowDirection.In)] PixelFormat format, [Flow(FlowDirection.In)] uint imageSize, [Count(Parameter = "imageSize"), Flow(FlowDirection.In)] ReadOnlySpan<T0> data) where T0 : unmanaged
{
// SpanOverloader
thisApi.CompressedTexSubImage1D(target, level, xoffset, width, format, imageSize, in data.GetPinnableReference());
}
public static unsafe void CompressedTexSubImage2D<T0>(this ArbTextureCompression thisApi, [Flow(FlowDirection.In)] ARB target, [Flow(FlowDirection.In)] int level, [Flow(FlowDirection.In)] int xoffset, [Flow(FlowDirection.In)] int yoffset, [Flow(FlowDirection.In)] uint width, [Flow(FlowDirection.In)] uint height, [Flow(FlowDirection.In)] ARB format, [Flow(FlowDirection.In)] uint imageSize, [Count(Parameter = "imageSize"), Flow(FlowDirection.In)] ReadOnlySpan<T0> data) where T0 : unmanaged
{
// SpanOverloader
thisApi.CompressedTexSubImage2D(target, level, xoffset, yoffset, width, height, format, imageSize, in data.GetPinnableReference());
}
public static unsafe void CompressedTexSubImage2D<T0>(this ArbTextureCompression thisApi, [Flow(FlowDirection.In)] ARB target, [Flow(FlowDirection.In)] int level, [Flow(FlowDirection.In)] int xoffset, [Flow(FlowDirection.In)] int yoffset, [Flow(FlowDirection.In)] uint width, [Flow(FlowDirection.In)] uint height, [Flow(FlowDirection.In)] PixelFormat format, [Flow(FlowDirection.In)] uint imageSize, [Count(Parameter = "imageSize"), Flow(FlowDirection.In)] ReadOnlySpan<T0> data) where T0 : unmanaged
{
// SpanOverloader
thisApi.CompressedTexSubImage2D(target, level, xoffset, yoffset, width, height, format, imageSize, in data.GetPinnableReference());
}
public static unsafe void CompressedTexSubImage2D<T0>(this ArbTextureCompression thisApi, [Flow(FlowDirection.In)] TextureTarget target, [Flow(FlowDirection.In)] int level, [Flow(FlowDirection.In)] int xoffset, [Flow(FlowDirection.In)] int yoffset, [Flow(FlowDirection.In)] uint width, [Flow(FlowDirection.In)] uint height, [Flow(FlowDirection.In)] ARB format, [Flow(FlowDirection.In)] uint imageSize, [Count(Parameter = "imageSize"), Flow(FlowDirection.In)] ReadOnlySpan<T0> data) where T0 : unmanaged
{
// SpanOverloader
thisApi.CompressedTexSubImage2D(target, level, xoffset, yoffset, width, height, format, imageSize, in data.GetPinnableReference());
}
public static unsafe void CompressedTexSubImage2D<T0>(this ArbTextureCompression thisApi, [Flow(FlowDirection.In)] TextureTarget target, [Flow(FlowDirection.In)] int level, [Flow(FlowDirection.In)] int xoffset, [Flow(FlowDirection.In)] int yoffset, [Flow(FlowDirection.In)] uint width, [Flow(FlowDirection.In)] uint height, [Flow(FlowDirection.In)] PixelFormat format, [Flow(FlowDirection.In)] uint imageSize, [Count(Parameter = "imageSize"), Flow(FlowDirection.In)] ReadOnlySpan<T0> data) where T0 : unmanaged
{
// SpanOverloader
thisApi.CompressedTexSubImage2D(target, level, xoffset, yoffset, width, height, format, imageSize, in data.GetPinnableReference());
}
public static unsafe void CompressedTexSubImage3D<T0>(this ArbTextureCompression thisApi, [Flow(FlowDirection.In)] ARB target, [Flow(FlowDirection.In)] int level, [Flow(FlowDirection.In)] int xoffset, [Flow(FlowDirection.In)] int yoffset, [Flow(FlowDirection.In)] int zoffset, [Flow(FlowDirection.In)] uint width, [Flow(FlowDirection.In)] uint height, [Flow(FlowDirection.In)] uint depth, [Flow(FlowDirection.In)] ARB format, [Flow(FlowDirection.In)] uint imageSize, [Count(Parameter = "imageSize"), Flow(FlowDirection.In)] ReadOnlySpan<T0> data) where T0 : unmanaged
{
// SpanOverloader
thisApi.CompressedTexSubImage3D(target, level, xoffset, yoffset, zoffset, width, height, depth, format, imageSize, in data.GetPinnableReference());
}
public static unsafe void CompressedTexSubImage3D<T0>(this ArbTextureCompression thisApi, [Flow(FlowDirection.In)] ARB target, [Flow(FlowDirection.In)] int level, [Flow(FlowDirection.In)] int xoffset, [Flow(FlowDirection.In)] int yoffset, [Flow(FlowDirection.In)] int zoffset, [Flow(FlowDirection.In)] uint width, [Flow(FlowDirection.In)] uint height, [Flow(FlowDirection.In)] uint depth, [Flow(FlowDirection.In)] PixelFormat format, [Flow(FlowDirection.In)] uint imageSize, [Count(Parameter = "imageSize"), Flow(FlowDirection.In)] ReadOnlySpan<T0> data) where T0 : unmanaged
{
// SpanOverloader
thisApi.CompressedTexSubImage3D(target, level, xoffset, yoffset, zoffset, width, height, depth, format, imageSize, in data.GetPinnableReference());
}
public static unsafe void CompressedTexSubImage3D<T0>(this ArbTextureCompression thisApi, [Flow(FlowDirection.In)] TextureTarget target, [Flow(FlowDirection.In)] int level, [Flow(FlowDirection.In)] int xoffset, [Flow(FlowDirection.In)] int yoffset, [Flow(FlowDirection.In)] int zoffset, [Flow(FlowDirection.In)] uint width, [Flow(FlowDirection.In)] uint height, [Flow(FlowDirection.In)] uint depth, [Flow(FlowDirection.In)] ARB format, [Flow(FlowDirection.In)] uint imageSize, [Count(Parameter = "imageSize"), Flow(FlowDirection.In)] ReadOnlySpan<T0> data) where T0 : unmanaged
{
// SpanOverloader
thisApi.CompressedTexSubImage3D(target, level, xoffset, yoffset, zoffset, width, height, depth, format, imageSize, in data.GetPinnableReference());
}
public static unsafe void CompressedTexSubImage3D<T0>(this ArbTextureCompression thisApi, [Flow(FlowDirection.In)] TextureTarget target, [Flow(FlowDirection.In)] int level, [Flow(FlowDirection.In)] int xoffset, [Flow(FlowDirection.In)] int yoffset, [Flow(FlowDirection.In)] int zoffset, [Flow(FlowDirection.In)] uint width, [Flow(FlowDirection.In)] uint height, [Flow(FlowDirection.In)] uint depth, [Flow(FlowDirection.In)] PixelFormat format, [Flow(FlowDirection.In)] uint imageSize, [Count(Parameter = "imageSize"), Flow(FlowDirection.In)] ReadOnlySpan<T0> data) where T0 : unmanaged
{
// SpanOverloader
thisApi.CompressedTexSubImage3D(target, level, xoffset, yoffset, zoffset, width, height, depth, format, imageSize, in data.GetPinnableReference());
}
public static unsafe void GetCompressedTexImage<T0>(this ArbTextureCompression thisApi, [Flow(FlowDirection.In)] ARB target, [Flow(FlowDirection.In)] int level, [Count(Computed = "target, level"), Flow(FlowDirection.Out)] Span<T0> img) where T0 : unmanaged
{
// SpanOverloader
thisApi.GetCompressedTexImage(target, level, out img.GetPinnableReference());
}
public static unsafe void GetCompressedTexImage<T0>(this ArbTextureCompression thisApi, [Flow(FlowDirection.In)] TextureTarget target, [Flow(FlowDirection.In)] int level, [Count(Computed = "target, level"), Flow(FlowDirection.Out)] Span<T0> img) where T0 : unmanaged
{
// SpanOverloader
thisApi.GetCompressedTexImage(target, level, out img.GetPinnableReference());
}
}
}
| 99.05 | 593 | 0.730327 | [
"MIT"
] | ThomasMiz/Silk.NET | src/OpenGL/Extensions/Silk.NET.OpenGL.Legacy.Extensions.ARB/ArbTextureCompressionOverloads.gen.cs | 17,829 | C# |
using System;
using System.IO;
using Hacknet;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Pathfinder.Util;
namespace Pathfinder.Mission
{
public static class MissionManager
{
public static MissionListingServer CreateMissionListingDaemon(this Computer c,
string serviceName,
string logoPath = null,
bool isPublic = false,
bool isAssigner = false,
OS os = null)
{
var s = new MissionListingServer(c, serviceName, serviceName, os ?? Utility.ClientOS, isPublic, isAssigner);
if(!string.IsNullOrEmpty(logoPath))
try
{
using (var fs = File.OpenRead(logoPath))
s.logo = Texture2D.FromStream(GuiData.spriteBatch.GraphicsDevice, fs);
}
catch (Exception e)
{
Logger.Error("Loading file {0} failed: {1}", logoPath, e);
s.logo = os.content.Load<Texture2D>("Sprites/Academic_Logo");
}
else s.logo = os.content.Load<Texture2D>("Sprites/Academic_Logo");
c.daemons.Add(s);
return s;
}
public static MissionListingServer SetThemeColor(this MissionListingServer s, Color color)
{
s.themeColor = color;
return s;
}
public static MissionListingServer SetGroupName(this MissionListingServer s, string name)
{
s.groupName = name;
return s;
}
public static MissionListingServer SetListingTitle(this MissionListingServer s, string title)
{
s.listingTitle = title;
return s;
}
public static MissionListingServer SetState(this MissionListingServer s, int state)
{
s.state = state;
return s;
}
public static MissionListingServer AddMission(this MissionListingServer s, ActiveMission m, bool injectTop = false)
{
s.addMisison(m, injectTop);
var inst = m as Instance;
if (inst != null)
inst.MissionComputer = s.comp;
return s;
}
public static MissionHubServer CreateMissionHubDaemon(this Computer c, string serviceName, OS os = null)
{
var s = new MissionHubServer(c, serviceName, serviceName, os ?? Utility.ClientOS);
c.daemons.Add(s);
return s;
}
public static MissionHubServer SetThemeColor(this MissionHubServer s, Color color)
{
s.themeColor = color;
return s;
}
public static MissionHubServer SetGroupName(this MissionHubServer s, string name)
{
s.groupName = name;
return s;
}
public static MissionHubServer AddMission(this MissionHubServer s, ActiveMission m, bool insertTop = false, bool preventRegistryChange = false, int desiredIndex = -1)
{
if (insertTop && desiredIndex <= -1)
{
desiredIndex = 0;
}
s.contractRegistryNumber += Utils.getRandomByte() + 1;
s.listingMissions.Add(string.Concat(s.contractRegistryNumber), m);
var item = new FileEntry(MissionSerializer.generateMissionFile(m, s.contractRegistryNumber, s.groupName), "Contract#" + s.contractRegistryNumber);
if (insertTop || desiredIndex >= 0)
s.listingsFolder.files.Insert(desiredIndex, item);
else
s.listingsFolder.files.Add(item);
var inst = m as Instance;
if (inst != null)
inst.MissionComputer = s.comp;
return s;
}
}
}
| 38.907407 | 175 | 0.519515 | [
"MIT"
] | BlackDragonCZ/Hacknet-Pathfinder | Pathfinder/Mission/MissionManager.cs | 4,204 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Globalization;
using System.Reflection;
using Microsoft.Internal;
namespace System.Composition
{
internal static class ExceptionBuilder
{
public static ArgumentException Argument_ExpressionMustBeNew(string parameterName)
{
return CreateArgumentException(Strings.Argument_ExpressionMustBeNew, parameterName);
}
public static ArgumentException Argument_ExpressionMustBePropertyMember(string parameterName)
{
return CreateArgumentException(Strings.Argument_ExpressionMustBePropertyMember, parameterName);
}
public static ArgumentException Argument_ExpressionMustBeVoidMethodWithNoArguments(string methodName)
{
return CreateArgumentException(Strings.Argument_ExpressionMustBeVoidMethodWithNoArguments, methodName);
}
private static ArgumentException CreateArgumentException(string message, string parameterName)
{
Assumes.NotNull(parameterName);
return new ArgumentException(Format(message, parameterName), parameterName);
}
private static string Format(string format, params string[] arguments)
{
return String.Format(CultureInfo.CurrentCulture, format, arguments);
}
}
}
| 34.386364 | 115 | 0.731659 | [
"MIT"
] | Acidburn0zzz/corefx | src/System.Composition.Convention/src/System/Composition/ExceptionBuilder.cs | 1,513 | C# |
namespace HL7Data.Contracts.Messages.AdmitDischargeTransferMessages
{
//ADT_A05
public interface IPreAdmitPatient : IBaseAdmitDischargeTransferMessage
{
}
} | 24.571429 | 74 | 0.784884 | [
"MIT"
] | amenkes/HL7Parser | Contracts/Messages/AdmitDischargeTransferMessages/IPreAdmitPatient.cs | 172 | C# |
using System;
namespace PS.Data.Parser
{
public interface IToken : IEquatable<IToken>
{
}
} | 13.125 | 48 | 0.657143 | [
"MIT"
] | BlackGad/PS | PS.Core/Data/Parser/IToken.cs | 107 | C# |
/*
* This file is subject to the terms and conditions defined in
* file 'license.txt', which is part of this source code package.
*/
using SteamKit2.Internal;
namespace SteamKit2
{
public partial class SteamUserStats
{
/// <summary>
/// This callback is fired in response to <see cref="GetNumberOfCurrentPlayers" />.
/// </summary>
public class NumberOfPlayersCallback : CallbackMsg
{
/// <summary>
/// Gets the result of the request.
/// </summary>
public EResult Result { get; private set; }
/// <summary>
/// Gets the current number of players according to Steam.
/// </summary>
public uint NumPlayers { get; private set; }
internal NumberOfPlayersCallback( MsgClientGetNumberOfCurrentPlayersResponse resp )
{
this.Result = resp.Result;
this.NumPlayers = resp.NumPlayers;
}
}
}
}
| 27.486486 | 95 | 0.569322 | [
"MIT"
] | kaevne/SteamBotDota | Lib/SteamKit2/SteamKit2/Steam3/Handlers/SteamUserStats/Callbacks.cs | 1,019 | C# |
using System;
using System.Collections.Concurrent;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using SimpleSoft.Mediator.Example.Cmd.Events;
namespace SimpleSoft.Mediator.Example.Cmd.Commands
{
public class CreateUserCommandHandler : ICommandHandler<CreateUserCommand, Guid>
{
private readonly ConcurrentDictionary<string, User> _store;
private readonly IMediator _mediator;
private readonly ILogger<CreateUserCommandHandler> _logger;
public CreateUserCommandHandler(
ConcurrentDictionary<string, User> store,
IMediator mediator,
ILogger<CreateUserCommandHandler> logger)
{
_store = store;
_mediator = mediator;
_logger = logger;
}
public async Task<Guid> HandleAsync(CreateUserCommand cmd, CancellationToken ct)
{
var email = cmd.Email.Trim().ToLowerInvariant();
using (_logger.BeginScope("Email:'{email}'", email))
{
_logger.LogDebug("Creating user");
var user = new User
{
Id = Guid.NewGuid(),
Email = email,
Name = cmd.Name
};
if (_store.TryAdd(email, user))
{
await _mediator.BroadcastAsync(new UserCreatedEvent(user.Id), ct);
return user.Id;
}
throw new InvalidOperationException($"Duplicated email '{email}'");
}
}
}
} | 31.588235 | 88 | 0.577902 | [
"MIT"
] | JTOne123/Mediator | work/SimpleSoft.Mediator.Example.Cmd/Commands/CreateUserCommandHandler.cs | 1,611 | C# |
using System.Collections.Generic;
using System.Web;
namespace XRepository {
using IRecord = IDictionary<string, object>;
public abstract class Interceptor {
protected internal HttpContextBase HttpContext { get; set; }
public virtual bool IsMatch(IEnumerable<string> tableNames) { return true; }
public virtual void InterceptCount(IEnumerable<string> tableNames, IEnumerable<Criterion> criteria) {}
public virtual void InterceptFind(IEnumerable<string> tableNames, IEnumerable<Criterion> criteria) {}
public virtual void InterceptFindComplete(IEnumerable<string> tableNames, IEnumerable<IRecord> records) {}
public virtual void InterceptRemove(IRecord record) {}
public virtual void InterceptSave(IRecord record) {}
public Executor Executor { get; internal set; }
} // end class
} // end namespace | 43.9 | 114 | 0.732346 | [
"MIT"
] | xanotech/.net-XRepository | Interceptor.cs | 880 | C# |
namespace Carter.Tests.StreamTests
{
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.TestHost;
using Xunit;
public class ResponseFromStreamTests
{
public ResponseFromStreamTests()
{
this.server = new TestServer(
new WebHostBuilder()
.ConfigureServices(x => { x.AddCarter(configurator: c => c.WithModule<StreamModule>()); })
.Configure(x =>
{
x.UseRouting();
x.UseEndpoints(builder => builder.MapCarter());
}));
this.httpClient = this.server.CreateClient();
}
private readonly TestServer server;
private readonly HttpClient httpClient;
[Theory]
[InlineData("0-2", "0-2", "012")]
[InlineData("2-4", "2-4", "234")]
[InlineData("4-6", "4-6", "456")]
[InlineData("0-", "0-9", "0123456789")]
public async Task Should_return_range(string range, string expectedRange, string expectedBody)
{
//Given & When
this.httpClient.DefaultRequestHeaders.Range = RangeHeaderValue.Parse($"bytes={range}");
var response = await this.httpClient.GetAsync("/downloadrange");
var body = await response.Content.ReadAsStringAsync();
//Then
Assert.Equal(expectedBody, body);
Assert.Equal(HttpStatusCode.PartialContent, response.StatusCode);
Assert.Equal($"bytes {expectedRange}/10", response.Content.Headers.ContentRange.ToString());
}
[Theory]
[InlineData("-1")]
[InlineData("0-9999999999")]
public async Task Should_return_requested_range_not_satisfiable(string range)
{
//Given & When
this.httpClient.DefaultRequestHeaders.Range = RangeHeaderValue.Parse($"bytes={range}");
var response = await this.httpClient.GetAsync("/downloadrange");
//Then
Assert.Equal(HttpStatusCode.RequestedRangeNotSatisfiable, response.StatusCode);
}
[Theory]
[InlineData("3-1")]
[InlineData("1+2")]
public async Task Should_return_full_stream_on_invalid_headers(string range)
{
//Given
this.httpClient.DefaultRequestHeaders.TryAddWithoutValidation("Range", $"bytes={range}");
//When
var response = await this.httpClient.GetAsync("/downloadrange");
var body = await response.Content.ReadAsStringAsync();
//Then
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
Assert.Equal("0123456789", body);
}
[Fact]
public async Task Should_not_set_content_disposition_header_by_default()
{
//Given & When
var response = await this.httpClient.GetAsync("/download");
var body = await response.Content.ReadAsStringAsync();
//Then
Assert.Null(response.Content.Headers.ContentDisposition);
Assert.Equal("application/csv", response.Content.Headers.ContentType.MediaType);
Assert.Equal("hi", body);
Assert.Equal("bytes", response.Headers.AcceptRanges.FirstOrDefault());
}
[Fact]
public async Task Should_set_content_type_body_acceptrange_header_content_disposition()
{
//Given & When
var response = await this.httpClient.GetAsync("/downloadwithcd");
var body = await response.Content.ReadAsStringAsync();
var filename = response.Content.Headers.ContentDisposition.FileName;
//Then
Assert.Equal("application/csv", response.Content.Headers.ContentType.MediaType);
Assert.Equal("hi", body);
Assert.Equal("bytes", response.Headers.AcceptRanges.FirstOrDefault());
Assert.Equal("journal.csv", filename);
}
}
}
| 37.196429 | 110 | 0.602736 | [
"MIT"
] | CarterCommunity/Carter | test/Carter.Tests/StreamTests/ResponseFromStreamTests.cs | 4,168 | C# |
namespace SulsApp
{
using SIS.MvcFramework;
using System.Threading.Tasks;
public static class Program
{
public static async Task Main()
{
await WebHost.StartAsync(new Startup());
}
}
}
| 17.357143 | 52 | 0.584362 | [
"MIT"
] | yotkoKanchev/csharp-web | 2020-Jan-Season/SoftUni-Information-Services/SIS/SulsApp/Program.cs | 245 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Nucleo.Web;
namespace Nucleo.Assertions.Controls
{
[TestClass]
public class ScriptComponentDescriptorConstraintTest
{
#region " Test Classes "
protected class TestControl : BaseAjaxControl
{
protected override void GetAjaxScriptDescriptors(IContentRegistrar registrar)
{
registrar.AddDescriptor(new ScriptDescriptionRequestDetails(this, typeof(TestControl), this.ID));
}
}
protected class TestExtender : BaseAjaxExtender
{
protected override void GetAjaxScriptDescriptors(IContentRegistrar registrar, System.Web.UI.Control targetControl)
{
registrar.AddDescriptor(new ScriptDescriptionRequestDetails(this, typeof(TestControl), targetControl.ID));
}
}
#endregion
#region " Tests "
[Test]
public void MatchingControlsOnTypeWorksOK()
{
//Arrange
var control = new TestControl();
control.ID = "TestControl";
var constraint = new ScriptComponentDescriptorConstraint(control);
//Act
var registry = new ContentRegistrar();
((IAjaxScriptableComponent)control).GetAjaxScriptDescriptors(registry, control);
//Assert
Assert.IsTrue(constraint.Matches(registry), "Values in registry didn't match");
}
[Test]
public void MatchingExtendersOnTypeWorksOK()
{
//Arrange
var control = new System.Web.UI.WebControls.TextBox();
control.ID = "test";
var extender = new TestExtender();
extender.ID = "TestControl";
var constraint = new ScriptComponentDescriptorConstraint(extender);
//Act
var registry = new ContentRegistrar();
((IAjaxScriptableComponent)extender).GetAjaxScriptDescriptors(registry, control);
//Assert
Assert.IsTrue(constraint.Matches(registry), "Values in registry didn't match");
}
[Test]
public void SettingUpControlsTypeViaTypeClassWorksOK()
{
//Arrange
var control = new TestControl();
//Act
var constraint = new ScriptComponentDescriptorConstraint(control);
//Assert
Assert.AreEqual(control, constraint.Expected);
Assert.AreEqual(typeof(ScriptComponentDescriptorConstraintTest).FullName + "+TestControl", constraint.ExpectedTypeName);
}
[Test]
public void SettingUpControlsTypeViaTypeNameWorksOK()
{
//Arrange
var control = new TestControl();
//Act
var constraint = new ScriptComponentDescriptorConstraint(control, "Nucleo.Test");
//Assert
Assert.AreEqual(control, constraint.Expected);
Assert.AreEqual("Nucleo.Test", constraint.ExpectedTypeName);
}
[Test]
public void SettingUpExtendersTypeViaTypeClassWorksOK()
{
//Arrange
var extender = new TestExtender();
//Act
var constraint = new ScriptComponentDescriptorConstraint(extender);
//Assert
Assert.AreEqual(extender, constraint.Expected);
Assert.AreEqual(typeof(ScriptComponentDescriptorConstraintTest).FullName + "+TestExtender", constraint.ExpectedTypeName);
}
[Test]
public void SettingUpExtendersTypeViaTypeNameWorksOK()
{
//Arrange
var extender = new TestExtender();
//Act
var constraint = new ScriptComponentDescriptorConstraint(extender, "Nucleo.Test");
//Assert
Assert.AreEqual(extender, constraint.Expected);
Assert.AreEqual("Nucleo.Test", constraint.ExpectedTypeName);
}
#endregion
}
}
| 25.363636 | 124 | 0.744624 | [
"MIT"
] | brianmains/Nucleo.NET | src/Nucleo.UnitTests.40.MS/Assertions/Controls/ScriptComponentDescriptorConstraintTest.cs | 3,350 | C# |
// WaterSimDCDC Regional Water Demand and Supply Model Version 5.0
// This is the C# API wrapper for the C# interface to the Fortran Model.
// Version 9.2.3
// 3/15/14
// Based on Model_interface.cs version "03.16.13_1:45:00";
// Keeper: Ray Quay ray.quay@asu.edu
//
// Copyright (C) 2011,2012.2013 , The Arizona Board of Regents
// on behalf of Arizona State University
// All rights reserved.
// Developed by the Decision Center for a Desert City
// Lead Model Development - David A. Sampson <david.a.sampson@asu.edu>
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License version 3 as published by
// the Free Software Foundation.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, please see <http://www.gnu.org/licenses/>.
//
// NOTES
// 9.0.6 Fixed WebPop parameter bug
// 9.0.7 Fixed Regional Value Bug for Input Parameters
// 9.0.8 Fixed Stopyr bug, if set for one run and not set in next run, did not use default 2085 used value from previous run
//====================================================================================
using System;
using System.Collections.Generic;
using System.Text;
#if ExtendedParameter
using WaterSimDCDC.Documentation;
#endif
/**************************************************
* WaterSimDCDC_API
* Version 4.1
* 7/24/12
* Keeper Ray Quay
* ************************************************/
namespace WaterSimDCDC
{
public class WaterSimManagerClass : IDisposable
{
static protected bool _isWaterSimInstatiated = false; // used to keep track if a WAterSimManager object has been constructed
public WaterSimManagerClass()
{
// Some Basic Tests
if (_isWaterSimInstatiated) throw new WaterSim_Exception(WS_Strings.wsOnlyOneObject);
_isWaterSimInstatiated = true;
}
protected virtual void Dispose(bool disposing)
{
WaterSimManager._isWaterSimInstatiated = false;
if (disposing)
{
}
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
/// <summary>
/// Tests if a WaterSimManager Object can be instantiated
/// </summary>
/// <returns> Trur if new object can be instantiated, false of an object already exists</returns>
static public bool isReadyToInstantiate
{
get { return (!_isWaterSimInstatiated); }
}
}
/// <summary>
/// This is the root class for interface with the WaterSimManager model.
/// </summary>
public partial class WaterSimManager : WaterSimManagerClass
{
#region Fields_Constructor_Base_Methods
// General Internal Constants
const string _APIVersion = "9.3.1" ; // latest version of API
const int _defaultEndYear = 2001; // Used to Set Default Start Year
//
// private fields
string _TempDirectoryName;
string _DataDirectoryName;
int _StartYear = 0;
int _EndYear = 0; // used to keep track of start and end year for run routines Available for new classes should not be exposed as public
int _CurrentYear = 0; // used to keep track of years inside run routines
int _NumberOfYears = 0; // Used to keep track of the total years for simulation
bool _inRun = false; // used to keep track if runs have started
bool _simulationStarted = false; // used to keep track if Simulation has been initialized False means not yet or stopped
bool FModelLocked = false; // used to keep track if model is locked
string _ModelBuild = "";
string _TimeStamp = "";
public static bool _FortranOutput = false; // used to set Fortran debug mode
static bool FSuspendRangeCheck = false;
// KLUDGE FOR USE GPCD
int[] GPCDDefaults = new int[ProviderClass.NumberOfProviders];
int[] GPCDBuffer = new int[ProviderClass.NumberOfProviders];
// STORAGE FOR SET POPULATION
// **** Changed 8 13 12 int[] SetPopultaionsValues = new int[ProviderClass.NumberOfProviders];
int[] SetPopultaionsValuesOn = new int[ProviderClass.NumberOfProviders];
int[] SetPopultaionsValuesOther = new int[ProviderClass.NumberOfProviders];
// ****
//
// STORAGE FOR Wateraugmentation
// **** Added on 03.15.14
// DAS
int[] WaterAugmentationMemory = new int[ProviderClass.NumberOfProviders];
internal ParameterManagerClass _pm;
internal ProcessManager _ProcessManager;
internal ProcessRegistry _ProcessRegistry;
internal WaterSimU _ws; // this is the interface to fortran model
//----------------------------------------------------------------------------------------------------
// Constructor
/// <summary>
/// Constructor - Loads DLL (if not yet loaded) and initializes the model, only one instance of this class can be created. Will throw an exception if more than one is created
/// </summary>
/// <param name="TempDirectoryName">This is where the model places its output files, Creates a diectoy (TempDirectoryName) if it does not exist</param>
/// <param name="DataDirectoryName">Location of data</param>
/// <exception cref="WaterSim_Exception"> If an object has already been instantiated</exception>
/// <exception cref="WaterSim_Exception">if the data directory is invalid</exception>
/// <exception cref="WaterSim_Exception">Internal Error - If Model Parameters as not initialized properly </exception>
public WaterSimManager(string DataDirectoryName, string TempDirectoryName
) : base()
{
if (!TestDataDirectory(DataDirectoryName)) throw new WaterSim_Exception(WS_Strings.wsBadDataDirectory);
// Ok Get started with create
UniDB.FileSupport.CreateDirectory(TempDirectoryName);
// does not create if alread exists
_TempDirectoryName = TempDirectoryName;
_DataDirectoryName = DataDirectoryName;
// Instantiate WaterSimU
_ws = new WaterSimU(_DataDirectoryName, _TempDirectoryName, _FortranOutput);
// Get version
_ModelBuild = _ws.get_Build + " " + _ws.get_TestVersion;
_TimeStamp = _ws.get_TestVersion;
_ModelBuild = _ws.get_Build;
// Setup Parameter Manager and Model Paramters
// Create a ParameterManager
_pm = new ParameterManagerClass(APiVersion, _ModelBuild);
// Ok create Process Manager
_ProcessManager = new ProcessManager();
// OK create a Process Registry
_ProcessRegistry = new ProcessRegistry();
// Initialize all of the Model Parameters
initialize_ModelParameters();
// now test that they are all there
string TestMsg = "";
if (!testParmeters(ref TestMsg, false)) throw new WaterSim_Exception(WS_Strings.wsModelParameterMissing + " " + TestMsg);
// Add any parameter Processes
// Last thing before setup Call the GPCD Fix
GPCDFIX();
InitDefaultVariables(); // Sets Variables to Default Values
// Commented out
// Changed 5 15 12 DAS - added the next two lines to clean up output files [01.25.12]
//_ws.CloseFiles(); // the model runs to 2012 and then is re-set
//_ws.OpenFiles();
////
}
//----------------------------------------------------------------------------------------------------
// finalizer
/// <summary> Finaliser. </summary>
/// <remarks>Do not want finalizer disposing of orphaned WaterSim_model.dll stuff</remarks>
~WaterSimManager()
{
Dispose(false);
}
//------------------------------------------------------------------------------------------
/// <summary>
/// Called by Dispose() and ~WaterSimManager() Finalizer Prevents Finalizer from closing model files.
/// </summary>
/// <param name="disposing">Finalizer will call with a false</param>
protected override void Dispose(bool disposing)
{
if (disposing)
{
WaterSimManager._isWaterSimInstatiated = false;
// This is now done by WaterSimU class _ws.CloseFiles();
_ws.Dispose();
}
// Get rid of unmanged stuff, like dbConnections
base.Dispose(disposing);
}
//------------------------------------------------------------------------------------------
/// <summary>
/// Must be called before WaterSim object loses scope or is lost (reassigned).
/// </summary>
public new void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
/*****************************************************
* General Properties
*
* ***************************************************/
/// <summary>
/// Exposes to inherited classes for read only the private StartYear field (int) that tracks the Start Year during Simulation Runs
/// </summary>
protected int Sim_StartYear
{ get { return _StartYear; } }
// -------------------------------------------
/// <summary>
/// Exposes to inherited class for read only the private EndYear field (int) that tracks the End Year during Simulation Runs
/// </summary>
protected int Sim_EndYear
{ get { return _EndYear; } }
// -------------------------------------------
/// <summary>
/// Exposes to inherited class for read only the private CurrentYear field (int) that tracks the Current Year during Simulation Runs
/// </summary>
protected int Sim_CurrentYear
{ get { return _CurrentYear; } }
// -------------------------------------------
/// <summary>
/// Provides access to the Parameter Manager
/// </summary>
///<remarks> This object is used to manage the model parameters, <see cref="ParameterManagerClass"/></remarks>
/// <seealso cref="ParameterManagerClass"/>
/// <seealso cref="ModelParameterClass"/>
public ParameterManagerClass ParamManager { get { return _pm; } }
///-------------------------------------------------------------------------------------------------
/// <summary> If true, suspends Range checking for special range checks. </summary>
///
/// <value> true if suspend range check, false if not. </value>
///-------------------------------------------------------------------------------------------------
public bool Suspend100PctRangeCheck
{
get { return FSuspendRangeCheck; }
set { FSuspendRangeCheck = value; }
}
// -------------------------------------------
/// <summary>
/// Provides access to the Process Manager
/// </summary>
/// <remarks>The process manager manages the pre and post processes of yearly Simulations <see cref="ProcessManager"/></remarks>
/// <seealso cref="ProcessManager"/>
/// <seealso cref="AnnualFeedbackProcess"/>
public ProcessManager ProcessManager { get { return _ProcessManager; } }
///-------------------------------------------------------------------------------------------------
/// <summary> Provides access to a registry of available AnnualFeedbackProcess classes. </summary>
///
/// <value> The process registry. </value>
/// <seealso cref="ProcessRegistry"/>
/// <seealso cref="ProcessManager"/>
/// <seealso cref="AnnualFeedbackProcess"/>
///-------------------------------------------------------------------------------------------------
public ProcessRegistry ProcessRegistry { get { return _ProcessRegistry; } }
// -------------------------------------------
/// <summary>
/// Version of the API interface
/// </summary>
public string APiVersion { get { return _APIVersion + " "+DateTime.Now.ToString("(M/d/y H:mm)"); } }
// -------------------------------------------
/// <summary>
/// Verson of the Fortran Model
/// </summary>
public string ModelBuild { get { return _ModelBuild; } }
// -------------------------------------------
/// <summary>
/// Tells FORTRAN model to write debug files. Must be set TRUE before WaterSimManager constructor is called.
/// </summary>
public static bool CreateModelOutputFiles
{ get { return _FortranOutput; } set {_FortranOutput = value; } }
// -------------------------------------------
///-------------------------------------------------------------------------------------------------
/// <summary> Gets the pathname of the data directory. </summary>
/// <value> The pathname of the data directory. </value>
///-------------------------------------------------------------------------------------------------
public string DataDirectory
{ get { return _DataDirectoryName; } }
///-------------------------------------------------------------------------------------------------
/// <summary> Gets the pathname of the temp directory. </summary>
/// <value> The pathname of the temp directory. </value>
///-------------------------------------------------------------------------------------------------
public string TempDirectory
{ get { return _TempDirectoryName; } }
//---------------------------------------------------
/// <summary>
/// Tests to make sure the specified data directoy (path) does contain input files the model needs.
/// </summary>
/// <param name="path">path to data directory</param>
/// <returns>True if data files found, false if not.</returns>
protected bool TestDataDirectory(string path)
{
//string datafile = path + "App_Data\\Data\\Initial_storage.txt";
//return System.IO.File.Exists(datafile);
return true;
}
#endregion
#region ClassInitialization
/*************************************************************
* Class Initialzation routines
*
* ************************************************************/
//----------------------------------------------------------------------------------------------------
// This method is defined in WaterSimDCDC_User_Mods.cs
partial void initialize_Other_ModelParameters();
//----------------------------------------------------------------------------------------------------
// This method is defined in WaterSimDCDC_User_Mods.cs
partial void initialize_Provider_Default_ModelParameters();
//----------------------------------------------------------------------------------------------------
// This method is defined in WaterSimDCDC_GWParameters.cs
partial void initialize_GWModelParameters();
//-----------------------------------------------------------------------
partial void initialize_Sustainable_ModelParameters();
//-----------------------------------------------------------------------
partial void initialize_Derived_ModelParameters();
//-----------------------------------------------------------------------
partial void initialize_WebInterface_DerivedParameters();
//-----------------------------------------------------------------------
private void initialize_ModelParameters()
{
// DAS
// Build some dependency groups
ModelParameterGroupClass DemandGroup = new ModelParameterGroupClass("Drill Down for OnOff Demand", new int[2] { eModelParam.epOnProjectDemand, eModelParam.epOffProjectDemand });
ParamManager.GroupManager.Add(DemandGroup);
ModelParameterGroupClass PopGroup = new ModelParameterGroupClass("Drill Down for OnOf Population", new int[2] { eModelParam.epOnProjectPopulation, eModelParam.epOtherPopulation });
ParamManager.GroupManager.Add(PopGroup);
// Initialize Model ProviderArray Input properties
PCT_alter_GPCD = new providerArrayProperty(_pm, eModelParam.epAlterGPCDpct, get_alterGPCDpct, set_alterGPCDpct, eProviderAggregateMode.agWeighted);
Use_GPCD = new providerArrayProperty(_pm, eModelParam.epUse_GPCD, get_Use_GPCD, set_Use_GPCD, eProviderAggregateMode.agWeighted);
PCT_Wastewater_Reclaimed = new providerArrayProperty(_pm, eModelParam.epPCT_WasteWater_to_Reclaimed, get_PCT_Wastewater_Reclaimed, set_PCT_Wastewater_Reclaimed, eProviderAggregateMode.agWeighted);
PCT_Wastewater_to_Effluent = new providerArrayProperty(_pm, eModelParam.epPCT_Wastewater_to_Effluent, get_PCT_Wastewater_to_Effluent, set_PCT_Wastewater_to_Effluent, eProviderAggregateMode.agWeighted);
PCT_Reclaimed_to_RO = new providerArrayProperty(_pm, eModelParam.epPCT_Reclaimed_to_RO, get_PCT_Reclaimed_to_RO, set_PCT_Reclaimed_to_RO, eProviderAggregateMode.agWeighted);
PCT_RO_to_Water_Supply = new providerArrayProperty(_pm, eModelParam.epPCT_RO_to_Water_Supply, get_PCT_RO_to_Water_Supply, set_PCT_RO_to_Water_Supply, eProviderAggregateMode.agWeighted);
PCT_Reclaimed_to_DirectInject = new providerArrayProperty(_pm, eModelParam.epPCT_Reclaimed_to_DirectInject, get_PCT_Reclaimed_to_DirectInject, set_PCT_Reclaimed_to_DirectInject, eProviderAggregateMode.agWeighted);
PCT_Reclaimed_to_Water_Supply = new providerArrayProperty(_pm, eModelParam.epPCT_Reclaimed_to_Water_Supply, get_PCT_Reclaimed_to_Water_Supply, set_PCT_Reclaimed_to_Water_Supply, eProviderAggregateMode.agWeighted);
PCT_Reclaimed_to_Vadose = new providerArrayProperty(_pm, eModelParam.epPCT_Reclaimed_to_Vadose, get_PCT_Reclaimed_to_Vadose, set_PCT_Reclaimed_to_Vadose, eProviderAggregateMode.agWeighted);
PCT_Effluent_to_Vadose = new providerArrayProperty(_pm, eModelParam.epPCT_Effluent_to_Vadose, get_PCT_Effluent_to_Vadose, set_PCT_Effluent_to_Vadose, eProviderAggregateMode.agWeighted);
PCT_Effluent_to_PowerPlant = new providerArrayProperty(_pm, eModelParam.epPCT_Effluent_to_PowerPlant, get_PCT_Effluent_to_PowerPlant, set_PCT_Effluent_to_PowerPlant, eProviderAggregateMode.agWeighted);
SurfaceWater__to_Vadose = new providerArrayProperty(_pm, eModelParam.epSurfaceWater__to_Vadose, get_SurfaceWater__to_Vadose, set_SurfaceWater__to_Vadose, eProviderAggregateMode.agSum);
Surface_to_Vadose_Time_Lag = new providerArrayProperty(_pm, eModelParam.epSurface_to_Vadose_Time_Lag, get_Surface_to_Vadose_Time_Lag, set_Surface_to_Vadose_Time_Lag, eProviderAggregateMode.agAverage);
WaterBank_Source_Option = new providerArrayProperty(_pm, eModelParam.epWaterBank_Source_Option, get_WaterBank_Source_Option, set_WaterBank_Source_Option, eProviderAggregateMode.agNone);
PCT_SurfaceWater_to_WaterBank = new providerArrayProperty(_pm, eModelParam.epPCT_SurfaceWater_to_WaterBank, get_PCT_SurfaceWater_to_WaterBank, set_PCT_SurfaceWater_to_WaterBank, eProviderAggregateMode.agWeighted);
Use_SurfaceWater_to_WaterBank = new providerArrayProperty(_pm, eModelParam.epUse_SurfaceWater_to_WaterBank, get_Use_SurfaceWater_to_WaterBank, set_Use_SurfaceWater_to_WaterBank, eProviderAggregateMode.agSum);
PCT_WaterSupply_to_Residential = new providerArrayProperty(_pm, eModelParam.epPCT_WaterSupply_to_Residential, get_PCT_WaterSupply_to_Residential, set_PCT_WaterSupply_to_Residential, eProviderAggregateMode.agWeighted);
PCT_WaterSupply_to_Commercial = new providerArrayProperty(_pm, eModelParam.epPCT_WaterSupply_to_Commercial, get_PCT_WaterSupply_to_Commercial, set_PCT_WaterSupply_to_Commercial, eProviderAggregateMode.agWeighted);
Use_WaterSupply_to_DirectInject = new providerArrayProperty(_pm, eModelParam.epUse_WaterSupply_to_DirectInject, get_Use_WaterSupply_to_DirectInject, set_Use_WaterSupply_to_DirectInject, eProviderAggregateMode.agWeighted);
//PCT_Outdoor_WaterUse = new providerArrayProperty(_pm, eModelParam.epPCT_Outdoor_WaterUse, get_PCT_Outdoor_WaterUse, set_PCT_Outdoor_WaterUse, eProviderAggregateMode.agNone);
PCT_Groundwater_Treated = new providerArrayProperty(_pm, eModelParam.epPCT_Groundwater_Treated, get_PCT_Groundwater_Treated, set_PCT_Groundwater_Treated, eProviderAggregateMode.agWeighted);
PCT_Reclaimed_Outdoor_Use = new providerArrayProperty(_pm, eModelParam.epPCT_Reclaimed_Outdoor_Use, get_PCT_Reclaimed_Outdoor_Use, set_PCT_Reclaimed_Outdoor_Use, eProviderAggregateMode.agWeighted);
PCT_Growth_Rate_Adjustment_OnProject = new providerArrayProperty(_pm, eModelParam.epPCT_Growth_Rate_Adjustment_OnProject, get_PCT_Growth_Rate_Adjustment_OnProject, set_PCT_Growth_Rate_Adjustment_OnProject, eProviderAggregateMode.agWeighted);
PCT_Growth_Rate_Adjustment_Other = new providerArrayProperty(_pm, eModelParam.epPCT_Growth_Rate_Adjustment_Other, get_PCT_Growth_Rate_Adjustment_Other, set_PCT_Growth_Rate_Adjustment_Other, eProviderAggregateMode.agWeighted);
PCT_Max_Demand_Reclaim = new providerArrayProperty(_pm, eModelParam.epPCT_Max_Demand_Reclaim, get_PCT_Max_Demand_Reclaim, set_PCT_Max_Demand_Reclaim, eProviderAggregateMode.agWeighted);
// *** Changed 8 12 12 Population_Override = new providerArrayProperty(_pm, eModelParam.epSetPopulations, get_populations, set_populations, eProviderAggregateMode.agNone);
Population_Override_On = new providerArrayProperty(_pm, eModelParam.epSetPopulationsOn, get_populationsOn, set_populationsOn, eProviderAggregateMode.agSum);
Population_Override_Other = new providerArrayProperty(_pm, eModelParam.epSetPopulationsOther, get_populationsOther, set_populationsOther, eProviderAggregateMode.agSum);
//******
//**** QUAY Added 3/6/13
WaterAugmentation = new providerArrayProperty(_pm, eModelParam.epWaterAugmentation, get_NewWater, set_NewWater, eProviderAggregateMode.agSum);
//******
// DAS Added 03.15.14
WaterAugmentationUsed = new providerArrayProperty(_pm, eModelParam.epWaterAugmentationUsed, get_NewWaterUsed, null, eProviderAggregateMode.agSum);
//
Maximum_normalFlow_rights = new providerArrayProperty(_pm, eModelParam.epProvider_Max_NormalFlow, get_normalFlow_rights_max, set_normalFlow_rights_max, eProviderAggregateMode.agSum);
PCT_modify_normalFlow = new providerArrayProperty(_pm, eModelParam.epModfyNormalFlow, get_modifyNormalFlow, set_modifyNormalFlow, eProviderAggregateMode.agWeighted);
// Initialize Model ProviderArray Output properties
Groundwater_Pumped_Municipal = new providerArrayProperty(_pm,eModelParam.epGroundwater_Pumped_Municipal, get_Groundwater_Pumped_Municipal, eProviderAggregateMode.agSum);
Groundwater_Balance = new providerArrayProperty(_pm, eModelParam.epGroundwater_Balance, get_Groundwater_Balance, eProviderAggregateMode.agSum);
SaltVerde_Annual_Deliveries_SRP = new providerArrayProperty(_pm, eModelParam.epSaltVerde_Annual_Deliveries_SRP, get_SaltVerde_Annual_Deliveries_SRP, eProviderAggregateMode.agSum);
SaltVerde_Class_BC_Designations = new providerArrayProperty(_pm, eModelParam.epSaltVerde_Class_BC_Designations, get_SaltVerde_Class_BC_Designations, eProviderAggregateMode.agSum);
Colorado_Annual_Deliveries = new providerArrayProperty(_pm, eModelParam.epColorado_Annual_Deliveries, get_Colorado_Annual_Deliveries, eProviderAggregateMode.agSum);
Groundwater_Bank_Used = new providerArrayProperty(_pm, eModelParam.epGroundwater_Bank_Used, get_Groundwater_Bank_Used, eProviderAggregateMode.agSum);
Groundwater_Bank_Balance = new providerArrayProperty(_pm, eModelParam.epGroundwater_Bank_Balance, get_Groundwater_Bank_Balance, eProviderAggregateMode.agSum);
Reclaimed_Water_Used = new providerArrayProperty(_pm, eModelParam.epReclaimed_Water_Used, get_Reclaimed_Water_Used, eProviderAggregateMode.agSum);
Reclaimed_Water_To_Vadose = new providerArrayProperty(_pm, eModelParam.epReclaimed_Water_To_Vadose, get_Reclaimed_Water_To_Vadose, eProviderAggregateMode.agSum);
Reclaimed_Water_Discharged = new providerArrayProperty(_pm, eModelParam.epReclaimed_Water_Discharged, get_Reclaimed_Water_Discharged, eProviderAggregateMode.agSum);
Reclaimed_Water_to_DirectInject = new providerArrayProperty(_pm, eModelParam.epReclaimed_Water_to_DirectInject, get_Reclaimed_Water_to_DirectInject, eProviderAggregateMode.agSum);
RO_Reclaimed_Water_Used = new providerArrayProperty(_pm, eModelParam.epRO_Reclaimed_Water_Used, get_RO_Reclaimed_Water_Used, eProviderAggregateMode.agSum);
RO_Reclaimed_Water_to_DirectInject = new providerArrayProperty(_pm, eModelParam.epRO_Reclaimed_Water_to_DirectInject, get_RO_Reclaimed_Water_to_DirectInject, eProviderAggregateMode.agSum);
Total_Effluent_Reused = new providerArrayProperty(_pm, eModelParam.epEffluent_Reused, get_Total_Effluent_Reused, eProviderAggregateMode.agSum);
Effluent_To_Vadose = new providerArrayProperty(_pm, eModelParam.epEffluent_To_Vadose, get_Effluent_To_Vadose, eProviderAggregateMode.agSum);
Effluent_To_PowerPlant = new providerArrayProperty(_pm, eModelParam.epEffluent_To_PowerPlant, get_Effluent_To_PowerPlant, eProviderAggregateMode.agSum);
Effluent_Discharged = new providerArrayProperty(_pm, eModelParam.epEffluent_Discharged, get_Effluent_Discharged, eProviderAggregateMode.agSum);
Demand_Deficit = new providerArrayProperty(_pm, eModelParam.epDemand_Deficit, get_Demand_Deficit, eProviderAggregateMode.agSum);
Total_Demand = new providerArrayProperty(_pm, eModelParam.epTotal_Demand, get_Total_Demand, eProviderAggregateMode.agSum);
GPCD_Used = new providerArrayProperty(_pm, eModelParam.epGPCD_Used, get_GPCD_Used, eProviderAggregateMode.agWeighted);
Population_Used = new providerArrayProperty(_pm, eModelParam.epPopulation_Used, get_Population_Used, eProviderAggregateMode.agSum);
PCT_WaterSupply_to_Industrial = new providerArrayProperty(_pm, eModelParam.epPCT_WaterSupply_to_Industrial, get_PCT_WaterSupply_to_Industrial, set_PCT_WaterSupply_to_Industrial, eProviderAggregateMode.agWeighted);
PCT_Outdoor_WaterUseRes = new providerArrayProperty(_pm, eModelParam.epPCT_Outdoor_WaterUseRes, get_PCT_Outdoor_WaterUseRes, set_PCT_Outdoor_WaterUseRes, eProviderAggregateMode.agWeighted);
PCT_Outdoor_WaterUseCom = new providerArrayProperty(_pm, eModelParam.epPCT_Outdoor_WaterUseCom, get_PCT_Outdoor_WaterUseCom, set_PCT_Outdoor_WaterUseCom, eProviderAggregateMode.agWeighted);
PCT_Outdoor_WaterUseInd = new providerArrayProperty(_pm, eModelParam.epPCT_Outdoor_WaterUseInd, get_PCT_Outdoor_WaterUseInd, set_PCT_Outdoor_WaterUseInd, eProviderAggregateMode.agWeighted);
Demand_On_Project = new providerArrayProperty(_pm, eModelParam.epOnProjectDemand, get_Demand_On_Project, eProviderAggregateMode.agSum);
Demand_Off_Project = new providerArrayProperty(_pm, eModelParam.epOffProjectDemand, get_Demand_Off_Project, eProviderAggregateMode.agSum);
Population_On_Project = new providerArrayProperty(_pm, eModelParam.epOnProjectPopulation, get_Population_OnProject, eProviderAggregateMode.agSum);
Population_Other = new providerArrayProperty(_pm, eModelParam.epOtherPopulation, get_Population_Other, eProviderAggregateMode.agSum);
Incidental_Water_Credit = new providerArrayProperty(_pm, eModelParam.epAnnualIncidental, get_Incidental_Water_Credit, eProviderAggregateMode.agSum);
Total_Vadose_To_Aquifer = new providerArrayProperty(_pm, eModelParam.epVadoseToAquifer, get_Total_Vadose_To_Aquifer_Flux, eProviderAggregateMode.agSum);
Total_WWTP_Effluent = new providerArrayProperty(_pm, eModelParam.epTWWTPCreated_AF, get_TWWTP_Created, eProviderAggregateMode.agWeighted);
GPCD_raw = new providerArrayProperty(_pm, eModelParam.epGPCDraw, get_GPCDraw, eProviderAggregateMode.agSum);
Reclaimed_Water_Created = new providerArrayProperty(_pm, eModelParam.epTotalReclaimedCreated_AF, get_Reclaimed_Water_Created, eProviderAggregateMode.agWeighted);
/*************************************************************************
* Setup all Model Parameters in the Prameter Manager
*
*
*************************************************************************/
// Base Inputs
_pm.AddParameter(new ModelParameterClass(eModelParam.epSimulation_Start_Year, "Simulation Start Year", "STARTYR", rangeChecktype.rctCheckRange, 2000, 2006, geti_Simulation_Start_Year, seti_Simulation_Start_Year, RangeCheck.NoSpecialBase));
_pm.AddParameter(new ModelParameterClass(eModelParam.epSimulation_End_Year, "Simulation End Year", "STOPYR", rangeChecktype.rctCheckRange, _defaultEndYear, 2085, geti_Simulation_End_Year, seti_Simulation_End_Year, RangeCheck.NoSpecialBase));
_pm.AddParameter(new ModelParameterClass(eModelParam.epColorado_Historical_Extraction_Start_Year, "Colorado Flow Trace Start Year", "COEXTSTYR", rangeChecktype.rctCheckRangeSpecial, 762, 1979, geti_Colorado_Historical_Extraction_Start_Year, seti_Colorado_Historical_Extraction_Start_Year, ColoradoYearRangeCheck));
_pm.AddParameter(new ModelParameterClass(eModelParam.epColorado_Historical_Data_Source, "Colorado Historical Data Source", "COSRC", rangeChecktype.rctCheckRange, 1, 3, geti_Colorado_Historical_Data_Source, seti_Colorado_Historical_Data_Source, RangeCheck.NoSpecialBase));
_pm.AddParameter(new ModelParameterClass(eModelParam.epColorado_Climate_Adjustment_Percent, "CO: Adjust Flows", "COCLMADJ", rangeChecktype.rctCheckRange, 0, 150, geti_Colorado_Climate_Adjustment_Percent, seti_Colorado_Climate_Adjustment_Percent, RangeCheck.NoSpecialBase));
_pm.AddParameter(new ModelParameterClass(eModelParam.epColorado_User_Adjustment_Percent, "CO: Adjust Drought", "COUSRADJ", rangeChecktype.rctCheckRange, 0, 150, geti_Colorado_User_Adjustment_Percent, seti_Colorado_User_Adjustment_Percent, RangeCheck.NoSpecialBase));
_pm.AddParameter(new ModelParameterClass(eModelParam.epColorado_User_Adjustment_StartYear, "Colorado Drought Start Year", "COUSRSTR", rangeChecktype.rctCheckRange, 2006, 2081, geti_Colorado_User_Adjustment_StartYear, seti_Colorado_User_Adjustment_StartYear,RangeCheck.NoSpecialBase));
_pm.AddParameter(new ModelParameterClass(eModelParam.epColorado_User_Adjustment_Stop_Year, "Colorado Drought Stop Year", "COUSRSTP", rangeChecktype.rctCheckRange, 2006, 2081, geti_Colorado_User_Adjustment_Stop_Year, seti_Colorado_User_Adjustment_Stop_Year, RangeCheck.NoSpecialBase));
_pm.AddParameter(new ModelParameterClass(eModelParam.epSaltVerde_Historical_Extraction_Start_Year, "SaltVerde Flows Trace Start Year", "SVEXTSTYR", rangeChecktype.rctCheckRangeSpecial, 1330, 1979, geti_SaltVerde_Historical_Extraction_Start_Year, seti_SaltVerde_Historical_Extraction_Start_Year, SaltVerdeYearRangeCheck));
_pm.AddParameter(new ModelParameterClass(eModelParam.epSaltVerde_Historical_Data, "Salt-Verde Trace Data Source", "SVSRC", rangeChecktype.rctCheckRange, 1, 3, geti_SaltVerde_Historical_Data, seti_SaltVerde_Historical_Data, RangeCheck.NoSpecialBase));
_pm.AddParameter(new ModelParameterClass(eModelParam.epSaltVerde_Climate_Adjustment_Percent, "Salt-Verde: Adjust Flows", "SVCLMADJ", rangeChecktype.rctCheckRange, 0, 150, geti_SaltVerde_Climate_Adjustment_Percent, seti_SaltVerde_Climate_Adjustment_Percent, RangeCheck.NoSpecialBase));
_pm.AddParameter(new ModelParameterClass(eModelParam.epSaltVerde_User_Adjustment_Percent, "Salt-Verde: Adjust Drought", "SVUSRADJ", rangeChecktype.rctCheckRange, 0, 150, geti_SaltVerde_User_Adjustment_Percent, seti_SaltVerde_User_Adjustment_Percent, RangeCheck.NoSpecialBase));
_pm.AddParameter(new ModelParameterClass(eModelParam.epSaltVerde_User_Adjustment_Start_Year, "Salt-Verde Drought Start Year", "SVUSRSTR", rangeChecktype.rctCheckRange, 2006, 2081, geti_SaltVerde_User_Adjustment_Start_Year, seti_SaltVerde_User_Adjustment_Start_Year, RangeCheck.NoSpecialBase));
_pm.AddParameter(new ModelParameterClass(eModelParam.epSaltVerde_User_Adjustment_Stop_Year, "Salt-Verde Drought Stop Year", "SVUSRSTP", rangeChecktype.rctCheckRange, 2006, 2081, geti_SaltVerde_User_Adjustment_Stop_Year, seti_SaltVerde_User_Adjustment_Stop_Year, RangeCheck.NoSpecialBase));
_pm.AddParameter(new ModelParameterClass(eModelParam.epProvider_Demand_Option, "Provider Demand Option", "DMOPT", rangeChecktype.rctCheckRange, 1, 4, geti_Provider_Demand_Option, seti_Provider_Demand_Option, RangeCheck.NoSpecialBase));
_pm.AddParameter(new ModelParameterClass(eModelParam.epPCT_Alter_GPCD, "Reduction in GPCD, by 2085", "PCRDGPCD", rangeChecktype.rctCheckRange, 0, 75, geti_PCT_Reduce_GPCD, seti_PCT_Reduce_GPCD, RangeCheck.NoSpecialBase));
_pm.AddParameter(new ModelParameterClass(eModelParam.epAWSAnnualGWLimit, "Ignore Rule to Limit Pumping to Annual AWS GW Credit (0=False)", "AWSLIMIT", rangeChecktype.rctCheckRange, 0, 1, geti_Assured_Water_Supply_Annual_Groundwater_Pumping_Limit, seti_Assured_Water_Supply_Annual_Groundwater_Pumping_Limit, RangeCheck.NoSpecialBase));
_pm.AddParameter(new ModelParameterClass(eModelParam.epPCT_REG_Growth_Rate_Adjustment, "Regional Pop Growth Rate", "REGPOPGR", rangeChecktype.rctCheckRange, 0, 300, geti_PCT_REG_Growth_Rate_Adjustment, seti_PCT_REG_Growth_Rate_Adjustment, RangeCheck.NoSpecialBase));
// Provider Inputs
_pm.AddParameter(new ModelParameterClass(eModelParam.epAlterGPCDpct, "Alter the provider trend in GPCD", "ALTRGPCD", modelParamtype.mptInputProvider, rangeChecktype.rctCheckRange, -70, 70, null, get_alterGPCDpct, null, set_alterGPCDpct, null, null, PCT_alter_GPCD));
_pm.AddParameter(new ModelParameterClass(eModelParam.epUse_GPCD, "Use GPCD", "USEGPCD", rangeChecktype.rctCheckRange, -1, 2000, RangeCheck.NoSpecialProvider,Use_GPCD));
_pm.AddParameter(new ModelParameterClass(eModelParam.epPCT_WasteWater_to_Reclaimed, "Effluent to Reclaimed Plant", "PCEFFREC", rangeChecktype.rctCheckRange, 0, 100, RangeCheck.NoSpecialProvider, PCT_Wastewater_Reclaimed));
_pm.AddParameter(new ModelParameterClass(eModelParam.epPCT_Wastewater_to_Effluent, "Total Wastewater is Usable Effluent", "PCWWEFF", rangeChecktype.rctCheckRange, 0, 100, RangeCheck.NoSpecialProvider,PCT_Wastewater_to_Effluent));
_pm.AddParameter(new ModelParameterClass(eModelParam.epPCT_Reclaimed_to_RO, "Reclaimed to RO", "PCRECRO", rangeChecktype.rctCheckRange, 0, 100, RangeCheck.NoSpecialProvider, PCT_Reclaimed_to_RO));
_pm.AddParameter(new ModelParameterClass(eModelParam.epPCT_RO_to_Water_Supply, "RO to Water Supply", "PCROWS", rangeChecktype.rctCheckRange, 0, 100, RangeCheck.NoSpecialProvider,PCT_RO_to_Water_Supply));
_pm.AddParameter(new ModelParameterClass(eModelParam.epPCT_Reclaimed_to_DirectInject, "Reclaimed to DirectInject", "PCRECDI", rangeChecktype.rctCheckRangeSpecial, 0, 100, PCTReclaimedRangeCheck,PCT_Reclaimed_to_DirectInject));
_pm.AddParameter(new ModelParameterClass(eModelParam.epPCT_Reclaimed_to_Water_Supply, "Reclaimed to Water Supply", "PCERECWS", rangeChecktype.rctCheckRangeSpecial, 0, 100, PCTReclaimedRangeCheck,PCT_Reclaimed_to_Water_Supply));
_pm.AddParameter(new ModelParameterClass(eModelParam.epPCT_Reclaimed_to_Vadose, "Reclaimed to Vadose", "PCRECVAD", rangeChecktype.rctCheckRangeSpecial, 0, 100, PCTReclaimedRangeCheck,PCT_Reclaimed_to_Vadose));
_pm.AddParameter(new ModelParameterClass(eModelParam.epPCT_Effluent_to_Vadose, "Effluent to Vadose", "PCEFFVAD", rangeChecktype.rctCheckRangeSpecial, 0, 100, PCTEffluentRangeCheck,PCT_Effluent_to_Vadose));
_pm.AddParameter(new ModelParameterClass(eModelParam.epPCT_Effluent_to_PowerPlant, "Effluent to PowerPlant", "PCEFFPP", rangeChecktype.rctCheckRangeSpecial, 0, 100, PCTEffluentRangeCheck,PCT_Effluent_to_PowerPlant));
_pm.AddParameter(new ModelParameterClass(eModelParam.epSurfaceWater__to_Vadose, "SurfaceWater to Vadose", "PCSWVAD", rangeChecktype.rctCheckRange, 0, 100000, RangeCheck.NoSpecialProvider,SurfaceWater__to_Vadose));
_pm.AddParameter(new ModelParameterClass(eModelParam.epSurface_to_Vadose_Time_Lag, "Surface to Vadose Time Lag in Years", "VADLAG", rangeChecktype.rctCheckRange, 0, 50, RangeCheck.NoSpecialProvider,Surface_to_Vadose_Time_Lag));
_pm.AddParameter(new ModelParameterClass(eModelParam.epWaterBank_Source_Option, "WaterBank Source Option", "WBOPT", rangeChecktype.rctCheckRange, 1, 2, RangeCheck.NoSpecialProvider,WaterBank_Source_Option));
_pm.AddParameter(new ModelParameterClass(eModelParam.epPCT_SurfaceWater_to_WaterBank, "SurfaceWater to WaterBank", "PCSWWB", rangeChecktype.rctCheckRange, 0, 100, RangeCheck.NoSpecialProvider,PCT_SurfaceWater_to_WaterBank));
_pm.AddParameter(new ModelParameterClass(eModelParam.epUse_SurfaceWater_to_WaterBank, "SurfaceWater to WaterBank", "SWWB", rangeChecktype.rctCheckRange, 0, 100000, RangeCheck.NoSpecialProvider,Use_SurfaceWater_to_WaterBank));
_pm.AddParameter(new ModelParameterClass(eModelParam.epPCT_WaterSupply_to_Residential, "WaterSupply to Residential", "PCWSRES", rangeChecktype.rctCheckRangeSpecial, 0, 100, ResComPCTRangeCheck,PCT_WaterSupply_to_Residential));
_pm.AddParameter(new ModelParameterClass(eModelParam.epPCT_WaterSupply_to_Commercial, "WaterSupply to Commercial", "PCWSCOM", rangeChecktype.rctCheckRangeSpecial, 0, 100, ResComPCTRangeCheck,PCT_WaterSupply_to_Commercial));
_pm.AddParameter(new ModelParameterClass(eModelParam.epUse_WaterSupply_to_DirectInject, "Water Supply to DirectInject", "USEWSDI", rangeChecktype.rctCheckRange, 0, 100000, RangeCheck.NoSpecialProvider,Use_WaterSupply_to_DirectInject));
// Modified 7 23 12 _pm.AddParameter(new ModelParameterClass(eModelParam.epPCT_Outdoor_WaterUse, "% Outdoor Water Use", "PGOUTUSE", rangeChecktype.rctCheckRange, 0, 100, RangeCheck.NoSpecialProvider, get_PCT_Outdoor_WaterUse, RangeCheck.NoSpecialProvider, set_PCT_Outdoor_WaterUse,RangeCheck.NoSpecialProvider,RangeCheck.NoSpecialProvider,PCT_Outdoor_WaterUse));
_pm.AddParameter(new ModelParameterClass(eModelParam.epPCT_Groundwater_Treated, "Groundwater Treated", "PCGWTRT", rangeChecktype.rctCheckRange, 0, 100, RangeCheck.NoSpecialProvider,PCT_Groundwater_Treated));
_pm.AddParameter(new ModelParameterClass(eModelParam.epPCT_Reclaimed_Outdoor_Use, "Outdoor Can Use Reclaimed", "PCRECOUT", rangeChecktype.rctCheckRange, 0, 100, RangeCheck.NoSpecialProvider,PCT_Reclaimed_Outdoor_Use));
// Modified 7 23 12 _pm.AddParameter(new ModelParameterClass(eModelParam.epPCT_Growth_Rate_Adjustment, "% Growth Rate Adjustment", "PCGRWRTE", rangeChecktype.rctCheckRange, 0, 300, RangeCheck.NoSpecialProvider, get_PCT_Growth_Rate_Adjustment, RangeCheck.NoSpecialProvider, set_PCT_Growth_Rate_Adjustment,RangeCheck.NoSpecialProvider,RangeCheck.NoSpecialProvider,PCT_Growth_Rate_Adjustment));
_pm.AddParameter(new ModelParameterClass(eModelParam.epPCT_Growth_Rate_Adjustment_OnProject, "Growth Rate Adj On Project", "PCGRTON", rangeChecktype.rctCheckRange, 0, 300, RangeCheck.NoSpecialProvider,PCT_Growth_Rate_Adjustment_OnProject));
_pm.AddParameter(new ModelParameterClass(eModelParam.epPCT_Growth_Rate_Adjustment_Other, "Growth Rate Adj Other", "PCGRTOFF", rangeChecktype.rctCheckRange, 0, 300, RangeCheck.NoSpecialProvider,PCT_Growth_Rate_Adjustment_Other));
_pm.AddParameter(new ModelParameterClass(eModelParam.epPCT_Max_Demand_Reclaim, "Max Demand Reclaimed", "PCDEMREC", rangeChecktype.rctCheckRange, 0, 70, RangeCheck.NoSpecialProvider, PCT_Max_Demand_Reclaim));
// *** changed 8 13 12 _pm.AddParameter(new ModelParameterClass(eModelParam.epSetPopulations, "Provider Population Override", "POPOVRD", rangeChecktype.rctNoRangeCheck, 0, 0, RangeCheck.NoSpecialProvider, get_populations , RangeCheck.NoSpecialProvider, set_populations, RangeCheck.NoSpecialProvider, RangeCheck.NoSpecialProvider, Population_Override));
_pm.AddParameter(new ModelParameterClass(eModelParam.epSetPopulationsOn, "Provider On-Project Pop Override", "POPOVON", rangeChecktype.rctNoRangeCheck, 0, 0, RangeCheck.NoSpecialProvider, Population_Override_On));
_pm.AddParameter(new ModelParameterClass(eModelParam.epSetPopulationsOther, "Provider Off-Project Pop Override", "POPOVOFF", rangeChecktype.rctNoRangeCheck, 0, 0, RangeCheck.NoSpecialProvider, Population_Override_Other));
//*************
_pm.AddParameter(new ModelParameterClass(eModelParam.epModfyNormalFlow, "Modify Normal Flow", "MNFLOW", rangeChecktype.rctCheckRange, 0, 554, RangeCheck.NoSpecialProvider, PCT_modify_normalFlow));
_pm.AddParameter(new ModelParameterClass(eModelParam.epPCT_WaterSupply_to_Industrial, "WaterSupply to Industrial", "PCWSIND", rangeChecktype.rctCheckRangeSpecial, 0, 100, ResComPCTRangeCheck, PCT_WaterSupply_to_Industrial));
_pm.AddParameter(new ModelParameterClass(eModelParam.epPCT_Outdoor_WaterUseRes, "Res Outdoor Water Use", "PROUTUSE", rangeChecktype.rctCheckRange, 0, 100, RangeCheck.NoSpecialProvider, PCT_Outdoor_WaterUseRes));
_pm.AddParameter(new ModelParameterClass(eModelParam.epPCT_Outdoor_WaterUseCom, "Com Outdoor Water Use", "PCOUTUSE", rangeChecktype.rctCheckRange, 0, 100, RangeCheck.NoSpecialProvider, PCT_Outdoor_WaterUseCom));
_pm.AddParameter(new ModelParameterClass(eModelParam.epPCT_Outdoor_WaterUseInd, "Ind Outdoor Water Use", "PIOUTUSE", rangeChecktype.rctCheckRange, 0, 100, RangeCheck.NoSpecialProvider, PCT_Outdoor_WaterUseInd));
// QUAY Added 3/6/13
_pm.AddParameter(new ModelParameterClass(eModelParam.epWaterAugmentation, "Amount of Augmented Water", "WATAUG", rangeChecktype.rctCheckRange, 0, 100000, RangeCheck.NoSpecialProvider, WaterAugmentation));
_pm.AddParameter(new ModelParameterClass(eModelParam.epProvider_Max_NormalFlow, "The maximum right usable", "NFLOWMAX", modelParamtype.mptInputProvider, rangeChecktype.rctCheckRange, 0, 554, null, get_normalFlow_rights_max, null, set_normalFlow_rights_max, null, null, Maximum_normalFlow_rights));
//*****
// Base Outputs
_pm.AddParameter(new ModelParameterClass(eModelParam.epColorado_River_Flow, "Colorado River Flow", "CORFLOW", geti_Colorado_River_Flow, 5000000, 30000000));
_pm.AddParameter(new ModelParameterClass(eModelParam.epPowell_Storage, "Powell Storage", "POWSTORE", geti_Powell_Storage, 5000000, 30000000));
_pm.AddParameter(new ModelParameterClass(eModelParam.epMead_Storage, "Mead Storage", "MEDSTORE", geti_Mead_Storage, 5000000, 30000000));
_pm.AddParameter(new ModelParameterClass(eModelParam.epSaltVerde_River_Flow, "Salt-Verde River Flow", "SVRFLOW", geti_SaltVerde_River_Flow, 0, 5000000));
_pm.AddParameter(new ModelParameterClass(eModelParam.epSaltVerde_Storage, "Salt-Verde Storage", "SVRSTORE", geti_SaltVerde_Storage, 500000, 2500000));
_pm.AddParameter(new ModelParameterClass(eModelParam.epEffluent_To_Agriculture, "Effluent To Agriculture", "EFLAG", geti_Effluent_To_Agriculture, 0, 550000 ));
_pm.AddParameter(new ModelParameterClass(eModelParam.epSaltVerde_Spillage, "Reservoir Spillage", "SVTSPILL", geti_SVTspillage, 0, 3500000 ));
_pm.AddParameter(new ModelParameterClass(eModelParam.epMeadLevel, "Mead Elevation", "MEADELEV", geti_ElevationMead, 800, 1300));
_pm.AddParameter(new ModelParameterClass(eModelParam.epRegionalNaturalRecharge, "Regional Aquifer Natural Recharge", "REGAQRCHG", geti_Regional_Natural_Recharge, 100000, 1200000));
_pm.AddParameter(new ModelParameterClass(eModelParam.epRegionalCAGRDRecharge, "Regional CAGRD Recharge", "REGCAGRDR", geti_Regional_CAGRD_Recharge, 0, 250000));
_pm.AddParameter(new ModelParameterClass(eModelParam.epRegionalInflow, "Regional Natural Aquifer Inflow", "REGAQIN", geti_Regional_Inflow, 20000, 50000 ));
_pm.AddParameter(new ModelParameterClass(eModelParam.epRegionalAgToVadose, "Regional Ag to Vadose Recharge", "REGAGVAD", geti_Regional_Ag_To_Vadose ));
_pm.AddParameter(new ModelParameterClass(eModelParam.epRegionalProviderRecharge, "Total Recharge All Providers", "REGPRRCHG", geti_Regional_Provider_Recharge, 0, 1500 ));
_pm.AddParameter(new ModelParameterClass(eModelParam.epRegionalAgOtherPumping, "Regional Ag and Other Pumping", "REGAOPMP", geti_Regional_Ag_Other_Pumping, 0, 700000 ));
_pm.AddParameter(new ModelParameterClass(eModelParam.epRegionalOutflow, "Regional Aquifer Natural Outflow", "REGNAOUT", geti_Regional_Outflow, 30000, 40000));
_pm.AddParameter(new ModelParameterClass(eModelParam.epRegionalGWBalance, "Regional Aquifer Balance", "REGAQBAL", geti_Regional_Groundwater_Balance, 50000000, 10000000 ));
_pm.AddParameter(new ModelParameterClass(eModelParam.epPowellLevel, "Powell Elevation (Feet-msl)", "POWELELEV", geti_ElevationPowell,3370, 3750));
// Provider Outputs
_pm.AddParameter(new ModelParameterClass(eModelParam.epGroundwater_Pumped_Municipal, "Groundwater Pumped Municipal", "MGWPUMP", Groundwater_Pumped_Municipal, 0, 150000));
_pm.AddParameter(new ModelParameterClass(eModelParam.epGroundwater_Balance, "Available Groundwater", "GWAVAIL", Groundwater_Balance, 0, 7000000));
_pm.AddParameter(new ModelParameterClass(eModelParam.epSaltVerde_Annual_Deliveries_SRP, "SaltVerde Annual Deliveries SRP", "SRPDELIV", SaltVerde_Annual_Deliveries_SRP, 0, 300000));
_pm.AddParameter(new ModelParameterClass(eModelParam.epSaltVerde_Class_BC_Designations, "SaltVerde Class BC Designations", "SRPBCDES", SaltVerde_Class_BC_Designations, 0, 300000));
_pm.AddParameter(new ModelParameterClass(eModelParam.epColorado_Annual_Deliveries, "Colorado Annual Deliveries", "COLDELIV", Colorado_Annual_Deliveries, 0, 250000));
_pm.AddParameter(new ModelParameterClass(eModelParam.epGroundwater_Bank_Used, "Groundwater Bank Used", "BNKUSED", Groundwater_Bank_Used, 0, 50000));
_pm.AddParameter(new ModelParameterClass(eModelParam.epGroundwater_Bank_Balance, "Groundwater Bank Balance", "BNKAVAIL", Groundwater_Bank_Balance, 0, 700000));
_pm.AddParameter(new ModelParameterClass(eModelParam.epReclaimed_Water_Used, "Reclaimed Water Used", "RECTOT", Reclaimed_Water_Used, 0, 50000));
_pm.AddParameter(new ModelParameterClass(eModelParam.epReclaimed_Water_To_Vadose, "Reclaimed Water To Vadose", "RECVADOS", Reclaimed_Water_To_Vadose));
_pm.AddParameter(new ModelParameterClass(eModelParam.epReclaimed_Water_Discharged, "Reclaimed Water Discharged ", "RECDISC", Reclaimed_Water_Discharged, 0, 50000));
_pm.AddParameter(new ModelParameterClass(eModelParam.epReclaimed_Water_to_DirectInject, "Reclaimed Water to DirectInject", "RECINJEC", Reclaimed_Water_to_DirectInject));
_pm.AddParameter(new ModelParameterClass(eModelParam.epRO_Reclaimed_Water_Used, "RO Reclaimed Water Used", "ROTOT", RO_Reclaimed_Water_Used));
_pm.AddParameter(new ModelParameterClass(eModelParam.epRO_Reclaimed_Water_to_DirectInject, "RO Reclaimed DirectInject", "ROINJEC", RO_Reclaimed_Water_to_DirectInject));
_pm.AddParameter(new ModelParameterClass(eModelParam.epEffluent_Reused, "Total Effluent Reused", "EFLCRT", Total_Effluent_Reused, 0, 250000));
_pm.AddParameter(new ModelParameterClass(eModelParam.epEffluent_To_Vadose, "Effluent To Vadose", "EFLVADOS", Effluent_To_Vadose, 0, 25000));
_pm.AddParameter(new ModelParameterClass(eModelParam.epEffluent_To_PowerPlant, "Effluent To PowerPlant", "EFLPP", Effluent_To_PowerPlant, 0, 85000));
_pm.AddParameter(new ModelParameterClass(eModelParam.epEffluent_Discharged, "Effluent Discharged", "EFLDISC", Effluent_Discharged, 0, 60000));
_pm.AddParameter(new ModelParameterClass(eModelParam.epDemand_Deficit, "Demand Deficit", "DEMDEF", Demand_Deficit));
_pm.AddParameter(new ModelParameterClass(eModelParam.epGPCD_Used, "GPCD Used", "GPCDUSED", GPCD_Used, 0, 400));
_pm.AddParameter(new ModelParameterClass(eModelParam.epPopulation_Used, "Population", "POPUSED", Population_Used,PopGroup, 1000, 4000000));
_pm.AddParameter(new ModelParameterClass(eModelParam.epTotal_Demand, "Total Demand", "TOTDEM", Total_Demand, DemandGroup, 0, 500000));
_pm.AddParameter(new ModelParameterClass(eModelParam.epOnProjectDemand, "On Project Demand (AF)", "ONDEM", Demand_On_Project, 0, 350000));
_pm.AddParameter(new ModelParameterClass(eModelParam.epOffProjectDemand, "Off Project Demand (AF)", "OFFDEM", Demand_Off_Project, 0, 350000));
_pm.AddParameter(new ModelParameterClass(eModelParam.epOnProjectPopulation, "On-project population (ppl)", "POPONPRJ", Population_On_Project, 0, 2000000));
_pm.AddParameter(new ModelParameterClass(eModelParam.epOtherPopulation, "Other population (ppl)", "POPOTHER", Population_Other, 0, 2000000));
_pm.AddParameter(new ModelParameterClass(eModelParam.epAnnualIncidental, "Incidental Recharge Credit", "INCCREDIT", Incidental_Water_Credit, 0, 75000));
_pm.AddParameter(new ModelParameterClass(eModelParam.epVadoseToAquifer, "Total Vadose Recharge", "VADRCHTOT", Total_Vadose_To_Aquifer, 0, 150000));
this.ParamManager.AddParameter(new ModelParameterClass(eModelParam.epTWWTPCreated_AF, "Total TWWTP Water Created", "TWWTP", Total_WWTP_Effluent, 0, 300000));
this.ParamManager.AddParameter(new ModelParameterClass(eModelParam.epGPCDraw, "GPCD raw", "GPCDRAW", GPCD_raw, 0, 600));
this.ParamManager.AddParameter(new ModelParameterClass(eModelParam.epTotalReclaimedCreated_AF, "Reclaimed Water Created", "TOTREC", Reclaimed_Water_Created, 0, 100000));
// DAS Added 02.15.14
_pm.AddParameter(new ModelParameterClass(eModelParam.epWaterAugmentationUsed, "Amount of Augmented Water Used", "WATAUGUSED", WaterAugmentationUsed, 0, 100000));
// Male a Call to initialize the Groundwater Parameters if implementation exists (WaterSimDCDC_GWPaameters ver N.cs)
initialize_GWModelParameters();
// Make Call to initialize Derived model parameters, if implmentation exists
initialize_Derived_ModelParameters();
// Make Call to initialize Sustainable model parameters, if implementation exists
initialize_Sustainable_ModelParameters();
// Make Call to initialize user model parameters , implemented in WaterSimDCDC_User_Mods.cs
initialize_Other_ModelParameters();
// Call for Web Parameters
initialize_WebInterface_DerivedParameters();
}
//--------------------------------------------------------------
private void InitDefaultVariables()
{
//
_ws.Startyear = _StartYear = _ws.SimulationStart = util.WaterSimDCDC_Default_Simulation_StartYear;
_ws.Endyear = _EndYear = _ws.SimulationEnd = util.WaterSimDCDC_Default_Simulation_EndYear;
// QUAY BEGIN EDIT 3 10 14
Simulation_End_Year = _ws.Endyear;
// QUAY end EDIT 3 10 14
// Call API.PARMS to Set up Default array
API.parms(_ws);
//TEMP FIX CHANGE IN FUTURE IF FIXED
Colorado_User_Adjustment_StartYear= util.WaterSimDCDC_Default_Colorado_User_Adjustment_StartYear;
SaltVerde_Historical_Data_Source = util.WaterSimDCDC_Default_SaltVerde_Historical_Data;
SaltVerde_User_Adjustment_Start_Year = util.WaterSimDCDC_Default_SaltVerde_User_Adjustment_Start_Year;
Provider_Demand_Option = util.WaterSimDCDC_Provider_Demand_Option;
Assured_Water_Supply_Annual_Groundwater_Pumping_Limit = 1;
// GPCDFIX
GPCDBuffer = GPCDDefaults;
initialize_Provider_Default_ModelParameters();
Web_Parms_setDefaultValues();
}
internal void GPCDFIX()
{
// OK This is not exactly elegant but is in place to handle odd nature of Use_GPCD and GPCD_Used.
// There is only on parameter in the model for provider GPCD. It can be set to a GPCD for Demand Option 4, for other options
// it is calculated and can not be set. The Get always reports the GPCD_Used in the last run, which for Option 4 is what it was set to, but for all other options
// is a calculated value changing each year.
// To mimic all other values two parameters were created, one input one ouput, that use the same model function, the set for the input, and the get for output.
// The get for the input paramter uses two dummy arrays, one for option 4 which is changed on a set, and one for all other options which returns
// the intitial default value used by the model in calculating GPCD. These defaults can only be changed in the provider input file.
// A special exception is added if USE_GPCD is set when option 4 is not selected since that does not work
// This sets up these arrays. In order to get the default values, the model has to be run for one year.
// fetch the defaults
int OldStart = Simulation_Start_Year;
int OldEnd = Simulation_End_Year;
Simulation_Initialize();
Simulation_Start_Year = 2000;
Simulation_End_Year = 2012;
Simulation_NextYear();
//// OK now fetch the GCPD defaults
GPCDBuffer = GPCDDefaults = _ws.ProviderGPCD;
Simulation_Stop();
// reset the defaults
Simulation_Start_Year = OldStart;
Simulation_End_Year = OldEnd;
// OK will use these inthe provider property routines
// NOTE, this is one of the exceptions where a get call and a run control is made into the model outside the ModelParamter interface.
}
#endregion
////------------------------------------------------------------------------
/*************************************************************
* Simulation Control Delegates, Fields, Properties and Methods
*
* **************************************************************/
#region Simulation_Control
/**************************************
* SimulationLock , LockSimulation(), UnLockSimulation()
* These can be used to lock down the simultaion so no input parameters can be set
* In event driven environments this is advised
* ************************************/
//----------------------------------------------------------------------------------------------------
/// <summary>
/// Property Locks and unlocks (true false) the simulation so no parameters can be set until unlocked.
/// </summary>
/// <remarks>I started with this and then moved to LockSimulation() and UnlockSimulation(), may remove this at some point.</remarks>
/// <seealso cref="UnLockSimulation"/>
/// <seealso cref="LockSimulation"/>
public bool SimulationLock
// Sets Model Locl
{
get { return FModelLocked; }
set { FModelLocked = value; }
}
//----------------------------------------------------------------------------------------------------
/// <summary>
/// Locks the simulation so Base Input parameters can be set until unlocked.
/// </summary>
/// <seealso cref="UnLockSimulation"/>
public void LockSimulation() { FModelLocked = true; }
//----------------------------------------------------------------------------------------------------
/// <summary> Unlock simulation so Base Input parameters can be set . </summary>
/// <seealso cref="LockSimulation"/>
public void UnLockSimulation() { FModelLocked = false; }
//----------------------------------------------------------------------------------------------------
internal bool isLocked() { return FModelLocked; }
//----------------------------------------------------------------------------------------------------
//----------------------------------------------------------------------------------------------------
/// <summary>
/// Must be called to setup a Simulation . Simulation can be run in two ways,
/// calling SimulationNextYear() for each year to be run, call SimulationAllYears() which runs all the years
/// All simulations should be stopped with StopSimulation(), which will make sure all files are closed
/// Will reset SimulationLock to false;
/// </summary>
public virtual void Simulation_Initialize()
/* -------------------------------------------
* Initializes a Simulation. Simulation can be run in two ways,
* calling SimulationNextYear() for each year to be run
* call SimulationAllYears() which runs all the years
* call fails if Simulation is locked
* All simulations should be stopped with StopSimulation(), whihc will make sure all files are closed
* --------------------------------------------*/
{
SimulationLock = false;
_inRun = false;
_CurrentYear = 0;
if (_simulationStarted) { Simulation_Stop(); }
// call model reset
_ws.ResetAll();
// Initiallize defaults
InitDefaultVariables(); // Sets Variables to Default Values
// clear process errors
_ProcessManager.ProcessInitializeAll(this);// ClearProcessErrors();
// tell model and API we are ready tio start
_ws.StartSimulation = true;
_simulationStarted = true;
// Ready but not yet running
}
//----------------------------------------------------------------------------------------------------
bool _inSimulationNextYear = false;
/// <summary>
/// Runs the next year in a series of years in a simulation, no pre or post process is evoked
/// </summary>
/// <returns>The year of the simulation run</returns>
public virtual int Simulation_NextYear()
/* --------------------------------------------------------
* Returns the year run, if has already run last year, returns 0;
* Calls close files afer running last year
----------------------------------------------------------- */
{
int runyear = 0;
if ((_simulationStarted)&(!_inSimulationNextYear))
{
// Keep from rentry
_inSimulationNextYear = true;
// Save Lock State and lock this down
bool locked = isLocked();
LockSimulation();
// Check if this is the first year
if (!_inRun)
{
// OK We are starting, set the STart and End years
_StartYear = _CurrentYear = Simulation_Start_Year;
_EndYear = Simulation_End_Year;
_NumberOfYears = (_EndYear - _StartYear)+1;
_inRun = true;
}
else
// OK, Not the first yeat, inc the year;
{ _CurrentYear++; }
// OK we should never get to this code, but to be safe, check of we have already called the last year, if so, lets shut it down
if (_CurrentYear > _EndYear)
{
_simulationStarted = false;
runyear = 0;
}
else
{
//OK run a year
// do Process Start for first year and PreProcess for all other years
// Unlock to allo parmeters to be set
UnLockSimulation();
if (_StartYear != _CurrentYear)
{
_ProcessManager.PreProcessAll(_CurrentYear, this);
}
else
{
_ProcessManager.ProcessStartedAll(_CurrentYear, this);
}
// Lock it back up
LockSimulation();;
// OK run Model
runYear(_CurrentYear);
// Set STartSimulatio to false
_ws.StartSimulation = false;
// do PostProcess
// Simulation is locked for this, ie can not change parameters
_ProcessManager.PostProcessAll(_CurrentYear,this);
// Return the year just done
runyear = _CurrentYear;
}
SimulationLock = locked;
}
_inSimulationNextYear = false;
return runyear;
}
//----------------------------------------------------------------
/// <summary> Executes the year operation. </summary>
/// <remarks>This has gone back and forth from protected to internal back again, might change in future</remarks>
/// <param name="year"> The year. </param>
internal virtual void runYear(int year)
// Iternal routine Runs one more year, call groundwater
// Fast as possible, no error checking, no reentry block
{
// call model for one year
_ws.RunOneYear();
// clean up
_ws.GroundWater(year);
}
//----------------------------------------------------------------------------------
bool _inSimulationAllYears = false;
/// <summary>
/// Runs all years of the specified simulation
/// </summary>
/// <remarks>Runs each year. Before each year, except the first, it calls a preprocess processes. After each year, including the last it calls all postprocess processes. No data is retained. If a post process does not collect data fater each year, the only output data available will be that for the last year run.</remarks>
public virtual void Simulation_AllYears()
{
if ((_simulationStarted)&(!_inSimulationAllYears))
{
_inSimulationAllYears = true;
_StartYear = _CurrentYear = Simulation_Start_Year;
_EndYear = Simulation_End_Year;
_inRun = true;
foreach (int year in simulationYears())
{ // do PreProcess, unless first year then do ProcessStarted
// Unlock things first
UnLockSimulation();
if (_StartYear != _CurrentYear)
{
_ProcessManager.PreProcessAll(_CurrentYear, this);
}
else
{
_ProcessManager.ProcessStartedAll(_CurrentYear, this);
}
// lock it back up
LockSimulation();
runYear(year);
// OK, Not the first yeat, inc the year;
_CurrentYear++;
// do PostProcess
_ProcessManager.PostProcessAll(_CurrentYear,this);
}
Simulation_Stop();
_inSimulationAllYears = false;
}
}
//----------------------------------------------------------------------------------
bool _instopSimulation = false;
/// <summary> Stops simulation stop </summary>
/// <remarks> Unlocks simulation, closes model files, unlocks base input parameters</remarks>
public virtual void Simulation_Stop()
// Stops RunByYear() closes out simulation.
{
if (!_instopSimulation)
{
_instopSimulation = true;
// if all years not run, run out the model
while (_CurrentYear < Simulation_End_Year)
{
_ws.RunOneYear();
_CurrentYear++;
}
// Commented out 8/5/13 When model runs last year, see abopve all files closed
// Close the model files
// _ws.CloseFiles();
_ProcessManager.StopProcessAll(this);
// Unset lock, recurrence, and in simulation flags
FModelLocked = false;
_inRun = false;
_simulationStarted = false;
_instopSimulation = false;
}
}
#endregion
//----------------------------------------------------------------------------------
// TESTING
internal bool testParmeters(ref string Results, bool debug)
{
return _pm.testModelParameters(ref Results);//,debug);
}
//----------------------------------------------------------------------------------
internal bool testParmeters()
{
string junk = " ";
return _pm.testModelParameters(ref junk);//,false);
}
//
//======================================================
// Model Parameters
// =====================================================
//
#region Model Parameters
// OutPut Properties for Model Variables OutPut after model year run
//************************************
// BASE OUTPUT PARAMETERS
// ************************************
#region Base output Parameters
// Regional Water Supply Data =========================
//---------------------------------------
//get_ColoradoRiverFlow
/// <summary> Gets the colorado river flow. </summary>
///<remarks>The total annual flow in the Colorado River above Lake Powell. Units AF</remarks>
/// <value> The colorado river flow. </value>
public int Colorado_River_Flow
{ get { return _ws.get_ColoradoRiverFlow; } }
//---------------------------------------
//get_PowellStorage
/// <summary> Gets the powell storage. </summary>
/// <value> The powell storage. </value>
///<remarks>The total water storage in Lake Powell. Units maf</remarks>
public int Powell_Storage
{ get { return _ws.get_PowellStorage; } }
//---------------------------------------
//get_MeadStorage
/// <summary> Gets the mead storage. </summary>
/// <value> The mead storage. </value>
///<remarks>The total annual water storage in Lake Mead Units maf</remarks>
public int Mead_Storage
{ get { return _ws.get_MeadStorage; } }
//---------------------------------------
//get_SaltVerdeRiverFlow
/// <summary> Gets the salt verde river flow. </summary>
/// <value> The salt verde river flow. </value>
///<remarks>The total annula flow of the Salt and Verde Rivers. Units AF</remarks>
public int SaltVerde_River_Flow
{ get { return _ws.get_SaltVerdeRiverFlow; } }
//---------------------------------------
//get_SaltVerdeStorage
/// <summary> Gets the salt verde storage. </summary>
/// <value> The salt verde storage. </value>
///<remarks>The total annual storage in the Salt River Project reservoirs. Units maf</remarks>
public int SaltVerde_Storage
{ get { return _ws.get_SaltVerdeStorage; } }
//---------------------------------------
//get_EffluentToAgriculture
/// <summary> Gets the effluent to agriculture. </summary>
/// <value> Units AF. </value>
///<remarks>The total amount of wastewater effluent delivered to agriculural users. Units AF</remarks>
public int Effluent_To_Agriculture
{ get { return _ws.get_EffluentToAgriculture; } }
//-------------------------------------------------------
///-------------------------------------------------------------------------------------------------
/// <summary> Gets the annual spillage over Granite Reef. </summary>
/// <value> The svt spillage. Units Af</value>
///<remarks>The total amount of water that is spilled from Granite Reef in the year. Units AF</remarks>
///-------------------------------------------------------------------------------------------------
public int SVT_Spillage
{ get { return _ws.get_SaltVerdeSpillage; } }
//----------------------------------------------------------------------------
///-------------------------------------------------------------------------------------------------
/// <summary> Gets the elevation ofLake Mead. </summary>
/// <value> The elevation of mead in feet. </value>
///<remarks> The Elevation of Lake Mead at the end of the year. Units Feet</remarks>
///-------------------------------------------------------------------------------------------------
public int Elevation_of_Mead
{ get { return _ws.get_MeadElevation; } }
///-------------------------------------------------------------------------------------------------
/// <summary> Gets the elevation ofLake Mead. </summary>
/// <value> The elevation of mead in feet. </value>
///<remarks> The Elevation of Lake Mead at the end of the year. Units Feet</remarks>
///-------------------------------------------------------------------------------------------------
public int Elevation_of_Powell
{ get { return _ws.get_PowellElevation; } }
///-------------------------------------------------------------------------------------------------
/// <summary> Gets the regional natural recharge. </summary>
///
/// <value> The regional natural recharge. Units AF </value>
///-------------------------------------------------------------------------------------------------
public int Regional_Natural_Recharge
{ get { return _ws.get_RegionalNaturalRecharge; } }
///-------------------------------------------------------------------------------------------------
/// <summary> Gets the regional cagrd recharge. </summary>
///
/// <value> The regional cagrd recharge. Units AF </value>
///-------------------------------------------------------------------------------------------------
public int Regional_CAGRD_Recharge
{ get { return _ws.CAGRD; } }
///-------------------------------------------------------------------------------------------------
/// <summary> Gets the regional inflow. </summary>
///
/// <value> The regional inflow. Units AF </value>
///-------------------------------------------------------------------------------------------------
public int Regional_Inflow
{ get { return _ws.get_RegionalInflow; } }
///-------------------------------------------------------------------------------------------------
/// <summary> Gets the regional ag to vadose. </summary>
///
/// <value> The regional ag to vadose flux. Units AF </value>
///-------------------------------------------------------------------------------------------------
public int Regional_Ag_To_Vadose
{ get { return _ws.get_RegionalAgToVadoseFlux; } }
///-------------------------------------------------------------------------------------------------
/// <summary> Gets the regional provider recharge. </summary>
///
/// <value> The total amount of recharge from all providers. Units AF</value>
///-------------------------------------------------------------------------------------------------
public int Regional_Provider_Recharge
{ get { return _ws.get_RegionalProviderRecharge; } }
///-------------------------------------------------------------------------------------------------
/// <summary> Gets the regional ag other pumping. </summary>
///
/// <value> The regional pumping from agriculture and other (non municiple ) uses. . Units AF </value>
///-------------------------------------------------------------------------------------------------
public int Regional_Ag_Other_Pumping
{ get { return _ws.get_RegionalAgOtherPumping; } }
///-------------------------------------------------------------------------------------------------
/// <summary> Gets the regional outflow. </summary>
///
/// <value> The regional natural aquifer outflow. . Units AF</value>
///-------------------------------------------------------------------------------------------------
public int Regional_Outflow
{ get { return _ws.get_RegionalOutflow; } }
///-------------------------------------------------------------------------------------------------
/// <summary> Gets the regional groundwater balance. </summary>
///
/// <value> The balance of the regional groundwater aquifer (estimate, assumes all recharge is in aquifer). Units AF </value>
///-------------------------------------------------------------------------------------------------
public int Regional_Groundwater_Balance
{ get { return _ws.get_RegionalGroundWaterBalance; } }
#endregion
//
// =========================================================
// Provider Outputs
//==========================================================
//
#region Provider Outputs
//---------------------------------------
/// <summary>
/// Gets the original Raw GPCD curves
/// </summary>
public providerArrayProperty GPCD_raw;
internal int[] get_GPCDraw() { return _ws.get_ProviderGPCDraw; }
//---------------------------------------
private int[] get_TWWTP_Created()
{ return _ws.get_TotalTWWTP; }
/// <summary> The reclaimed water created </summary>
///<remarks>The total annual amount of reclaimed water created, used and discharged. Units AF</remarks>
public providerArrayProperty Total_WWTP_Effluent;
//---------------------------------------
// get_ProviderGWPumpedMunicipal
private int[] get_Groundwater_Pumped_Municipal()
{ return _ws.get_ProviderGWPumpedMunicipal; }
/// <summary> The groundwater pumped municipal </summary>
///<remarks>The total amount of annual groundwater pumped. Units AF</remarks>
public providerArrayProperty Groundwater_Pumped_Municipal;
//---------------------------------------
//ProviderGroundwater
private int[] get_Groundwater_Balance()
//{ return _ws.ModelGroundwater; } Changed based on new credit model
{ return _ws.get_WaterCreditTotals; }
/// <summary> The groundwater balance </summary>
///<remarks>The total groundwater supply available at end of year. Units AF.
/// A call to this method before the first year has been run returns 0 values</remarks>
public providerArrayProperty Groundwater_Balance;
//---------------------------------------
//get_SVTAnnualDeliveriesSRP
private int[] get_SaltVerde_Annual_Deliveries_SRP()
{ return _ws.get_SVTAnnualDeliveriesSRP; }
/// <summary> The salt verde annual deliveries srp </summary>
///<remarks>The total annual surface water and pumped groundwater delivered by SRP. Units AF</remarks>
/// <seealso cref="Groundwater_Bank_Used"/>
///
public providerArrayProperty SaltVerde_Annual_Deliveries_SRP;
//---------------------------------------
//get_SaltVerdeClassBCDesignations
private int[] get_SaltVerde_Class_BC_Designations()
{ return _ws.get_SaltVerdeClassBCDesignationsUsed; }
// Quay Changed to get_SaltVerdeClassBCDesignationsUsed from get_SaltVerdeClassBCDesignations 3/6/13
/// <summary> The salt verde class bc designations </summary>
///<remarks>The total annual B / C designated surface water delivered by SRP. Units AF</remarks>
public providerArrayProperty SaltVerde_Class_BC_Designations;
//---------------------------------------
//get_ColoradoAnnualDeliveries
private int[] get_Colorado_Annual_Deliveries()
{ return _ws.get_ColoradoAnnualDeliveries; }
/// <summary> The colorado annual deliveries </summary>
///<remarks>The total annual surface water deliveries by CAP, does not included banked water. Units AF</remarks>
/// <seealso cref="Groundwater_Bank_Used"/>
public providerArrayProperty Colorado_Annual_Deliveries;
//---------------------------------------
//get_GroundwaterBankUsed
private int[] get_Groundwater_Bank_Used()
{ return _ws.get_GroundwaterBankUsed; }
/// <summary> The groundwater bank used </summary>
///<remarks>The total annual amount of water delivered from water banking facilities. These ground water facilities are assumed to be physically outside the providers groundwater assets and would be delivered from these remote facilities to the provider. Some of this may be delivered through the CAP or SRP canals but is not icnluded in SRP or CAP totals. Units AF</remarks>
/// <seealso cref="SaltVerde_Annual_Deliveries_SRP"/>
/// <seealso cref="Colorado_Annual_Deliveries"/>
public providerArrayProperty Groundwater_Bank_Used;
//---------------------------------------
//get_GroundwaterBankBalance
private int[] get_Groundwater_Bank_Balance()
{ return _ws.get_GroundwaterBankBalance; }
/// <summary> The groundwater bank balance </summary>
///<remarks>The total banked water supply available at end of year. Units AF</remarks>
public providerArrayProperty Groundwater_Bank_Balance;
//---------------------------------------
//get_ReclaimedWaterCreated
private int[] get_Reclaimed_Water_Created()
{ return _ws.get_ReclaimedWaterCreated; }
/// <summary> The reclaimed water created </summary>
///<remarks>The total annual amount of reclaimed water created, used and discharged. Units AF</remarks>
public providerArrayProperty Reclaimed_Water_Created;
//---------------------------------------
//get_ReclaimedWaterUsed
private int[] get_Reclaimed_Water_Used()
{ return _ws.get_ReclaimedWaterUsed; }
/// <summary> The reclaimed water used </summary>
///<remarks>The total annual amount of reclaimed water used. Units AF</remarks>
///<see cref="Reclaimed_Water_Created"/>
public providerArrayProperty Reclaimed_Water_Used;
//---------------------------------------
//get_ReclaimedWaterToVadose
private int[] get_Reclaimed_Water_To_Vadose()
{ return _ws.get_ReclaimedWaterToVadose; }
/// <summary> The reclaimed water to vadose </summary>
///<remarks>The annual amount of reclimed water used for vadose zone recharge. Units AF</remarks>
public providerArrayProperty Reclaimed_Water_To_Vadose;
//---------------------------------------
//get_ReclaimedWaterDischarged
private int[] get_Reclaimed_Water_Discharged()
{ return _ws.get_ReclaimedWaterDischarged; }
/// <summary> The reclaimed water discharged </summary>
public providerArrayProperty Reclaimed_Water_Discharged;
//---------------------------------------
//get_ReclaimedWaterDirectInject
private int[] get_Reclaimed_Water_to_DirectInject()
{ return _ws.get_ReclaimedWaterDirectInject; }
/// <summary> The reclaimed water to direct inject </summary>
public providerArrayProperty Reclaimed_Water_to_DirectInject;
//---------------------------------------
//get_ROreclaimedWaterCreated
private int[] get_RO_Reclaimed_Water_Created()
{ return _ws.get_ROreclaimedWaterCreated; }
/// <summary> The ro reclaimed water created </summary>
public providerArrayProperty RO_Reclaimed_Water_Created;
//---------------------------------------
//get_ROreclaimedWaterUsed
private int[] get_RO_Reclaimed_Water_Used()
{ return _ws.get_ROreclaimedWaterUsed; }
/// <summary> The ro reclaimed water used </summary>
public providerArrayProperty RO_Reclaimed_Water_Used;
//---------------------------------------
//get_ROreclaimedWaterDirectInject
private int[] get_RO_Reclaimed_Water_to_DirectInject()
{ return _ws.get_ROreclaimedWaterDirectInject; }
/// <summary> The ro reclaimed water to direct inject </summary>
public providerArrayProperty RO_Reclaimed_Water_to_DirectInject;
//---------------------------------------
//get_EffluentCreated
private int[] get_Total_Effluent_Reused()
{ return _ws.get_TotalEffluentReused; }
/// <summary> The effluent created </summary>
///<remarks>The total annual amount of wastewater effluent produced. Units </remarks>
public providerArrayProperty Total_Effluent_Reused;
//---------------------------------------
//get_EffluentToVadose
private int[] get_Effluent_To_Vadose()
{ return _ws.get_EffluentToVadose; }
/// <summary> The effluent to vadose </summary>
///<remarks>The annual amount of reclaimed water used for vadose zone recharge. Units AF</remarks>
public providerArrayProperty Effluent_To_Vadose;
//---------------------------------------
//get_EffluentToPowerPlant
private int[] get_Effluent_To_PowerPlant()
{ return _ws.get_EffluentToPowerPlant; }
/// <summary> The effluent to power plant </summary>
///<remarks>The annual amount of effluent delivered to power plants. Units AF</remarks>
public providerArrayProperty Effluent_To_PowerPlant;
//---------------------------------------
//get_EffluentDischarged
private int[] get_Effluent_Discharged()
{ return _ws.get_EffluentDischarged; }
/// <summary> The effluent discharged </summary>
///<remarks>The annual amount of wastewater effluent discharged to a water course (envirionment). Units AF</remarks>
public providerArrayProperty Effluent_Discharged;
// get_WaterCreditIncidental
internal int[] get_Incidental_Water_Credit()
{ return _ws.get_WaterCreditIncidental; }
/// <summary> The amount of annual incendental recharge credit by provider</summary>
///<remarks>The annual amount of incidental water use that is credited annually as recharge to the aquifer. Units AF</remarks>
public providerArrayProperty Incidental_Water_Credit;
// get_VadoseToAquiferFlux
internal int[] get_Total_Vadose_To_Aquifer_Flux()
{ return _ws.get_VadoseToAquiferFlux; }
/// <summary> The amount of annual incendental recharge credit by provider</summary>
///<remarks>The annual amount of incidental water use that is credited annually as recharge to the aquifer. Units AF</remarks>
public providerArrayProperty Total_Vadose_To_Aquifer;
// On-Project Population - Provider level: internal int[] get_PopulationOnProject
private int[] get_Population_OnProject()
{ return _ws.get_PopulationOnProject; }
/// <summary> The population project. </summary>
public providerArrayProperty Population_On_Project;
// On-Project Population - Provider level: internal int[] get_PopulationOnProject
private int[] get_Population_Other()
{ return _ws.get_PopulationOther; }
/// <summary> The population other. </summary>
public providerArrayProperty Population_Other;
//---
// ------------------------------------
//get_DemandDeficit
private int[] get_Demand_Deficit()
{ return _ws.get_DemandDeficit; }
/// <summary> The demand deficit </summary>
///<remarks>The annual difference between demand and supply (demand - supply), 0 if supply is larger than demand. Units AF. This is a good candidate as a indicator parameter.
/// There are a number of management actions that can be taken, and reflected in the model parameters to manage water supplies and demand.
/// A community's demand exceeding supply is an indicator of either a non-sustainable water resources budget or inadequate management of available water supplies and demand.
/// Both indicate an unresolved water resource issue for the community. Currently there is no feedback in the model to reduce growth (thus demand growth) for a community when a demand deficit occurs, nor a feedback to allocate this growth to other providers.</remarks>
public providerArrayProperty Demand_Deficit;
//---------------------------------------
//ProviderGPCD
private int[] get_GPCD_Used()
{ return _ws.ProviderGPCD; }
/// <summary> The gpcd used </summary>
///<remarks>The GPCD used to estimate demand for the completed simulation year. When Provider_Demand_Option is 1,2, or 3, this is the calculated GPCD used to estimate demand.
/// if the Provider_Demand_Option =4, this is the GPCD specified by Use_GPCD parameter. Units: gpcd-gallons per capita per daya of water use</remarks>
/// <seealso cref="Provider_Demand_Option"/>
/// <seealso cref="Use_GPCD"/>
public providerArrayProperty GPCD_Used;
//---------------------------------------
//TotalDemands
private int[] get_Total_Demand()
{ return _ws.get_WaterDemand; } // { return _ws.TotalDemands; }
/// <summary> The total demand </summary>
///<remarks>The total annual demand from all water customers. Units AF. This calculated based on provider demand</remarks>
public providerArrayProperty Total_Demand;
//---------------------------------------
//Population
private int[] get_Population_Used()
{ return _ws.get_Populations; }
/// <summary> The population used </summary>
///<remarks>The population used to estimate demand for the completed simulation year. Units people</remarks>
public providerArrayProperty Population_Used;
//----------------------------------
// Off Project Demand
private int[] get_Demand_Off_Project()
{ return _ws.get_WaterDemandOther; }
/// <summary> The demand off project. </summary>
public providerArrayProperty Demand_Off_Project;
//----------------------------------
// Off Project Demand
private int[] get_Demand_On_Project()
{ return _ws.get_WaterDemandOnProject; }
/// <summary> The demand on project. </summary>
public providerArrayProperty Demand_On_Project;
#endregion
/*****************************************************************
* Base Input Parameters
*
* ****************************************************************/
#region Base Input Parameters
//===============================================================
// Model Dummy Input Parameters (REMEMBER TO PUT NEW ONES IN THE DEFAULT INIIALIZE ROUTINE
private int _Simulation_Start_Year = util.WaterSimDCDC_Default_Simulation_StartYear;
private int _Simulation_End_Year = util.WaterSimDCDC_Default_Simulation_EndYear;
//---------------------------------------
// Start year of simulation
// Cannot be set while simulation in progress
// Using shadow value _Simulation_Start_Year; no get in WaterSimU
/// <summary>
/// Simulation_Start_Year
/// </summary>
/// <value>The first year of the Simulation.</value>
/// <remarks> The first year of the Simulation. Range = 2000 to 2006 Cannot be set after Simulation starts.</remarks>
/// <exception cref="WaterSim_Exception">if setting a value that does not pass the range check</exception>
public int Simulation_Start_Year
{
set
{
if ((!_inRun)&(!FModelLocked))
{
_pm.CheckBaseValueRange(eModelParam.epSimulation_Start_Year, value);
_ws.SimulationStart = value;
_Simulation_Start_Year = value;
}
}
get { return _Simulation_Start_Year; } //
}
//---------------------------------------
//End year of simulation SimulationEnd
// Cannot be set while simulation in progress
// Using shadow value _Simulation_End_Year; no get in WaterSimU
/// <summary> Gets or sets the simulation end year. </summary>
/// <value> The simulation end year. </value>
///<remarks> The last year of the Simulation. Range = 2012 to 2085 Cannot be set after Simulation starts.</remarks>
/// <exception cref="WaterSim_Exception">if setting a value that does not pass the range check</exception>
public int Simulation_End_Year
{
set
{
if ((!_inRun) & (!FModelLocked))
{
_pm.CheckBaseValueRange(eModelParam.epSimulation_End_Year, value);
_ws.SimulationEnd = value + 1; // Added this to force model to run last year;
_Simulation_End_Year = value;
}
// ELSE do we throw an exception? No Just document that it is ignored
}
get { return _Simulation_End_Year; }
}
//---------------------------------------
//Index Year ColoradoHistoricalExtractionStartYear
// Cannot be set while simulation in progress
/// <summary> Gets or sets the colorado historical extraction start year. </summary>
/// <value> The colorado historical extraction start year. </value>
///<remarks> The first year of the Colorado River flow record that will be used to create a 25 year trace to simulate river flow conditions. Special Range Check Applies See ColoradoYearRangeCheck Cannot be set after Simulation starts.
/// Valid ranges are defined as follows <code>
/// internal RiverRange ColoradoPaleo = new RiverRange(762, 1982);
/// internal RiverRange ColoradoBureau = new RiverRange(1906, 1982);</code> </remarks>
/// <exception cref="WaterSim_Exception">if setting a value that does not pass the range check</exception>
/// <seealso cref="RiverRange"/>
/// <seealso cref="Colorado_Historical_Data_Source"/>
public int Colorado_Historical_Extraction_Start_Year
{
set
{
if ((!_inRun) & (!FModelLocked))
{
_pm.CheckBaseValueRange(eModelParam.epColorado_Historical_Extraction_Start_Year, value);
_ws.ColoradoHistoricalExtractionStartYear = value;
}
// ELSE do we throw an exception, A Message? No Just document that it is ignored
}
get { return _ws.ColoradoHistoricalExtractionStartYear; }
}
//---------------------------------------
//Replace File ColoradoHistoricalData =1, paleo data; =2, Bireau of Rec data;=3, scenario data
// Cannot be set while simulation in progress
// using shadow value _Colorado_Historical_Data_Source no get in WaterSimU
/// <summary> Gets or sets the colorado historical data source. </summary>
/// <value> The colorado historical data source. </value>
/// <remarks> The source of the Colorado River flow record: Value 1 uses the Bureau of Reclamation recorded record, Value 2 uses the tree ring reconstructed paleo record, Value 3 uses a user supplied river flow trace record Range = 1 to 3 Cannot be set after Simulation starts.</remarks>
/// <exception cref="WaterSim_Exception">if setting a value that does not pass the range check</exception>
public int Colorado_Historical_Data_Source
{
set
{
if ((!_inRun) & (!FModelLocked))
{
_pm.CheckBaseValueRange(eModelParam.epColorado_Historical_Data_Source, value);
// ok setting but start and stop may not be set, change these and document
ColoradoRiverHistoricalReSetStart(value);
_ws.ColoradoHistoricalData = value;
// _Colorado_Historical_Data_Source = value; changed 7 24 11
}
}
get { return _ws.ColoradoHistoricalData; } // _Colorado_Historical_Data_Source; } changed 7 24 11
}
//---------------------------------------
//Climate Adjustment ColoradoClimateAdjustmentPercent
/// <summary> Gets or sets the colorado climate adjustment percent. </summary>
/// <value> The colorado climate adjustment percent. </value>
/// <remarks> The percent (Value=50 is 50%) which is used to modify the Colorado river flow record, simulating impacts of climate change. Change starts at beginning of Simulation. Range = 0 to 300 Cannot be set after Simulation starts.</remarks>
/// <exception cref="WaterSim_Exception">if setting a value that does not pass the range check</exception>
public int Colorado_Climate_Adjustment_Percent
{
set
{
if ((!_inRun) & (!FModelLocked))
{
_pm.CheckBaseValueRange(eModelParam.epColorado_Climate_Adjustment_Percent, value);
_ws.ColoradoClimateAdjustmentPercent = value;
}
}
get { return _ws.ColoradoClimateAdjustmentPercent; }
}
//---------------------------------------
//Drought-Adjustment ColoradoUserAdjustmentPercent
/// <summary> Gets or sets the colorado user adjustment percent. </summary>
/// <value> The colorado user adjustment percent. </value>
/// <remarks> The percent (Value=50 is 50%) which is used to modify the Colorado River flow record, starting and stopping in the years specified. This is used to simulate a drought condition. Range = 0 to 300 Cannot be set after Simulation starts.</remarks>
/// <exception cref="WaterSim_Exception">if setting a value that does not pass the range check</exception>
/// <seealso cref="Colorado_User_Adjustment_StartYear"/>
/// <seealso cref="Colorado_User_Adjustment_Stop_Year"/>
public int Colorado_User_Adjustment_Percent
{
set
{
if ((!_inRun) & (!FModelLocked))
{
_pm.CheckBaseValueRange(eModelParam.epColorado_User_Adjustment_Percent, value);
_ws.ColoradoUserAdjustmentPercent = value;
}
}
get { return _ws.ColoradoUserAdjustmentPercent; }
}
//---------------------------------------
//Drought-Start Year ColoradoUserAdjustmentStartYear
/// <summary> Gets or sets the colorado user adjustment start year. </summary>
/// <value> The colorado user adjustment start year. </value>
/// <remarks> Determines the year the [Colorado User Adjustment %] will be start being applied. Range = 2006 to 2081 Cannot be set after Simulation starts.</remarks>
/// <exception cref="WaterSim_Exception">if setting a value that does not pass the range check</exception>
/// <seealso cref="Colorado_User_Adjustment_Percent"/>
/// <seealso cref="Colorado_User_Adjustment_Stop_Year"/>
public int Colorado_User_Adjustment_StartYear
{
set
{
if ((!_inRun) & (!FModelLocked))
{
_pm.CheckBaseValueRange(eModelParam.epColorado_User_Adjustment_StartYear, value);
_ws.ColoradoUserAdjustmentStartYear = value;
}
}
get { return _ws.ColoradoUserAdjustmentStartYear; }
}
//---------------------------------------
//Drought_Stop year ColoradoUserAdjustmentStopYear
/// <summary> Gets or sets the colorado user adjustment stop year. </summary>
/// <value> The colorado user adjustment stop year. </value>
/// <remarks> Determines the year the [Colorado User Adjustment %] will be stopped being applied. Range = 2006 to 2081 Cannot be set after Simulation starts.</remarks>
/// <exception cref="WaterSim_Exception">if setting a value that does not pass the range check</exception>
/// <seealso cref="Colorado_User_Adjustment_Percent"/>
/// <seealso cref="Colorado_User_Adjustment_StartYear"/>
public int Colorado_User_Adjustment_Stop_Year
{
set
{
if ((!_inRun) & (!FModelLocked))
{
_pm.CheckBaseValueRange(eModelParam.epColorado_User_Adjustment_Stop_Year, value);
_ws.ColoradoUserAdjustmentStopYear = value;
}
}
get { return _ws.ColoradoUserAdjustmentStopYear; }
}
//---------------------------------------
//Index Year SaltVerdeHistoricalExtractionStartYear
/// <summary> Gets or sets the salt verde historical extraction start year. </summary>
/// <value> The salt verde historical extraction start year. </value>
/// <remarks> The first year of the Salt Verde River flow record that will be used to create a 25 year trace to simulate river flow conditions. Special Range Check Applies See SaltVerdeYearRangeCheck Cannot be set after Simulation starts.
/// Valid ranges are defined as follows <code>
/// internal RiverRange SaltVerdePaleo = new RiverRange(1330, 1982);
/// internal RiverRange SaltVerdeBureau = new RiverRange(1945, 1982);
/// </code></remarks>
/// <exception cref="WaterSim_Exception">if setting a value that does not pass the range check</exception>
/// <seealso cref="SaltVerde_Historical_Data_Source"/>
/// <seealso cref="RiverRange"/>
public int SaltVerde_Historical_Extraction_Start_Year
{
set
{
if ((!_inRun) & (!FModelLocked))
{
_pm.CheckBaseValueRange(eModelParam.epSaltVerde_Historical_Extraction_Start_Year, value);
_ws.SaltVerdeHistoricalExtractionStartYear = value;
}
}
get { return _ws.SaltVerdeHistoricalExtractionStartYear; }
}
//---------------------------------------
//Replace File SaltVerdeTontoHistoricalData
/// <summary> Gets or sets the salt verde historical data source. </summary>
/// <value> The salt verde historical data source. </value>
/// <remarks> The source of the Salt Verde Rivers flow record: Value=1 uses the tree ring reconstructed paleo record, Value=2 uses the Bureau of Reclamation recorded record, Value=3 uses a user supplied river flow trace record. Range = 1 to 3 Cannot be set after Simulation starts.</remarks>
/// <exception cref="WaterSim_Exception">if setting a value that does not pass the range check</exception>
public int SaltVerde_Historical_Data_Source
{
set
{
if ((!_inRun) & (!FModelLocked))
{
_pm.CheckBaseValueRange(eModelParam.epSaltVerde_Historical_Data, value);
// ok setting but start and stop may not be set, change these and document
SaltVerdeRiverHistoricalReSetStart(value);
_ws.SaltVerdeTontoHistoricalData = value;
// _SaltVerde_Historical_Data = value; // changed 7 24 11
}
}
get { return _ws.SaltVerdeTontoHistoricalData; } // _SaltVerde_Historical_Data; } changed 7 24 11
}
//---------------------------------------
//Climate Adjustment SaltVerdeClimateAdjustmentPercent
/// <summary> Gets or sets the salt verde climate adjustment percent. </summary>
///
/// <value> The salt verde climate adjustment percent. </value>
/// <remarks> The percent (Value=50 is 50%) which is used to modify the Salt Verde River flow record, simulating impacts of climate change. Change starts at beginning of Simulation. Range = 0 to 300 Cannot be set after Simulation starts.</remarks>
/// <exception cref="WaterSim_Exception">if setting a value that does not pass the range check</exception>
public int SaltVerde_Climate_Adjustment_Percent
{
set
{
if ((!_inRun) & (!FModelLocked))
{
_pm.CheckBaseValueRange(eModelParam.epSaltVerde_Climate_Adjustment_Percent, value);
_ws.SaltVerdeClimateAdjustmentPercent = value;
}
}
get { return _ws.SaltVerdeClimateAdjustmentPercent; }
}
//---------------------------------------
//Drought-Adjustment SaltVerdeUserAdjustmentPercent
/// <summary> Gets or sets the salt verde user adjustment percent. </summary>
/// <value> The salt verde user adjustment percent. </value>
/// <remarks> The percent (Value=50 is 50%) which is used to modify the Salt Verde River flow record, starting and stopping in the years specified. This is used to simulate a drought condition. Range = 0 to 300 Cannot be set after Simulation starts.</remarks>
/// <exception cref="WaterSim_Exception">if setting a value that does not pass the range check</exception>
/// <seealso cref="SaltVerde_User_Adjustment_Start_Year"/>
/// <seealso cref="SaltVerde_User_Adjustment_Stop_Year"/>
public int SaltVerde_User_Adjustment_Percent
{
set
{
if ((!_inRun) & (!FModelLocked))
{
_pm.CheckBaseValueRange(eModelParam.epSaltVerde_User_Adjustment_Percent, value);
_ws.SaltVerdeUserAdjustmentPercent = value;
}
}
get { return _ws.SaltVerdeUserAdjustmentPercent; }
}
//---------------------------------------
//Drought-Start Year SaltVerdeUserAdjustmentStartYear
/// <summary> Gets or sets the salt verde user adjustment start year. </summary>
/// <value> The salt verde user adjustment start year. </value>
/// <remarks> Determines the year the [SaltVerde User Adjustment %] will be start being applied. Range = 2006 to 2081 Cannot be set after Simulation starts.</remarks>
/// <exception cref="WaterSim_Exception">if setting a value that does not pass the range check</exception>
/// <seealso cref="SaltVerde_User_Adjustment_Stop_Year"/>
/// <seealso cref="SaltVerde_User_Adjustment_Percent"/>
public int SaltVerde_User_Adjustment_Start_Year
{
set
{
if ((!_inRun) & (!FModelLocked))
{
_pm.CheckBaseValueRange(eModelParam.epSaltVerde_User_Adjustment_Start_Year, value);
_ws.SaltVerdeUserAdjustmentStartYear = value;
}
}
get { return _ws.SaltVerdeUserAdjustmentStartYear; }
}
//---------------------------------------
//Drought_Stop year SaltVerdeUserAdjustmentStopYear
/// <summary> Gets or sets the salt verde user adjustment stop year. </summary>
/// <value> The salt verde user adjustment stop year. </value>
/// <remarks> Determines the year the [SaltVerde User Adjustment %] will be stopped being applied. Range = 2006 to 2081 Cannot be set after Simulation starts.</remarks>
/// <exception cref="WaterSim_Exception">if setting a value that does not pass the range check</exception>"
/// <seealso cref="SaltVerde_User_Adjustment_Start_Year"/>
/// <seealso cref="SaltVerde_User_Adjustment_Percent"/>
public int SaltVerde_User_Adjustment_Stop_Year
{
set
{
if ((!_inRun) & (!FModelLocked))
{
_pm.CheckBaseValueRange(eModelParam.epSaltVerde_User_Adjustment_Stop_Year, value);
_ws.SaltVerdeUserAdjustmentStopYear = value;
}
}
get { return _ws.SaltVerdeUserAdjustmentStopYear; }
}
//---------------------------------------
//Water demand option ProviderDemandOption
/// <summary> Demand from file </summary>
/// <remarks> Use with Provider_Demand_Option <see cref="Provider_Demand_Option"/></remarks> <seealso cref="Provider_Demand_Option"/>
public const int pdoDemandFromFile = 1;
/// <summary> Average gpcd and pop </summary>
/// <remarks> Use with Provider_Demand_Option <see cref="Provider_Demand_Option"/></remarks> <seealso cref="Provider_Demand_Option"/>
public const int pdoAverageGPCDandPOP = 2;
/// <summary> Declining gpcd and pop </summary>
/// <remarks> Use with Provider_Demand_Option <see cref="Provider_Demand_Option"/></remarks> <seealso cref="Provider_Demand_Option"/>
public const int pdoDecliningGPCDandPOP = 3;
/// <summary> User gpcd and pop </summary>
/// <remarks> Use with Provider_Demand_Option <see cref="Provider_Demand_Option"/></remarks> <seealso cref="Provider_Demand_Option"/>
public const int pdoUserGPCDandPOP = 4;
/// <summary> Gets or sets the provider demand option. </summary>
///
/// <value> The provider demand option. </value>
/// <remarks> The method that will be used to estimate annual demand for all providers. Value=1 reads demand values from an external file, Value=2 calculates demand based on a six year average GPCD and population read from a file, Value=3 estimates demand based on population estimates read from and external file and a smoothing function that slowly declines GPCD, Value=4 uses same method as 3, but allows the user to chnage the GPCD with Use_GPCD Paramtere <see cref="Use_GPCD"/>used for each provider at the beginning or during the simulation. Range = 1 to 4 Cannot be set after Simulation starts.</remarks>
/// <exception cref="WaterSim_Exception">if setting a value that does not pass the range check</exception>
/// <seealso cref="Use_GPCD"/>
public int Provider_Demand_Option
{
set
{
_pm.CheckBaseValueRange(eModelParam.epProvider_Demand_Option, value);
_ws.ProviderDemandOption = value;
}
get { return _ws.ProviderDemandOption;}
}
//===========================================================
/// <summary> Provider demand option label. </summary>
/// <param name="value"> provider demand option value. </param>
/// <returns>a string lable for the provider demand option values </returns>
public string Provider_Demand_Option_Label(int value)
{
_pm.CheckBaseValueRange(eModelParam.epProvider_Demand_Option, value);
switch (value)
{
case pdoDemandFromFile:
return "Demand from file";
case pdoAverageGPCDandPOP:
return "6 Year Average GPCD and Population";
case pdoDecliningGPCDandPOP:
return "Declining GPCD and Population";
case pdoUserGPCDandPOP:
return "User Assigned GPCD";
default:
return "Bad Value";
}
}
//---------------------------------------------------------------------------------------------------------------
//set_ReduceGPCDpct
// Fix for no get on GOCD
int ReduceGPCDValue = util.DefaultReduceGPCDValue;
/// <summary> Gets or sets the Percent to Reduce GPCD. </summary>
/// <value> The percent reduction in gpcd. </value>
/// <remarks>The amount by which GPCD is expected to decrease by the end of the simulation (i.e., 2085).
/// Use this when Provider Demand Option is = 3 or Provider Demand Option=4.</remarks>
/// <seealso cref="Provider_Demand_Option"/>
///
public int PCT_Reduce_GPCD
{
set
{
if ((!_inRun) & (!FModelLocked))
{
_pm.CheckBaseValueRange(eModelParam.epPCT_Alter_GPCD, value);
_ws.set_AlterGPCDpct = value;
// Store is this shadow value becuase model does not have one.
ReduceGPCDValue = value;
}
}
get { return ReduceGPCDValue;}
}
//---------------------------------------
// get_ProviderPopGrowthRateAdjustmentPct
// provides for region wide adjusted growth rate
// Must be 0 to use provider level pop growth rate adjustement
// public void seti_PCT_REG_Growth_Rate_Adjustment_Value(int value) { if (!FModelLocked) _ws.PopulationGrowthRateAdjustmentPercent = value; }
///-------------------------------------------------------------------------------------------------
/// <summary> Gets or sets the regional growth rate adjustment factor. </summary>
///
/// <value> The regional growth rate adjustment factor </value>
/// <remarks>Adjuses the project growth rate for all providers by this factor. 100 means no change, 50 means 50% less than projection, 150 means 150% more than projected</remarks>
///-------------------------------------------------------------------------------------------------
public int Regional_Growth_Rate_Adjust
{
set
{
/// DAVID Changed 2/24/14
//if ((!_inRun) & (!FModelLocked))
if (!FModelLocked)
{
_pm.CheckBaseValueRange(eModelParam.epPCT_REG_Growth_Rate_Adjustment, value);
seti_PCT_REG_Growth_Rate_Adjustment(value);
}
// ELSE do we throw an exception? No Just document that it is ignored
}
get { return geti_PCT_REG_Growth_Rate_Adjustment(); }
}
//--------------------------------------------------
internal bool _Assured_Water_Supply_Annual_Groundwater_Pumping_Limit = false;
///-------------------------------------------------------------------------------------------------
/// <summary> Gets or sets the assured water supply annual groundwater pumping limit.
/// </summary>
///
/// <value> The assured water supply annual groundwater pumping limit. </value>
///-------------------------------------------------------------------------------------------------
public int Assured_Water_Supply_Annual_Groundwater_Pumping_Limit
{
set
{
if ((!_inRun) & (!FModelLocked))
{
_pm.CheckBaseValueRange(eModelParam.epAWSAnnualGWLimit, value);
seti_Assured_Water_Supply_Annual_Groundwater_Pumping_Limit(value);
}
}
get
{
return geti_Assured_Water_Supply_Annual_Groundwater_Pumping_Limit();
}
}
#endregion
//=====================================
// Provider Inputs
//=====================================
#region Provider Inputs
//----------------------------------------------------------------
/// <summary>
///
/// </summary>
public providerArrayProperty Maximum_normalFlow_rights;
internal int[] get_normalFlow_rights_max()
{ return _ws.NormalFlow_rights_max; }
internal void set_normalFlow_rights_max(int[] value)
{
if (!FModelLocked) _ws.NormalFlow_rights_max = value;
}
//----------------------------------------------------------------
// QUAY revised 3/16/13
//
// DAS revised 03.15.14
/// <summary>
/// An Amount of Augmented Water to add to Supply
/// </summary>
/// <remarks> Factor used to add additional water from some source external to the region to a providers water supply</remarks>
public providerArrayProperty WaterAugmentation;
internal int[] get_NewWater() { return WaterAugmentationMemory; }
internal void set_NewWater(int[] value)
{
if (!FModelLocked)
{
_ws.NewWaterSupplies = value;
WaterAugmentationMemory = value;
}
}
//
public providerArrayProperty WaterAugmentationUsed;
internal int[] get_NewWaterUsed() { return _ws.get_NewWaterSuppliesUsed ; }
//
public providerArrayProperty PCT_alter_GPCD;
internal void set_alterGPCDpct(int[] value) { if (!FModelLocked) _ws.AlterProviderGPCDpct = value; }
internal int[] get_alterGPCDpct() {return _ws.AlterProviderGPCDpct ; }
// Normal Flow
internal int[] get_modifyNormalFlow() { return _ws.ModifyProviderNormalFlowPct; }
internal void set_modifyNormalFlow(int[] value) { if (!FModelLocked) _ws.ModifyProviderNormalFlowPct = value; }
/// <summary> The pct modify normal flow </summary>
/// <remarks> Factor used to adjust normal flow allocation per acre (SRP)</remarks>
public providerArrayProperty PCT_modify_normalFlow;
//WWtoRWWTP parmWWtoRWWTPpct
internal int[] get_PCT_Wastewater_Reclaimed() { return _ws.parmWWtoRWWTPpct; }
internal void set_PCT_Wastewater_Reclaimed(int[] value)
{ //pm.CheckValueRange(eModelParam.epPCT_Effluent_Reclaimed, value, true);
if (!FModelLocked) _ws.parmWWtoRWWTPpct = value;
}
/// <summary> The percent wastewater reclaimed </summary>
/// <remarks> The percent of wasterwater that is sent to a Reclaim Plant, Range 0 to 100 </remarks>
/// <exception cref="WaterSim_Exception">if setting a value that does not pass the range check</exception>
public providerArrayProperty PCT_Wastewater_Reclaimed;
//---------------------------------------
//WWtoEffluent parmWWtoEffluentPct
internal int[] get_PCT_Wastewater_to_Effluent() { return _ws.parmWWtoEffluentPct; }
internal void set_PCT_Wastewater_to_Effluent(int[] value) { if (!FModelLocked) _ws.parmWWtoEffluentPct = value; }
/// <summary> The percent wastewater to effluent </summary>
/// <remarks> The percent of wasterwater effluent that is used and not discharged into a water course. Range = 0 to 100</remarks>
/// <exception cref="WaterSim_Exception">if setting a value that does not pass the range check</exception>
public providerArrayProperty PCT_Wastewater_to_Effluent;
//---------------------------------------
//RWWtoRO parmReclaimedWWtoROpct
internal int[] get_PCT_Reclaimed_to_RO() { return _ws.parmReclaimedWWtoROpct; }
internal void set_PCT_Reclaimed_to_RO(int[] value) { if (!FModelLocked) _ws.parmReclaimedWWtoROpct = value; }
/// <summary> The percent reclaimed to Reverse Osmosis </summary>
/// <remarks> The percent of reclaimed water that is sent to a Reverse Osmosis Plant (becomes potable). Special Range Check Applies See PCTReclaimedRangeCheck</remarks>
/// <exception cref="WaterSim_Exception">if setting a value that does not pass the range check</exception>
/// <seealso cref="WaterSimDCDC.WaterSimManager.PCTReclaimedRangeCheck(int, WaterSimDCDC.eProvider, int)"/>
/// <seealso cref="WaterSimDCDC.WaterSimManager.PCTReclaimedRangeCheck(int, WaterSimDCDC.eProvider, ref string, WaterSimDCDC.ModelParameterBaseClass)"/>
public providerArrayProperty PCT_Reclaimed_to_RO;
//---------------------------------------
//ROtoOutput parmROReclaimedToOutputPct
internal int[] get_PCT_RO_to_Water_Supply() { return _ws.parmROReclaimedToOutputPct; }
internal void set_PCT_RO_to_Water_Supply(int[] value) { if (!FModelLocked) _ws.parmROReclaimedToOutputPct = value; }
/// <summary> The percent reverse osmosis water to water supply </summary>
/// <remarks> The percent of water from Reverse Osmosis Plant that is used for potable water demand. Range = 0 to 100</remarks>
/// <exception cref="WaterSim_Exception">if setting a value that does not pass the range check</exception>
public providerArrayProperty PCT_RO_to_Water_Supply;
//---------------------------------------
//RtoDInjection parmReclaimedToDirectInjectPct
internal int[] get_PCT_Reclaimed_to_DirectInject() { return _ws.parmReclaimedToDirectInjectPct; }
internal void set_PCT_Reclaimed_to_DirectInject(int[] value) { if (!FModelLocked) _ws.parmReclaimedToDirectInjectPct = value; }
/// <summary> The percent reclaimed to direct inject </summary>
/// <remarks> The percent of reclaimed ater that is used to recharge an aquifer by direct injection into an aquifer. Special Range Check Applies See PCTReclaimedRangeCheck</remarks>
/// <exception cref="WaterSim_Exception">if setting a value that does not pass the range check</exception>
/// <seealso cref="WaterSimDCDC.WaterSimManager.PCTReclaimedRangeCheck(int, WaterSimDCDC.eProvider, int)"/>
/// <seealso cref="WaterSimDCDC.WaterSimManager.PCTReclaimedRangeCheck(int, WaterSimDCDC.eProvider, ref string, WaterSimDCDC.ModelParameterBaseClass)"/>
/// <seealso cref="ParameterManagerClass.reclaimedchecklist"/>
public providerArrayProperty PCT_Reclaimed_to_DirectInject;
//---------------------------------------
//RtoOutput parmReclaimedToOutputPct
internal int[] get_PCT_Reclaimed_to_Water_Supply() { return _ws.parmReclaimedToOutputPct; }
internal void set_PCT_Reclaimed_to_Water_Supply(int[] value) { if (!FModelLocked) _ws.parmReclaimedToOutputPct = value; }
/// <summary> The percent reclaimed to water supply </summary>
/// <remarks> The percent of recliamed water that is used to meet qualified user demands (non-potable). Special Range Check Applies See PCTReclaimedRangeCheck</remarks>
/// <exception cref="WaterSim_Exception">if setting a value that does not pass the range check</exception>
/// <seealso cref="WaterSimDCDC.WaterSimManager.PCTReclaimedRangeCheck(int, WaterSimDCDC.eProvider, int)"/>
/// <seealso cref="WaterSimDCDC.WaterSimManager.PCTReclaimedRangeCheck(int, WaterSimDCDC.eProvider, ref string, WaterSimDCDC.ModelParameterBaseClass)"/>
/// <seealso cref="ParameterManagerClass.reclaimedchecklist"/>
public providerArrayProperty PCT_Reclaimed_to_Water_Supply;
//---------------------------------------
//RtoVadose parmReclaimedToVadosePct
internal int[] get_PCT_Reclaimed_to_Vadose() { return _ws.parmReclaimedToVadosePct; }
internal void set_PCT_Reclaimed_to_Vadose(int[] value) { if (!FModelLocked) _ws.parmReclaimedToVadosePct = value; }
/// <summary> The percent reclaimed to vadose </summary>
/// <remarks> The percent of reclaimed water that is delivered to a vadoze zone recharge basin. Special Range Check Applies See PCTReclaimedRangeCheck</remarks>
/// <exception cref="WaterSim_Exception">if setting a value that does not pass the range check</exception>
/// <seealso cref="WaterSimDCDC.WaterSimManager.PCTReclaimedRangeCheck(int, WaterSimDCDC.eProvider, int)"/>
/// <seealso cref="WaterSimDCDC.WaterSimManager.PCTReclaimedRangeCheck(int, WaterSimDCDC.eProvider, ref string, WaterSimDCDC.ModelParameterBaseClass)"/>
/// <seealso cref="ParameterManagerClass.reclaimedchecklist"/>
public providerArrayProperty PCT_Reclaimed_to_Vadose;
//---------------------------------------
//get_EffluentToVadose parmEffluentToVadosePct
internal int[] get_PCT_Effluent_to_Vadose() { return _ws.parmEffluentToVadosePct; }
internal void set_PCT_Effluent_to_Vadose(int[] value) { if (!FModelLocked) _ws.parmEffluentToVadosePct = value; }
/// <summary> The percent effluent to vadose </summary>
/// <remarks> The percent of wastewater effluent delivered to a vadose zone recharge basin. Special Range Check Applies See PCTEffluentRangeCheck</remarks>
/// <exception cref="WaterSim_Exception">if setting a value that does not pass the range check</exception>
/// <seealso cref="WaterSimDCDC.WaterSimManager.PCTReclaimedRangeCheck(int, WaterSimDCDC.eProvider, int)"/>
/// <seealso cref="WaterSimDCDC.WaterSimManager.PCTReclaimedRangeCheck(int, WaterSimDCDC.eProvider, ref string, WaterSimDCDC.ModelParameterBaseClass)"/>
/// <seealso cref="WaterSimDCDC.ParameterManagerClass.effluentchecklist"/>
public providerArrayProperty PCT_Effluent_to_Vadose;
//---------------------------------------
//EffluentToPP parmEffluentToPowerPlantPct
internal int[] get_PCT_Effluent_to_PowerPlant() { return _ws.parmEffluentToPowerPlantPct; }
internal void set_PCT_Effluent_to_PowerPlant(int[] value) { if (!FModelLocked) _ws.parmEffluentToPowerPlantPct = value; }
/// <summary> The percent effluent to power plant </summary>
/// <remarks> The percent of wastewater effluent delivered to a power plants for cooling towers. Special Range Check Applies See PCTEffluentRangeCheck</remarks>
/// <exception cref="WaterSim_Exception">if setting a value that does not pass the range check</exception>
/// <seealso cref="WaterSimDCDC.WaterSimManager.PCTEffluentRangeCheck(int, WaterSimDCDC.eProvider, int)"/>
/// <seealso cref="WaterSimDCDC.WaterSimManager.PCTEffluentRangeCheck(int, WaterSimDCDC.eProvider, ref string, WaterSimDCDC.ModelParameterBaseClass)"/>
/// <seealso cref="ParameterManagerClass.effluentchecklist"/>
public providerArrayProperty PCT_Effluent_to_PowerPlant;
//---------------------------------------
//SWtoVadose parmSurfaceWaterToVadosePct
internal int[] get_SurfaceWater__to_Vadose() { return _ws.parmSurfaceWaterToVadoseAmt; } // changed 7 22 11 from get_parmSurfaceWaterToVadosePCT
internal void set_SurfaceWater__to_Vadose(int[] value) { if (!FModelLocked) _ws.parmSurfaceWaterToVadoseAmt = value; } // changed 7 22 11 from get_parmSurfaceWaterToVadosePCT
/// <summary> Surface water to vadose </summary>
/// <remarks> The amount of surface water supply delivered to a vadose zone basin. Range = 0 to 100000</remarks>
/// <exception cref="WaterSim_Exception">if setting a value that does not pass the range check</exception>
public providerArrayProperty SurfaceWater__to_Vadose;
//---------------------------------------
//SWtoWB parmSurfaceWaterToWBankPct
internal int[] get_PCT_SurfaceWater_to_WaterBank() { return _ws.parmSurfaceWaterToWbankPct; } // _ws.parmSurfaceWaterToWbankPct chnaged in model 7 20 11
internal void set_PCT_SurfaceWater_to_WaterBank(int[] value) { if (!FModelLocked) _ws.parmSurfaceWaterToWbankPct = value; } // _ws.parmSurfaceWaterToWbankPct chnaged in model 7 20 11
/// <summary> The percent surface water to water bank </summary>
/// <remarks> The percent of extra surface water that is sent to a water bank if [WaterBank Source Option] is set to a Value=1. Range = 0 to 100</remarks>
/// <exception cref="WaterSim_Exception">if setting a value that does not pass the range check</exception>
public providerArrayProperty PCT_SurfaceWater_to_WaterBank;
//---------------------------------------
// parmSurfaceWaterToWBankAmt
internal int[] get_Use_SurfaceWater_to_WaterBank()
{ return _ws.parmSurfaceWaterToWBankAmt; } // changed 7 26 11 API.set_parmSurfaceWaterToWbankAmt; } // Using array of myAPI as Dummy, have to think about this
internal void set_Use_SurfaceWater_to_WaterBank(int[] value)
{
if (!FModelLocked)
{
_ws.parmSurfaceWaterToWBankAmt = value;
}
}
/// <summary> The use surface water to water bank </summary>
/// <remarks> The amount of water (source unknown) sent to a water bank if [WaterBank Source Option] is set to a Value=2. Range = 0 to 100000. This parameter is essentially a way to create a new bucket of water that can be used when other supplies do not meet demand. This could include fallowing of Colorado River farms, desalination of water in Mexico or California, sale of upper basic water rights etc.</remarks>
/// <exception cref="WaterSim_Exception">if setting a value that does not pass the range check</exception>
public providerArrayProperty Use_SurfaceWater_to_WaterBank;
//---------------------------------------
//WStoRes parmWaterSupplyToResidentialPct
internal int[] get_PCT_WaterSupply_to_Residential() { return _ws.parmWaterSupplyToResPct; }
internal void set_PCT_WaterSupply_to_Residential(int[] value) { if (!FModelLocked) _ws.parmWaterSupplyToResPct = value; }
/// <summary> The percent water supply to residential </summary>
/// <remarks> The percent of total water supply used by residential customers. Special Range Check Applies See ResComPCTRangeCheck</remarks>
/// <exception cref="WaterSim_Exception">if setting a value that does not pass the range check</exception>
/// <seealso cref="ResComPCTRangeCheck"/>
/// <seealso cref="ParameterManagerClass.wateruserchecklist"/>
public providerArrayProperty PCT_WaterSupply_to_Residential;
//---------------------------------------
//WStoCio parmWaterSupplyToComPct
internal int[] get_PCT_WaterSupply_to_Commercial() { return _ws.parmWaterSupplyToComPct; }
internal void set_PCT_WaterSupply_to_Commercial(int[] value) { if (!FModelLocked) _ws.parmWaterSupplyToComPct = value; }
/// <summary> The percent water supply to commercial </summary>
/// <remarks> The percent of total water supply used by commercial customers. Special Range Check Applies See ResComPCTRangeCheck</remarks>
/// <exception cref="WaterSim_Exception">if setting a value that does not pass the range check</exception>
/// <seealso cref="PCTResComRangeCheck"/>
/// <seealso cref="ParameterManagerClass.wateruserchecklist"/>
public providerArrayProperty PCT_WaterSupply_to_Commercial;
//---------------------------------------
internal int[] get_PCT_WaterSupply_to_Industrial() { return _ws.parmWaterSupplyToIndPct; }
internal void set_PCT_WaterSupply_to_Industrial(int[] value) { if (!FModelLocked) _ws.parmWaterSupplyToIndPct = value; }
/// <summary> The percent water supply to industrial uses</summary>
/// <remarks> The percent of total water supply used by industiral vustomers. Special Range Check Applies See ResComPCTRangeCheck</remarks>
/// <exception cref="WaterSim_Exception">if setting a value that does not pass the range check</exception>
/// <seealso cref="PCTResComRangeCheck"/>
/// <seealso cref="ParameterManagerClass.wateruserchecklist"/>
public providerArrayProperty PCT_WaterSupply_to_Industrial;
//
//---------------------------------------
////OutDoorPct parmOutdoorWaterUsePct
//internal int[] get_PCT_Outdoor_WaterUse() { return _ws.get_parmOutdoorWaterUsePct; }
//internal void set_PCT_Outdoor_WaterUse(int[] value) { if (!FModelLocked) _ws.get_parmOutdoorWaterUsePct = value; }
///// <summary> The percent outdoor water use </summary>
///// <remarks> The percent of potable water supply used for outdoor wate uses. Range = 0 to 100</remarks>
///// <exception cref="WaterSim_Exception">if setting a value that does not pass the range check</exception>
//public providerArrayProperty PCT_Outdoor_WaterUse;
//---------------------------------------
//GWtoGWTP parmGroundwaterToGWTPlantPct
internal int[] get_PCT_Groundwater_Treated() { return _ws.parmGroundwaterToGWTPlantPct; }
internal void set_PCT_Groundwater_Treated(int[] value) { if (!FModelLocked) _ws.parmGroundwaterToGWTPlantPct = value; }
/// <summary> The percent groundwater treated </summary>
/// <remarks> The percent of groundwater that is treated before it is used for potable water supply. Range = 0 to 100</remarks>
/// <exception cref="WaterSim_Exception">if setting a value that does not pass the range check</exception>
public providerArrayProperty PCT_Groundwater_Treated;
//---------------------------------------
//ReclaimedOutdoor parmReclaimedOutdoorUsePct
internal int[] get_PCT_Reclaimed_Outdoor_Use() { return _ws.parmReclaimedOutdoorUsePct; }
internal void set_PCT_Reclaimed_Outdoor_Use(int[] value) { if (!FModelLocked) _ws.parmReclaimedOutdoorUsePct = value; }
/// <summary> The percent reclaimed outdoor use </summary>
/// <remarks> The percent of outdoor water use that can be supplied by reclaimed water. Range = 0 to 100</remarks>
/// <exception cref="WaterSim_Exception">if setting a value that does not pass the range check</exception>
public providerArrayProperty PCT_Reclaimed_Outdoor_Use;
// New Added to version 3
//---------------------------------------
// Use_WaterSupply_to_DirectInject
internal int[] get_Use_WaterSupply_to_DirectInject()
{ return _ws.parmWaterSupplyToDirectInjectAmt; } // chnaged 7 24 11 API.set_parmWaterSupplyToDirectInjectAmt; } // Using array of myAPI as Dummy, have to think about this
internal void set_Use_WaterSupply_to_DirectInject(int[] value)
{
if (!FModelLocked)
{
_ws.parmWaterSupplyToDirectInjectAmt = value;
}
}
/// <summary> The amount of water to direct inject </summary>
/// <remarks> A fixed amount of potable water supply used for aquifer recharge by directly injecting into a potable aquifer. Range = 0 to 100000</remarks>
/// <exception cref="WaterSim_Exception">if setting a value that does not pass the range check</exception>
public providerArrayProperty Use_WaterSupply_to_DirectInject;
//---------------------------------------
// ***** Changed 8 13 12
//// SetPopulation Set_Population // added 12 19 11 based on changes to model interface
//internal int[] get_populations()
//{ return SetPopultaionsValues; }
//internal void set_populations(int [] value)
// {
// if (!FModelLocked)
// {
// _ws.SetPopulations = value;
// SetPopultaionsValues = value;
// }
//}
internal int[] get_populationsOn()
{ return SetPopultaionsValuesOn; }
internal void set_populationsOn(int [] value)
{
if (!FModelLocked)
{
_ws.set_PopulationsOn = value;
SetPopultaionsValuesOn = value;
}
}
//*********
/// <summary> Provider On Project Population Override</summary>
/// <remarks> If set to a value other than 0, is used as the population of the provider, if zero then population calculated by model</remarks>
// Changed 8 13 12 public providerArrayProperty Population_Override;
public providerArrayProperty Population_Override_On;
//******** Added 8 13 12
internal int[] get_populationsOther()
{ return SetPopultaionsValuesOther; }
internal void set_populationsOther(int[] value)
{
if (!FModelLocked)
{
_ws.set_PopulationsOther = value;
SetPopultaionsValuesOther = value;
}
}
/// <summary> Provider Off Project Population Override</summary>
/// <remarks> If set to a value other than 0, is used as the population of the provider, if zero then population calculated by model</remarks>
public providerArrayProperty Population_Override_Other;
//*********
//
//---------------------------------------
// TimeLagVadoseYears Surface_to_Vadose_Time_Lag
internal int[] get_Surface_to_Vadose_Time_Lag()
{ return _ws.TimeLagVadoseYears; } // changed 7 26 11 API.set_TimeLagVadoseYears; } // Using array of myAPI as Dummy, have to think about this
internal void set_Surface_to_Vadose_Time_Lag(int[] value)
{
if (!FModelLocked)
{
_ws.TimeLagVadoseYears = value;
}
}
/// <summary> The surface to vadose time lag </summary>
/// <remarks> The time in years it takes water recharged to the vadose zone to reach the aquifer used for groundwater supply. Range = 0 to 50</remarks>
/// <exception cref="WaterSim_Exception">if setting a value that does not pass the range check</exception>
public providerArrayProperty Surface_to_Vadose_Time_Lag;
//---------------------------------------
//ProviderGPCD
// This is a complicated property depends on how Provider_demand_option is set
internal int[] get_Use_GPCD()
{
if (Provider_Demand_Option == 4)
return GPCDBuffer ;
else
return GPCDDefaults;
}
internal void set_Use_GPCD(int[] value)
{
if (!FModelLocked)
{
if (Provider_Demand_Option == 4)
{
_ws.ProviderGPCD = value;
GPCDBuffer = value;
}
else
{
// OK ignore for now ----- throw new WaterSim_Exception(WS_Strings.wsSetGPCDError);
}
}
}
/// <summary> The gpcd to use with User Supplied GPCD</summary>
/// <remarks> The GPCD that will be used if [Provider Demand Option] is set to Value=4. Range = 30 to 500</remarks>
/// <exception cref="WaterSim_Exception">if setting a value that does not pass the range check, for now ignoring if Provider_Demand_Option is not set to 4 and values are set</exception>
/// <seealso cref="Provider_Demand_Option"/>
public providerArrayProperty Use_GPCD;
////---------------------------------------
//// get_ProviderPopGrowthRateAdjustPct
//// this is a bit compliated, in order for this to work, get_ProviderPopGrowthRateAdjustmentPct (see below) must be set to 0, Once set to 0,
//// it shold not be set back to 100 until a model run is over, otherwise growth curves will revert back to olld growth curves
//internal int[] get_PCT_Growth_Rate_Adjustment() { return _ws.get_ProviderPopGrowthRateAdjustPct; }
//internal void set_PCT_Growth_Rate_Adjustment(int[] value)
//{
// if (!FModelLocked)
// {
// // if regional growth factor is not 0 then check if value has non 100 values, if so set regional to 0
// //if (geti_PCT_REG_Growth_Rate_Adjustment() != 0)
// //{
// // bool found = false;
// // foreach(int pct in value)
// // if (pct != 100)
// // {
// // found = true;
// // break;
// // }
// if (found) seti_PCT_REG_Growth_Rate_Adjustment(0);
// //}
// _ws.get_ProviderPopGrowthRateAdjustPct = value;
// }
//}
///// <summary> The percent growth rate adjustment </summary>
///// <remarks> A factor (percent) that is used to adjust the rate of population growth. Used to create faster or slower growth rate scenarios. 100 (100%) means no factor is applied. A zero means I pack my bags and move to one of the coasts. Range = 0 to 300</remarks>
///// <exception cref="WaterSim_Exception">if setting a value that does not pass the range check</exception>
//public providerArrayProperty PCT_Growth_Rate_Adjustment;
//=============================================================
// ProviderPopGrowthRateOnProjectPct
internal int[] get_PCT_Growth_Rate_Adjustment_OnProject() { return _ws.ProviderPopGrowthRateOnProjectPct; }
internal void set_PCT_Growth_Rate_Adjustment_OnProject(int[] value)
{
if (!FModelLocked)
{
//if regional growth factor is not 0 then check if value has non 100 values, if so set regional to 0
//if (geti_PCT_REG_Growth_Rate_Adjustment() != 0)
//{
// bool found = false;
// foreach(int pct in value)
// if (pct != 100)
// {
// found = true;
// break;
// }
//if (found) seti_PCT_REG_Growth_Rate_Adjustment(0);
//}
_ws.ProviderPopGrowthRateOnProjectPct = value;
}
}
/// <summary> The percent growth rate adjustment for OnProject Demand</summary>
/// <remarks> A factor (percent) that is used to adjust the rate of population growth. Used to create faster or slower growth rate scenarios. 100 (100%) means no factor is applied. A zero means I pack my bags and move to one of the coasts. Range = 0 to 300</remarks>
/// <exception cref="WaterSim_Exception">if setting a value that does not pass the range check</exception>
public providerArrayProperty PCT_Growth_Rate_Adjustment_OnProject;
//=============================================================
// ProviderPopGrowthRateOtherPct
internal int[] get_PCT_Growth_Rate_Adjustment_Other() { return _ws.ProviderPopGrowthRateOtherPct; }
internal void set_PCT_Growth_Rate_Adjustment_Other(int[] value)
{
if (!FModelLocked)
{
//if regional growth factor is not 0 then check if value has non 100 values, if so set regional to 0
//if (geti_PCT_REG_Growth_Rate_Adjustment() != 0)
//{
// bool found = false;
// foreach (int pct in value)
// if (pct != 100)
// {
// found = true;
// break;
// }
// if (found) seti_PCT_REG_Growth_Rate_Adjustment(0);
//}
_ws.ProviderPopGrowthRateOtherPct = value;
}
}
/// <summary> The percent growth rate adjustment for Off Project Demand</summary>
/// <remarks> A factor (percent) that is used to adjust the rate of population growth. Used to create faster or slower growth rate scenarios. 100 (100%) means no factor is applied. A zero means I pack my bags and move to one of the coasts. Range = 0 to 300</remarks>
/// <exception cref="WaterSim_Exception">if setting a value that does not pass the range check</exception>
public providerArrayProperty PCT_Growth_Rate_Adjustment_Other;
//---------------------------------------
//_ws.WaterBankingOption = set_WaterBankingOption;
internal int[] get_WaterBank_Source_Option() { return _ws.WaterBankingOption; } // API.set_WaterBankingOption; } changed 7 24 11
internal void set_WaterBank_Source_Option(int[] value)
{
if (!FModelLocked)
{
_ws.WaterBankingOption = value;
}
}
/// <summary> The water bank source option </summary>
/// <remarks> The source of water used for external water banking (outside provider groundwater): Value=1 a percent [% SurfaceWater to WaterBank] of ""unused"" surface water is sent to a water bank, Value= 2 a fixed amount[Amount of SurfaceWater to WaterBank] of an unknown extra source of water is sent to a water bank. Range = 1 to 2</remarks>
/// <exception cref="WaterSim_Exception">if setting a value that does not pass the range check</exception>
public providerArrayProperty WaterBank_Source_Option;
// Added to Model 8 10 2011
//---------------------------------------
//parmReclaimedToInputPct
internal int[] get_PCT_Max_Demand_Reclaim() { return _ws.parmReclaimedToInputPct; }
internal void set_PCT_Max_Demand_Reclaim(int[] value) { if (!FModelLocked) _ws.parmReclaimedToInputPct = value; }
/// <summary> The percent maximum demand reclaim </summary>
/// <remarks> The maximum percent of total demand that can be met by reclaimed water Range = 0 to 70</remarks>
/// <exception cref="WaterSim_Exception">if setting a value that does not pass the range check</exception>"
public providerArrayProperty PCT_Max_Demand_Reclaim;
//--------------------------------------------------------------------------
//OutDoorPct internal int[] get_parmWaterSupplyToResPct
// Changed 8 13 12 internal int[] get_PCT_Outdoor_WaterUseRes() { return _ws.get_parmOutdoorWaterUseResPct; }
internal int[] get_PCT_Outdoor_WaterUseRes() { return _ws.parmOutdoorWaterUseResPct; } // changed 8 13 12
// Changed 8 13 12 internal void set_PCT_Outdoor_WaterUseRes(int[] value) { if (!FModelLocked) _ws.get_parmOutdoorWaterUseResPct = value; }
internal void set_PCT_Outdoor_WaterUseRes(int[] value) { if (!FModelLocked) _ws.parmOutdoorWaterUseResPct = value; }
/// <summary> The percent outdoor water use for residential </summary>
/// <remarks> Indoor water use is 100 - PCT_Outdoor_WaterUseRes</remarks>
public providerArrayProperty PCT_Outdoor_WaterUseRes;
//-----------------------------------------------------
//OutDoorPct internal int[] get_parmWaterSupplyToComPct
// Changed 8 13 12 internal int[] get_PCT_Outdoor_WaterUseCom() { return _ws.get_parmOutdoorWaterUseComPct; }
// Changed 8 13 12 internal void set_PCT_Outdoor_WaterUseCom(int[] value) { if (!FModelLocked) _ws.get_parmOutdoorWaterUseComPct = value; }
internal int[] get_PCT_Outdoor_WaterUseCom() { return _ws.parmOutdoorWaterUseComPct; }
internal void set_PCT_Outdoor_WaterUseCom(int[] value) { if (!FModelLocked) _ws.parmOutdoorWaterUseComPct = value; }
/// <summary> The pct outdoor water use for commercial </summary>
/// <remarks> Indoor water use is 100 - PCT_Outdoor_WaterUseCom</remarks>
public providerArrayProperty PCT_Outdoor_WaterUseCom;
//OutDoorPct :internal int[] get_parmWaterSupplyToIndPct
// Changed 8 13 12 internal int[] get_PCT_Outdoor_WaterUseInd() { return _ws.get_parmOutdoorWaterUseIndPct; }
// Changed 8 13 12 internal void set_PCT_Outdoor_WaterUseInd(int[] value) { if (!FModelLocked) _ws.get_parmOutdoorWaterUseIndPct = value; }
internal int[] get_PCT_Outdoor_WaterUseInd() { return _ws.parmOutdoorWaterUseIndPct; }
internal void set_PCT_Outdoor_WaterUseInd(int[] value) { if (!FModelLocked) _ws.parmOutdoorWaterUseIndPct = value; }
/// <summary> The pct outdoor water use for industiral </summary>
/// <remarks> Indoor water use is 100 - PCT_Outdoor_WaterUseInd</remarks>
public providerArrayProperty PCT_Outdoor_WaterUseInd;
#endregion
//==========================================
// Gets and Sets for Base input and out Properties
//============================================
#region Gets And Sets for Base Inputs/outputs
// gets for Base outputs
private int geti_Colorado_River_Flow() { return Colorado_River_Flow; }
private int geti_Powell_Storage() { return Powell_Storage; }
private int geti_Mead_Storage() { return Mead_Storage; }
private int geti_SaltVerde_River_Flow() { return SaltVerde_River_Flow; }
private int geti_SaltVerde_Storage() { return SaltVerde_Storage; }
private int geti_Effluent_To_Agriculture() { return Effluent_To_Agriculture; }
internal int geti_SVTspillage() { return SVT_Spillage; }
internal int geti_ElevationMead() { return Elevation_of_Mead; }
//DAS
internal int geti_ElevationPowell() { return Elevation_of_Powell; }
internal int geti_Regional_Natural_Recharge() { return Regional_Natural_Recharge; }
internal int geti_Regional_CAGRD_Recharge() { return Regional_CAGRD_Recharge; }
internal int geti_Regional_Inflow() { return Regional_Inflow; }
internal int geti_Regional_Ag_To_Vadose() { return Regional_Ag_To_Vadose; }
internal int geti_Regional_Provider_Recharge(){ return Regional_Provider_Recharge; }
internal int geti_Regional_Ag_Other_Pumping(){ return Regional_Ag_Other_Pumping; }
internal int geti_Regional_Outflow() { return Regional_Outflow; }
internal int geti_Regional_Groundwater_Balance() { return Regional_Groundwater_Balance; }
// Gets for Base Inputs
private int geti_Simulation_Start_Year() { return Simulation_Start_Year; }
private int geti_Simulation_End_Year() { return Simulation_End_Year; }
private int geti_Colorado_Historical_Extraction_Start_Year() { return Colorado_Historical_Extraction_Start_Year; }
private int geti_Colorado_Historical_Data_Source() { return Colorado_Historical_Data_Source; }
private int geti_Colorado_Climate_Adjustment_Percent() { return Colorado_Climate_Adjustment_Percent; }
private int geti_Colorado_User_Adjustment_Percent() { return Colorado_User_Adjustment_Percent; }
private int geti_Colorado_User_Adjustment_StartYear() { return Colorado_User_Adjustment_StartYear; }
private int geti_Colorado_User_Adjustment_Stop_Year() { return Colorado_User_Adjustment_Stop_Year; }
private int geti_SaltVerde_Historical_Extraction_Start_Year() { return SaltVerde_Historical_Extraction_Start_Year; }
private int geti_SaltVerde_Historical_Data() { return SaltVerde_Historical_Data_Source; }
private int geti_SaltVerde_Climate_Adjustment_Percent() { return SaltVerde_Climate_Adjustment_Percent; }
private int geti_SaltVerde_User_Adjustment_Percent() { return SaltVerde_User_Adjustment_Percent; }
private int geti_SaltVerde_User_Adjustment_Start_Year() { return SaltVerde_User_Adjustment_Start_Year; }
private int geti_SaltVerde_User_Adjustment_Stop_Year() { return SaltVerde_User_Adjustment_Stop_Year; }
private int geti_Provider_Demand_Option() { return Provider_Demand_Option; }
private int geti_PCT_Reduce_GPCD() { return PCT_Reduce_GPCD; }
private int geti_Assured_Water_Supply_Annual_Groundwater_Pumping_Limit()
{
if (_Assured_Water_Supply_Annual_Groundwater_Pumping_Limit) return 1;
else return 0;
}
// QUAY Changed 3 7 13 removing Model_Interface PopulationGrowthRateAdjustmentPercent to use Provider Growth Rates
private int geti_PCT_REG_Growth_Rate_Adjustment()
{
int Total = 0;
// Get the On Project Growth Provider array
int[] GrowthRates = _ws.ProviderPopGrowthRateOnProjectPct;
// add these up
foreach (int value in GrowthRates)
Total += value;
// get off project growth provider array
GrowthRates = _ws.ProviderPopGrowthRateOtherPct;
// continue adding
foreach (int value in GrowthRates)
Total += value;
// now calculate an un weighted average (since we do not no population of each provider at this point)
int AvgRate = Total / (GrowthRates.Length*2);
return AvgRate;
}
//***************
// Sets for Base Inputs
private void seti_Simulation_Start_Year(int value) { Simulation_Start_Year = value; }
private void seti_Simulation_End_Year(int value) { Simulation_End_Year = value; }
private void seti_Colorado_Historical_Extraction_Start_Year(int value) { Colorado_Historical_Extraction_Start_Year = value; }
private void seti_Colorado_Historical_Data_Source(int value) { Colorado_Historical_Data_Source = value; }
private void seti_Colorado_Climate_Adjustment_Percent(int value) { Colorado_Climate_Adjustment_Percent = value; }
private void seti_Colorado_User_Adjustment_Percent(int value) { Colorado_User_Adjustment_Percent = value; }
private void seti_Colorado_User_Adjustment_StartYear(int value) { Colorado_User_Adjustment_StartYear = value; }
private void seti_Colorado_User_Adjustment_Stop_Year(int value) { Colorado_User_Adjustment_Stop_Year = value; }
private void seti_SaltVerde_Historical_Extraction_Start_Year(int value) { SaltVerde_Historical_Extraction_Start_Year = value; }
private void seti_SaltVerde_Historical_Data(int value) { SaltVerde_Historical_Data_Source = value; }
private void seti_SaltVerde_Climate_Adjustment_Percent(int value) { SaltVerde_Climate_Adjustment_Percent = value; }
private void seti_SaltVerde_User_Adjustment_Percent(int value) { SaltVerde_User_Adjustment_Percent = value; }
private void seti_SaltVerde_User_Adjustment_Start_Year(int value) { SaltVerde_User_Adjustment_Start_Year = value; }
private void seti_SaltVerde_User_Adjustment_Stop_Year(int value) { SaltVerde_User_Adjustment_Stop_Year = value; }
private void seti_Provider_Demand_Option(int value) { Provider_Demand_Option = value; }
private void seti_PCT_Reduce_GPCD(int value) { PCT_Reduce_GPCD = value; }
// QUAY Modified 3 7 13 to Remove old model Regional Growth Adjust
private void seti_PCT_REG_Growth_Rate_Adjustment(int value)
{
if (!FModelLocked)
{
int[] NewRates = new int[ProviderClass.NumberOfProviders];
for (int i = 0; i < NewRates.Length; i++)
NewRates[i] = value;
_ws.ProviderPopGrowthRateOnProjectPct = NewRates;
_ws.ProviderPopGrowthRateOtherPct = NewRates;
}
}
//************
private void seti_Assured_Water_Supply_Annual_Groundwater_Pumping_Limit(int value)
{
bool LimitToggle = false;
if (value > 0)
{
LimitToggle = true;
}
else
LimitToggle = false;
_ws.set_parmAllStrawsSucking = LimitToggle;
_Assured_Water_Supply_Annual_Groundwater_Pumping_Limit = LimitToggle;
}
#endregion
// Special
/// <summary> Fast get annual data.</summary>
/// <param name="AS_Results"> [out] annual results all output parameters of Simulation. </param>
public void FastGetAnnualData(ref AnnualSimulationResults AS_Results)
{
ModelParameterBaseClass MP;
int ib_index = 0;
int ob_index = 0;
int ip_index = 0;
int op_index = 0;
foreach (int emp in _pm.eModelParameters())
{
MP = _pm.Model_ParameterBaseClass(emp);
switch (MP.ParamType)
{
case modelParamtype.mptInputBase :
AS_Results.Inputs.BaseInput[ib_index] = (MP as ModelParameterClass).Value; // 7/29 (MP as BaseModelParameterClass).Value;
AS_Results.Inputs.BaseInputModelParam[ib_index] = MP.ModelParam;
//AS_Results.BaseInput[ib_index] = MP.Value;
ib_index++;
break;
case modelParamtype.mptInputProvider:;
AS_Results.Inputs.ProviderInput[ip_index] = MP.ProviderProperty.getvalues();
AS_Results.Inputs.ProviderInputModelParam[ip_index] = MP.ModelParam;
// AS_Results.ProviderInput.Values[ip_index] = MP.ProviderProperty.getvalues();;
ip_index++;
break;
case modelParamtype.mptOutputBase:
AS_Results.Outputs.BaseOutput[ib_index] = (MP as ModelParameterClass).Value; // 7/29 (MP as BaseModelParameterClass).Value;
AS_Results.Outputs.BaseOutputModelParam[ib_index] = MP.ModelParam;
// AS_Results.BaseOutput[ob_index] = MP.Value;
ob_index++;
break;
case modelParamtype.mptOutputProvider:
AS_Results.Outputs.ProviderOutput[ip_index] = MP.ProviderProperty.getvalues();
AS_Results.Outputs.ProviderOutputModelParam[ip_index] = MP.ModelParam;
//AS_Results.ProviderOutput.Values[op_index] = MP.ProviderProperty.getvalues();
op_index++;
break;
}
}
}
// SPecial Range Checks
/// <summary> River range. </summary>
/// <remarks> a struct used to define the range in years of a river's flow record</remarks>
public class RiverRange
{
/// <summary> The first </summary>
protected int _First = 0;
/// <summary> The last </summary>
protected int _Last = 0;
/// <summary> First year of record </summary>
/// <value>a year</value>
public int First
{ get { return _First; } }
/// <summary> Last year of record </summary>
/// <value>a year</value>
public int Last
{ get { return _Last;} }
internal RiverRange(int first, int last)
{
_First = first;
_Last = last;
}
}
/// <summary> User river range. </summary>
/// <remarks> A struct used for defining the range of user supplied river flow records. </remarks>
public class UserRiverRange : RiverRange
{
/// <summary> First year of record </summary>
/// <value>a year</value>
new public int First
{
get { return _First; }
set { _First = value; }
}
/// <summary> Last year of record </summary>
/// <value>a year</value>
new public int Last
{
get { return _Last;}
set { _Last = value; }
}
internal UserRiverRange(int first, int last) : base(first,last) {}
}
/// <summary> The Colorado River Paleo River Range</summary>
/// <seealso cref="RiverRange"/>
public static RiverRange ColoradoPaleo = new RiverRange(762, 1982);
/// <summary> The Colorado River Bureau/Historical River Range </summary>
/// <seealso cref="RiverRange"/>
public static RiverRange ColoradoBureau = new RiverRange(1906, 1982);
/// <summary> The Salt Verde Rivers Paleo/Tree Ring River Range </summary>
/// <seealso cref="RiverRange"/>
public static RiverRange SaltVerdePaleo = new RiverRange(1330, 1982);
/// <summary> The Salt Verde Bureau/Historical River Range </summary>
/// <seealso cref="RiverRange"/>
public static RiverRange SaltVerdeBureau = new RiverRange(1945, 1982);
/// <summary> Colorado river range for user supplied data</summary>
/// <seealso cref="UserRiverRange"/>
public static UserRiverRange ColoradoUser = new UserRiverRange(1906, 2005);
/// <summary> Salt Verde river range for user supplied data</summary>
/// <seealso cref="UserRiverRange"/>
public static UserRiverRange SaltVerdeUser = new UserRiverRange(1945, 2005);
/// <summary> Constant for Tree Ring Paleo River Record source </summary>
/// <value> Riversource </value>
public const int rsPaleosource = 2;
/// <summary> Constant for Bureau Historical River Record source </summary>
/// <value> Riversource </value>
public const int rsBureausource = 1;
/// <summary> Constant for User Riversource </summary>
/// <value> Riversource </value>
public const int rsUsersource = 3;
/// <summary> Source of River Trace Information. </summary>
public static string[] SourceString = new string[] { "Source = 0", "Bureau Records", "Paleo Records", "User Records", "Source = 4", "Source = 5", "Source =6" };
internal const int rcColorado = 1;
internal const int rcSaltVerde = 2;
// string[] RiverString = new string[] {"River = 0","Colorado River","Salt and Verde Rivers"};
//---------------------------------------------------------------------
internal void ColoradoRiverHistoricalReSetStart(int source)
{
int First = 0; int Last = 0;
int start = ParamManager.Model_Parameter(eModelParam.epColorado_Historical_Extraction_Start_Year).Value; // 7/29 ParamManager.BaseModel_ParameterBaseClass(eModelParam.epColorado_Historical_Extraction_Start_Year).Value;
if (!RiverHistoricalYearRangeCheck(start,source,rcColorado, ref First, ref Last))
{
ParamManager.Model_Parameter(eModelParam.epColorado_Historical_Extraction_Start_Year).Value = First; // 7/29 ParamManager.BaseModel_ParameterBaseClass(eModelParam.epColorado_Historical_Extraction_Start_Year).Value = First;
ParamManager.Model_Parameter(eModelParam.epColorado_Historical_Extraction_Start_Year).EvokeReloadEvent(); // 7/29 ParamManager.BaseModel_ParameterBaseClass(eModelParam.epColorado_Historical_Extraction_Start_Year).EvokeReloadEvent();
}
}
//---------------------------------------------------------------------
internal void SaltVerdeRiverHistoricalReSetStart(int source)
{
int First = 0; int Last = 0;
int start = ParamManager.Model_Parameter(eModelParam.epSaltVerde_Historical_Extraction_Start_Year).Value; // 7/29 ParamManager.BaseModel_ParameterBaseClass(eModelParam.epSaltVerde_Historical_Extraction_Start_Year).Value;
if (!RiverHistoricalYearRangeCheck(start, source, rcSaltVerde , ref First, ref Last))
{
ParamManager.Model_Parameter(eModelParam.epSaltVerde_Historical_Extraction_Start_Year).Value = First; // 7/ 29 ParamManager.BaseModel_ParameterBaseClass(eModelParam.epSaltVerde_Historical_Extraction_Start_Year).Value = First;
ParamManager.Model_Parameter(eModelParam.epSaltVerde_Historical_Extraction_Start_Year).EvokeReloadEvent(); // 7/29 ParamManager.BaseModel_ParameterBaseClass(eModelParam.epSaltVerde_Historical_Extraction_Start_Year).EvokeReloadEvent();
}
}
//-----------------------------------------------
internal static string RiverRangeString(int Source, int First, int Last)
{
string rrstr = "";
if ((Source > 0) & (Source < SourceString.Length))
rrstr = ": " + SourceString[Source] + " (value = " + Source.ToString() + ") start " + First.ToString() + "and end " + Last.ToString();
return rrstr;
}
//-----------------------------------------------
internal static bool RiverHistoricalYearRangeCheck(int Value, int source, int River, ref int FirstYear, ref int LastYear)
{
int First = 0;
int Last = 0;
switch (River)
{
//------------------------------------
case 1:
switch (source)
{
case rsPaleosource:
First = ColoradoPaleo.First;
Last = ColoradoPaleo.Last;
break;
//------------------
case rsBureausource:
First = ColoradoBureau.First;
Last = ColoradoBureau.Last;
break;
//------------------
case rsUsersource:
First = ColoradoUser.First;
Last = ColoradoUser.Last;
break;
//------------------
default:
break;
//------------------
} // swithc case 1 source
break;
//------------------------------------
case 2:
switch (source)
{
case rsPaleosource:
First = SaltVerdePaleo.First;
Last = SaltVerdePaleo.Last;
break;
//------------------
case rsBureausource:
First = SaltVerdeBureau.First;
Last = SaltVerdeBureau.Last;
break;
//------------------
case rsUsersource:
First = SaltVerdeUser.First;
Last = SaltVerdeUser.Last;
break;
//------------------
default:
break;
//------------------
} // switch case 2 source
break;
//------------------------------------
default:
break;
} // switch source
FirstYear = First;
LastYear = Last;
return ((Value >= First) & (Value <= Last));
}
//-----------------------------------------------
//-----------------------------------------------
/// <summary>
/// ColoradoYearRangeCheck
/// </summary>
/// <param name="Value">year</param>
/// <param name="errMessage"></param>
/// <param name="aModelParameter"></param>
/// <returns></returns>
internal bool ColoradoYearRangeCheck(int Value, ref string errMessage, ModelParameterBaseClass aModelParameter)
{
if ((Value == SpecialValues.MissingIntValue) && (errMessage.ToUpper() == "INFO"))
{
ModelParameterGroupClass GroupCodes = new ModelParameterGroupClass("SaltVerde Range", new int[2] {eModelParam.epColorado_Historical_Data_Source, aModelParameter.ModelParam} );
errMessage = BuildModelParameterGroupFieldList(aModelParameter.ParameterManager, GroupCodes, "Different Range for each source");
return true;
}
else
{
bool valid = false;
errMessage = "";
int First = 0;
int Last = 0; int source = aModelParameter.ParameterManager.Model_Parameter(eModelParam.epColorado_Historical_Data_Source).Value; // Colorado_Historical_Data_Source; // 7/29 int Last = 0; int source = aModelParameter.ParameterManager.BaseModel_ParameterBaseClass(eModelParam.epColorado_Historical_Data_Source).Value;
valid = RiverHistoricalYearRangeCheck(Value, source, rcColorado, ref First, ref Last);
if (!valid) errMessage = "Invalid year of " + Value.ToString() + RiverRangeString(source, First, Last);
return valid;
}
}
//-----------------------------------------------
/// <summary>
/// Colorado_Historical_Extraction_Start_Year_RangeCheck
/// </summary>
/// <param name="Year">year to check</param>
/// <returns>true if year is valid, false otherwise </returns>
public bool Colorado_Historical_Extraction_Start_Year_RangeCheck(int Year)
{
string junk = "";
return ColoradoYearRangeCheck(Year, ref junk, ParamManager.Model_ParameterBaseClass(eModelParam.epColorado_Historical_Extraction_Start_Year));
}
//-----------------------------------------------
internal bool SaltVerdeYearRangeCheck(int Value, ref string errMessage, ModelParameterBaseClass aModelParameter)
{
if ((Value == SpecialValues.MissingIntValue) && (errMessage.ToUpper() == "INFO"))
{
ModelParameterGroupClass GroupCodes = new ModelParameterGroupClass("Salt Verde Range", new int[2] {eModelParam.epSaltVerde_Historical_Data,aModelParameter.ModelParam});
errMessage = BuildModelParameterGroupFieldList(aModelParameter.ParameterManager, GroupCodes, "Different Range for each source");
return true;
}
else
{
bool valid = false;
errMessage = "";
int source = aModelParameter.ParameterManager.Model_Parameter(eModelParam.epSaltVerde_Historical_Data).Value;// SaltVerde_Historical_Data_Source; // 7/29 aModelParameter.ParameterManager.BaseModel_ParameterBaseClass(eModelParam.epSaltVerde_Historical_Data).Value;
int First = 0;
int Last = 0;
valid = RiverHistoricalYearRangeCheck(Value, source, rcSaltVerde, ref First, ref Last);
if (!valid) errMessage = "Invalid year of " + Value.ToString() + RiverRangeString(source, First, Last);
return valid;
}
}
//-----------------------------------------------
/// <summary>
/// SaltVerde_Historical_Extraction_Start_Year_RangeCheck
/// </summary>
/// <param name="Value"></param>
/// <returns></returns>
public bool SaltVerde_Historical_Extraction_Start_Year_RangeCheck(int Value)
{
string junk = "";
return SaltVerdeYearRangeCheck(Value, ref junk, ParamManager.Model_ParameterBaseClass(eModelParam.epSaltVerde_Historical_Extraction_Start_Year));
}
//-----------------------------------------------
//------------------------------------------------
static internal string BuildModelParameterGroupFieldList(ParameterManagerClass PM, ModelParameterGroupClass Group, string Rule)
{
string temp = "{\"ParameterGroup\":[";
int cnt = 0;
foreach (int mpcode in Group.ModelParameters())
{
try
{
ModelParameterClass MP = PM.Model_Parameter(mpcode);
if (MP != null)
{
string fldstr = MP.Fieldname;
if (cnt > 0)
{
temp += ",";
}
temp += '\"' + fldstr + '\"';
cnt++;
}
}
catch
{
}
}
temp += "], \"RULE\":\""+Rule+"\"}";
return temp;
}
//-----------------------------------------------
/// <summary>
/// PCTEffluentRangeCheck
/// </summary>
/// <param name="Value"></param>
/// <param name="provider"></param>
/// <param name="emp"></param>
/// <returns></returns>
public bool PCTEffluentRangeCheck(int Value, eProvider provider, int emp)
{
bool test = false;
string junk = "";
if (ModelParamClass.valid(emp))
{
ModelParameterBaseClass MP = ParamManager.Model_ParameterBaseClass(emp);
test = PCTEffluentRangeCheck(Value, provider, ref junk, MP);
}
else
throw new WaterSim_Exception(WS_Strings.wsInvalid_EModelPAram);
return test;
}
//-----------------------------------------------
/// <summary>PCTEffluentRangeCheck. </summary>
///
/// <remarks> Ray, 8/20/2011. </remarks>
///
/// <param name="Value"> . </param>
/// <param name="provider"> . </param>
/// <param name="errMessage"> [in,out]. </param>
/// <param name="MP"> The. </param>
///
/// <returns> true if it succeeds, false if it fails. </returns>
internal static bool PCTEffluentRangeCheck(int Value, eProvider provider, ref string errMessage, ModelParameterBaseClass MP)
{
if ((Value == SpecialValues.MissingIntValue) && (errMessage.ToUpper() == "INFO"))
{
errMessage = BuildModelParameterGroupFieldList(MP.ParameterManager, MP.ParameterManager.EffluentGroup,"Equal 100");
return true;
}
else
{
bool valid = true;
if (!FSuspendRangeCheck)
{
ProviderIntArray currentvalues = new ProviderIntArray(0);
currentvalues = MP.ProviderProperty.getvalues();
ProviderIntArray CTotals = MP.ParameterManager.EffluentGroup.Totals;
int currenttotal = CTotals[provider];
int total = currenttotal + Value - currentvalues[(int)provider];
valid = ((Value <= 100) & (Value >= 0) & (total <= 100));
if (!valid) errMessage = "Total effluent allocated can not exceed 100 (%) " +
MP.ParameterManager.eParamGroupMessage(MP.ParameterManager.EffluentGroup, provider);
}
return valid;
}
}
//-----------------------------------------------
/// <summary>
/// PCTReclaimedRangeCheck - Check to see of all the PCT reclaimed model paramters do nt eceeed 100% total
/// </summary>
/// <param name="Value">int: to be checked if violates over 100% rule</param>
/// <param name="provider">eProvider: who will set the value</param>
/// <param name="emp">eModelParam: This is the actual ModelParameter that is doing the check.</param>
/// <returns>bool True if all values are less than or equal to 100, False of the do not</returns>
public bool PCTReclaimedRangeCheck(int Value, eProvider provider, int emp)
{
bool test = false;
string junk = "";
if (ModelParamClass.valid(emp))
{
ModelParameterBaseClass MP = ParamManager.Model_ParameterBaseClass(emp);
test = PCTReclaimedRangeCheck(Value, provider, ref junk, MP);
}
else
throw new WaterSim_Exception(WS_Strings.wsInvalid_EModelPAram);
return test;
}
//-----------------------------------------------------------------------
internal static bool PCTReclaimedRangeCheck(int Value, eProvider provider, ref string errMessage, ModelParameterBaseClass MP)
{
if ((Value == SpecialValues.MissingIntValue) && (errMessage.ToUpper() == "INFO"))
{
errMessage = BuildModelParameterGroupFieldList(MP.ParameterManager, MP.ParameterManager.ReclaimedGroup, "Equal 100");
return true;
}
else
{
bool valid = true;
if (!FSuspendRangeCheck)
{
ProviderIntArray currentvalues = new ProviderIntArray(0);
currentvalues = MP.ProviderProperty.getvalues();
int currenttotal = MP.ParameterManager.eParamGroupTotal(MP.ParameterManager.reclaimedchecklist, provider);
int total = currenttotal + Value - currentvalues[(int)provider];
valid = ((Value <= 100) & (Value >= 0) & (total <= 100));
if (!valid) errMessage = "Total reclaimed allocated can not exceed 100 (%) " +
MP.ParameterManager.eParamGroupMessage(MP.ParameterManager.ReclaimedGroup, provider);
}
return valid;
}
}
//-----------------------------------------------
/// <summary>
/// PCTResComRangeCheck - Checks to see if Residential an Commerical water use PCT does not excede 100.
/// </summary>
/// <param name="Value">int: to be checked if violates over 100% rule</param>
/// <param name="provider">eProvider: who will set the value</param>
/// <param name="emp">eModelParam: This is the actual ModelParameter that is doing the check.</param>
/// <returns>bool True if all values are less than or equal to 100, False of the do not</returns>
public bool PCTResComRangeCheck(int Value, eProvider provider, int emp)
{
bool test = false;
string junk = "";
if (ModelParamClass.valid(emp))
{
ModelParameterBaseClass MP = ParamManager.Model_ParameterBaseClass(emp);
test = ResComPCTRangeCheck(Value, provider, ref junk, MP);
}
else
throw new WaterSim_Exception(WS_Strings.wsInvalid_EModelPAram);
return test;
}
//-----------------------------------------------
internal static bool ResComPCTRangeCheck(int Value, eProvider provider, ref string errMessage, ModelParameterBaseClass MP)
{
if ((Value == SpecialValues.MissingIntValue) && (errMessage.ToUpper() == "INFO"))
{
errMessage = BuildModelParameterGroupFieldList(MP.ParameterManager, MP.ParameterManager.WaterUseGroup, "Equal 100");
return true;
}
else
{
bool valid = true;
if (!FSuspendRangeCheck)
{
ProviderIntArray currentvalues = new ProviderIntArray(0);
currentvalues = MP.ProviderProperty.getvalues();
int currenttotal = MP.ParameterManager.eParamGroupTotal(MP.ParameterManager.wateruserchecklist, provider);
int total = currenttotal + Value - currentvalues[(int)provider];
valid = ((Value <= 100) & (Value >= 0) & (total <= 100));
if (!valid) errMessage = "Total water use can not exceed 100 (%) " +
MP.ParameterManager.eParamGroupMessage(MP.ParameterManager.WaterUseGroup, provider);
}
return valid;
}
}
#endregion
//------------------------------------------------------------------------
// STATIC MEMBERS AND CONST
//---------------------------------------------------------
/// <summary>
/// IEnumerable for simulationYears()
/// </summary>
/// <returns>a year from range of Simulation_Start_Year to Simulation_End_Year</returns>
public IEnumerable<int> simulationYears()
{
for (int i = Simulation_Start_Year; i <= Simulation_End_Year; i++)
{
yield return i;
}
}
//============================================================
} // end of WaterSimManager
} // End of WaterSimDCDC
| 65.470531 | 631 | 0.547488 | [
"MIT"
] | DCDCWaterSim/API_SOURCE_FILES | Old/WaterSimDCDC_API_ver_9_2_3.cs | 201,060 | C# |
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
namespace Microsoft.Azure.PowerShell.Cmdlets.ResourceMover.Runtime.Json
{
public sealed class UInt32Converter : JsonConverter<uint>
{
internal override JsonNode ToJson(uint value) => new JsonNumber(value);
internal override uint FromJson(JsonNode node) => (uint)node;
}
} | 51.153846 | 97 | 0.512782 | [
"MIT"
] | 3quanfeng/azure-powershell | src/ResourceMover/generated/runtime/Conversions/Instances/UInt32Converter.cs | 655 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
namespace System.Diagnostics.SymbolStore
{
public interface ISymbolDocumentWriter
{
void SetCheckSum(Guid algorithmId, byte[] checkSum);
void SetSource(byte[] source);
}
}
| 31.076923 | 71 | 0.727723 | [
"MIT"
] | 06needhamt/runtime | src/libraries/System.Private.CoreLib/src/System/Diagnostics/SymbolStore/ISymbolDocumentWriter.cs | 404 | C# |
/*
* Copyright (c) .NET Foundation and Contributors
*
* This software may be modified and distributed under the terms
* of the MIT license. See the LICENSE file for details.
*
* https://github.com/piranhacms/piranha.core
*
*/
using Microsoft.AspNetCore.Http;
using Piranha.AspNetCore.Helpers;
using Piranha.Models;
namespace Piranha.AspNetCore.Services
{
/// <summary>
/// The main application service. This service must be
/// registered as a scoped service as it contains information
/// about the current requst.
/// </summary>
public interface IApplicationService
{
/// <summary>
/// Gets the current api.
/// </summary>
IApi Api { get; }
/// <summary>
/// Gets the site helper.
/// </summary>
ISiteHelper Site { get; }
/// <summary>
/// Gets the media helper.
/// </summary>
IMediaHelper Media { get; }
/// <summary>
/// Gets the request helper.
/// </summary>
IRequestHelper Request { get; }
/// <summary>
/// Gets/sets the id of the currently requested page.
/// </summary>
Guid PageId { get; set; }
/// <summary>
/// Gets/sets the current page.
/// </summary>
PageBase CurrentPage { get; set; }
/// <summary>
/// Gets/sets the current post.
/// </summary>
PostBase CurrentPost { get; set; }
/// <summary>
/// Initializes the service.
/// </summary>
Task InitAsync(HttpContext context);
/// <summary>
/// Gets the gravatar URL from the given parameters.
/// </summary>
/// <param name="email">The email address</param>
/// <param name="size">The requested size</param>
/// <returns>The gravatar URL</returns>
string GetGravatarUrl(string email, int size = 0);
}
}
| 26.479452 | 65 | 0.560269 | [
"MIT"
] | AllPIM/RhHERO-Web | core/Piranha.AspNetCore/Services/IApplicationService.cs | 1,933 | C# |
using System;
namespace Exercicios_aula
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Digite seu salário : ");
string Salario = Console.ReadLine();
Console.WriteLine("Digite a Quantidade de carros Vendidos: ");
string CarVend = Console.ReadLine();
Console.WriteLine("Digite a Comissão Fixa: ");
string ComissaoFixa = Console.ReadLine();
Console.WriteLine("Digite o Valor total de carros vendido no mês (R$): ");
string ValorTotal = Console.ReadLine();
double salarioFixo = Convert.ToInt32(Salario);
double carVend = Convert.ToInt32(CarVend);
double comissaoFixa = Convert.ToInt32(ComissaoFixa);
double valorVendido = Convert.ToInt32(ValorTotal);
double comissaoTotal = carVend * comissaoFixa;
double comissaoValorDeVendas = valorVendido * 5 /100;
double salarioTotal = salarioFixo + ( comissaoTotal + comissaoValorDeVendas);
Console.WriteLine( " O Vendedor ganhou de salário o valor de R$ " + salarioTotal );
}
}
}
| 32.810811 | 96 | 0.596376 | [
"MIT"
] | rafaaelcorrea/Exercicios_aula_c- | exe_8.cs | 1,218 | C# |
using System;
namespace TodoList
{
public class WeatherForecast
{
public DateTime Date { get; set; }
public int TemperatureC { get; set; }
public int TemperatureF => 32 + (int)(TemperatureC / 0.5556);
public string Summary { get; set; }
}
}
| 19 | 70 | 0.569079 | [
"MIT"
] | codemillmatt/IdentityWebBlog | WebAndAPI/TheWebAPI/WeatherForecast.cs | 304 | C# |
// Copyright (c) RISStudio, 2020. All rights reserved.
// Licensed under the Apache License, Version 2.0. See LICENSE file in the project root for license information.
using System;
using System.IO;
using RIS.Extensions;
namespace RIS.Cryptography.Hash
{
public class HashService
{
public event EventHandler<RInformationEventArgs> Information;
public event EventHandler<RWarningEventArgs> Warning;
public event EventHandler<RErrorEventArgs> Error;
public IHashMethod HashMethod { get; private set; }
public HashService(IHashMethod hashMethod)
{
if (!SetHashMethod(hashMethod))
{
var exception = new Exception("SetHashMethod return false. HashService is not initialized");
Events.OnError(this, new RErrorEventArgs(exception, exception.Message));
OnError(new RErrorEventArgs(exception, exception.Message));
throw exception;
}
}
public void OnInformation(RInformationEventArgs e)
{
OnInformation(this, e);
}
public void OnInformation(object sender, RInformationEventArgs e)
{
Information?.Invoke(sender, e);
}
public void OnWarning(RWarningEventArgs e)
{
OnWarning(this, e);
}
public void OnWarning(object sender, RWarningEventArgs e)
{
Warning?.Invoke(sender, e);
}
public void OnError(RErrorEventArgs e)
{
OnError(this, e);
}
public void OnError(object sender, RErrorEventArgs e)
{
Error?.Invoke(sender, e);
}
public bool SetHashMethod(IHashMethod hashMethod)
{
if (!hashMethod.Initialized)
return false;
HashMethod = hashMethod;
return true;
}
public string GetHash(string plainText)
{
return HashMethod.GetHash(plainText);
}
public string GetHash(string plainText, ushort saltLength, out string hashSalt)
{
hashSalt = HashMethodsUtils.GenerateSalt(saltLength);
return HashMethod.GetHash(hashSalt + plainText + hashSalt);
}
public string GetFileHash(string filePath, bool includeFileName = true)
{
return HashMethod.GetHash(GetFileHashInternal(filePath, includeFileName));
}
private string GetFileHashInternal(string filePath, bool includeFileName = true)
{
filePath = !Path.IsPathRooted(filePath)
? Path.GetFullPath(filePath)
: filePath;
if (!File.Exists(filePath))
{
var exception = new FileNotFoundException($"File at path '{filePath}' not found");
Events.OnError(this, new RErrorEventArgs(exception, exception.Message));
OnError(new RErrorEventArgs(exception, exception.Message));
throw exception;
}
FileStream file;
try
{
file = new FileStream(filePath, FileMode.Open, FileAccess.Read);
}
catch (Exception ex)
{
Events.OnError(this, new RErrorEventArgs(ex, ex.Message));
OnError(new RErrorEventArgs(ex, ex.Message));
throw;
}
string result = HashMethod.GetHash("0");
byte[] buffer = new byte[4096];
int countReadBytes;
do
{
countReadBytes = file.Read(buffer, 0, 4096);
if (countReadBytes > 0)
{
result = HashMethod.GetHash(
HashMethod.GetHash(buffer) +
result);
}
}
while (countReadBytes > 0);
if (includeFileName)
{
result = HashMethod.GetHash(
HashMethod.GetHash(Path.GetFileName(file.Name)) +
result);
}
file.Close();
return result;
}
public string GetDirectoryHash(string directoryPath,
bool includeDirectoryName = true, string[] blacklistPaths = null)
{
return HashMethod.GetHash(GetDirectoryHashInternal(directoryPath, includeDirectoryName, blacklistPaths));
}
private string GetDirectoryHashInternal(string directoryPath,
bool includeDirectoryName = true, string[] blacklistPaths = null)
{
directoryPath = directoryPath
.TrimEnd(Path.DirectorySeparatorChar)
.TrimEnd(Path.AltDirectorySeparatorChar);
directoryPath = !Path.IsPathRooted(directoryPath)
? Path.GetFullPath(directoryPath)
: directoryPath;
if (!Directory.Exists(directoryPath))
{
var exception = new FileNotFoundException($"Directory at path '{directoryPath}' not found");
Events.OnError(this, new RErrorEventArgs(exception, exception.Message));
OnError(new RErrorEventArgs(exception, exception.Message));
throw exception;
}
if (directoryPath.EndsWith(":", StringComparison.Ordinal))
includeDirectoryName = false;
int directorySeparatorIndex = directoryPath
.LastIndexOfAny(new[] { Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar });
string directoryName = directoryPath.Substring(directorySeparatorIndex + 1);
string result = HashMethod.GetHash("0");
foreach (string file in DirectoryExtensions.EnumerateAllFiles(directoryPath, blacklistPaths))
{
string fileDirectoryPath = Path.GetDirectoryName(file);
if (!string.IsNullOrEmpty(fileDirectoryPath))
{
int fileDirectorySeparatorIndex = fileDirectoryPath
.LastIndexOfAny(new[] { Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar });
string fileDirectoryName = fileDirectoryPath.Substring(fileDirectorySeparatorIndex + 1);
if (fileDirectoryName != directoryName)
{
result = HashMethod.GetHash(
HashMethod.GetHash(fileDirectoryName) +
result);
}
}
result = HashMethod.GetHash(
GetFileHash(file) +
result);
}
if (includeDirectoryName)
{
result = HashMethod.GetHash(
HashMethod.GetHash(directoryName) +
result);
}
return result;
}
public bool VerifyHash(string plainText, string hashText)
{
return HashMethod.VerifyHash(plainText, hashText);
}
public bool VerifyHash(string plainText, string hashText, string hashSalt)
{
return HashMethod.VerifyHash(hashSalt + plainText + hashSalt, hashText);
}
public bool VerifyFileHash(string filePath, string hashText,
bool includeFileName = true)
{
return HashMethod.VerifyHash(GetFileHashInternal(filePath, includeFileName), hashText);
}
public bool VerifyDirectoryHash(string directoryPath, string hashText,
bool includeDirectoryName = true, string[] blacklistPaths = null)
{
return HashMethod.VerifyHash(GetDirectoryHashInternal(directoryPath, includeDirectoryName, blacklistPaths), hashText);
}
}
}
| 35.116592 | 130 | 0.570681 | [
"Apache-2.0"
] | RISStudio-tm/RIS-Libraries | RIS.Cryptography/Hash/HashService.cs | 7,833 | C# |
// This file is part of the DSharpPlus project.
//
// Copyright (c) 2015 Mike Santiago
// Copyright (c) 2016-2022 DSharpPlus Contributors
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using DSharpPlus.EventArgs;
using DSharpPlus.Exceptions;
using DSharpPlus.Net;
using DSharpPlus.Net.Abstractions;
using DSharpPlus.Net.Models;
using DSharpPlus.Net.Serialization;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
namespace DSharpPlus.Entities
{
/// <summary>
/// Represents a Discord guild.
/// </summary>
public class DiscordGuild : SnowflakeObject, IEquatable<DiscordGuild>
{
/// <summary>
/// Gets the guild's name.
/// </summary>
[JsonProperty("name", NullValueHandling = NullValueHandling.Ignore)]
public string Name { get; internal set; }
/// <summary>
/// Gets the guild icon's hash.
/// </summary>
[JsonProperty("icon", NullValueHandling = NullValueHandling.Ignore)]
public string IconHash { get; internal set; }
/// <summary>
/// Gets the guild icon's url.
/// </summary>
[JsonIgnore]
public string IconUrl
=> this.GetIconUrl(ImageFormat.Auto, 1024);
/// <summary>
/// Gets the guild splash's hash.
/// </summary>
[JsonProperty("splash", NullValueHandling = NullValueHandling.Ignore)]
public string SplashHash { get; internal set; }
/// <summary>
/// Gets the guild splash's url.
/// </summary>
[JsonIgnore]
public string SplashUrl
=> !string.IsNullOrWhiteSpace(this.SplashHash) ? $"https://cdn.discordapp.com/splashes/{this.Id.ToString(CultureInfo.InvariantCulture)}/{this.SplashHash}.jpg" : null;
/// <summary>
/// Gets the guild discovery splash's hash.
/// </summary>
[JsonProperty("discovery_splash", NullValueHandling = NullValueHandling.Ignore)]
public string DiscoverySplashHash { get; internal set; }
/// <summary>
/// Gets the guild discovery splash's url.
/// </summary>
[JsonIgnore]
public string DiscoverySplashUrl
=> !string.IsNullOrWhiteSpace(this.DiscoverySplashHash) ? $"https://cdn.discordapp.com/discovery-splashes/{this.Id.ToString(CultureInfo.InvariantCulture)}/{this.DiscoverySplashHash}.jpg" : null;
/// <summary>
/// Gets the preferred locale of this guild.
/// <para>This is used for server discovery and notices from Discord. Defaults to en-US.</para>
/// </summary>
[JsonProperty("preferred_locale", NullValueHandling = NullValueHandling.Ignore)]
public string PreferredLocale { get; internal set; }
/// <summary>
/// Gets the ID of the guild's owner.
/// </summary>
[JsonProperty("owner_id", NullValueHandling = NullValueHandling.Ignore)]
public ulong OwnerId { get; internal set; }
/// <summary>
/// Gets permissions for the user in the guild (does not include channel overrides)
/// </summary>
[JsonProperty("permissions", NullValueHandling = NullValueHandling.Ignore)]
public Permissions? Permissions { get; set; }
/// <summary>
/// Gets the guild's owner.
/// </summary>
[JsonIgnore]
public DiscordMember Owner
=> this.Members.TryGetValue(this.OwnerId, out var owner)
? owner
: this.Discord.ApiClient.GetGuildMemberAsync(this.Id, this.OwnerId).ConfigureAwait(false).GetAwaiter().GetResult();
/// <summary>
/// Gets the guild's voice region ID.
/// </summary>
[JsonProperty("region", NullValueHandling = NullValueHandling.Ignore)]
internal string VoiceRegionId { get; set; }
/// <summary>
/// Gets the guild's voice region.
/// </summary>
[JsonIgnore]
public DiscordVoiceRegion VoiceRegion
=> this.Discord.VoiceRegions[this.VoiceRegionId];
/// <summary>
/// Gets the guild's AFK voice channel ID.
/// </summary>
[JsonProperty("afk_channel_id", NullValueHandling = NullValueHandling.Ignore)]
internal ulong AfkChannelId { get; set; } = 0;
/// <summary>
/// Gets the guild's AFK voice channel.
/// </summary>
[JsonIgnore]
public DiscordChannel AfkChannel
=> this.GetChannel(this.AfkChannelId);
/// <summary>
/// Gets the guild's AFK timeout.
/// </summary>
[JsonProperty("afk_timeout", NullValueHandling = NullValueHandling.Ignore)]
public int AfkTimeout { get; internal set; }
/// <summary>
/// Gets the guild's verification level.
/// </summary>
[JsonProperty("verification_level", NullValueHandling = NullValueHandling.Ignore)]
public VerificationLevel VerificationLevel { get; internal set; }
/// <summary>
/// Gets the guild's default notification settings.
/// </summary>
[JsonProperty("default_message_notifications", NullValueHandling = NullValueHandling.Ignore)]
public DefaultMessageNotifications DefaultMessageNotifications { get; internal set; }
/// <summary>
/// Gets the guild's explicit content filter settings.
/// </summary>
[JsonProperty("explicit_content_filter")]
public ExplicitContentFilter ExplicitContentFilter { get; internal set; }
/// <summary>
/// Gets the guild's nsfw level.
/// </summary>
[JsonProperty("nsfw_level")]
public NsfwLevel NsfwLevel { get; internal set; }
[JsonProperty("system_channel_id", NullValueHandling = NullValueHandling.Include)]
internal ulong? SystemChannelId { get; set; }
/// <summary>
/// Gets the channel where system messages (such as boost and welcome messages) are sent.
/// </summary>
[JsonIgnore]
public DiscordChannel SystemChannel => this.SystemChannelId.HasValue
? this.GetChannel(this.SystemChannelId.Value)
: null;
/// <summary>
/// Gets the settings for this guild's system channel.
/// </summary>
[JsonProperty("system_channel_flags")]
public SystemChannelFlags SystemChannelFlags { get; internal set; }
/// <summary>
/// Gets whether this guild's widget is enabled.
/// </summary>
[JsonProperty("widget_enabled", NullValueHandling = NullValueHandling.Ignore)]
public bool? WidgetEnabled { get; internal set; }
[JsonProperty("widget_channel_id", NullValueHandling = NullValueHandling.Ignore)]
internal ulong? WidgetChannelId { get; set; }
/// <summary>
/// Gets the widget channel for this guild.
/// </summary>
[JsonIgnore]
public DiscordChannel WidgetChannel => this.WidgetChannelId.HasValue
? this.GetChannel(this.WidgetChannelId.Value)
: null;
[JsonProperty("rules_channel_id")]
internal ulong? RulesChannelId { get; set; }
/// <summary>
/// Gets the rules channel for this guild.
/// <para>This is only available if the guild is considered "discoverable".</para>
/// </summary>
[JsonIgnore]
public DiscordChannel RulesChannel => this.RulesChannelId.HasValue
? this.GetChannel(this.RulesChannelId.Value)
: null;
[JsonProperty("public_updates_channel_id")]
internal ulong? PublicUpdatesChannelId { get; set; }
/// <summary>
/// Gets the public updates channel (where admins and moderators receive messages from Discord) for this guild.
/// <para>This is only available if the guild is considered "discoverable".</para>
/// </summary>
[JsonIgnore]
public DiscordChannel PublicUpdatesChannel => this.PublicUpdatesChannelId.HasValue
? this.GetChannel(this.PublicUpdatesChannelId.Value)
: null;
/// <summary>
/// Gets the application ID of this guild if it is bot created.
/// </summary>
[JsonProperty("application_id")]
public ulong? ApplicationId { get; internal set; }
/// <summary>
/// Sceduled events for this guild.
/// </summary>
public IReadOnlyDictionary<ulong, DiscordScheduledGuildEvent> ScheduledEvents
=> new ReadOnlyConcurrentDictionary<ulong, DiscordScheduledGuildEvent>(this._scheduledEvents);
[JsonProperty("guild_scheduled_events")]
[JsonConverter(typeof(SnowflakeArrayAsDictionaryJsonConverter))]
internal ConcurrentDictionary<ulong, DiscordScheduledGuildEvent> _scheduledEvents = new();
/// <summary>
/// Gets a collection of this guild's roles.
/// </summary>
[JsonIgnore]
public IReadOnlyDictionary<ulong, DiscordRole> Roles => new ReadOnlyConcurrentDictionary<ulong, DiscordRole>(this._roles);
[JsonProperty("roles", NullValueHandling = NullValueHandling.Ignore)]
[JsonConverter(typeof(SnowflakeArrayAsDictionaryJsonConverter))]
internal ConcurrentDictionary<ulong, DiscordRole> _roles;
/// <summary>
/// Gets a collection of this guild's stickers.
/// </summary>
[JsonIgnore]
public IReadOnlyDictionary<ulong, DiscordMessageSticker> Stickers => new ReadOnlyConcurrentDictionary<ulong, DiscordMessageSticker>(this._stickers);
[JsonProperty("stickers", NullValueHandling = NullValueHandling.Ignore)]
[JsonConverter(typeof(SnowflakeArrayAsDictionaryJsonConverter))]
internal ConcurrentDictionary<ulong, DiscordMessageSticker> _stickers = new();
/// <summary>
/// Gets a collection of this guild's emojis.
/// </summary>
[JsonIgnore]
public IReadOnlyDictionary<ulong, DiscordEmoji> Emojis => new ReadOnlyConcurrentDictionary<ulong, DiscordEmoji>(this._emojis);
[JsonProperty("emojis", NullValueHandling = NullValueHandling.Ignore)]
[JsonConverter(typeof(SnowflakeArrayAsDictionaryJsonConverter))]
internal ConcurrentDictionary<ulong, DiscordEmoji> _emojis;
/// <summary>
/// Gets a collection of this guild's features.
/// </summary>
[JsonProperty("features", NullValueHandling = NullValueHandling.Ignore)]
public IReadOnlyList<string> Features { get; internal set; }
/// <summary>
/// Gets the required multi-factor authentication level for this guild.
/// </summary>
[JsonProperty("mfa_level", NullValueHandling = NullValueHandling.Ignore)]
public MfaLevel MfaLevel { get; internal set; }
/// <summary>
/// Gets this guild's join date.
/// </summary>
[JsonProperty("joined_at", NullValueHandling = NullValueHandling.Ignore)]
public DateTimeOffset JoinedAt { get; internal set; }
/// <summary>
/// Gets whether this guild is considered to be a large guild.
/// </summary>
[JsonProperty("large", NullValueHandling = NullValueHandling.Ignore)]
public bool IsLarge { get; internal set; }
/// <summary>
/// Gets whether this guild is unavailable.
/// </summary>
[JsonProperty("unavailable", NullValueHandling = NullValueHandling.Ignore)]
public bool IsUnavailable { get; internal set; }
/// <summary>
/// Gets the total number of members in this guild.
/// </summary>
[JsonProperty("member_count", NullValueHandling = NullValueHandling.Ignore)]
public int MemberCount { get; internal set; }
/// <summary>
/// Gets the maximum amount of members allowed for this guild.
/// </summary>
[JsonProperty("max_members")]
public int? MaxMembers { get; internal set; }
/// <summary>
/// Gets the maximum amount of presences allowed for this guild.
/// </summary>
[JsonProperty("max_presences")]
public int? MaxPresences { get; internal set; }
#pragma warning disable CS1734
/// <summary>
/// Gets the approximate number of members in this guild, when using <see cref="DiscordClient.GetGuildAsync(ulong, bool?)"/> and having <paramref name="withCounts"></paramref> set to true.
/// </summary>
[JsonProperty("approximate_member_count", NullValueHandling = NullValueHandling.Ignore)]
public int? ApproximateMemberCount { get; internal set; }
/// <summary>
/// Gets the approximate number of presences in this guild, when using <see cref="DiscordClient.GetGuildAsync(ulong, bool?)"/> and having <paramref name="withCounts"></paramref> set to true.
/// </summary>
[JsonProperty("approximate_presence_count", NullValueHandling = NullValueHandling.Ignore)]
public int? ApproximatePresenceCount { get; internal set; }
#pragma warning restore CS1734
/// <summary>
/// Gets the maximum amount of users allowed per video channel.
/// </summary>
[JsonProperty("max_video_channel_users", NullValueHandling = NullValueHandling.Ignore)]
public int? MaxVideoChannelUsers { get; internal set; }
/// <summary>
/// Gets a dictionary of all the voice states for this guilds. The key for this dictionary is the ID of the user
/// the voice state corresponds to.
/// </summary>
[JsonIgnore]
public IReadOnlyDictionary<ulong, DiscordVoiceState> VoiceStates => new ReadOnlyConcurrentDictionary<ulong, DiscordVoiceState>(this._voiceStates);
[JsonProperty("voice_states", NullValueHandling = NullValueHandling.Ignore)]
[JsonConverter(typeof(SnowflakeArrayAsDictionaryJsonConverter))]
internal ConcurrentDictionary<ulong, DiscordVoiceState> _voiceStates;
/// <summary>
/// Gets a dictionary of all the members that belong to this guild. The dictionary's key is the member ID.
/// </summary>
[JsonIgnore] // TODO overhead of => vs Lazy? it's a struct
public IReadOnlyDictionary<ulong, DiscordMember> Members => new ReadOnlyConcurrentDictionary<ulong, DiscordMember>(this._members);
[JsonProperty("members", NullValueHandling = NullValueHandling.Ignore)]
[JsonConverter(typeof(SnowflakeArrayAsDictionaryJsonConverter))]
internal ConcurrentDictionary<ulong, DiscordMember> _members;
/// <summary>
/// Gets a dictionary of all the channels associated with this guild. The dictionary's key is the channel ID.
/// </summary>
[JsonIgnore]
public IReadOnlyDictionary<ulong, DiscordChannel> Channels => new ReadOnlyConcurrentDictionary<ulong, DiscordChannel>(this._channels);
[JsonProperty("channels", NullValueHandling = NullValueHandling.Ignore)]
[JsonConverter(typeof(SnowflakeArrayAsDictionaryJsonConverter))]
internal ConcurrentDictionary<ulong, DiscordChannel> _channels;
/// <summary>
/// Gets a dictionary of all the active threads associated with this guild the user has permission to view. The dictionary's key is the channel ID.
/// </summary>
[JsonIgnore]
public IReadOnlyDictionary<ulong, DiscordThreadChannel> Threads => new ReadOnlyConcurrentDictionary<ulong, DiscordThreadChannel>(this._threads);
[JsonProperty("threads", NullValueHandling = NullValueHandling.Ignore)]
[JsonConverter(typeof(SnowflakeArrayAsDictionaryJsonConverter))]
internal ConcurrentDictionary<ulong, DiscordThreadChannel> _threads = new();
internal ConcurrentDictionary<string, DiscordInvite> _invites;
/// <summary>
/// Gets the guild member for current user.
/// </summary>
[JsonIgnore]
public DiscordMember CurrentMember
=> this._current_member_lazy.Value;
[JsonIgnore]
private readonly Lazy<DiscordMember> _current_member_lazy;
/// <summary>
/// Gets the @everyone role for this guild.
/// </summary>
[JsonIgnore]
public DiscordRole EveryoneRole
=> this.GetRole(this.Id);
[JsonIgnore]
internal bool _isOwner;
/// <summary>
/// Gets whether the current user is the guild's owner.
/// </summary>
[JsonProperty("owner", NullValueHandling = NullValueHandling.Ignore)]
public bool IsOwner
{
get => this._isOwner || this.OwnerId == this.Discord.CurrentUser.Id;
internal set => this._isOwner = value;
}
/// <summary>
/// Gets the vanity URL code for this guild, when applicable.
/// </summary>
[JsonProperty("vanity_url_code")]
public string VanityUrlCode { get; internal set; }
/// <summary>
/// Gets the guild description, when applicable.
/// </summary>
[JsonProperty("description")]
public string Description { get; internal set; }
/// <summary>
/// Gets this guild's banner hash, when applicable.
/// </summary>
[JsonProperty("banner")]
public string Banner { get; internal set; }
/// <summary>
/// Gets this guild's banner in url form.
/// </summary>
[JsonIgnore]
public string BannerUrl
=> !string.IsNullOrWhiteSpace(this.Banner) ? $"https://cdn.discordapp.com/banners/{this.Id}/{this.Banner}" : null;
/// <summary>
/// Gets this guild's premium tier (Nitro boosting).
/// </summary>
[JsonProperty("premium_tier")]
public PremiumTier PremiumTier { get; internal set; }
/// <summary>
/// Gets the amount of members that boosted this guild.
/// </summary>
[JsonProperty("premium_subscription_count", NullValueHandling = NullValueHandling.Ignore)]
public int? PremiumSubscriptionCount { get; internal set; }
/// <summary>
/// Whether the guild has the boost progress bar enabled.
/// </summary>
[JsonProperty("premium_progress_bar_enabled", NullValueHandling = NullValueHandling.Ignore)]
public bool PremiumProgressBarEnabled { get; internal set; }
/// <summary>
/// Gets whether this guild is designated as NSFW.
/// </summary>
[JsonProperty("nsfw", NullValueHandling = NullValueHandling.Ignore)]
public bool IsNSFW { get; internal set; }
/// <summary>
/// Gets the stage instances in this guild.
/// </summary>
[JsonIgnore]
public IReadOnlyDictionary<ulong, DiscordStageInstance> StageInstances => new ReadOnlyConcurrentDictionary<ulong, DiscordStageInstance>(this._stageInstances);
[JsonProperty("stage_instances", NullValueHandling = NullValueHandling.Ignore)]
[JsonConverter(typeof(SnowflakeArrayAsDictionaryJsonConverter))]
internal ConcurrentDictionary<ulong, DiscordStageInstance> _stageInstances;
// Seriously discord?
// I need to work on this
//
// /// <summary>
// /// Gets channels ordered in a manner in which they'd be ordered in the UI of the discord client.
// /// </summary>
// [JsonIgnore]
// public IEnumerable<DiscordChannel> OrderedChannels
// => this._channels.OrderBy(xc => xc.Parent?.Position).ThenBy(xc => xc.Type).ThenBy(xc => xc.Position);
[JsonIgnore]
internal bool IsSynced { get; set; }
internal DiscordGuild()
{
this._current_member_lazy = new Lazy<DiscordMember>(() => (this._members != null && this._members.TryGetValue(this.Discord.CurrentUser.Id, out var member)) ? member : null);
this._invites = new ConcurrentDictionary<string, DiscordInvite>();
}
#region Guild Methods
/// <summary>
/// Gets guild's icon URL, in requested format and size.
/// </summary>
/// <param name="imageFormat">The image format of the icon to get.</param>
/// <param name="imageSize">The maximum size of the icon. Must be a power of two, minimum 16, maximum 4096.</param>
/// <returns>The URL of the guild's icon.</returns>
public string GetIconUrl(ImageFormat imageFormat, ushort imageSize = 1024)
{
if (string.IsNullOrWhiteSpace(this.IconHash))
return null;
if (imageFormat == ImageFormat.Unknown)
throw new ArgumentException("You must specify valid image format.", nameof(imageFormat));
// Makes sure the image size is in between Discord's allowed range.
if (imageSize < 16 || imageSize > 4096)
throw new ArgumentOutOfRangeException(nameof(imageSize), imageSize, "Image Size is not in between 16 and 4096.");
// Checks to see if the image size is not a power of two.
if (!(imageSize is not 0 && (imageSize & (imageSize - 1)) is 0))
throw new ArgumentOutOfRangeException(nameof(imageSize), imageSize, "Image size is not a power of two.");
// Get the string variants of the method parameters to use in the urls.
var stringImageFormat = imageFormat switch
{
ImageFormat.Gif => "gif",
ImageFormat.Jpeg => "jpg",
ImageFormat.Png => "png",
ImageFormat.WebP => "webp",
ImageFormat.Auto => !string.IsNullOrWhiteSpace(this.IconHash) ? (this.IconHash.StartsWith("a_") ? "gif" : "png") : "png",
_ => throw new ArgumentOutOfRangeException(nameof(imageFormat)),
};
var stringImageSize = imageSize.ToString(CultureInfo.InvariantCulture);
return $"https://cdn.discordapp.com{Endpoints.ICONS}/{this.Id}/{this.IconHash}.{stringImageFormat}?size={stringImageSize}";
}
/// <summary>
/// Creates a new scheduled event in this guild.
/// </summary>
/// <param name="name">The name of the event to create, up to 100 characters.</param>
/// <param name="description">The description of the event, up to 1000 characters.</param>
/// <param name="channelId">If a <see cref="ScheduledGuildEventType.StageInstance"/> or <see cref="ScheduledGuildEventType.VoiceChannel"/>, the id of the channel the event will be hosted in</param>
/// <param name="type">The type of the event. <see paramref="channelId"/> must be supplied if not an external event.</param>
/// <param name="privacyLevel">The privacy level of thi</param>
/// <param name="start">When this event starts. Must be in the future, and before the end date.</param>
/// <param name="end">When this event ends. If supplied, must be in the future and after the end date. This is requred for <see cref="ScheduledGuildEventType.External"/>.</param>
/// <param name="location">Where this event takes place, up to 100 characters. Only applicable if the type is <see cref="ScheduledGuildEventType.External"/></param>
/// <param name="reason">Reason for audit log.</param>
/// <returns>The created event.</returns>
public Task<DiscordScheduledGuildEvent> CreateEventAsync(string name, string description, ulong? channelId, ScheduledGuildEventType type, ScheduledGuildEventPrivacyLevel privacyLevel, DateTimeOffset start, DateTimeOffset? end, string location = null, string reason = null)
{
if (start <= DateTimeOffset.Now)
throw new ArgumentOutOfRangeException("The start time for an event must be in the future.");
if (end != null && end <= start)
throw new ArgumentOutOfRangeException("The end time for an event must be after the start time.");
DiscordScheduledGuildEventMetadata metadata = null;
switch (type)
{
case ScheduledGuildEventType.StageInstance or ScheduledGuildEventType.VoiceChannel when channelId == null:
throw new ArgumentException($"{nameof(channelId)} must not be null when type is {type}", nameof(channelId));
case ScheduledGuildEventType.External when channelId != null:
throw new ArgumentException($"{nameof(channelId)} must be null when using external event type", nameof(channelId));
case ScheduledGuildEventType.External when location == null:
throw new ArgumentException($"{nameof(location)} must not be null when using external event type", nameof(location));
case ScheduledGuildEventType.External when end == null:
throw new ArgumentException($"{nameof(end)} must not be null when using external event type", nameof(end));
}
if (!string.IsNullOrEmpty(location))
metadata = new DiscordScheduledGuildEventMetadata()
{
Location = location
};
return this.Discord.ApiClient.CreateScheduledGuildEventAsync(this.Id, name, description, channelId, start, end, type, privacyLevel, metadata, reason);
}
/// <summary>
/// Starts a scheduled event in this guild.
/// </summary>
/// <param name="guildEvent">The event to cancel.</param>
/// <returns></returns>
/// <exception cref="InvalidOperationException"></exception>
public Task StartEventAsync(DiscordScheduledGuildEvent guildEvent)
{
if (guildEvent.Status is not ScheduledGuildEventStatus.Scheduled)
throw new InvalidOperationException("The event must be scheduled for it to be started.");
return this.ModifyEventAsync(guildEvent, m => m.Status = ScheduledGuildEventStatus.Active);
}
/// <summary>
/// Cancels an event. The event must be scheduled for it to be cancelled.
/// </summary>
/// <param name="guildEvent">The event to delete.</param>
public Task CancelEventAsync(DiscordScheduledGuildEvent guildEvent)
{
if (guildEvent.Status is not ScheduledGuildEventStatus.Scheduled)
throw new InvalidOperationException("The event must be scheduled for it to be cancelled.");
return this.ModifyEventAsync(guildEvent, m => m.Status = ScheduledGuildEventStatus.Cancelled);
}
/// <summary>
/// Modifies an existing scheduled event in this guild.
/// </summary>
/// <param name="guildEvent">The event to modify.</param>
/// <param name="mdl">The action to perform on this event</param>
/// <param name="reason">The reason this event is being modified</param>
/// <returns>The modified object</returns>
/// <exception cref="ArgumentException"></exception>
public async Task ModifyEventAsync(DiscordScheduledGuildEvent guildEvent, Action<ScheduledGuildEventEditModel> mdl, string reason = null)
{
var model = new ScheduledGuildEventEditModel();
mdl(model);
if (model.Type.HasValue && model.Type.Value is not ScheduledGuildEventType.External)
{
if (!model.Channel.HasValue)
throw new ArgumentException("Channel must be supplied if the event is a stage instance or voice channel event.");
if (model.Type.Value is ScheduledGuildEventType.StageInstance && model.Channel.Value.Type is not ChannelType.Stage)
throw new ArgumentException("Channel must be a stage channel if the event is a stage instance event.");
if (model.Type.Value is ScheduledGuildEventType.VoiceChannel && model.Channel.Value.Type is not ChannelType.Voice)
throw new ArgumentException("Channel must be a voice channel if the event is a voice channel event.");
if (model.EndTime.HasValue && model.EndTime.Value < guildEvent.StartTime)
throw new ArgumentException("End time must be after the start time.");
}
if (model.Type.HasValue && model.Type.Value is ScheduledGuildEventType.External)
{
if (!model.EndTime.HasValue)
throw new ArgumentException("End must be supplied if the event is an external event.");
if (!model.Metadata.HasValue || string.IsNullOrEmpty(model.Metadata.Value.Location))
throw new ArgumentException("Location must be supplied if the event is an external event.");
if (model.Channel.HasValue && model.Channel.Value != null)
throw new ArgumentException("Channel must not be supplied if the event is an external event.");
}
if (guildEvent.Status is ScheduledGuildEventStatus.Completed)
throw new ArgumentException("The event must not be completed for it to be modified.");
if (guildEvent.Status is ScheduledGuildEventStatus.Cancelled)
throw new ArgumentException("The event must not be cancelled for it to be modified.");
if (model.Status.HasValue)
{
switch (model.Status.Value)
{
case ScheduledGuildEventStatus.Scheduled:
throw new ArgumentException("Status must not be set to scheduled.");
case ScheduledGuildEventStatus.Active when guildEvent.Status is not ScheduledGuildEventStatus.Scheduled:
throw new ArgumentException("Event status must be scheduled to progress to active.");
case ScheduledGuildEventStatus.Completed when guildEvent.Status is not ScheduledGuildEventStatus.Active:
throw new ArgumentException("Event status must be active to progress to completed.");
case ScheduledGuildEventStatus.Cancelled when guildEvent.Status is not ScheduledGuildEventStatus.Scheduled:
throw new ArgumentException("Event status must be scheduled to progress to cancelled.");
}
}
var modifiedEvent = await this.Discord.ApiClient.ModifyScheduledGuildEventAsync(
this.Id, guildEvent.Id,
model.Name, model.Description,
model.Channel.IfPresent(c => c?.Id),
model.StartTime, model.EndTime,
model.Type, model.PrivacyLevel,
model.Metadata, model.Status, reason).ConfigureAwait(false);
this._scheduledEvents[modifiedEvent.Id] = modifiedEvent;
return;
}
/// <summary>
/// Deletes an exising scheduled event in this guild.
/// </summary>
/// <param name="guildEvent"></param>
/// <param name="reason"></param>
/// <returns></returns>
public Task DeleteEventAsync(DiscordScheduledGuildEvent guildEvent, string reason = null)
{
this._scheduledEvents.TryRemove(guildEvent.Id, out _);
return this.Discord.ApiClient.DeleteScheduledGuildEventAsync(this.Id, guildEvent.Id);
}
/// <summary>
/// Gets the currently active or scheduled events in this guild.
/// </summary>
/// <param name="withUserCounts">Whether to include number of users subscribed to each event</param>
/// <returns>The active and scheduled events on the server, if any.</returns>
public async Task<IReadOnlyList<DiscordScheduledGuildEvent>> GetEventsAsync(bool withUserCounts = false)
{
var events = await this.Discord.ApiClient.GetScheduledGuildEventsAsync(this.Id, withUserCounts);
foreach (var @event in events)
this._scheduledEvents[@event.Id] = @event;
return events;
}
/// <summary>
/// Gets a list of users who are interested in this event.
/// </summary>
/// <param name="guildEvent">The event to query users from</param>
/// <param name="limit">How many users to fetch.</param>
/// <param name="after">Fetch users after this id. Mutually exclusive with before</param>
/// <param name="before">Fetch users before this id. Mutually exclusive with after</param>
public async Task<IReadOnlyList<DiscordUser>> GetEventUsersAsync(DiscordScheduledGuildEvent guildEvent, int limit = 100, ulong? after = null, ulong? before = null)
{
var remaining = limit;
ulong? last = null;
var isAfter = after != null;
var users = new List<DiscordUser>();
int lastCount;
do
{
var fetchSize = remaining > 100 ? 100 : remaining;
var fetch = await this.Discord.ApiClient.GetScheduledGuildEventUsersAsync(this.Id, guildEvent.Id, true, fetchSize, !isAfter ? last ?? before : null, isAfter ? last ?? after : null);
lastCount = fetch.Count;
remaining -= lastCount;
if (!isAfter)
{
users.AddRange(fetch);
last = fetch.LastOrDefault()?.Id;
}
else
{
users.InsertRange(0, fetch);
last = fetch.FirstOrDefault()?.Id;
}
}
while (remaining > 0 && lastCount > 0);
return users.AsReadOnly();
}
/// <summary>
/// Searches the current guild for members who's display name start with the specified name.
/// </summary>
/// <param name="name">The name to search for.</param>
/// <param name="limit">The maximum amount of members to return. Max 1000. Defaults to 1.</param>
/// <returns>The members found, if any.</returns>
public Task<IReadOnlyList<DiscordMember>> SearchMembersAsync(string name, int? limit = 1)
=> this.Discord.ApiClient.SearchMembersAsync(this.Id, name, limit);
/// <summary>
/// Adds a new member to this guild
/// </summary>
/// <param name="user">User to add</param>
/// <param name="access_token">User's access token (OAuth2)</param>
/// <param name="nickname">new nickname</param>
/// <param name="roles">new roles</param>
/// <param name="muted">whether this user has to be muted</param>
/// <param name="deaf">whether this user has to be deafened</param>
/// <returns></returns>
/// <exception cref="UnauthorizedException">Thrown when the client does not have the <see cref="Permissions.CreateInstantInvite" /> permission.</exception>
/// <exception cref="NotFoundException">Thrown when the <paramref name="user"/> or <paramref name="access_token"/> is not found.</exception>
/// <exception cref="BadRequestException">Thrown when an invalid parameter was provided.</exception>
/// <exception cref="ServerErrorException">Thrown when Discord is unable to process the request.</exception>
public Task AddMemberAsync(DiscordUser user, string access_token, string nickname = null, IEnumerable<DiscordRole> roles = null,
bool muted = false, bool deaf = false)
=> this.Discord.ApiClient.AddGuildMemberAsync(this.Id, user.Id, access_token, nickname, roles, muted, deaf);
/// <summary>
/// Deletes this guild. Requires the caller to be the owner of the guild.
/// </summary>
/// <returns></returns>
/// <exception cref="UnauthorizedException">Thrown when the client is not the owner of the guild.</exception>
/// <exception cref="ServerErrorException">Thrown when Discord is unable to process the request.</exception>
public Task DeleteAsync()
=> this.Discord.ApiClient.DeleteGuildAsync(this.Id);
/// <summary>
/// Modifies this guild.
/// </summary>
/// <param name="action">Action to perform on this guild..</param>
/// <returns>The modified guild object.</returns>
/// <exception cref="UnauthorizedException">Thrown when the client does not have the <see cref="Permissions.ManageGuild"/> permission.</exception>
/// <exception cref="NotFoundException">Thrown when the guild does not exist.</exception>
/// <exception cref="BadRequestException">Thrown when an invalid parameter was provided.</exception>
/// <exception cref="ServerErrorException">Thrown when Discord is unable to process the request.</exception>
public async Task<DiscordGuild> ModifyAsync(Action<GuildEditModel> action)
{
var mdl = new GuildEditModel();
action(mdl);
if (mdl.AfkChannel.HasValue && mdl.AfkChannel.Value.Type != ChannelType.Voice)
throw new ArgumentException("AFK channel needs to be a voice channel.");
var iconb64 = Optional.FromNoValue<string>();
if (mdl.Icon.HasValue && mdl.Icon.Value != null)
using (var imgtool = new ImageTool(mdl.Icon.Value))
iconb64 = imgtool.GetBase64();
else if (mdl.Icon.HasValue)
iconb64 = null;
var splashb64 = Optional.FromNoValue<string>();
if (mdl.Splash.HasValue && mdl.Splash.Value != null)
using (var imgtool = new ImageTool(mdl.Splash.Value))
splashb64 = imgtool.GetBase64();
else if (mdl.Splash.HasValue)
splashb64 = null;
var bannerb64 = Optional.FromNoValue<string>();
if (mdl.Banner.HasValue)
{
if (mdl.Banner.Value == null)
bannerb64 = null;
else
using (var imgtool = new ImageTool(mdl.Banner.Value))
bannerb64 = imgtool.GetBase64();
}
return await this.Discord.ApiClient.ModifyGuildAsync(this.Id, mdl.Name, mdl.Region.IfPresent(e => e.Id),
mdl.VerificationLevel, mdl.DefaultMessageNotifications, mdl.MfaLevel, mdl.ExplicitContentFilter,
mdl.AfkChannel.IfPresent(e => e?.Id), mdl.AfkTimeout, iconb64, mdl.Owner.IfPresent(e => e.Id), splashb64,
mdl.SystemChannel.IfPresent(e => e?.Id), bannerb64,
mdl.Description, mdl.DiscoverySplash, mdl.Features, mdl.PreferredLocale,
mdl.PublicUpdatesChannel.IfPresent(e => e?.Id), mdl.RulesChannel.IfPresent(e => e?.Id),
mdl.SystemChannelFlags, mdl.AuditLogReason).ConfigureAwait(false);
}
/// <summary>
/// Bans a specified member from this guild.
/// </summary>
/// <param name="member">Member to ban.</param>
/// <param name="delete_message_days">How many days to remove messages from.</param>
/// <param name="reason">Reason for audit logs.</param>
/// <returns></returns>
/// <exception cref="UnauthorizedException">Thrown when the client does not have the <see cref="Permissions.BanMembers"/> permission.</exception>
/// <exception cref="NotFoundException">Thrown when the member does not exist.</exception>
/// <exception cref="BadRequestException">Thrown when an invalid parameter was provided.</exception>
/// <exception cref="ServerErrorException">Thrown when Discord is unable to process the request.</exception>
public Task BanMemberAsync(DiscordMember member, int delete_message_days = 0, string reason = null)
=> this.Discord.ApiClient.CreateGuildBanAsync(this.Id, member.Id, delete_message_days, reason);
/// <summary>
/// Bans a specified user by ID. This doesn't require the user to be in this guild.
/// </summary>
/// <param name="user_id">ID of the user to ban.</param>
/// <param name="delete_message_days">How many days to remove messages from.</param>
/// <param name="reason">Reason for audit logs.</param>
/// <returns></returns>
/// <exception cref="UnauthorizedException">Thrown when the client does not have the <see cref="Permissions.BanMembers"/> permission.</exception>
/// <exception cref="NotFoundException">Thrown when the member does not exist.</exception>
/// <exception cref="BadRequestException">Thrown when an invalid parameter was provided.</exception>
/// <exception cref="ServerErrorException">Thrown when Discord is unable to process the request.</exception>
public Task BanMemberAsync(ulong user_id, int delete_message_days = 0, string reason = null)
=> this.Discord.ApiClient.CreateGuildBanAsync(this.Id, user_id, delete_message_days, reason);
/// <summary>
/// Unbans a user from this guild.
/// </summary>
/// <param name="user">User to unban.</param>
/// <param name="reason">Reason for audit logs.</param>
/// <returns></returns>
/// <exception cref="UnauthorizedException">Thrown when the client does not have the <see cref="Permissions.BanMembers"/> permission.</exception>
/// <exception cref="NotFoundException">Thrown when the user does not exist.</exception>
/// <exception cref="BadRequestException">Thrown when an invalid parameter was provided.</exception>
/// <exception cref="ServerErrorException">Thrown when Discord is unable to process the request.</exception>
public Task UnbanMemberAsync(DiscordUser user, string reason = null)
=> this.Discord.ApiClient.RemoveGuildBanAsync(this.Id, user.Id, reason);
/// <summary>
/// Unbans a user by ID.
/// </summary>
/// <param name="user_id">ID of the user to unban.</param>
/// <param name="reason">Reason for audit logs.</param>
/// <returns></returns>
/// <exception cref="UnauthorizedException">Thrown when the client does not have the <see cref="Permissions.BanMembers"/> permission.</exception>
/// <exception cref="NotFoundException">Thrown when the user does not exist.</exception>
/// <exception cref="BadRequestException">Thrown when an invalid parameter was provided.</exception>
/// <exception cref="ServerErrorException">Thrown when Discord is unable to process the request.</exception>
public Task UnbanMemberAsync(ulong user_id, string reason = null)
=> this.Discord.ApiClient.RemoveGuildBanAsync(this.Id, user_id, reason);
/// <summary>
/// Leaves this guild.
/// </summary>
/// <returns></returns>
/// <exception cref="ServerErrorException">Thrown when Discord is unable to process the request.</exception>
public Task LeaveAsync()
=> this.Discord.ApiClient.LeaveGuildAsync(this.Id);
/// <summary>
/// Gets the bans for this guild.
/// </summary>
/// <param name="limit">The number of users to return (up to maximum 1000, default 1000).</param>
/// <param name="before">Consider only users before the given user id.</param>
/// <param name="after">Consider only users after the given user id.</param>
/// <returns>Collection of bans in this guild.</returns>
/// <exception cref="UnauthorizedException">Thrown when the client does not have the <see cref="Permissions.BanMembers"/> permission.</exception>
/// <exception cref="ServerErrorException">Thrown when Discord is unable to process the request.</exception>
public Task<IReadOnlyList<DiscordBan>> GetBansAsync(int? limit = null, ulong? before = null, ulong? after = null)
=> this.Discord.ApiClient.GetGuildBansAsync(this.Id, limit, before, after);
/// <summary>
/// Gets a ban for a specific user.
/// </summary>
/// <param name="userId">The ID of the user to get the ban for.</param>
/// <exception cref="NotFoundException">Thrown when the specified user is not banned.</exception>
/// <returns>The requested ban object.</returns>
public Task<DiscordBan> GetBanAsync(ulong userId)
=> this.Discord.ApiClient.GetGuildBanAsync(this.Id, userId);
/// <summary>
/// Gets a ban for a specific user.
/// </summary>
/// <param name="user">The user to get the ban for.</param>
/// <exception cref="NotFoundException">Thrown when the specified user is not banned.</exception>
/// <returns>The requested ban object.</returns>
public Task<DiscordBan> GetBanAsync(DiscordUser user)
=> this.GetBanAsync(user.Id);
/// <summary>
/// Creates a new text channel in this guild.
/// </summary>
/// <param name="name">Name of the new channel.</param>
/// <param name="parent">Category to put this channel in.</param>
/// <param name="topic">Topic of the channel.</param>
/// <param name="overwrites">Permission overwrites for this channel.</param>
/// <param name="nsfw">Whether the channel is to be flagged as not safe for work.</param>
/// <param name="position">Sorting position of the channel.</param>
/// <param name="reason">Reason for audit logs.</param>
/// <param name="perUserRateLimit">Slow mode timeout for users.</param>
/// <returns>The newly-created channel.</returns>
/// <exception cref="UnauthorizedException">Thrown when the client does not have the <see cref="Permissions.ManageChannels"/> permission.</exception>
/// <exception cref="NotFoundException">Thrown when the guild does not exist.</exception>
/// <exception cref="BadRequestException">Thrown when an invalid parameter was provided.</exception>
/// <exception cref="ServerErrorException">Thrown when Discord is unable to process the request.</exception>
public Task<DiscordChannel> CreateTextChannelAsync(string name, DiscordChannel parent = null, Optional<string> topic = default, IEnumerable<DiscordOverwriteBuilder> overwrites = null, bool? nsfw = null, Optional<int?> perUserRateLimit = default, int? position = null, string reason = null)
=> this.CreateChannelAsync(name, ChannelType.Text, parent, topic, null, null, overwrites, nsfw, perUserRateLimit, null, position, reason);
/// <summary>
/// Creates a new channel category in this guild.
/// </summary>
/// <param name="name">Name of the new category.</param>
/// <param name="overwrites">Permission overwrites for this category.</param>
/// <param name="position">Sorting position of the channel.</param>
/// <param name="reason">Reason for audit logs.</param>
/// <returns>The newly-created channel category.</returns>
/// <exception cref="UnauthorizedException">Thrown when the client does not have the <see cref="Permissions.ManageChannels"/> permission.</exception>
/// <exception cref="NotFoundException">Thrown when the guild does not exist.</exception>
/// <exception cref="BadRequestException">Thrown when an invalid parameter was provided.</exception>
/// <exception cref="ServerErrorException">Thrown when Discord is unable to process the request.</exception>
public Task<DiscordChannel> CreateChannelCategoryAsync(string name, IEnumerable<DiscordOverwriteBuilder> overwrites = null, int? position = null, string reason = null)
=> this.CreateChannelAsync(name, ChannelType.Category, null, Optional.FromNoValue<string>(), null, null, overwrites, null, Optional.FromNoValue<int?>(), null, position, reason);
/// <summary>
/// Creates a new voice channel in this guild.
/// </summary>
/// <param name="name">Name of the new channel.</param>
/// <param name="parent">Category to put this channel in.</param>
/// <param name="bitrate">Bitrate of the channel.</param>
/// <param name="user_limit">Maximum number of users in the channel.</param>
/// <param name="overwrites">Permission overwrites for this channel.</param>
/// <param name="qualityMode">Video quality mode of the channel.</param>
/// <param name="position">Sorting position of the channel.</param>
/// <param name="reason">Reason for audit logs.</param>
/// <returns>The newly-created channel.</returns>
/// <exception cref="UnauthorizedException">Thrown when the client does not have the <see cref="Permissions.ManageChannels"/> permission.</exception>
/// <exception cref="NotFoundException">Thrown when the guild does not exist.</exception>
/// <exception cref="BadRequestException">Thrown when an invalid parameter was provided.</exception>
/// <exception cref="ServerErrorException">Thrown when Discord is unable to process the request.</exception>
public Task<DiscordChannel> CreateVoiceChannelAsync(string name, DiscordChannel parent = null, int? bitrate = null, int? user_limit = null, IEnumerable<DiscordOverwriteBuilder> overwrites = null, VideoQualityMode? qualityMode = null, int? position = null, string reason = null)
=> this.CreateChannelAsync(name, ChannelType.Voice, parent, Optional.FromNoValue<string>(), bitrate, user_limit, overwrites, null, Optional.FromNoValue<int?>(), qualityMode, position, reason);
/// <summary>
/// Creates a new channel in this guild.
/// </summary>
/// <param name="name">Name of the new channel.</param>
/// <param name="type">Type of the new channel.</param>
/// <param name="parent">Category to put this channel in.</param>
/// <param name="topic">Topic of the channel.</param>
/// <param name="bitrate">Bitrate of the channel. Applies to voice only.</param>
/// <param name="userLimit">Maximum number of users in the channel. Applies to voice only.</param>
/// <param name="overwrites">Permission overwrites for this channel.</param>
/// <param name="nsfw">Whether the channel is to be flagged as not safe for work. Applies to text only.</param>
/// <param name="perUserRateLimit">Slow mode timeout for users.</param>
/// <param name="qualityMode">Video quality mode of the channel. Applies to voice only.</param>
/// <param name="position">Sorting position of the channel.</param>
/// <param name="reason">Reason for audit logs.</param>
/// <returns>The newly-created channel.</returns>
/// <exception cref="UnauthorizedException">Thrown when the client does not have the <see cref="Permissions.ManageChannels"/> permission.</exception>
/// <exception cref="NotFoundException">Thrown when the guild does not exist.</exception>
/// <exception cref="BadRequestException">Thrown when an invalid parameter was provided.</exception>
/// <exception cref="ServerErrorException">Thrown when Discord is unable to process the request.</exception>
public Task<DiscordChannel> CreateChannelAsync(string name, ChannelType type, DiscordChannel parent = null, Optional<string> topic = default, int? bitrate = null, int? userLimit = null, IEnumerable<DiscordOverwriteBuilder> overwrites = null, bool? nsfw = null, Optional<int?> perUserRateLimit = default, VideoQualityMode? qualityMode = null, int? position = null, string reason = null)
{
// technically you can create news/store channels but not always
if (type != ChannelType.Text && type != ChannelType.Voice && type != ChannelType.Category && type != ChannelType.News && type != ChannelType.Store && type != ChannelType.Stage)
throw new ArgumentException("Channel type must be text, voice, stage, or category.", nameof(type));
return type == ChannelType.Category && parent != null
? throw new ArgumentException("Cannot specify parent of a channel category.", nameof(parent))
: this.Discord.ApiClient.CreateGuildChannelAsync(this.Id, name, type, parent?.Id, topic, bitrate, userLimit, overwrites, nsfw, perUserRateLimit, qualityMode, position, reason);
}
// this is to commemorate the Great DAPI Channel Massacre of 2017-11-19.
/// <summary>
/// <para>Deletes all channels in this guild.</para>
/// <para>Note that this is irreversible. Use carefully!</para>
/// </summary>
/// <returns></returns>
public Task DeleteAllChannelsAsync()
{
var tasks = this.Channels.Values.Select(xc => xc.DeleteAsync());
return Task.WhenAll(tasks);
}
/// <summary>
/// Estimates the number of users to be pruned.
/// </summary>
/// <param name="days">Minimum number of inactivity days required for users to be pruned. Defaults to 7.</param>
/// <param name="includedRoles">The roles to be included in the prune.</param>
/// <returns>Number of users that will be pruned.</returns>
/// <exception cref="UnauthorizedException">Thrown when the client does not have the <see cref="Permissions.KickMembers"/> permission.</exception>
/// <exception cref="NotFoundException">Thrown when the guild does not exist.</exception>
/// <exception cref="BadRequestException">Thrown when an invalid parameter was provided.</exception>
/// <exception cref="ServerErrorException">Thrown when Discord is unable to process the request.</exception>
public Task<int> GetPruneCountAsync(int days = 7, IEnumerable<DiscordRole> includedRoles = null)
{
if (includedRoles != null)
{
includedRoles = includedRoles.Where(r => r != null);
var roleCount = includedRoles.Count();
var roleArr = includedRoles.ToArray();
var rawRoleIds = new List<ulong>();
for (var i = 0; i < roleCount; i++)
{
if (this._roles.ContainsKey(roleArr[i].Id))
rawRoleIds.Add(roleArr[i].Id);
}
return this.Discord.ApiClient.GetGuildPruneCountAsync(this.Id, days, rawRoleIds);
}
return this.Discord.ApiClient.GetGuildPruneCountAsync(this.Id, days, null);
}
/// <summary>
/// Prunes inactive users from this guild.
/// </summary>
/// <param name="days">Minimum number of inactivity days required for users to be pruned. Defaults to 7.</param>
/// <param name="computePruneCount">Whether to return the prune count after this method completes. This is discouraged for larger guilds.</param>
/// <param name="includedRoles">The roles to be included in the prune.</param>
/// <param name="reason">Reason for audit logs.</param>
/// <returns>Number of users pruned.</returns>
/// <exception cref="UnauthorizedException">Thrown when the client does not have the <see cref="Permissions.ManageChannels"/> permission.</exception>
/// <exception cref="NotFoundException">Thrown when the guild does not exist.</exception>
/// <exception cref="BadRequestException">Thrown when an invalid parameter was provided.</exception>
/// <exception cref="ServerErrorException">Thrown when Discord is unable to process the request.</exception>
public Task<int?> PruneAsync(int days = 7, bool computePruneCount = true, IEnumerable<DiscordRole> includedRoles = null, string reason = null)
{
if (includedRoles != null)
{
includedRoles = includedRoles.Where(r => r != null);
var roleCount = includedRoles.Count();
var roleArr = includedRoles.ToArray();
var rawRoleIds = new List<ulong>();
for (var i = 0; i < roleCount; i++)
{
if (this._roles.ContainsKey(roleArr[i].Id))
rawRoleIds.Add(roleArr[i].Id);
}
return this.Discord.ApiClient.BeginGuildPruneAsync(this.Id, days, computePruneCount, rawRoleIds, reason);
}
return this.Discord.ApiClient.BeginGuildPruneAsync(this.Id, days, computePruneCount, null, reason);
}
/// <summary>
/// Gets integrations attached to this guild.
/// </summary>
/// <returns>Collection of integrations attached to this guild.</returns>
/// <exception cref="UnauthorizedException">Thrown when the client does not have the <see cref="Permissions.ManageGuild"/> permission.</exception>
/// <exception cref="NotFoundException">Thrown when the guild does not exist.</exception>
/// <exception cref="BadRequestException">Thrown when an invalid parameter was provided.</exception>
/// <exception cref="ServerErrorException">Thrown when Discord is unable to process the request.</exception>
public Task<IReadOnlyList<DiscordIntegration>> GetIntegrationsAsync()
=> this.Discord.ApiClient.GetGuildIntegrationsAsync(this.Id);
/// <summary>
/// Attaches an integration from current user to this guild.
/// </summary>
/// <param name="integration">Integration to attach.</param>
/// <returns>The integration after being attached to the guild.</returns>
/// <exception cref="UnauthorizedException">Thrown when the client does not have the <see cref="Permissions.ManageGuild"/> permission.</exception>
/// <exception cref="NotFoundException">Thrown when the guild does not exist.</exception>
/// <exception cref="BadRequestException">Thrown when an invalid parameter was provided.</exception>
/// <exception cref="ServerErrorException">Thrown when Discord is unable to process the request.</exception>
public Task<DiscordIntegration> AttachUserIntegrationAsync(DiscordIntegration integration)
=> this.Discord.ApiClient.CreateGuildIntegrationAsync(this.Id, integration.Type, integration.Id);
/// <summary>
/// Modifies an integration in this guild.
/// </summary>
/// <param name="integration">Integration to modify.</param>
/// <param name="expire_behaviour">Number of days after which the integration expires.</param>
/// <param name="expire_grace_period">Length of grace period which allows for renewing the integration.</param>
/// <param name="enable_emoticons">Whether emotes should be synced from this integration.</param>
/// <returns>The modified integration.</returns>
/// <exception cref="UnauthorizedException">Thrown when the client does not have the <see cref="Permissions.ManageGuild"/> permission.</exception>
/// <exception cref="NotFoundException">Thrown when the guild does not exist.</exception>
/// <exception cref="BadRequestException">Thrown when an invalid parameter was provided.</exception>
/// <exception cref="ServerErrorException">Thrown when Discord is unable to process the request.</exception>
public Task<DiscordIntegration> ModifyIntegrationAsync(DiscordIntegration integration, int expire_behaviour, int expire_grace_period, bool enable_emoticons)
=> this.Discord.ApiClient.ModifyGuildIntegrationAsync(this.Id, integration.Id, expire_behaviour, expire_grace_period, enable_emoticons);
/// <summary>
/// Removes an integration from this guild.
/// </summary>
/// <param name="integration">Integration to remove.</param>
/// <param name="reason">Reason for audit logs.</param>
/// <returns></returns>
/// <exception cref="UnauthorizedException">Thrown when the client does not have the <see cref="Permissions.ManageGuild"/> permission.</exception>
/// <exception cref="NotFoundException">Thrown when the guild does not exist.</exception>
/// <exception cref="BadRequestException">Thrown when an invalid parameter was provided.</exception>
/// <exception cref="ServerErrorException">Thrown when Discord is unable to process the request.</exception>
public Task DeleteIntegrationAsync(DiscordIntegration integration, string reason = null)
=> this.Discord.ApiClient.DeleteGuildIntegrationAsync(this.Id, integration, reason);
/// <summary>
/// Forces re-synchronization of an integration for this guild.
/// </summary>
/// <param name="integration">Integration to synchronize.</param>
/// <returns></returns>
/// <exception cref="UnauthorizedException">Thrown when the client does not have the <see cref="Permissions.ManageGuild"/> permission.</exception>
/// <exception cref="NotFoundException">Thrown when the guild does not exist.</exception>
/// <exception cref="BadRequestException">Thrown when an invalid parameter was provided.</exception>
/// <exception cref="ServerErrorException">Thrown when Discord is unable to process the request.</exception>
public Task SyncIntegrationAsync(DiscordIntegration integration)
=> this.Discord.ApiClient.SyncGuildIntegrationAsync(this.Id, integration.Id);
/// <summary>
/// Gets the voice regions for this guild.
/// </summary>
/// <returns>Voice regions available for this guild.</returns>
/// <exception cref="ServerErrorException">Thrown when Discord is unable to process the request.</exception>
public async Task<IReadOnlyList<DiscordVoiceRegion>> ListVoiceRegionsAsync()
{
var vrs = await this.Discord.ApiClient.GetGuildVoiceRegionsAsync(this.Id).ConfigureAwait(false);
foreach (var xvr in vrs)
this.Discord.InternalVoiceRegions.TryAdd(xvr.Id, xvr);
return vrs;
}
/// <summary>
/// Gets the active and private threads for this guild.
/// </summary>
/// <returns>A list of all the active and private threads the user can access in the server.</returns>
/// <exception cref="ServerErrorException">Thrown when Discord is unable to process the request.</exception>
public async Task<ThreadQueryResult> ListActiveThreadsAsync()
{
var threads = await this.Discord.ApiClient.ListActiveThreadsAsync(this.Id);
// Gateway handles thread cache (if it does it properly
/*foreach (var thread in threads)
this._threads[thread.Id] = thread;*/
return threads;
}
/// <summary>
/// Gets an invite from this guild from an invite code.
/// </summary>
/// <param name="code">The invite code</param>
/// <returns>An invite, or null if not in cache.</returns>
public DiscordInvite GetInvite(string code)
=> this._invites.TryGetValue(code, out var invite) ? invite : null;
/// <summary>
/// Gets all the invites created for all the channels in this guild.
/// </summary>
/// <returns>A collection of invites.</returns>
/// <exception cref="ServerErrorException">Thrown when Discord is unable to process the request.</exception>
public async Task<IReadOnlyList<DiscordInvite>> GetInvitesAsync()
{
var res = await this.Discord.ApiClient.GetGuildInvitesAsync(this.Id).ConfigureAwait(false);
var intents = this.Discord.Configuration.Intents;
if (!intents.HasIntent(DiscordIntents.GuildInvites))
{
for (var i = 0; i < res.Count; i++)
this._invites[res[i].Code] = res[i];
}
return res;
}
/// <summary>
/// Gets the vanity invite for this guild.
/// </summary>
/// <returns>A partial vanity invite.</returns>
/// <exception cref="UnauthorizedException">Thrown when the client does not have the <see cref="Permissions.ManageGuild"/> permission.</exception>
/// <exception cref="ServerErrorException">Thrown when Discord is unable to process the request.</exception>
public Task<DiscordInvite> GetVanityInviteAsync()
=> this.Discord.ApiClient.GetGuildVanityUrlAsync(this.Id);
/// <summary>
/// Gets all the webhooks created for all the channels in this guild.
/// </summary>
/// <returns>A collection of webhooks this guild has.</returns>
/// <exception cref="UnauthorizedException">Thrown when the client does not have the <see cref="Permissions.ManageWebhooks"/> permission.</exception>
/// <exception cref="ServerErrorException">Thrown when Discord is unable to process the request.</exception>
public Task<IReadOnlyList<DiscordWebhook>> GetWebhooksAsync()
=> this.Discord.ApiClient.GetGuildWebhooksAsync(this.Id);
/// <summary>
/// Gets this guild's widget image.
/// </summary>
/// <param name="bannerType">The format of the widget.</param>
/// <returns>The URL of the widget image.</returns>
public string GetWidgetImage(WidgetType bannerType = WidgetType.Shield)
{
var param = bannerType switch
{
WidgetType.Banner1 => "banner1",
WidgetType.Banner2 => "banner2",
WidgetType.Banner3 => "banner3",
WidgetType.Banner4 => "banner4",
_ => "shield",
};
return $"{Net.Endpoints.BASE_URI}{Net.Endpoints.GUILDS}/{this.Id}{Net.Endpoints.WIDGET_PNG}?style={param}";
}
/// <summary>
/// Gets a member of this guild by their user ID.
/// </summary>
/// <param name="userId">ID of the member to get.</param>
/// <param name="updateCache">Whether to always make a REST request and update the member cache.</param>
/// <returns>The requested member.</returns>
/// <exception cref="ServerErrorException">Thrown when Discord is unable to process the request.</exception>
public async Task<DiscordMember> GetMemberAsync(ulong userId, bool updateCache = false)
{
if (!updateCache && this._members != null && this._members.TryGetValue(userId, out var mbr))
return mbr;
mbr = await this.Discord.ApiClient.GetGuildMemberAsync(this.Id, userId).ConfigureAwait(false);
var intents = this.Discord.Configuration.Intents;
if (intents.HasIntent(DiscordIntents.GuildMembers))
{
if (this._members != null)
{
this._members[userId] = mbr;
}
}
return mbr;
}
/// <summary>
/// Retrieves a full list of members from Discord. This method will bypass cache.
/// </summary>
/// <returns>A collection of all members in this guild.</returns>
/// <exception cref="ServerErrorException">Thrown when Discord is unable to process the request.</exception>
public async Task<IReadOnlyCollection<DiscordMember>> GetAllMembersAsync()
{
var recmbr = new HashSet<DiscordMember>();
var recd = 1000;
var last = 0ul;
while (recd > 0)
{
var tms = await this.Discord.ApiClient.ListGuildMembersAsync(this.Id, 1000, last == 0 ? null : (ulong?)last).ConfigureAwait(false);
recd = tms.Count;
foreach (var xtm in tms)
{
var usr = new DiscordUser(xtm.User) { Discord = this.Discord };
usr = this.Discord.UpdateUserCache(usr);
recmbr.Add(new DiscordMember(xtm) { Discord = this.Discord, _guild_id = this.Id });
}
var tm = tms.LastOrDefault();
last = tm?.User.Id ?? 0;
}
return new ReadOnlySet<DiscordMember>(recmbr);
}
/// <summary>
/// Requests that Discord send a list of guild members based on the specified arguments. This method will fire the <see cref="DiscordClient.GuildMembersChunked"/> event.
/// <para>If no arguments aside from <paramref name="presences"/> and <paramref name="nonce"/> are specified, this will request all guild members.</para>
/// </summary>
/// <param name="query">Filters the returned members based on what the username starts with. Either this or <paramref name="userIds"/> must not be null.
/// The <paramref name="limit"/> must also be greater than 0 if this is specified.</param>
/// <param name="limit">Total number of members to request. This must be greater than 0 if <paramref name="query"/> is specified.</param>
/// <param name="presences">Whether to include the <see cref="GuildMembersChunkEventArgs.Presences"/> associated with the fetched members.</param>
/// <param name="userIds">Whether to limit the request to the specified user ids. Either this or <paramref name="query"/> must not be null.</param>
/// <param name="nonce">The unique string to identify the response.</param>
public async Task RequestMembersAsync(string query = "", int limit = 0, bool? presences = null, IEnumerable<ulong> userIds = null, string nonce = null)
{
if (this.Discord is not DiscordClient client)
throw new InvalidOperationException("This operation is only valid for regular Discord clients.");
if (query == null && userIds == null)
throw new ArgumentException("The query and user IDs cannot both be null.");
if (query != null && userIds != null)
query = null;
var grgm = new GatewayRequestGuildMembers(this)
{
Query = query,
Limit = limit >= 0 ? limit : 0,
Presences = presences,
UserIds = userIds,
Nonce = nonce
};
var payload = new GatewayPayload
{
OpCode = GatewayOpCode.RequestGuildMembers,
Data = grgm
};
var payloadStr = JsonConvert.SerializeObject(payload, Formatting.None);
await client.WsSendAsync(payloadStr).ConfigureAwait(false);
}
/// <summary>
/// Gets all the channels this guild has.
/// </summary>
/// <returns>A collection of this guild's channels.</returns>
/// <exception cref="ServerErrorException">Thrown when Discord is unable to process the request.</exception>
public Task<IReadOnlyList<DiscordChannel>> GetChannelsAsync()
=> this.Discord.ApiClient.GetGuildChannelsAsync(this.Id);
/// <summary>
/// Creates a new role in this guild.
/// </summary>
/// <param name="name">Name of the role.</param>
/// <param name="permissions">Permissions for the role.</param>
/// <param name="color">Color for the role.</param>
/// <param name="hoist">Whether the role is to be hoisted.</param>
/// <param name="mentionable">Whether the role is to be mentionable.</param>
/// <param name="reason">Reason for audit logs.</param>
/// <param name="icon">The icon to add to this role</param>
/// <param name="emoji">The emoji to add to this role. Must be unicode.</param>
/// <returns>The newly-created role.</returns>
/// <exception cref="UnauthorizedException">Thrown when the client does not have the <see cref="Permissions.ManageRoles"/> permission.</exception>
/// <exception cref="ServerErrorException">Thrown when Discord is unable to process the request.</exception>
public Task<DiscordRole> CreateRoleAsync(string name = null, Permissions? permissions = null, DiscordColor? color = null, bool? hoist = null, bool? mentionable = null, string reason = null, Stream icon = null, DiscordEmoji emoji = null)
=> this.Discord.ApiClient.CreateGuildRoleAsync(this.Id, name, permissions, color?.Value, hoist, mentionable, reason, icon, emoji?.ToString());
/// <summary>
/// Gets a role from this guild by its ID.
/// </summary>
/// <param name="id">ID of the role to get.</param>
/// <returns>Requested role.</returns>
/// <exception cref="ServerErrorException">Thrown when Discord is unable to process the request.</exception>
public DiscordRole GetRole(ulong id)
=> this._roles.TryGetValue(id, out var role) ? role : null;
/// <summary>
/// Gets a channel from this guild by its ID.
/// </summary>
/// <param name="id">ID of the channel to get.</param>
/// <returns>Requested channel.</returns>
/// <exception cref="ServerErrorException">Thrown when Discord is unable to process the request.</exception>
public DiscordChannel GetChannel(ulong id)
=> (this._channels != null && this._channels.TryGetValue(id, out var channel)) ? channel : null;
/// <summary>
/// Gets audit log entries for this guild.
/// </summary>
/// <param name="limit">Maximum number of entries to fetch.</param>
/// <param name="by_member">Filter by member responsible.</param>
/// <param name="action_type">Filter by action type.</param>
/// <returns>A collection of requested audit log entries.</returns>
/// <exception cref="UnauthorizedException">Thrown when the client does not have the <see cref="Permissions.ViewAuditLog"/> permission.</exception>
/// <exception cref="ServerErrorException">Thrown when Discord is unable to process the request.</exception>
public async Task<IReadOnlyList<DiscordAuditLogEntry>> GetAuditLogsAsync(int? limit = null, DiscordMember by_member = null, AuditLogActionType? action_type = null)
{
var alrs = new List<AuditLog>();
int ac = 1, tc = 0, rmn = 100;
var last = 0ul;
while (ac > 0)
{
rmn = limit != null ? limit.Value - tc : 100;
rmn = Math.Min(100, rmn);
if (rmn <= 0) break;
var alr = await this.Discord.ApiClient.GetAuditLogsAsync(this.Id, rmn, null, last == 0 ? null : (ulong?)last, by_member?.Id, (int?)action_type).ConfigureAwait(false);
ac = alr.Entries.Count();
tc += ac;
if (ac > 0)
{
last = alr.Entries.Last().Id;
alrs.Add(alr);
}
}
var amr = alrs.SelectMany(xa => xa.Users)
.GroupBy(xu => xu.Id)
.Select(xgu => xgu.First());
foreach (var xau in amr)
{
if (this.Discord.UserCache.ContainsKey(xau.Id))
continue;
var xtu = new TransportUser
{
Id = xau.Id,
Username = xau.Username,
Discriminator = xau.Discriminator,
AvatarHash = xau.AvatarHash
};
var xu = new DiscordUser(xtu) { Discord = this.Discord };
xu = this.Discord.UpdateUserCache(xu);
}
var ahr = alrs.SelectMany(xa => xa.Webhooks)
.GroupBy(xh => xh.Id)
.Select(xgh => xgh.First());
var eve = alrs.SelectMany(xr => xr.Events)
.GroupBy(xa => xa.Id)
.Select(xu => xu.First());
var thr = alrs.SelectMany(xr => xr.Threads)
.GroupBy(xa => xa.Id)
.Select(xu => xu.First());
Dictionary<ulong, DiscordWebhook> ahd = null;
if (ahr.Any())
{
var whr = await this.GetWebhooksAsync().ConfigureAwait(false);
var whs = whr.ToDictionary(xh => xh.Id, xh => xh);
var amh = ahr.Select(xah => whs.TryGetValue(xah.Id, out var webhook) ? webhook : new DiscordWebhook { Discord = this.Discord, Name = xah.Name, Id = xah.Id, AvatarHash = xah.AvatarHash, ChannelId = xah.ChannelId, GuildId = xah.GuildId, Token = xah.Token });
ahd = amh.ToDictionary(xh => xh.Id, xh => xh);
}
Dictionary<ulong, DiscordScheduledGuildEvent> events = null;
if (eve.Any())
{
var evb = this._scheduledEvents;
var evf = eve.Select(xa => evb.TryGetValue(xa.Id, out var Event) ? Event : new DiscordScheduledGuildEvent { Discord = this.Discord, Name = xa.Name, Id = xa.Id, ChannelId = xa.ChannelId, GuildId = xa.GuildId, Creator = xa.Creator, Description = xa.Description, EndTime = xa.EndTime, Metadata = xa.Metadata, PrivacyLevel = xa.PrivacyLevel, StartTime = xa.StartTime, Status = xa.Status, Type = xa.Type, UserCount = xa.UserCount});
events = evf.ToDictionary(xb => xb.Id, xb => xb);
}
Dictionary<ulong, DiscordThreadChannel> threads = null;
if (thr.Any())
{
var thb = thr.Select(xr => xr ?? new DiscordThreadChannel{ Discord = this.Discord, Id = xr.Id, Name = xr.Name, GuildId = xr.GuildId});
threads = thb.ToDictionary(xa => xa.Id, xa => xa);
}
var ams = amr.Select(xau => (this._members != null && this._members.TryGetValue(xau.Id, out var member)) ? member : new DiscordMember { Discord = this.Discord, Id = xau.Id, _guild_id = this.Id });
var amd = ams.ToDictionary(xm => xm.Id, xm => xm);
var acs = alrs.SelectMany(xa => xa.Entries).OrderByDescending(xa => xa.Id);
var entries = new List<DiscordAuditLogEntry>();
foreach (var xac in acs)
{
DiscordAuditLogEntry entry = null;
ulong t1, t2;
int t3, t4;
long t5, t6;
bool p1, p2;
switch (xac.ActionType)
{
case AuditLogActionType.GuildUpdate:
entry = new DiscordAuditLogGuildEntry
{
Target = this
};
var entrygld = entry as DiscordAuditLogGuildEntry;
foreach (var xc in xac.Changes)
{
switch (xc.Key.ToLowerInvariant())
{
case "name":
entrygld.NameChange = new PropertyChange<string>
{
Before = xc.OldValueString,
After = xc.NewValueString
};
break;
case "owner_id":
entrygld.OwnerChange = new PropertyChange<DiscordMember>
{
Before = (this._members != null && this._members.TryGetValue(xc.OldValueUlong, out var oldMember)) ? oldMember : await this.GetMemberAsync(xc.OldValueUlong).ConfigureAwait(false),
After = (this._members != null && this._members.TryGetValue(xc.NewValueUlong, out var newMember)) ? newMember : await this.GetMemberAsync(xc.NewValueUlong).ConfigureAwait(false)
};
break;
case "icon_hash":
entrygld.IconChange = new PropertyChange<string>
{
Before = xc.OldValueString != null ? $"https://cdn.discordapp.com/icons/{this.Id}/{xc.OldValueString}.webp" : null,
After = xc.OldValueString != null ? $"https://cdn.discordapp.com/icons/{this.Id}/{xc.NewValueString}.webp" : null
};
break;
case "verification_level":
entrygld.VerificationLevelChange = new PropertyChange<VerificationLevel>
{
Before = (VerificationLevel)(long)xc.OldValue,
After = (VerificationLevel)(long)xc.NewValue
};
break;
case "afk_channel_id":
ulong.TryParse(xc.NewValue as string, NumberStyles.Integer, CultureInfo.InvariantCulture, out t1);
ulong.TryParse(xc.OldValue as string, NumberStyles.Integer, CultureInfo.InvariantCulture, out t2);
entrygld.AfkChannelChange = new PropertyChange<DiscordChannel>
{
Before = this.GetChannel(t1) ?? new DiscordChannel { Id = t1, Discord = this.Discord, GuildId = this.Id },
After = this.GetChannel(t2) ?? new DiscordChannel { Id = t1, Discord = this.Discord, GuildId = this.Id }
};
break;
case "widget_channel_id":
ulong.TryParse(xc.NewValue as string, NumberStyles.Integer, CultureInfo.InvariantCulture, out t1);
ulong.TryParse(xc.OldValue as string, NumberStyles.Integer, CultureInfo.InvariantCulture, out t2);
entrygld.EmbedChannelChange = new PropertyChange<DiscordChannel>
{
Before = this.GetChannel(t1) ?? new DiscordChannel { Id = t1, Discord = this.Discord, GuildId = this.Id },
After = this.GetChannel(t2) ?? new DiscordChannel { Id = t1, Discord = this.Discord, GuildId = this.Id }
};
break;
case "splash_hash":
entrygld.SplashChange = new PropertyChange<string>
{
Before = xc.OldValueString != null ? $"https://cdn.discordapp.com/splashes/{this.Id}/{xc.OldValueString}.webp?size=2048" : null,
After = xc.NewValueString != null ? $"https://cdn.discordapp.com/splashes/{this.Id}/{xc.NewValueString}.webp?size=2048" : null
};
break;
case "default_message_notifications":
entrygld.NotificationSettingsChange = new PropertyChange<DefaultMessageNotifications>
{
Before = (DefaultMessageNotifications)(long)xc.OldValue,
After = (DefaultMessageNotifications)(long)xc.NewValue
};
break;
case "system_channel_id":
ulong.TryParse(xc.NewValue as string, NumberStyles.Integer, CultureInfo.InvariantCulture, out t1);
ulong.TryParse(xc.OldValue as string, NumberStyles.Integer, CultureInfo.InvariantCulture, out t2);
entrygld.SystemChannelChange = new PropertyChange<DiscordChannel>
{
Before = this.GetChannel(t1) ?? new DiscordChannel { Id = t1, Discord = this.Discord, GuildId = this.Id },
After = this.GetChannel(t2) ?? new DiscordChannel { Id = t1, Discord = this.Discord, GuildId = this.Id }
};
break;
case "explicit_content_filter":
entrygld.ExplicitContentFilterChange = new PropertyChange<ExplicitContentFilter>
{
Before = (ExplicitContentFilter)(long)xc.OldValue,
After = (ExplicitContentFilter)(long)xc.NewValue
};
break;
case "mfa_level":
entrygld.MfaLevelChange = new PropertyChange<MfaLevel>
{
Before = (MfaLevel)(long)xc.OldValue,
After = (MfaLevel)(long)xc.NewValue
};
break;
case "region":
entrygld.RegionChange = new PropertyChange<string>
{
Before = xc.OldValueString,
After = xc.NewValueString
};
break;
default:
this.Discord.Logger.LogWarning(LoggerEvents.AuditLog, "Unknown key in guild update: {Key} - this should be reported to library developers", xc.Key);
break;
}
}
break;
case AuditLogActionType.ChannelCreate:
case AuditLogActionType.ChannelDelete:
case AuditLogActionType.ChannelUpdate:
entry = new DiscordAuditLogChannelEntry
{
Target = this.GetChannel(xac.TargetId.Value) ?? new DiscordChannel { Id = xac.TargetId.Value, Discord = this.Discord, GuildId = this.Id }
};
var entrychn = entry as DiscordAuditLogChannelEntry;
foreach (var xc in xac.Changes)
{
switch (xc.Key.ToLowerInvariant())
{
case "name":
entrychn.NameChange = new PropertyChange<string>
{
Before = xc.OldValue != null ? xc.OldValueString : null,
After = xc.NewValue != null ? xc.NewValueString : null
};
break;
case "type":
p1 = ulong.TryParse(xc.NewValue as string, NumberStyles.Integer, CultureInfo.InvariantCulture, out t1);
p2 = ulong.TryParse(xc.OldValue as string, NumberStyles.Integer, CultureInfo.InvariantCulture, out t2);
entrychn.TypeChange = new PropertyChange<ChannelType?>
{
Before = p1 ? (ChannelType?)t1 : null,
After = p2 ? (ChannelType?)t2 : null
};
break;
case "permission_overwrites":
var olds = xc.OldValues?.OfType<JObject>()
?.Select(xjo => xjo.ToDiscordObject<DiscordOverwrite>())
?.Select(xo => { xo.Discord = this.Discord; return xo; });
var news = xc.NewValues?.OfType<JObject>()
?.Select(xjo => xjo.ToDiscordObject<DiscordOverwrite>())
?.Select(xo => { xo.Discord = this.Discord; return xo; });
entrychn.OverwriteChange = new PropertyChange<IReadOnlyList<DiscordOverwrite>>
{
Before = olds != null ? new ReadOnlyCollection<DiscordOverwrite>(new List<DiscordOverwrite>(olds)) : null,
After = news != null ? new ReadOnlyCollection<DiscordOverwrite>(new List<DiscordOverwrite>(news)) : null
};
break;
case "topic":
entrychn.TopicChange = new PropertyChange<string>
{
Before = xc.OldValueString,
After = xc.NewValueString
};
break;
case "nsfw":
entrychn.NsfwChange = new PropertyChange<bool?>
{
Before = (bool?)xc.OldValue,
After = (bool?)xc.NewValue
};
break;
case "bitrate":
entrychn.BitrateChange = new PropertyChange<int?>
{
Before = (int?)(long?)xc.OldValue,
After = (int?)(long?)xc.NewValue
};
break;
case "rate_limit_per_user":
entrychn.PerUserRateLimitChange = new PropertyChange<int?>
{
Before = (int?)(long?)xc.OldValue,
After = (int?)(long?)xc.NewValue
};
break;
default:
this.Discord.Logger.LogWarning(LoggerEvents.AuditLog, "Unknown key in channel update: {Key} - this should be reported to library developers", xc.Key);
break;
}
}
break;
case AuditLogActionType.OverwriteCreate:
case AuditLogActionType.OverwriteDelete:
case AuditLogActionType.OverwriteUpdate:
entry = new DiscordAuditLogOverwriteEntry
{
Target = this.GetChannel(xac.TargetId.Value)?.PermissionOverwrites.FirstOrDefault(xo => xo.Id == xac.Options.Id),
Channel = this.GetChannel(xac.TargetId.Value)
};
var entryovr = entry as DiscordAuditLogOverwriteEntry;
foreach (var xc in xac.Changes)
{
switch (xc.Key.ToLowerInvariant())
{
case "deny":
p1 = ulong.TryParse(xc.OldValue as string, NumberStyles.Integer, CultureInfo.InvariantCulture, out t1);
p2 = ulong.TryParse(xc.OldValue as string, NumberStyles.Integer, CultureInfo.InvariantCulture, out t2);
entryovr.DenyChange = new PropertyChange<Permissions?>
{
Before = p1 ? (Permissions?)t1 : null,
After = p2 ? (Permissions?)t2 : null
};
break;
case "allow":
p1 = ulong.TryParse(xc.OldValue as string, NumberStyles.Integer, CultureInfo.InvariantCulture, out t1);
p2 = ulong.TryParse(xc.OldValue as string, NumberStyles.Integer, CultureInfo.InvariantCulture, out t2);
entryovr.AllowChange = new PropertyChange<Permissions?>
{
Before = p1 ? (Permissions?)t1 : null,
After = p2 ? (Permissions?)t2 : null
};
break;
case "type":
entryovr.TypeChange = new PropertyChange<string>
{
Before = xc.OldValueString,
After = xc.NewValueString
};
break;
case "id":
p1 = ulong.TryParse(xc.OldValue as string, NumberStyles.Integer, CultureInfo.InvariantCulture, out t1);
p2 = ulong.TryParse(xc.NewValue as string, NumberStyles.Integer, CultureInfo.InvariantCulture, out t2);
entryovr.TargetIdChange = new PropertyChange<ulong?>
{
Before = p1 ? (ulong?)t1 : null,
After = p2 ? (ulong?)t2 : null
};
break;
default:
this.Discord.Logger.LogWarning(LoggerEvents.AuditLog, "Unknown key in overwrite update: {Key} - this should be reported to library developers", xc.Key);
break;
}
}
break;
case AuditLogActionType.Kick:
entry = new DiscordAuditLogKickEntry
{
Target = amd.TryGetValue(xac.TargetId.Value, out var kickMember) ? kickMember : new DiscordMember { Id = xac.TargetId.Value, Discord = this.Discord, _guild_id = this.Id }
};
break;
case AuditLogActionType.Prune:
entry = new DiscordAuditLogPruneEntry
{
Days = xac.Options.DeleteMemberDays,
Toll = xac.Options.MembersRemoved
};
break;
case AuditLogActionType.Ban:
case AuditLogActionType.Unban:
entry = new DiscordAuditLogBanEntry
{
Target = amd.TryGetValue(xac.TargetId.Value, out var unbanMember) ? unbanMember : new DiscordMember { Id = xac.TargetId.Value, Discord = this.Discord, _guild_id = this.Id }
};
break;
case AuditLogActionType.MemberUpdate:
case AuditLogActionType.MemberRoleUpdate:
entry = new DiscordAuditLogMemberUpdateEntry
{
Target = amd.TryGetValue(xac.TargetId.Value, out var roleUpdMember) ? roleUpdMember : new DiscordMember { Id = xac.TargetId.Value, Discord = this.Discord, _guild_id = this.Id }
};
var entrymbu = entry as DiscordAuditLogMemberUpdateEntry;
foreach (var xc in xac.Changes)
{
switch (xc.Key.ToLowerInvariant())
{
case "nick":
entrymbu.NicknameChange = new PropertyChange<string>
{
Before = xc.OldValueString,
After = xc.NewValueString
};
break;
case "deaf":
entrymbu.DeafenChange = new PropertyChange<bool?>
{
Before = (bool?)xc.OldValue,
After = (bool?)xc.NewValue
};
break;
case "mute":
entrymbu.MuteChange = new PropertyChange<bool?>
{
Before = (bool?)xc.OldValue,
After = (bool?)xc.NewValue
};
break;
case "communication_disabled_until":
entrymbu.TimeoutChange = new PropertyChange<DateTime?>
{
Before = xc.OldValue != null ? (DateTime)xc.OldValue : null,
After = xc.NewValue != null ? (DateTime)xc.NewValue : null
};
break;
case "$add":
entrymbu.AddedRoles = new ReadOnlyCollection<DiscordRole>(xc.NewValues.Select(xo => (ulong)xo["id"]).Select(this.GetRole).ToList());
break;
case "$remove":
entrymbu.RemovedRoles = new ReadOnlyCollection<DiscordRole>(xc.NewValues.Select(xo => (ulong)xo["id"]).Select(this.GetRole).ToList());
break;
default:
this.Discord.Logger.LogWarning(LoggerEvents.AuditLog, "Unknown key in member update: {Key} - this should be reported to library developers", xc.Key);
break;
}
}
break;
case AuditLogActionType.RoleCreate:
case AuditLogActionType.RoleDelete:
case AuditLogActionType.RoleUpdate:
entry = new DiscordAuditLogRoleUpdateEntry
{
Target = this.GetRole(xac.TargetId.Value) ?? new DiscordRole { Id = xac.TargetId.Value, Discord = this.Discord }
};
var entryrol = entry as DiscordAuditLogRoleUpdateEntry;
foreach (var xc in xac.Changes)
{
switch (xc.Key.ToLowerInvariant())
{
case "name":
entryrol.NameChange = new PropertyChange<string>
{
Before = xc.OldValueString,
After = xc.NewValueString
};
break;
case "color":
p1 = int.TryParse(xc.OldValue as string, NumberStyles.Integer, CultureInfo.InvariantCulture, out t3);
p2 = int.TryParse(xc.NewValue as string, NumberStyles.Integer, CultureInfo.InvariantCulture, out t4);
entryrol.ColorChange = new PropertyChange<int?>
{
Before = p1 ? (int?)t3 : null,
After = p2 ? (int?)t4 : null
};
break;
case "permissions":
entryrol.PermissionChange = new PropertyChange<Permissions?>
{
Before = xc.OldValue != null ? (Permissions?)long.Parse((string)xc.OldValue) : null,
After = xc.NewValue != null ? (Permissions?)long.Parse((string)xc.NewValue) : null
};
break;
case "position":
entryrol.PositionChange = new PropertyChange<int?>
{
Before = xc.OldValue != null ? (int?)(long)xc.OldValue : null,
After = xc.NewValue != null ? (int?)(long)xc.NewValue : null,
};
break;
case "mentionable":
entryrol.MentionableChange = new PropertyChange<bool?>
{
Before = xc.OldValue != null ? (bool?)xc.OldValue : null,
After = xc.NewValue != null ? (bool?)xc.NewValue : null
};
break;
case "hoist":
entryrol.HoistChange = new PropertyChange<bool?>
{
Before = (bool?)xc.OldValue,
After = (bool?)xc.NewValue
};
break;
default:
this.Discord.Logger.LogWarning(LoggerEvents.AuditLog, "Unknown key in role update: {Key} - this should be reported to library developers", xc.Key);
break;
}
}
break;
case AuditLogActionType.InviteCreate:
case AuditLogActionType.InviteDelete:
case AuditLogActionType.InviteUpdate:
entry = new DiscordAuditLogInviteEntry();
var inv = new DiscordInvite
{
Discord = this.Discord,
Guild = new DiscordInviteGuild
{
Discord = this.Discord,
Id = this.Id,
Name = this.Name,
SplashHash = this.SplashHash
}
};
var entryinv = entry as DiscordAuditLogInviteEntry;
foreach (var xc in xac.Changes)
{
switch (xc.Key.ToLowerInvariant())
{
case "max_age":
p1 = int.TryParse(xc.OldValue as string, NumberStyles.Integer, CultureInfo.InvariantCulture, out t3);
p2 = int.TryParse(xc.OldValue as string, NumberStyles.Integer, CultureInfo.InvariantCulture, out t4);
entryinv.MaxAgeChange = new PropertyChange<int?>
{
Before = p1 ? (int?)t3 : null,
After = p2 ? (int?)t4 : null
};
break;
case "code":
inv.Code = xc.OldValueString ?? xc.NewValueString;
entryinv.CodeChange = new PropertyChange<string>
{
Before = xc.OldValueString,
After = xc.NewValueString
};
break;
case "temporary":
entryinv.TemporaryChange = new PropertyChange<bool?>
{
Before = xc.OldValue != null ? (bool?)xc.OldValue : null,
After = xc.NewValue != null ? (bool?)xc.NewValue : null
};
break;
case "inviter_id":
p1 = ulong.TryParse(xc.OldValue as string, NumberStyles.Integer, CultureInfo.InvariantCulture, out t1);
p2 = ulong.TryParse(xc.NewValue as string, NumberStyles.Integer, CultureInfo.InvariantCulture, out t2);
entryinv.InviterChange = new PropertyChange<DiscordMember>
{
Before = amd.TryGetValue(t1, out var propBeforeMember) ? propBeforeMember : new DiscordMember { Id = t1, Discord = this.Discord, _guild_id = this.Id },
After = amd.TryGetValue(t2, out var propAfterMember) ? propAfterMember : new DiscordMember { Id = t1, Discord = this.Discord, _guild_id = this.Id },
};
break;
case "channel_id":
p1 = ulong.TryParse(xc.OldValue as string, NumberStyles.Integer, CultureInfo.InvariantCulture, out t1);
p2 = ulong.TryParse(xc.NewValue as string, NumberStyles.Integer, CultureInfo.InvariantCulture, out t2);
entryinv.ChannelChange = new PropertyChange<DiscordChannel>
{
Before = p1 ? this.GetChannel(t1) ?? new DiscordChannel { Id = t1, Discord = this.Discord, GuildId = this.Id } : null,
After = p2 ? this.GetChannel(t2) ?? new DiscordChannel { Id = t1, Discord = this.Discord, GuildId = this.Id } : null
};
var ch = entryinv.ChannelChange.Before ?? entryinv.ChannelChange.After;
var cht = ch?.Type;
inv.Channel = new DiscordInviteChannel
{
Discord = this.Discord,
Id = p1 ? t1 : t2,
Name = ch?.Name,
Type = cht != null ? cht.Value : ChannelType.Unknown
};
break;
case "uses":
p1 = int.TryParse(xc.OldValue as string, NumberStyles.Integer, CultureInfo.InvariantCulture, out t3);
p2 = int.TryParse(xc.OldValue as string, NumberStyles.Integer, CultureInfo.InvariantCulture, out t4);
entryinv.UsesChange = new PropertyChange<int?>
{
Before = p1 ? (int?)t3 : null,
After = p2 ? (int?)t4 : null
};
break;
case "max_uses":
p1 = int.TryParse(xc.OldValue as string, NumberStyles.Integer, CultureInfo.InvariantCulture, out t3);
p2 = int.TryParse(xc.OldValue as string, NumberStyles.Integer, CultureInfo.InvariantCulture, out t4);
entryinv.MaxUsesChange = new PropertyChange<int?>
{
Before = p1 ? (int?)t3 : null,
After = p2 ? (int?)t4 : null
};
break;
default:
this.Discord.Logger.LogWarning(LoggerEvents.AuditLog, "Unknown key in invite update: {Key} - this should be reported to library developers", xc.Key);
break;
}
}
entryinv.Target = inv;
break;
case AuditLogActionType.WebhookCreate:
case AuditLogActionType.WebhookDelete:
case AuditLogActionType.WebhookUpdate:
entry = new DiscordAuditLogWebhookEntry
{
Target = ahd.TryGetValue(xac.TargetId.Value, out var webhook) ? webhook : new DiscordWebhook { Id = xac.TargetId.Value, Discord = this.Discord }
};
var entrywhk = entry as DiscordAuditLogWebhookEntry;
foreach (var xc in xac.Changes)
{
switch (xc.Key.ToLowerInvariant())
{
case "name":
entrywhk.NameChange = new PropertyChange<string>
{
Before = xc.OldValueString,
After = xc.NewValueString
};
break;
case "channel_id":
p1 = ulong.TryParse(xc.OldValue as string, NumberStyles.Integer, CultureInfo.InvariantCulture, out t1);
p2 = ulong.TryParse(xc.NewValue as string, NumberStyles.Integer, CultureInfo.InvariantCulture, out t2);
entrywhk.ChannelChange = new PropertyChange<DiscordChannel>
{
Before = p1 ? this.GetChannel(t1) ?? new DiscordChannel { Id = t1, Discord = this.Discord, GuildId = this.Id } : null,
After = p2 ? this.GetChannel(t2) ?? new DiscordChannel { Id = t1, Discord = this.Discord, GuildId = this.Id } : null
};
break;
case "type": // ???
p1 = int.TryParse(xc.OldValue as string, NumberStyles.Integer, CultureInfo.InvariantCulture, out t3);
p2 = int.TryParse(xc.NewValue as string, NumberStyles.Integer, CultureInfo.InvariantCulture, out t4);
entrywhk.TypeChange = new PropertyChange<int?>
{
Before = p1 ? (int?)t3 : null,
After = p2 ? (int?)t4 : null
};
break;
case "avatar_hash":
entrywhk.AvatarHashChange = new PropertyChange<string>
{
Before = xc.OldValueString,
After = xc.NewValueString
};
break;
case "application_id": //Why the fuck does discord send this as a string if it's supposed to be a snowflake
entrywhk.ApplicationIdChange = new PropertyChange<ulong?>
{
Before = xc.OldValue != null ? Convert.ToUInt64(xc.OldValueString) : null,
After = xc.NewValue != null ? Convert.ToUInt64(xc.NewValueString) : null
};
break;
default:
this.Discord.Logger.LogWarning(LoggerEvents.AuditLog, "Unknown key in webhook update: {Key} - this should be reported to library developers", xc.Key);
break;
}
}
break;
case AuditLogActionType.EmojiCreate:
case AuditLogActionType.EmojiDelete:
case AuditLogActionType.EmojiUpdate:
entry = new DiscordAuditLogEmojiEntry
{
Target = this._emojis.TryGetValue(xac.TargetId.Value, out var target) ? target : new DiscordEmoji { Id = xac.TargetId.Value, Discord = this.Discord }
};
var entryemo = entry as DiscordAuditLogEmojiEntry;
foreach (var xc in xac.Changes)
{
switch (xc.Key.ToLowerInvariant())
{
case "name":
entryemo.NameChange = new PropertyChange<string>
{
Before = xc.OldValueString,
After = xc.NewValueString
};
break;
default:
this.Discord.Logger.LogWarning(LoggerEvents.AuditLog, "Unknown key in emote update: {Key} - this should be reported to library developers", xc.Key);
break;
}
}
break;
case AuditLogActionType.StickerCreate:
case AuditLogActionType.StickerDelete:
case AuditLogActionType.StickerUpdate:
entry = new DiscordAuditLogStickerEntry
{
Target = this._stickers.TryGetValue(xac.TargetId.Value, out var sticker) ? sticker : new DiscordMessageSticker { Id = xac.TargetId.Value, Discord = this.Discord }
};
var entrysti = entry as DiscordAuditLogStickerEntry;
foreach (var xc in xac.Changes)
{
switch (xc.Key.ToLowerInvariant())
{
case "name":
entrysti.NameChange = new PropertyChange<string>
{
Before = xc.OldValueString,
After = xc.NewValueString
};
break;
case "description":
entrysti.DescriptionChange = new PropertyChange<string>
{
Before = xc.OldValueString,
After = xc.NewValueString
};
break;
case "tags":
entrysti.TagsChange = new PropertyChange<string>
{
Before = xc.OldValueString,
After = xc.NewValueString
};
break;
case "guild_id":
entrysti.GuildIdChange = new PropertyChange<ulong?>
{
Before = ulong.TryParse(xc.OldValueString, out var ogid) ? ogid : null,
After = ulong.TryParse(xc.NewValueString, out var ngid) ? ngid : null
};
break;
case "available":
entrysti.AvailabilityChange = new PropertyChange<bool?>
{
Before = (bool?)xc.OldValue,
After = (bool?)xc.NewValue,
};
break;
case "asset":
entrysti.AssetChange = new PropertyChange<string>
{
Before = xc.OldValueString,
After = xc.NewValueString
};
break;
case "id":
entrysti.IdChange = new PropertyChange<ulong?>
{
Before = ulong.TryParse(xc.OldValueString, out var oid) ? oid : null,
After = ulong.TryParse(xc.NewValueString, out var nid) ? nid : null
};
break;
case "type":
p1 = long.TryParse(xc.OldValue as string, NumberStyles.Integer, CultureInfo.InvariantCulture, out t5);
p2 = long.TryParse(xc.NewValue as string, NumberStyles.Integer, CultureInfo.InvariantCulture, out t6);
entrysti.TypeChange = new PropertyChange<StickerType?>
{
Before = p1 ? (StickerType?)t5 : null,
After = p2 ? (StickerType?)t6 : null
};
break;
case "format_type":
p1 = long.TryParse(xc.OldValue as string, NumberStyles.Integer, CultureInfo.InvariantCulture, out t5);
p2 = long.TryParse(xc.NewValue as string, NumberStyles.Integer, CultureInfo.InvariantCulture, out t6);
entrysti.FormatChange = new PropertyChange<StickerFormat?>
{
Before = p1 ? (StickerFormat?)t5 : null,
After = p2 ? (StickerFormat?)t6 : null
};
break;
default:
this.Discord.Logger.LogWarning(LoggerEvents.AuditLog, "Unknown key in sticker update: {Key} - this should be reported to library developers", xc.Key);
break;
}
}
break;
case AuditLogActionType.MessageDelete:
case AuditLogActionType.MessageBulkDelete:
{
entry = new DiscordAuditLogMessageEntry();
var entrymsg = entry as DiscordAuditLogMessageEntry;
if (xac.Options != null)
{
entrymsg.Channel = this.GetChannel(xac.Options.ChannelId) ?? new DiscordChannel { Id = xac.Options.ChannelId, Discord = this.Discord, GuildId = this.Id };
entrymsg.MessageCount = xac.Options.Count;
}
if (entrymsg.Channel != null)
{
entrymsg.Target = this.Discord is DiscordClient dc
&& dc.MessageCache != null
&& dc.MessageCache.TryGet(xm => xm.Id == xac.TargetId.Value && xm.ChannelId == entrymsg.Channel.Id, out var msg)
? msg
: new DiscordMessage { Discord = this.Discord, Id = xac.TargetId.Value };
}
break;
}
case AuditLogActionType.MessagePin:
case AuditLogActionType.MessageUnpin:
{
entry = new DiscordAuditLogMessagePinEntry();
var entrypin = entry as DiscordAuditLogMessagePinEntry;
if (this.Discord is not DiscordClient dc)
{
break;
}
if (xac.Options != null)
{
DiscordMessage message = default;
dc.MessageCache?.TryGet(x => x.Id == xac.Options.MessageId && x.ChannelId == xac.Options.ChannelId, out message);
entrypin.Channel = this.GetChannel(xac.Options.ChannelId) ?? new DiscordChannel { Id = xac.Options.ChannelId, Discord = this.Discord, GuildId = this.Id };
entrypin.Message = message ?? new DiscordMessage { Id = xac.Options.MessageId, Discord = this.Discord };
}
if (xac.TargetId.HasValue)
{
dc.UserCache.TryGetValue(xac.TargetId.Value, out var user);
entrypin.Target = user ?? new DiscordUser { Id = user.Id, Discord = this.Discord };
}
break;
}
case AuditLogActionType.BotAdd:
{
entry = new DiscordAuditLogBotAddEntry();
if (!(this.Discord is DiscordClient dc && xac.TargetId.HasValue))
{
break;
}
dc.UserCache.TryGetValue(xac.TargetId.Value, out var bot);
(entry as DiscordAuditLogBotAddEntry).TargetBot = bot ?? new DiscordUser { Id = xac.TargetId.Value, Discord = this.Discord };
break;
}
case AuditLogActionType.MemberMove:
entry = new DiscordAuditLogMemberMoveEntry();
if (xac.Options == null)
{
break;
}
var moveentry = entry as DiscordAuditLogMemberMoveEntry;
moveentry.UserCount = xac.Options.Count;
moveentry.Channel = this.GetChannel(xac.Options.ChannelId) ?? new DiscordChannel { Id = xac.Options.ChannelId, Discord = this.Discord, GuildId = this.Id };
break;
case AuditLogActionType.MemberDisconnect:
entry = new DiscordAuditLogMemberDisconnectEntry
{
UserCount = xac.Options?.Count ?? 0
};
break;
case AuditLogActionType.IntegrationCreate:
case AuditLogActionType.IntegrationDelete:
case AuditLogActionType.IntegrationUpdate:
entry = new DiscordAuditLogIntegrationEntry();
var integentry = entry as DiscordAuditLogIntegrationEntry;
foreach (var xc in xac.Changes)
{
switch (xc.Key.ToLowerInvariant())
{
case "enable_emoticons":
integentry.EnableEmoticons = new PropertyChange<bool?>
{
Before = (bool?)xc.OldValue,
After = (bool?)xc.NewValue
};
break;
case "expire_behavior":
integentry.ExpireBehavior = new PropertyChange<int?>
{
Before = (int?)xc.OldValue,
After = (int?)xc.NewValue
};
break;
case "expire_grace_period":
integentry.ExpireBehavior = new PropertyChange<int?>
{
Before = (int?)xc.OldValue,
After = (int?)xc.NewValue
};
break;
default:
this.Discord.Logger.LogWarning(LoggerEvents.AuditLog, "Unknown key in integration update: {Key} - this should be reported to library developers", xc.Key);
break;
}
}
break;
case AuditLogActionType.GuildScheduledEventCreate:
case AuditLogActionType.GuildScheduledEventDelete:
case AuditLogActionType.GuildScheduledEventUpdate:
entry = new DiscordAuditLogGuildScheduledEventEntry()
{
Target = events.TryGetValue(xac.TargetId.Value, out var ta) ? ta : new DiscordScheduledGuildEvent() { Id = xac.TargetId.Value, Discord = this.Discord },
};
var evententry = entry as DiscordAuditLogGuildScheduledEventEntry;
foreach (var xc in xac.Changes)
{
switch (xc.Key.ToLowerInvariant())
{
case "name":
evententry.Name = new PropertyChange<string?>
{
Before = xc.OldValue != null ? xc.OldValueString : null,
After = xc.NewValue != null ? xc.NewValueString : null
};
break;
case "channel_id":
ulong.TryParse(xc.NewValue as string, NumberStyles.Integer, CultureInfo.InvariantCulture, out t1);
ulong.TryParse(xc.OldValue as string, NumberStyles.Integer, CultureInfo.InvariantCulture, out t2);
evententry.Channel = new PropertyChange<DiscordChannel?>
{
Before = this.GetChannel(t2) ?? new DiscordChannel { Id = t2, Discord = this.Discord, GuildId = this.Id },
After = this.GetChannel(t1) ?? new DiscordChannel { Id = t1, Discord = this.Discord, GuildId = this.Id }
};
break;
case "description":
evententry.Description = new PropertyChange<string?>
{
Before = xc.OldValue != null ? xc.OldValueString : null,
After = xc.NewValue != null ? xc.NewValueString : null
};
break;
case "entity_type":
evententry.Type = new PropertyChange<ScheduledGuildEventType?>
{
Before = xc.OldValue != null ? (ScheduledGuildEventType)(long)xc.OldValue : null,
After = xc.NewValue != null ? (ScheduledGuildEventType)(long)xc.NewValue : null
};
break;
case "image_hash":
evententry.ImageHash = new PropertyChange<string?>
{
Before = (string?)xc.OldValue,
After = (string?)xc.NewValue
};
break;
case "location":
evententry.Location = new PropertyChange<string?>
{
Before = (string?)xc.OldValue,
After = (string?)xc.NewValue
};
break;
case "privacy_level":
evententry.PrivacyLevel = new PropertyChange<ScheduledGuildEventPrivacyLevel?>
{
Before = xc.OldValue != null ? (ScheduledGuildEventPrivacyLevel)(long)xc.OldValue : null,
After = xc.NewValue != null ? (ScheduledGuildEventPrivacyLevel)(long)xc.NewValue : null
};
break;
case "status":
evententry.Status = new PropertyChange<ScheduledGuildEventStatus?>
{
Before = xc.OldValue != null ? (ScheduledGuildEventStatus)(long)xc.OldValue : null,
After = xc.NewValue != null ? (ScheduledGuildEventStatus)(long)xc.NewValue : null
};
break;
default:
this.Discord.Logger.LogWarning(LoggerEvents.AuditLog, "Unknown key in scheduled event update: {Key} - this should be reported to library developers", xc.Key);
break;
}
}
break;
case AuditLogActionType.ThreadCreate:
case AuditLogActionType.ThreadDelete:
case AuditLogActionType.ThreadUpdate:
entry = new DiscordAuditLogThreadEventEntry()
{
Target = this.Threads.TryGetValue(xac.TargetId.Value, out var channel) ? channel : new DiscordThreadChannel() { Id = xac.TargetId.Value, Discord = this.Discord },
};
var threadentry = entry as DiscordAuditLogThreadEventEntry;
foreach(var xc in xac.Changes)
{
switch(xc.Key.ToLowerInvariant())
{
case "name":
threadentry.Name = new PropertyChange<string?>
{
Before = xc.OldValue != null ? xc.OldValueString : null,
After = xc.NewValue != null ? xc.NewValueString : null
};
break;
case "type":
threadentry.Type = new PropertyChange<ChannelType?>
{
Before = xc.OldValue != null ? (ChannelType)xc.OldValueLong : null,
After = xc.NewValue != null ? (ChannelType)xc.NewValueLong : null
};
break;
case "archived":
threadentry.Archived = new PropertyChange<bool?>
{
Before = xc.OldValue != null ? xc.OldValueBool : null,
After = xc.NewValue != null ? xc.NewValueBool : null
};
break;
case "auto_archive_duration":
threadentry.AutoArchiveDuration = new PropertyChange<int?>
{
Before = xc.OldValue != null ? (int)xc.OldValueLong : null,
After = xc.NewValue != null ? (int)xc.NewValueLong : null
};
break;
case "invitable":
threadentry.Invitable = new PropertyChange<bool?>
{
Before = xc.OldValue != null ? xc.OldValueBool : null,
After = xc.NewValue != null ? xc.NewValueBool : null
};
break;
case "locked":
threadentry.Locked = new PropertyChange<bool?>
{
Before = xc.OldValue != null ? xc.OldValueBool : null,
After = xc.NewValue != null ? xc.NewValueBool : null
};
break;
case "rate_limit_per_user":
threadentry.PerUserRateLimit = new PropertyChange<int?>
{
Before = xc.OldValue != null ? (int)xc.OldValueLong : null,
After = xc.NewValue != null ? (int)xc.NewValueLong : null
};
break;
default:
this.Discord.Logger.LogWarning(LoggerEvents.AuditLog, "Unknown key in thread update: {Key} - this should be reported to library developers", xc.Key);
break;
}
}
break;
default:
this.Discord.Logger.LogWarning(LoggerEvents.AuditLog, "Unknown audit log action type: {0} - this should be reported to library developers", (int)xac.ActionType);
break;
}
if (entry == null)
continue;
entry.ActionCategory = xac.ActionType switch
{
AuditLogActionType.ChannelCreate or AuditLogActionType.EmojiCreate or AuditLogActionType.InviteCreate or AuditLogActionType.OverwriteCreate or AuditLogActionType.RoleCreate or AuditLogActionType.WebhookCreate or AuditLogActionType.IntegrationCreate or AuditLogActionType.StickerCreate => AuditLogActionCategory.Create,
AuditLogActionType.ChannelDelete or AuditLogActionType.EmojiDelete or AuditLogActionType.InviteDelete or AuditLogActionType.MessageDelete or AuditLogActionType.MessageBulkDelete or AuditLogActionType.OverwriteDelete or AuditLogActionType.RoleDelete or AuditLogActionType.WebhookDelete or AuditLogActionType.IntegrationDelete or AuditLogActionType.StickerDelete => AuditLogActionCategory.Delete,
AuditLogActionType.ChannelUpdate or AuditLogActionType.EmojiUpdate or AuditLogActionType.InviteUpdate or AuditLogActionType.MemberRoleUpdate or AuditLogActionType.MemberUpdate or AuditLogActionType.OverwriteUpdate or AuditLogActionType.RoleUpdate or AuditLogActionType.WebhookUpdate or AuditLogActionType.IntegrationUpdate or AuditLogActionType.StickerUpdate => AuditLogActionCategory.Update,
_ => AuditLogActionCategory.Other,
};
entry.Discord = this.Discord;
entry.ActionType = xac.ActionType;
entry.Id = xac.Id;
entry.Reason = xac.Reason;
entry.UserResponsible = amd[xac.UserId];
entries.Add(entry);
}
return new ReadOnlyCollection<DiscordAuditLogEntry>(entries);
}
/// <summary>
/// Gets all of this guild's custom emojis.
/// </summary>
/// <returns>All of this guild's custom emojis.</returns>
/// <exception cref="ServerErrorException">Thrown when Discord is unable to process the request.</exception>
public Task<IReadOnlyList<DiscordGuildEmoji>> GetEmojisAsync()
=> this.Discord.ApiClient.GetGuildEmojisAsync(this.Id);
/// <summary>
/// Gets this guild's specified custom emoji.
/// </summary>
/// <param name="id">ID of the emoji to get.</param>
/// <returns>The requested custom emoji.</returns>
/// <exception cref="ServerErrorException">Thrown when Discord is unable to process the request.</exception>
public Task<DiscordGuildEmoji> GetEmojiAsync(ulong id)
=> this.Discord.ApiClient.GetGuildEmojiAsync(this.Id, id);
/// <summary>
/// Creates a new custom emoji for this guild.
/// </summary>
/// <param name="name">Name of the new emoji.</param>
/// <param name="image">Image to use as the emoji.</param>
/// <param name="roles">Roles for which the emoji will be available. This works only if your application is whitelisted as integration.</param>
/// <param name="reason">Reason for audit log.</param>
/// <returns>The newly-created emoji.</returns>
/// <exception cref="UnauthorizedException">Thrown when the client does not have the <see cref="Permissions.ManageEmojis"/> permission.</exception>
/// <exception cref="ServerErrorException">Thrown when Discord is unable to process the request.</exception>
public Task<DiscordGuildEmoji> CreateEmojiAsync(string name, Stream image, IEnumerable<DiscordRole> roles = null, string reason = null)
{
if (string.IsNullOrWhiteSpace(name))
throw new ArgumentNullException(nameof(name));
name = name.Trim();
if (name.Length < 2 || name.Length > 50)
throw new ArgumentException("Emoji name needs to be between 2 and 50 characters long.");
if (image == null)
throw new ArgumentNullException(nameof(image));
string image64 = null;
using (var imgtool = new ImageTool(image))
image64 = imgtool.GetBase64();
return this.Discord.ApiClient.CreateGuildEmojiAsync(this.Id, name, image64, roles?.Select(xr => xr.Id), reason);
}
/// <summary>
/// Modifies a this guild's custom emoji.
/// </summary>
/// <param name="emoji">Emoji to modify.</param>
/// <param name="name">New name for the emoji.</param>
/// <param name="roles">Roles for which the emoji will be available. This works only if your application is whitelisted as integration.</param>
/// <param name="reason">Reason for audit log.</param>
/// <returns>The modified emoji.</returns>
/// <exception cref="UnauthorizedException">Thrown when the client does not have the <see cref="Permissions.ManageEmojis"/> permission.</exception>
/// <exception cref="ServerErrorException">Thrown when Discord is unable to process the request.</exception>
public Task<DiscordGuildEmoji> ModifyEmojiAsync(DiscordGuildEmoji emoji, string name, IEnumerable<DiscordRole> roles = null, string reason = null)
{
if (emoji == null)
throw new ArgumentNullException(nameof(emoji));
if (emoji.Guild.Id != this.Id)
throw new ArgumentException("This emoji does not belong to this guild.");
if (string.IsNullOrWhiteSpace(name))
throw new ArgumentNullException(nameof(name));
name = name.Trim();
return name.Length < 2 || name.Length > 50
? throw new ArgumentException("Emoji name needs to be between 2 and 50 characters long.")
: this.Discord.ApiClient.ModifyGuildEmojiAsync(this.Id, emoji.Id, name, roles?.Select(xr => xr.Id), reason);
}
/// <summary>
/// Deletes this guild's custom emoji.
/// </summary>
/// <param name="emoji">Emoji to delete.</param>
/// <param name="reason">Reason for audit log.</param>
/// <returns></returns>
/// <exception cref="UnauthorizedException">Thrown when the client does not have the <see cref="Permissions.ManageEmojis"/> permission.</exception>
/// <exception cref="ServerErrorException">Thrown when Discord is unable to process the request.</exception>
public Task DeleteEmojiAsync(DiscordGuildEmoji emoji, string reason = null)
{
if (emoji == null)
throw new ArgumentNullException(nameof(emoji));
return emoji.Guild.Id != this.Id
? throw new ArgumentException("This emoji does not belong to this guild.")
: this.Discord.ApiClient.DeleteGuildEmojiAsync(this.Id, emoji.Id, reason);
}
/// <summary>
/// <para>Gets the default channel for this guild.</para>
/// <para>Default channel is the first channel current member can see.</para>
/// </summary>
/// <returns>This member's default guild.</returns>
/// <exception cref="ServerErrorException">Thrown when Discord is unable to process the request.</exception>
public DiscordChannel GetDefaultChannel()
{
return this._channels?.Values.Where(xc => xc.Type == ChannelType.Text)
.OrderBy(xc => xc.Position)
.FirstOrDefault(xc => (xc.PermissionsFor(this.CurrentMember) & DSharpPlus.Permissions.AccessChannels) == DSharpPlus.Permissions.AccessChannels);
}
/// <summary>
/// Gets the guild's widget
/// </summary>
/// <returns>The guild's widget</returns>
public Task<DiscordWidget> GetWidgetAsync()
=> this.Discord.ApiClient.GetGuildWidgetAsync(this.Id);
/// <summary>
/// Gets the guild's widget settings
/// </summary>
/// <returns>The guild's widget settings</returns>
public Task<DiscordWidgetSettings> GetWidgetSettingsAsync()
=> this.Discord.ApiClient.GetGuildWidgetSettingsAsync(this.Id);
/// <summary>
/// Modifies the guild's widget settings
/// </summary>
/// <param name="isEnabled">If the widget is enabled or not</param>
/// <param name="channel">Widget channel</param>
/// <param name="reason">Reason the widget settings were modified</param>
/// <returns>The newly modified widget settings</returns>
public Task<DiscordWidgetSettings> ModifyWidgetSettingsAsync(bool? isEnabled = null, DiscordChannel channel = null, string reason = null)
=> this.Discord.ApiClient.ModifyGuildWidgetSettingsAsync(this.Id, isEnabled, channel?.Id, reason);
/// <summary>
/// Gets all of this guild's templates.
/// </summary>
/// <returns>All of the guild's templates.</returns>
/// <exception cref="UnauthorizedException">Throws when the client does not have the <see cref="Permissions.ManageGuild"/> permission.</exception>
/// <exception cref="ServerErrorException">Thrown when Discord is unable to process the request.</exception>
public Task<IReadOnlyList<DiscordGuildTemplate>> GetTemplatesAsync()
=> this.Discord.ApiClient.GetGuildTemplatesAsync(this.Id);
/// <summary>
/// Creates a guild template.
/// </summary>
/// <param name="name">Name of the template.</param>
/// <param name="description">Description of the template.</param>
/// <returns>The template created.</returns>
/// <exception cref="BadRequestException">Throws when a template already exists for the guild or a null parameter is provided for the name.</exception>
/// <exception cref="UnauthorizedException">Throws when the client does not have the <see cref="Permissions.ManageGuild"/> permission.</exception>
/// <exception cref="ServerErrorException">Thrown when Discord is unable to process the request.</exception>
public Task<DiscordGuildTemplate> CreateTemplateAsync(string name, string description = null)
=> this.Discord.ApiClient.CreateGuildTemplateAsync(this.Id, name, description);
/// <summary>
/// Syncs the template to the current guild's state.
/// </summary>
/// <param name="code">The code of the template to sync.</param>
/// <returns>The template synced.</returns>
/// <exception cref="NotFoundException">Throws when the template for the code cannot be found</exception>
/// <exception cref="UnauthorizedException">Throws when the client does not have the <see cref="Permissions.ManageGuild"/> permission.</exception>
/// <exception cref="ServerErrorException">Thrown when Discord is unable to process the request.</exception>
public Task<DiscordGuildTemplate> SyncTemplateAsync(string code)
=> this.Discord.ApiClient.SyncGuildTemplateAsync(this.Id, code);
/// <summary>
/// Modifies the template's metadata.
/// </summary>
/// <param name="code">The template's code.</param>
/// <param name="name">Name of the template.</param>
/// <param name="description">Description of the template.</param>
/// <returns>The template modified.</returns>
/// <exception cref="NotFoundException">Throws when the template for the code cannot be found</exception>
/// <exception cref="UnauthorizedException">Throws when the client does not have the <see cref="Permissions.ManageGuild"/> permission.</exception>
/// <exception cref="ServerErrorException">Thrown when Discord is unable to process the request.</exception>
public Task<DiscordGuildTemplate> ModifyTemplateAsync(string code, string name = null, string description = null)
=> this.Discord.ApiClient.ModifyGuildTemplateAsync(this.Id, code, name, description);
/// <summary>
/// Deletes the template.
/// </summary>
/// <param name="code">The code of the template to delete.</param>
/// <returns>The deleted template.</returns>
/// <exception cref="NotFoundException">Throws when the template for the code cannot be found</exception>
/// <exception cref="UnauthorizedException">Throws when the client does not have the <see cref="Permissions.ManageGuild"/> permission.</exception>
/// <exception cref="ServerErrorException">Thrown when Discord is unable to process the request.</exception>
public Task<DiscordGuildTemplate> DeleteTemplateAsync(string code)
=> this.Discord.ApiClient.DeleteGuildTemplateAsync(this.Id, code);
/// <summary>
/// Gets this guild's membership screening form.
/// </summary>
/// <returns>This guild's membership screening form.</returns>
/// <exception cref="ServerErrorException">Thrown when Discord is unable to process the request.</exception>
public Task<DiscordGuildMembershipScreening> GetMembershipScreeningFormAsync()
=> this.Discord.ApiClient.GetGuildMembershipScreeningFormAsync(this.Id);
/// <summary>
/// Modifies this guild's membership screening form.
/// </summary>
/// <param name="action">Action to perform</param>
/// <returns>The modified screening form.</returns>
/// <exception cref="UnauthorizedException">Thrown when the client doesn't have the <see cref="Permissions.ManageGuild"/> permission, or community is not enabled on this guild.</exception>
/// <exception cref="ServerErrorException">Thrown when Discord is unable to process the request.</exception>
public Task<DiscordGuildMembershipScreening> ModifyMembershipScreeningFormAsync(Action<MembershipScreeningEditModel> action)
{
var mdl = new MembershipScreeningEditModel();
action(mdl);
return this.Discord.ApiClient.ModifyGuildMembershipScreeningFormAsync(this.Id, mdl.Enabled, mdl.Fields, mdl.Description);
}
/// <summary>
/// Gets a list of stickers from this guild.
/// </summary>
/// <returns></returns>
public Task<IReadOnlyList<DiscordMessageSticker>> GetStickersAsync()
=> this.Discord.ApiClient.GetGuildStickersAsync(this.Id);
/// <summary>
/// Gets a sticker from this guild.
/// </summary>
/// <param name="stickerId">The id of the sticker.</param>
/// <returns></returns>
public Task<DiscordMessageSticker> GetStickerAsync(ulong stickerId)
=> this.Discord.ApiClient.GetGuildStickerAsync(this.Id, stickerId);
/// <summary>
/// Creates a sticker in this guild. Lottie stickers can only be created on verified and/or partnered servers.
/// </summary>
/// <param name="name">The name of the sticker.</param>
/// <param name="description">The description of the sticker.</param>
/// <param name="tags">The tags of the sticker. This must be a unicode emoji.</param>
/// <param name="imageContents">The image content of the sticker.</param>
/// <param name="format">The image format of the sticker.</param>
/// <param name="reason">The reason this sticker is being created.</param>
public Task<DiscordMessageSticker> CreateStickerAsync(string name, string description, string tags, Stream imageContents, StickerFormat format, string reason = null)
{
string contentType = null, extension = null;
if (format == StickerFormat.PNG || format == StickerFormat.APNG)
{
contentType = "image/png";
extension = "png";
}
else
{
if (!this.Features.Contains("PARTNERED") && !this.Features.Contains("VERIFIED"))
throw new InvalidOperationException("Lottie stickers can only be created on partnered or verified guilds.");
contentType = "application/json";
extension = "json";
}
return this.Discord.ApiClient.CreateGuildStickerAsync(this.Id, name, description ?? string.Empty, tags, new DiscordMessageFile(null, imageContents, null, extension, contentType), reason);
}
/// <summary>
/// Modifies a sticker in this guild.
/// </summary>
/// <param name="stickerId">The id of the sticker.</param>
/// <param name="action">Action to perform.</param>
/// <param name="reason">Reason for audit log.</param>
public Task<DiscordMessageSticker> ModifyStickerAsync(ulong stickerId, Action<StickerEditModel> action, string reason = null)
{
var mdl = new StickerEditModel();
action(mdl);
return this.Discord.ApiClient.ModifyStickerAsync(this.Id, stickerId, mdl.Name, mdl.Description, mdl.Tags, reason ?? mdl.AuditLogReason);
}
/// <summary>
/// Modifies a sticker in this guild.
/// </summary>
/// <param name="sticker">Sticker to modify.</param>
/// <param name="action">Action to perform.</param>
/// <param name="reason">Reason for audit log.</param>
public Task<DiscordMessageSticker> ModifyStickerAsync(DiscordMessageSticker sticker, Action<StickerEditModel> action, string reason = null)
{
var mdl = new StickerEditModel();
action(mdl);
return this.Discord.ApiClient.ModifyStickerAsync(this.Id, sticker.Id, mdl.Name, mdl.Description, mdl.Tags, reason ?? mdl.AuditLogReason);
}
/// <summary>
/// Deletes a sticker in this guild.
/// </summary>
/// <param name="stickerId">The id of the sticker.</param>
/// <param name="reason">Reason for audit log.</param>
public Task DeleteStickerAsync(ulong stickerId, string reason = null)
=> this.Discord.ApiClient.DeleteStickerAsync(this.Id, stickerId, reason);
/// <summary>
/// Deletes a sticker in this guild.
/// </summary>
/// <param name="sticker">Sticker to delete.</param>
/// <param name="reason">Reason for audit log.</param>
public Task DeleteStickerAsync(DiscordMessageSticker sticker, string reason = null)
=> this.Discord.ApiClient.DeleteStickerAsync(this.Id, sticker.Id, reason);
/// <summary>
/// Gets all the application commands in this guild.
/// </summary>
/// <returns>A list of application commands in this guild.</returns>
public Task<IReadOnlyList<DiscordApplicationCommand>> GetApplicationCommandsAsync() =>
this.Discord.ApiClient.GetGuildApplicationCommandsAsync(this.Discord.CurrentApplication.Id, this.Id);
/// <summary>
/// Overwrites the existing application commands in this guild. New commands are automatically created and missing commands are automatically delete
/// </summary>
/// <param name="commands">The list of commands to overwrite with.</param>
/// <returns>The list of guild commands</returns>
public Task<IReadOnlyList<DiscordApplicationCommand>> BulkOverwriteApplicationCommandsAsync(IEnumerable<DiscordApplicationCommand> commands) =>
this.Discord.ApiClient.BulkOverwriteGuildApplicationCommandsAsync(this.Discord.CurrentApplication.Id, this.Id, commands);
/// <summary>
/// Creates or overwrites a application command in this guild.
/// </summary>
/// <param name="command">The command to create.</param>
/// <returns>The created command.</returns>
public Task<DiscordApplicationCommand> CreateApplicationCommandAsync(DiscordApplicationCommand command) =>
this.Discord.ApiClient.CreateGuildApplicationCommandAsync(this.Discord.CurrentApplication.Id, this.Id, command);
/// <summary>
/// Edits a application command in this guild.
/// </summary>
/// <param name="commandId">The id of the command to edit.</param>
/// <param name="action">Action to perform.</param>
/// <returns>The edit command.</returns>
public async Task<DiscordApplicationCommand> EditApplicationCommandAsync(ulong commandId, Action<ApplicationCommandEditModel> action)
{
var mdl = new ApplicationCommandEditModel();
action(mdl);
return await this.Discord.ApiClient.EditGuildApplicationCommandAsync(this.Discord.CurrentApplication.Id, this.Id, commandId, mdl.Name, mdl.Description, mdl.Options, mdl.DefaultPermission, default, default, mdl.AllowDMUsage, mdl.DefaultMemberPermissions).ConfigureAwait(false);
}
/// <summary>
/// Gets this guild's welcome screen.
/// </summary>
/// <returns>This guild's welcome screen object.</returns>
/// <exception cref="ServerErrorException">Thrown when Discord is unable to process the request.</exception>
public Task<DiscordGuildWelcomeScreen> GetWelcomeScreenAsync() =>
this.Discord.ApiClient.GetGuildWelcomeScreenAsync(this.Id);
/// <summary>
/// Modifies this guild's welcome screen.
/// </summary>
/// <param name="action">Action to perform.</param>
/// <param name="reason">Reason for audit log.</param>
/// <returns>The modified welcome screen.</returns>
/// <exception cref="UnauthorizedException">Thrown when the client doesn't have the <see cref="Permissions.ManageGuild"/> permission, or community is not enabled on this guild.</exception>
/// <exception cref="ServerErrorException">Thrown when Discord is unable to process the request.</exception>
public async Task<DiscordGuildWelcomeScreen> ModifyWelcomeScreenAsync(Action<WelcomeScreenEditModel> action, string reason = null)
{
var mdl = new WelcomeScreenEditModel();
action(mdl);
return await this.Discord.ApiClient.ModifyGuildWelcomeScreenAsync(this.Id, mdl.Enabled, mdl.WelcomeChannels, mdl.Description, reason).ConfigureAwait(false);
}
/// <summary>
/// Gets all application command permissions in this guild.
/// </summary>
/// <returns>A list of permissions.</returns>
public Task<IReadOnlyList<DiscordGuildApplicationCommandPermissions>> GetApplicationCommandsPermissionsAsync()
=> this.Discord.ApiClient.GetGuildApplicationCommandPermissionsAsync(this.Discord.CurrentApplication.Id, this.Id);
/// <summary>
/// Gets permissions for a application command in this guild.
/// </summary>
/// <param name="command">The command to get them for.</param>
/// <returns>The permissions.</returns>
public Task<DiscordGuildApplicationCommandPermissions> GetApplicationCommandPermissionsAsync(DiscordApplicationCommand command)
=> this.Discord.ApiClient.GetApplicationCommandPermissionsAsync(this.Discord.CurrentApplication.Id, this.Id, command.Id);
/// <summary>
/// Edits permissions for a application command in this guild.
/// </summary>
/// <param name="command">The command to edit permissions for.</param>
/// <param name="permissions">The list of permissions to use.</param>
/// <returns>The edited permissions.</returns>
public Task<DiscordGuildApplicationCommandPermissions> EditApplicationCommandPermissionsAsync(DiscordApplicationCommand command, IEnumerable<DiscordApplicationCommandPermission> permissions)
=> this.Discord.ApiClient.EditApplicationCommandPermissionsAsync(this.Discord.CurrentApplication.Id, this.Id, command.Id, permissions);
/// <summary>
/// Batch edits permissions for a application command in this guild.
/// </summary>
/// <param name="permissions">The list of permissions to use.</param>
/// <returns>A list of edited permissions.</returns>
public Task<IReadOnlyList<DiscordGuildApplicationCommandPermissions>> BatchEditApplicationCommandPermissionsAsync(IEnumerable<DiscordGuildApplicationCommandPermissions> permissions)
=> this.Discord.ApiClient.BatchEditApplicationCommandPermissionsAsync(this.Discord.CurrentApplication.Id, this.Id, permissions);
#endregion
/// <summary>
/// Returns a string representation of this guild.
/// </summary>
/// <returns>String representation of this guild.</returns>
public override string ToString() => $"Guild {this.Id}; {this.Name}";
/// <summary>
/// Checks whether this <see cref="DiscordGuild"/> is equal to another object.
/// </summary>
/// <param name="obj">Object to compare to.</param>
/// <returns>Whether the object is equal to this <see cref="DiscordGuild"/>.</returns>
public override bool Equals(object obj) => this.Equals(obj as DiscordGuild);
/// <summary>
/// Checks whether this <see cref="DiscordGuild"/> is equal to another <see cref="DiscordGuild"/>.
/// </summary>
/// <param name="e"><see cref="DiscordGuild"/> to compare to.</param>
/// <returns>Whether the <see cref="DiscordGuild"/> is equal to this <see cref="DiscordGuild"/>.</returns>
public bool Equals(DiscordGuild e)
{
if (e is null)
return false;
return ReferenceEquals(this, e) || this.Id == e.Id;
}
/// <summary>
/// Gets the hash code for this <see cref="DiscordGuild"/>.
/// </summary>
/// <returns>The hash code for this <see cref="DiscordGuild"/>.</returns>
public override int GetHashCode() => this.Id.GetHashCode();
/// <summary>
/// Gets whether the two <see cref="DiscordGuild"/> objects are equal.
/// </summary>
/// <param name="e1">First member to compare.</param>
/// <param name="e2">Second member to compare.</param>
/// <returns>Whether the two members are equal.</returns>
public static bool operator ==(DiscordGuild e1, DiscordGuild e2)
{
var o1 = e1 as object;
var o2 = e2 as object;
if ((o1 == null && o2 != null) || (o1 != null && o2 == null))
return false;
return (o1 == null && o2 == null) || e1.Id == e2.Id;
}
/// <summary>
/// Gets whether the two <see cref="DiscordGuild"/> objects are not equal.
/// </summary>
/// <param name="e1">First member to compare.</param>
/// <param name="e2">Second member to compare.</param>
/// <returns>Whether the two members are not equal.</returns>
public static bool operator !=(DiscordGuild e1, DiscordGuild e2)
=> !(e1 == e2);
}
/// <summary>
/// Represents guild verification level.
/// </summary>
public enum VerificationLevel : int
{
/// <summary>
/// No verification. Anyone can join and chat right away.
/// </summary>
None = 0,
/// <summary>
/// Low verification level. Users are required to have a verified email attached to their account in order to be able to chat.
/// </summary>
Low = 1,
/// <summary>
/// Medium verification level. Users are required to have a verified email attached to their account, and account age need to be at least 5 minutes in order to be able to chat.
/// </summary>
Medium = 2,
/// <summary>
/// (╯°□°)╯︵ ┻━┻ verification level. Users are required to have a verified email attached to their account, account age need to be at least 5 minutes, and they need to be in the server for at least 10 minutes in order to be able to chat.
/// </summary>
High = 3,
/// <summary>
/// ┻━┻ ミヽ(ಠ益ಠ)ノ彡┻━┻ verification level. Users are required to have a verified phone number attached to their account.
/// </summary>
Highest = 4
}
/// <summary>
/// Represents default notification level for a guild.
/// </summary>
public enum DefaultMessageNotifications : int
{
/// <summary>
/// All messages will trigger push notifications.
/// </summary>
AllMessages = 0,
/// <summary>
/// Only messages that mention the user (or a role he's in) will trigger push notifications.
/// </summary>
MentionsOnly = 1
}
/// <summary>
/// Represents multi-factor authentication level required by a guild to use administrator functionality.
/// </summary>
public enum MfaLevel : int
{
/// <summary>
/// Multi-factor authentication is not required to use administrator functionality.
/// </summary>
Disabled = 0,
/// <summary>
/// Multi-factor authentication is required to use administrator functionality.
/// </summary>
Enabled = 1
}
/// <summary>
/// Represents the value of explicit content filter in a guild.
/// </summary>
public enum ExplicitContentFilter : int
{
/// <summary>
/// Explicit content filter is disabled.
/// </summary>
Disabled = 0,
/// <summary>
/// Only messages from members without any roles are scanned.
/// </summary>
MembersWithoutRoles = 1,
/// <summary>
/// Messages from all members are scanned.
/// </summary>
AllMembers = 2
}
/// <summary>
/// Represents the formats for a guild widget.
/// </summary>
public enum WidgetType : int
{
/// <summary>
/// The widget is represented in shield format.
/// <para>This is the default widget type.</para>
/// </summary>
Shield = 0,
/// <summary>
/// The widget is represented as the first banner type.
/// </summary>
Banner1 = 1,
/// <summary>
/// The widget is represented as the second banner type.
/// </summary>
Banner2 = 2,
/// <summary>
/// The widget is represented as the third banner type.
/// </summary>
Banner3 = 3,
/// <summary>
/// The widget is represented in the fourth banner type.
/// </summary>
Banner4 = 4
}
}
| 54.350792 | 443 | 0.54761 | [
"MIT"
] | F1restar4/DSharpPlus | DSharpPlus/Entities/Guild/DiscordGuild.cs | 168,151 | C# |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Text;
namespace Bb.Sdk.Decompiler.IlParser
{
public static class ImmutableStack
{
// Methods
public static ImmutableStack<T> Create<T>()
{
return ImmutableStack<T>.Empty;
}
public static ImmutableStack<T> Create<T>(this T item)
{
return ImmutableStack<T>.Empty.Push(item);
}
public static ImmutableStack<T> Create<T>(params T[] items)
{
Debug.Assert(items != null, "items");
ImmutableStack<T> empty = ImmutableStack<T>.Empty;
foreach (T local in items)
{
empty = empty.Push(local);
}
return empty;
}
public static ImmutableStack<T> CreateRange<T>(this IEnumerable<T> items)
{
Debug.Assert(items != null, "items");
ImmutableStack<T> empty = ImmutableStack<T>.Empty;
foreach (T local in items)
{
empty = empty.Push(local);
}
return empty;
}
public static ImmutableStack<T> Pop<T>(this ImmutableStack<T> stack, out T value)
{
Debug.Assert(stack != null, "stack");
value = stack.Peek();
return stack.Pop();
}
}
//[DebuggerDisplay("IsEmpty = {IsEmpty}; Top = {_head}"), DebuggerTypeProxy((Type)typeof(ImmutableStackDebuggerProxy<>))]
public sealed class ImmutableStack<T> : /*IImmutableStack<T>,*/ IEnumerable<T>, IEnumerable
{
// Fields
private readonly T _head;
private readonly ImmutableStack<T> _tail;
private static readonly ImmutableStack<T> s_EmptyField;
// Methods
static ImmutableStack()
{
ImmutableStack<T>.s_EmptyField = new ImmutableStack<T>();
}
private ImmutableStack()
{
}
private ImmutableStack(T head, ImmutableStack<T> tail)
{
Debug.Assert(tail != null, "tail");
this._head = head;
this._tail = tail;
}
public ImmutableStack<T> Clear()
{
return ImmutableStack<T>.Empty;
}
public Enumerator<T> GetEnumerator()
{
return new Enumerator<T>((ImmutableStack<T>)this);
}
public T Peek()
{
if (this.IsEmpty)
{
throw new InvalidOperationException("InvalidEmptyOperation=This operation does not apply to an empty instance.");
}
return this._head;
}
public ImmutableStack<T> Pop()
{
if (this.IsEmpty)
{
throw new InvalidOperationException("InvalidEmptyOperation=This operation does not apply to an empty instance.");
}
return this._tail;
}
public ImmutableStack<T> Pop(out T value)
{
value = this.Peek();
return this.Pop();
}
public ImmutableStack<T> Push(T value)
{
return new ImmutableStack<T>(value, (ImmutableStack<T>)this);
}
internal ImmutableStack<T> Reverse()
{
ImmutableStack<T> stack = this.Clear();
for (ImmutableStack<T> stack2 = (ImmutableStack<T>)this; !stack2.IsEmpty; stack2 = stack2.Pop())
{
stack = stack.Push(stack2.Peek());
}
return stack;
}
IEnumerator<T> IEnumerable<T>.GetEnumerator()
{
return new EnumeratorObject<T>((ImmutableStack<T>)this);
}
IEnumerator IEnumerable.GetEnumerator()
{
return new EnumeratorObject<T>((ImmutableStack<T>)this);
}
// Properties
public static ImmutableStack<T> Empty
{
get
{
return ImmutableStack<T>.s_EmptyField;
}
}
public bool IsEmpty
{
get
{
return (this._tail == null);
}
}
// Nested Types
//[StructLayout(LayoutKind.Sequential), EditorBrowsable((EditorBrowsableState)EditorBrowsableState.Advanced)]
public struct Enumerator<T>
{
private readonly ImmutableStack<T> _originalStack;
private ImmutableStack<T> _remainingStack;
internal Enumerator(ImmutableStack<T> stack)
{
Debug.Assert(stack != null, "stack");
this._originalStack = stack;
this._remainingStack = null;
}
public T Current
{
get
{
if ((this._remainingStack == null) || this._remainingStack.IsEmpty)
throw new InvalidOperationException();
return this._remainingStack.Peek();
}
}
public bool MoveNext()
{
if (this._remainingStack == null)
this._remainingStack = this._originalStack;
else if (!this._remainingStack.IsEmpty)
this._remainingStack = this._remainingStack.Pop();
return !this._remainingStack.IsEmpty;
}
}
private class EnumeratorObject<T> : IEnumerator<T>, IEnumerator, IDisposable
{
// Fields
private bool _disposed;
private readonly ImmutableStack<T> _originalStack;
private ImmutableStack<T> _remainingStack;
// Methods
internal EnumeratorObject(ImmutableStack<T> stack)
{
Debug.Assert(stack != null, "stack");
this._originalStack = stack;
}
public void Dispose()
{
this._disposed = true;
}
public bool MoveNext()
{
this.ThrowIfDisposed();
if (this._remainingStack == null)
this._remainingStack = this._originalStack;
else if (!this._remainingStack.IsEmpty)
this._remainingStack = this._remainingStack.Pop();
return !this._remainingStack.IsEmpty;
}
public void Reset()
{
this.ThrowIfDisposed();
this._remainingStack = null;
}
private void ThrowIfDisposed()
{
if (this._disposed)
Debug.Fail("allready disposed");
}
// Properties
public T Current
{
get
{
this.ThrowIfDisposed();
if ((this._remainingStack == null) || this._remainingStack.IsEmpty)
{
throw new InvalidOperationException();
}
return this._remainingStack.Peek();
}
}
object IEnumerator.Current
{
get
{
return this.Current;
}
}
}
}
}
| 28.234615 | 129 | 0.500068 | [
"BSD-3-Clause"
] | Black-Beard-Sdk/Decompile | src/Black.Beard.Sdk.Decompiler/Decompiler/IlParser/ImmutableStack.cs | 7,343 | C# |
using System;
using System.Collections.Generic;
using System.Text;
using AltairCA.EntityFrameworkCore.PomeloMysql.Extensions.Attribute;
using AltairCA.EntityFrameworkCore.PomeloMysql.Extensions.EfExtensions;
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;
namespace WebApplication1.Data
{
public class ApplicationDbContext : IdentityDbContext
{
public DbSet<TestModel> TModels { get; set; }
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
: base(options)
{
}
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
base.OnConfiguring(optionsBuilder);
optionsBuilder.UseEncryptionFunctions("HelloWorld1");
}
protected override void OnModelCreating(ModelBuilder builder)
{
base.OnModelCreating(builder);
builder.UseEncryptAttribute("HelloWorld1");
}
}
public class TestModel
{
public string Id { get; set; } = Guid.NewGuid().ToString();
[MysqlEncrypt]
public string Name { get; set; }
public string Name2 { get; set; }
}
}
| 29.190476 | 85 | 0.683524 | [
"MIT"
] | AltairCA/EntityFrameworkCore.PomeloMysql.Extensions | WebApplication1/Data/ApplicationDbContext.cs | 1,228 | C# |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
namespace QuoteOfTheMoment.Server
{
using System;
using System.Threading.Tasks;
using DotNetty.Handlers.Logging;
using DotNetty.Transport.Bootstrapping;
using DotNetty.Transport.Channels;
using DotNetty.Transport.Channels.Sockets;
using Examples.Common;
class Program
{
static async Task RunServerAsync()
{
ExampleHelper.SetConsoleLogger();
var group = new MultithreadEventLoopGroup();
try
{
var bootstrap = new Bootstrap();
bootstrap
.Group(group)
.Channel<SocketDatagramChannel>()
.Option(ChannelOption.SoBroadcast, true)
.Handler(new LoggingHandler("SRV-LSTN"))
.Handler(new ActionChannelInitializer<IChannel>(channel =>
{
channel.Pipeline.AddLast("Quote", new QuoteOfTheMomentServerHandler());
}));
IChannel boundChannel = await bootstrap.BindAsync(ServerSettings.Port);
Console.WriteLine("Press any key to terminate the server.");
Console.ReadLine();
await boundChannel.CloseAsync();
}
finally
{
await group.ShutdownGracefullyAsync(TimeSpan.FromMilliseconds(100), TimeSpan.FromSeconds(1));
}
}
static void Main() => RunServerAsync().Wait();
}
} | 34.395833 | 109 | 0.578437 | [
"MIT"
] | 15000775075/DotNetty | examples/QuoteOfTheMoment.Server/Program.cs | 1,653 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
namespace VN {
public class Menu : GameState {
Texture2D button;
List<Button> current;
List<Button> MainMenu;
List<Button> Settings;
List<Button> Save;
List<Button> Load;
public Menu(Game1 game) : base(game) {
InitializeMenus();
current = MainMenu;
}
void InitializeMenus() {
button = global.Content.Load<Texture2D>("button");
MainMenu = new List<Button> {
new Button {
BoundingBox = new Rectangle(100, 100, 200, 40),
Function = ButtonFunction.StartGame,
Text = "Start game",
Sprite = button,
},
new Button {
BoundingBox = new Rectangle(100, 150, 200, 40),
Function = ButtonFunction.LoadGame,
Text = "Load game",
Sprite = button,
},
new Button {
BoundingBox = new Rectangle(100, 200, 200, 40),
Function = ButtonFunction.CGGallery,
Text = "CG Gallery",
Sprite = button,
},
new Button {
BoundingBox = new Rectangle(100, 250, 200, 40),
Function = ButtonFunction.Exit,
Text = "Exit",
Sprite = button,
},
};
}
public override void Update(GameTime gameTime) {
prevMouseState = currentMouseState;
currentMouseState = Mouse.GetState();
HandleInput(currentMouseState, prevMouseState);
}
//Handles clicking the buttons for the current menu
public override void HandleInput(MouseState currentMouseState, MouseState prevMouseState) {
if (currentMouseState.LeftButton == ButtonState.Pressed && prevMouseState.LeftButton == ButtonState.Released) {
foreach (var button in current) {
if (button.BoundingBox.Contains(new Point(currentMouseState.X, currentMouseState.Y))) {
switch (button.Function) {
case ButtonFunction.StartGame:
global.StartGame();
break;
case ButtonFunction.Exit:
global.Exit();
break;
default:
break;
}
break;
}
}
}
}
//Draws the buttons in the current menu
public override void Draw(GameTime gameTime) {
foreach (Button b in current) {
DrawMenuButton(b, gameTime);
}
}
//Draws the actual buttons
void DrawMenuButton(Button button, GameTime gameTime) {
if (button.Sprite != null) {
global.spriteBatch.Draw(button.Sprite, button.BoundingBox, Color.White);
}
global.spriteBatch.DrawString(global.font, button.Text, new Vector2(button.BoundingBox.X + 10, button.BoundingBox.Y + 5), Color.Black);
}
public override void Reset() {
}
}
} | 30.59 | 142 | 0.579274 | [
"MIT"
] | Zkarts/VNgine | VN/VN/Menu.cs | 3,061 | 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.Immutable;
using System.Composition;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.Options.Providers;
using Microsoft.CodeAnalysis.Utilities;
namespace Microsoft.CodeAnalysis.Editor.Shared.Options
{
internal static class FeatureOnOffOptions
{
public static readonly PerLanguageOption<bool> EndConstruct = new PerLanguageOption<bool>(nameof(FeatureOnOffOptions), nameof(EndConstruct), defaultValue: true,
storageLocations: new RoamingProfileStorageLocation("TextEditor.%LANGUAGE%.Specific.AutoEndInsert"));
// This value is only used by Visual Basic, and so is using the old serialization name that was used by VB.
public static readonly PerLanguageOption<bool> AutomaticInsertionOfAbstractOrInterfaceMembers = new PerLanguageOption<bool>(nameof(FeatureOnOffOptions), nameof(AutomaticInsertionOfAbstractOrInterfaceMembers), defaultValue: true,
storageLocations: new RoamingProfileStorageLocation("TextEditor.%LANGUAGE%.Specific.AutoRequiredMemberInsert"));
public static readonly PerLanguageOption<bool> LineSeparator = new PerLanguageOption<bool>(nameof(FeatureOnOffOptions), nameof(LineSeparator), defaultValue: false,
storageLocations: new RoamingProfileStorageLocation(language => language == LanguageNames.VisualBasic ? "TextEditor.%LANGUAGE%.Specific.DisplayLineSeparators" : "TextEditor.%LANGUAGE%.Specific.Line Separator"));
public static readonly PerLanguageOption<bool> Outlining = new PerLanguageOption<bool>(nameof(FeatureOnOffOptions), nameof(Outlining), defaultValue: true,
storageLocations: new RoamingProfileStorageLocation("TextEditor.%LANGUAGE%.Specific.Outlining"));
public static readonly PerLanguageOption<bool> KeywordHighlighting = new PerLanguageOption<bool>(nameof(FeatureOnOffOptions), nameof(KeywordHighlighting), defaultValue: true,
storageLocations: new RoamingProfileStorageLocation(language => language == LanguageNames.VisualBasic ? "TextEditor.%LANGUAGE%.Specific.EnableHighlightRelatedKeywords" : "TextEditor.%LANGUAGE%.Specific.Keyword Highlighting"));
public static readonly PerLanguageOption<bool> ReferenceHighlighting = new PerLanguageOption<bool>(nameof(FeatureOnOffOptions), nameof(ReferenceHighlighting), defaultValue: true,
storageLocations: new RoamingProfileStorageLocation(language => language == LanguageNames.VisualBasic ? "TextEditor.%LANGUAGE%.Specific.EnableHighlightReferences" : "TextEditor.%LANGUAGE%.Specific.Reference Highlighting"));
public static readonly PerLanguageOption<bool> FormatOnPaste = new PerLanguageOption<bool>(nameof(FeatureOnOffOptions), nameof(FormatOnPaste), defaultValue: true,
storageLocations: new RoamingProfileStorageLocation("TextEditor.%LANGUAGE%.Specific.FormatOnPaste"));
public static readonly PerLanguageOption<bool> AutoXmlDocCommentGeneration = new PerLanguageOption<bool>(nameof(FeatureOnOffOptions), nameof(AutoXmlDocCommentGeneration), defaultValue: true,
storageLocations: new RoamingProfileStorageLocation(language => language == LanguageNames.VisualBasic ? "TextEditor.%LANGUAGE%.Specific.AutoComment" : "TextEditor.%LANGUAGE%.Specific.Automatic XML Doc Comment Generation"));
public static readonly PerLanguageOption<bool> AutoInsertBlockCommentStartString = new PerLanguageOption<bool>(nameof(FeatureOnOffOptions), nameof(AutoInsertBlockCommentStartString), defaultValue: true,
storageLocations: new RoamingProfileStorageLocation("TextEditor.%LANGUAGE%.Specific.Auto Insert Block Comment Start String"));
public static readonly PerLanguageOption<bool> PrettyListing = new PerLanguageOption<bool>(nameof(FeatureOnOffOptions), nameof(PrettyListing), defaultValue: true,
storageLocations: new RoamingProfileStorageLocation("TextEditor.%LANGUAGE%.Specific.PrettyListing"));
public static readonly PerLanguageOption<bool> AutoFormattingOnTyping = new PerLanguageOption<bool>(
nameof(FeatureOnOffOptions), nameof(AutoFormattingOnTyping), defaultValue: true,
storageLocations: new RoamingProfileStorageLocation("TextEditor.%LANGUAGE%.Specific.Auto Formatting On Typing"));
public static readonly PerLanguageOption<bool> AutoFormattingOnCloseBrace = new PerLanguageOption<bool>(
nameof(FeatureOnOffOptions), nameof(AutoFormattingOnCloseBrace), defaultValue: true,
storageLocations: new RoamingProfileStorageLocation("TextEditor.%LANGUAGE%.Specific.Auto Formatting On Close Brace"));
public static readonly PerLanguageOption<bool> AutoFormattingOnSemicolon = new PerLanguageOption<bool>(
nameof(FeatureOnOffOptions), nameof(AutoFormattingOnSemicolon), defaultValue: true,
storageLocations: new RoamingProfileStorageLocation("TextEditor.%LANGUAGE%.Specific.Auto Formatting On Semicolon"));
public static readonly PerLanguageOption<bool> RenameTrackingPreview = new PerLanguageOption<bool>(nameof(FeatureOnOffOptions), nameof(RenameTrackingPreview), defaultValue: true,
storageLocations: new RoamingProfileStorageLocation(language => language == LanguageNames.VisualBasic ? "TextEditor.%LANGUAGE%.Specific.RenameTrackingPreview" : "TextEditor.%LANGUAGE%.Specific.Rename Tracking Preview"));
/// <summary>
/// This option is currently used by Roslyn, but we might want to implement it in the
/// future. Keeping the option while it's unimplemented allows all upgrade paths to
/// maintain any customized value for this setting, even through versions that have not
/// implemented this feature yet.
/// </summary>
public static readonly PerLanguageOption<bool> RenameTracking = new PerLanguageOption<bool>(nameof(FeatureOnOffOptions), nameof(RenameTracking), defaultValue: true);
/// <summary>
/// This option is currently used by Roslyn, but we might want to implement it in the
/// future. Keeping the option while it's unimplemented allows all upgrade paths to
/// maintain any customized value for this setting, even through versions that have not
/// implemented this feature yet.
/// </summary>
public static readonly PerLanguageOption<bool> RefactoringVerification = new PerLanguageOption<bool>(
nameof(FeatureOnOffOptions), nameof(RefactoringVerification), defaultValue: false);
public static readonly PerLanguageOption<bool> StreamingGoToImplementation = new PerLanguageOption<bool>(
nameof(FeatureOnOffOptions), nameof(StreamingGoToImplementation), defaultValue: true);
public static readonly Option<bool> NavigateToDecompiledSources = new Option<bool>(
nameof(FeatureOnOffOptions), nameof(NavigateToDecompiledSources), defaultValue: false,
storageLocations: new RoamingProfileStorageLocation($"TextEditor.{nameof(NavigateToDecompiledSources)}"));
public static readonly Option<int> UseEnhancedColors = new Option<int>(
nameof(FeatureOnOffOptions), nameof(UseEnhancedColors), defaultValue: 1,
storageLocations: new RoamingProfileStorageLocation("WindowManagement.Options.UseEnhancedColorsForManagedLanguages"));
/// <summary>
/// Feature to enable <see cref="CompilerFeatureFlags.RunNullableAnalysis"/> in the compiler flags for all csharp projects.
/// 0 = default, which leaves the flag unset.
/// 1 = set to true
/// -1 = set to false
/// </summary>
public static readonly Option<int> UseNullableReferenceTypeAnalysis = new Option<int>(
nameof(FeatureOnOffOptions), nameof(UseNullableReferenceTypeAnalysis), defaultValue: 0,
storageLocations: new RoamingProfileStorageLocation($"TextEditor.CSharp.{nameof(UseNullableReferenceTypeAnalysis)}"));
// Note: no storage location since this is intentionally a session variable
public static readonly Option<bool> AcceptedDecompilerDisclaimer = new Option<bool>(
nameof(FeatureOnOffOptions), nameof(AcceptedDecompilerDisclaimer), defaultValue: false);
}
[ExportOptionProvider, Shared]
internal class FeatureOnOffOptionsProvider : IOptionProvider
{
[ImportingConstructor]
public FeatureOnOffOptionsProvider()
{
}
public ImmutableArray<IOption> Options { get; } = ImmutableArray.Create<IOption>(
FeatureOnOffOptions.EndConstruct,
FeatureOnOffOptions.AutomaticInsertionOfAbstractOrInterfaceMembers,
FeatureOnOffOptions.LineSeparator,
FeatureOnOffOptions.Outlining,
FeatureOnOffOptions.KeywordHighlighting,
FeatureOnOffOptions.ReferenceHighlighting,
FeatureOnOffOptions.FormatOnPaste,
FeatureOnOffOptions.AutoXmlDocCommentGeneration,
FeatureOnOffOptions.AutoInsertBlockCommentStartString,
FeatureOnOffOptions.PrettyListing,
FeatureOnOffOptions.AutoFormattingOnTyping,
FeatureOnOffOptions.AutoFormattingOnCloseBrace,
FeatureOnOffOptions.AutoFormattingOnSemicolon,
FeatureOnOffOptions.RenameTrackingPreview,
FeatureOnOffOptions.RenameTracking,
FeatureOnOffOptions.RefactoringVerification,
FeatureOnOffOptions.StreamingGoToImplementation,
FeatureOnOffOptions.NavigateToDecompiledSources,
FeatureOnOffOptions.AcceptedDecompilerDisclaimer,
FeatureOnOffOptions.UseEnhancedColors);
}
}
| 73.62406 | 238 | 0.758578 | [
"Apache-2.0"
] | GKotfis/roslyn | src/EditorFeatures/Core/Shared/Options/FeatureOnOffOptions.cs | 9,794 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
namespace Microsoft.Azure.Batch.Auth
{
using System;
using System.Threading.Tasks;
/// <summary>
/// Azure Active Directory token credentials for an Azure Batch account.
/// </summary>
public class BatchTokenCredentials : BatchCredentials
{
/// <summary>
/// Gets a function which returns an authentication token.
/// </summary>
public Func<Task<string>> TokenProvider { get; }
/// <summary>
/// Initializes a new instance of the <see cref="BatchTokenCredentials"/> class with the specified Batch service endpoint and authentication token.
/// </summary>
/// <param name="baseUrl">The Batch service endpoint.</param>
/// <param name="token">An authentication token provided by Azure Active Directory.</param>
public BatchTokenCredentials(string baseUrl, string token)
{
if (string.IsNullOrEmpty(baseUrl))
{
throw new ArgumentNullException(nameof(baseUrl));
}
if (string.IsNullOrEmpty(token))
{
throw new ArgumentNullException(nameof(token));
}
this.BaseUrl = baseUrl;
var tokenTask = Task.FromResult(token);
TokenProvider = () => tokenTask;
}
/// <summary>
/// Initializes a new instance of the <see cref="BatchTokenCredentials" /> class with the specified Batch service endpoint and authentication token provider function.
/// </summary>
/// <param name="baseUrl">The Batch service endpoint.</param>
/// <param name="tokenProvider">A function which returns an authentication token.</param>
public BatchTokenCredentials(string baseUrl, Func<Task<string>> tokenProvider)
{
if (string.IsNullOrEmpty(baseUrl))
{
throw new ArgumentNullException(nameof(baseUrl));
}
if (tokenProvider == null)
{
throw new ArgumentNullException(nameof(tokenProvider));
}
this.BaseUrl = baseUrl;
this.TokenProvider = tokenProvider;
}
}
}
| 38.95 | 174 | 0.610184 | [
"MIT"
] | 0rland0Wats0n/azure-sdk-for-net | sdk/batch/Microsoft.Azure.Batch/src/Auth/BatchTokenCredentials.cs | 2,339 | C# |
using Unity.Entities;
using Unity.Physics;
using Unity.Physics.Systems;
using Unity.Transforms;
namespace TinyPhysics.Systems
{
/// <summary>
/// Find and store distance of closest entity
/// Use CollisionFilter of source entity to find target
/// </summary>
public class ProximitySystem : SystemBase
{
protected override void OnUpdate()
{
Entities.ForEach((ref Proximity proximity, ref Translation translation, ref PhysicsCollider collider) =>
{
ref PhysicsWorld physicsWorld = ref World.DefaultGameObjectInjectionWorld.GetExistingSystem<BuildPhysicsWorld>().PhysicsWorld;
if (collider.Value.IsCreated)
{
var pointDistanceInput = new PointDistanceInput
{
Position = translation.Value,
MaxDistance = proximity.maxDistance,
Filter = collider.Value.Value.Filter
};
// Assign DistanceHit data to proximiy component
physicsWorld.CalculateDistance(pointDistanceInput, out proximity.distanceHit);
}
}).WithoutBurst().Run();
}
}
}
| 35 | 142 | 0.586508 | [
"MIT"
] | Ayrtonfoster/ResumeSite | Assets/Scripts/Systems/ProximitySystem.cs | 1,262 | C# |
/*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the resiliencehub-2020-04-30.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Net;
using System.Text;
using System.Xml.Serialization;
using Amazon.ResilienceHub.Model;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
using Amazon.Runtime.Internal.Transform;
using Amazon.Runtime.Internal.Util;
using ThirdParty.Json.LitJson;
namespace Amazon.ResilienceHub.Model.Internal.MarshallTransformations
{
/// <summary>
/// Response Unmarshaller for DeleteAppAssessment operation
/// </summary>
public class DeleteAppAssessmentResponseUnmarshaller : JsonResponseUnmarshaller
{
/// <summary>
/// Unmarshaller the response from the service to the response class.
/// </summary>
/// <param name="context"></param>
/// <returns></returns>
public override AmazonWebServiceResponse Unmarshall(JsonUnmarshallerContext context)
{
DeleteAppAssessmentResponse response = new DeleteAppAssessmentResponse();
context.Read();
int targetDepth = context.CurrentDepth;
while (context.ReadAtDepth(targetDepth))
{
if (context.TestExpression("assessmentArn", targetDepth))
{
var unmarshaller = StringUnmarshaller.Instance;
response.AssessmentArn = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("assessmentStatus", targetDepth))
{
var unmarshaller = StringUnmarshaller.Instance;
response.AssessmentStatus = unmarshaller.Unmarshall(context);
continue;
}
}
return response;
}
/// <summary>
/// Unmarshaller error response to exception.
/// </summary>
/// <param name="context"></param>
/// <param name="innerException"></param>
/// <param name="statusCode"></param>
/// <returns></returns>
public override AmazonServiceException UnmarshallException(JsonUnmarshallerContext context, Exception innerException, HttpStatusCode statusCode)
{
var errorResponse = JsonErrorResponseUnmarshaller.GetInstance().Unmarshall(context);
errorResponse.InnerException = innerException;
errorResponse.StatusCode = statusCode;
var responseBodyBytes = context.GetResponseBodyBytes();
using (var streamCopy = new MemoryStream(responseBodyBytes))
using (var contextCopy = new JsonUnmarshallerContext(streamCopy, false, null))
{
if (errorResponse.Code != null && errorResponse.Code.Equals("AccessDeniedException"))
{
return AccessDeniedExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse);
}
if (errorResponse.Code != null && errorResponse.Code.Equals("ConflictException"))
{
return ConflictExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse);
}
if (errorResponse.Code != null && errorResponse.Code.Equals("InternalServerException"))
{
return InternalServerExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse);
}
if (errorResponse.Code != null && errorResponse.Code.Equals("ResourceNotFoundException"))
{
return ResourceNotFoundExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse);
}
if (errorResponse.Code != null && errorResponse.Code.Equals("ThrottlingException"))
{
return ThrottlingExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse);
}
if (errorResponse.Code != null && errorResponse.Code.Equals("ValidationException"))
{
return ValidationExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse);
}
}
return new AmazonResilienceHubException(errorResponse.Message, errorResponse.InnerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, errorResponse.StatusCode);
}
private static DeleteAppAssessmentResponseUnmarshaller _instance = new DeleteAppAssessmentResponseUnmarshaller();
internal static DeleteAppAssessmentResponseUnmarshaller GetInstance()
{
return _instance;
}
/// <summary>
/// Gets the singleton.
/// </summary>
public static DeleteAppAssessmentResponseUnmarshaller Instance
{
get
{
return _instance;
}
}
}
} | 41.220588 | 196 | 0.634856 | [
"Apache-2.0"
] | EbstaLimited/aws-sdk-net | sdk/src/Services/ResilienceHub/Generated/Model/Internal/MarshallTransformations/DeleteAppAssessmentResponseUnmarshaller.cs | 5,606 | C# |
using System;
using System.Xml.Serialization;
namespace Aop.Api.Domain
{
/// <summary>
/// BizActionComsumedAmountDTO Data Structure.
/// </summary>
[Serializable]
public class BizActionComsumedAmountDTO : AopObject
{
/// <summary>
/// 业务预算申请Code
/// </summary>
[XmlElement("biz_budget_apply_code")]
public string BizBudgetApplyCode { get; set; }
/// <summary>
/// 外部系统bizUkId
/// </summary>
[XmlElement("biz_uk_id")]
public string BizUkId { get; set; }
/// <summary>
/// 占用金额
/// </summary>
[XmlElement("consumed_amount")]
public string ConsumedAmount { get; set; }
}
}
| 24.258065 | 56 | 0.538564 | [
"Apache-2.0"
] | 554393109/alipay-sdk-net-all | AlipaySDKNet.Standard/Domain/BizActionComsumedAmountDTO.cs | 780 | C# |
namespace HonzaBotner.Discord.Services.Options;
public class ButtonOptions
{
public static string ConfigName => "ButtonOptions";
public string? VerificationId { get; set; }
public string? StaffVerificationId { get; set; }
public string? StaffRemoveRoleId { get; set; }
public ulong[]? CzechChannelsIds { get; set; }
}
| 28.333333 | 55 | 0.717647 | [
"MIT"
] | fit-ctu-discord/honza-botner-dev | src/HonzaBotner.Discord.Services/Options/ButtonOptions.cs | 340 | C# |
// ------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information.
// ------------------------------------------------------------------------------
// **NOTE** This file was generated by a tool and any changes will be overwritten.
// <auto-generated/>
// Template Source: Templates\CSharp\Requests\MethodRequestBuilder.cs.tt
namespace Microsoft.Graph
{
using System;
using System.Collections.Generic;
using System.IO;
/// <summary>
/// The type InformationProtectionPolicyRemoveLabelRequestBuilder.
/// </summary>
public partial class InformationProtectionPolicyRemoveLabelRequestBuilder : BaseActionMethodRequestBuilder<IInformationProtectionPolicyRemoveLabelRequest>, IInformationProtectionPolicyRemoveLabelRequestBuilder
{
/// <summary>
/// Constructs a new <see cref="InformationProtectionPolicyRemoveLabelRequestBuilder"/>.
/// </summary>
/// <param name="requestUrl">The URL for the request.</param>
/// <param name="client">The <see cref="IBaseClient"/> for handling requests.</param>
/// <param name="contentInfo">A contentInfo parameter for the OData method call.</param>
/// <param name="downgradeJustification">A downgradeJustification parameter for the OData method call.</param>
public InformationProtectionPolicyRemoveLabelRequestBuilder(
string requestUrl,
IBaseClient client,
ContentInfo contentInfo,
DowngradeJustification downgradeJustification)
: base(requestUrl, client)
{
this.SetParameter("contentInfo", contentInfo, false);
this.SetParameter("downgradeJustification", downgradeJustification, true);
}
/// <summary>
/// A method used by the base class to construct a request class instance.
/// </summary>
/// <param name="functionUrl">The request URL to </param>
/// <param name="options">The query and header options for the request.</param>
/// <returns>An instance of a specific request class.</returns>
protected override IInformationProtectionPolicyRemoveLabelRequest CreateRequest(string functionUrl, IEnumerable<Option> options)
{
var request = new InformationProtectionPolicyRemoveLabelRequest(functionUrl, this.Client, options);
if (this.HasParameter("contentInfo"))
{
request.RequestBody.ContentInfo = this.GetParameter<ContentInfo>("contentInfo");
}
if (this.HasParameter("downgradeJustification"))
{
request.RequestBody.DowngradeJustification = this.GetParameter<DowngradeJustification>("downgradeJustification");
}
return request;
}
}
}
| 46.84127 | 213 | 0.644188 | [
"MIT"
] | gurry/msgraph-beta-sdk-dotnet | src/Microsoft.Graph/Requests/Generated/InformationProtectionPolicyRemoveLabelRequestBuilder.cs | 2,951 | C# |
namespace DotNet.Testcontainers.Configurations
{
using System.Collections.Generic;
/// <inheritdoc cref="IDockerResourceConfiguration" />
public class DockerResourceConfiguration : IDockerResourceConfiguration
{
/// <summary>
/// Initializes a new instance of the <see cref="DockerResourceConfiguration" /> class.
/// </summary>
/// <param name="dockerResourceConfiguration">The Docker resource configuration.</param>
public DockerResourceConfiguration(IDockerResourceConfiguration dockerResourceConfiguration)
: this(dockerResourceConfiguration.DockerEndpointAuthConfig, dockerResourceConfiguration.Labels)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="DockerResourceConfiguration" /> class.
/// </summary>
/// <param name="dockerEndpointAuthenticationConfiguration">The Docker endpoint authentication configuration.</param>
/// <param name="labels">A list of labels.</param>
public DockerResourceConfiguration(
IDockerEndpointAuthenticationConfiguration dockerEndpointAuthenticationConfiguration = null,
IReadOnlyDictionary<string, string> labels = null)
{
this.DockerEndpointAuthConfig = dockerEndpointAuthenticationConfiguration;
this.Labels = labels;
}
/// <inheritdoc />
public IDockerEndpointAuthenticationConfiguration DockerEndpointAuthConfig { get; }
/// <inheritdoc />
public IReadOnlyDictionary<string, string> Labels { get; }
}
}
| 40.135135 | 121 | 0.746128 | [
"MIT"
] | studentutu/dotnet-testcontainers | src/DotNet.Testcontainers/Configurations/DockerResourceConfiguration.cs | 1,487 | C# |
using System;
using System.Runtime.InteropServices;
using System.Security;
namespace NitraLibSodium.Stream
{
public unsafe partial class Chacha20
{
public partial struct __Internal
{
[SuppressUnmanagedCodeSecurity]
[DllImport("libsodium", CallingConvention = global::System.Runtime.InteropServices.CallingConvention.Cdecl,
EntryPoint = "crypto_stream_chacha20_keybytes")]
internal static extern ulong Keybytes();
[SuppressUnmanagedCodeSecurity]
[DllImport("libsodium", CallingConvention = global::System.Runtime.InteropServices.CallingConvention.Cdecl,
EntryPoint = "crypto_stream_chacha20_noncebytes")]
internal static extern ulong Noncebytes();
[SuppressUnmanagedCodeSecurity]
[DllImport("libsodium", CallingConvention = global::System.Runtime.InteropServices.CallingConvention.Cdecl,
EntryPoint = "crypto_stream_chacha20_messagebytes_max")]
internal static extern ulong MessagebytesMax();
[SuppressUnmanagedCodeSecurity]
[DllImport("libsodium", CallingConvention = global::System.Runtime.InteropServices.CallingConvention.Cdecl,
EntryPoint = "crypto_stream_chacha20")]
internal static extern int Chacha20(byte* c, ulong clen, byte* n, byte* k);
[SuppressUnmanagedCodeSecurity]
[DllImport("libsodium", CallingConvention = global::System.Runtime.InteropServices.CallingConvention.Cdecl,
EntryPoint = "crypto_stream_chacha20_xor")]
internal static extern int Xor(byte* c, byte* m, ulong mlen, byte* n, byte* k);
[SuppressUnmanagedCodeSecurity]
[DllImport("libsodium", CallingConvention = global::System.Runtime.InteropServices.CallingConvention.Cdecl,
EntryPoint = "crypto_stream_chacha20_xor_ic")]
internal static extern int XorIc(byte* c, byte* m, ulong mlen, byte* n, ulong ic, byte* k);
[SuppressUnmanagedCodeSecurity]
[DllImport("libsodium", CallingConvention = global::System.Runtime.InteropServices.CallingConvention.Cdecl,
EntryPoint = "crypto_stream_chacha20_keygen")]
internal static extern void Keygen(byte[] k);
[SuppressUnmanagedCodeSecurity]
[DllImport("libsodium", CallingConvention = global::System.Runtime.InteropServices.CallingConvention.Cdecl,
EntryPoint = "crypto_stream_chacha20_ietf_keybytes")]
internal static extern ulong IetfKeybytes();
[SuppressUnmanagedCodeSecurity]
[DllImport("libsodium", CallingConvention = global::System.Runtime.InteropServices.CallingConvention.Cdecl,
EntryPoint = "crypto_stream_chacha20_ietf_noncebytes")]
internal static extern ulong IetfNoncebytes();
[SuppressUnmanagedCodeSecurity]
[DllImport("libsodium", CallingConvention = global::System.Runtime.InteropServices.CallingConvention.Cdecl,
EntryPoint = "crypto_stream_chacha20_ietf_messagebytes_max")]
internal static extern ulong IetfMessagebytesMax();
[SuppressUnmanagedCodeSecurity]
[DllImport("libsodium", CallingConvention = global::System.Runtime.InteropServices.CallingConvention.Cdecl,
EntryPoint = "crypto_stream_chacha20_ietf")]
internal static extern int Ietf(byte* c, ulong clen, byte* n, byte* k);
[SuppressUnmanagedCodeSecurity]
[DllImport("libsodium", CallingConvention = global::System.Runtime.InteropServices.CallingConvention.Cdecl,
EntryPoint = "crypto_stream_chacha20_ietf_xor")]
internal static extern int IetfXor(byte* c, byte* m, ulong mlen, byte* n, byte* k);
[SuppressUnmanagedCodeSecurity]
[DllImport("libsodium", CallingConvention = global::System.Runtime.InteropServices.CallingConvention.Cdecl,
EntryPoint = "crypto_stream_chacha20_ietf_xor_ic")]
internal static extern int IetfXorIc(byte* c, byte* m, ulong mlen, byte* n, uint ic, byte* k);
[SuppressUnmanagedCodeSecurity]
[DllImport("libsodium", CallingConvention = global::System.Runtime.InteropServices.CallingConvention.Cdecl,
EntryPoint = "crypto_stream_chacha20_ietf_keygen")]
internal static extern void IetfKeygen(byte[] k);
}
public static ulong Keybytes()
{
var __ret = __Internal.Keybytes();
return __ret;
}
public static ulong Noncebytes()
{
var __ret = __Internal.Noncebytes();
return __ret;
}
public static ulong MessagebytesMax()
{
var __ret = __Internal.MessagebytesMax();
return __ret;
}
public static int CryptoChacha20(byte[] c, ulong clen, byte[] n, byte[] k)
{
var __ret = __Internal.Chacha20(MarshalHelper.ByteArrayToIntPtr(c), clen, MarshalHelper.ByteArrayToIntPtr(n), MarshalHelper.ByteArrayToIntPtr(k));
return __ret;
}
public static int Xor(byte[] c, byte[] m, ulong mlen, byte[] n, byte[] k)
{
var __ret = __Internal.Xor(MarshalHelper.ByteArrayToIntPtr(c), MarshalHelper.ByteArrayToIntPtr(m), mlen, MarshalHelper.ByteArrayToIntPtr(n), MarshalHelper.ByteArrayToIntPtr(k));
return __ret;
}
public static int XorIc(byte[] c, byte[] m, ulong mlen, byte[] n, ulong ic, byte[] k)
{
var __ret = __Internal.XorIc(MarshalHelper.ByteArrayToIntPtr(c), MarshalHelper.ByteArrayToIntPtr(m), mlen, MarshalHelper.ByteArrayToIntPtr(n), ic, MarshalHelper.ByteArrayToIntPtr(k));
return __ret;
}
public static void Keygen(byte[] k)
{
if (k == null || k.Length != 32)
throw new ArgumentOutOfRangeException("k", "The dimensions of the provided array don't match the required size.");
__Internal.Keygen(k);
}
public static ulong IetfKeybytes()
{
var __ret = __Internal.IetfKeybytes();
return __ret;
}
public static ulong IetfNoncebytes()
{
var __ret = __Internal.IetfNoncebytes();
return __ret;
}
public static ulong IetfMessagebytesMax()
{
var __ret = __Internal.IetfMessagebytesMax();
return __ret;
}
public static int Ietf(byte[] c, ulong clen, byte[] n, byte[] k)
{
var __ret = __Internal.Ietf(MarshalHelper.ByteArrayToIntPtr(c), clen, MarshalHelper.ByteArrayToIntPtr(n), MarshalHelper.ByteArrayToIntPtr(k));
return __ret;
}
public static int IetfXor(byte[] c, byte[] m, ulong mlen, byte[] n, byte[] k)
{
var __ret = __Internal.IetfXor(MarshalHelper.ByteArrayToIntPtr(c), MarshalHelper.ByteArrayToIntPtr(m), mlen, MarshalHelper.ByteArrayToIntPtr(n), MarshalHelper.ByteArrayToIntPtr(k));
return __ret;
}
public static int IetfXorIc(byte[] c, byte[] m, ulong mlen, byte[] n, uint ic, byte[] k)
{
var __ret = __Internal.IetfXorIc(MarshalHelper.ByteArrayToIntPtr(c), MarshalHelper.ByteArrayToIntPtr(m), mlen, MarshalHelper.ByteArrayToIntPtr(n), ic, MarshalHelper.ByteArrayToIntPtr(k));
return __ret;
}
public static void IetfKeygen(byte[] k)
{
if (k == null || k.Length != 32)
throw new ArgumentOutOfRangeException("k", "The dimensions of the provided array don't match the required size.");
__Internal.IetfKeygen(k);
}
}
}
| 47.213018 | 200 | 0.632911 | [
"MIT"
] | nitrachain/NitraLibSodium | NitraLibSodium/Stream/Chacha20.cs | 7,981 | C# |
// Lucene version compatibility level 4.8.1
/*
Copyright © 2003,
Center for Intelligent Information Retrieval,
University of Massachusetts, Amherst.
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
3. The names "Center for Intelligent Information Retrieval" and
"University of Massachusetts" must not be used to endorse or promote products
derived from this software without prior written permission. To obtain
permission, contact info@ciir.cs.umass.edu.
THIS SOFTWARE IS PROVIDED BY UNIVERSITY OF MASSACHUSETTS AND OTHER 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 HOLDERS 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.
*/
/* This is a .NET version of Bob Krovetz' KStem.
*
* Java version by Sergio Guzman-Lara.
* CIIR-UMass Amherst http://ciir.cs.umass.edu
*/
namespace Lucene.Net.Analysis.En
{
/// <summary>
/// A list of words used by Kstem
/// </summary>
internal class KStemData3
{
private KStemData3()
{
}
internal static string[] data = new string[] {
"distasteful","distemper","distempered","distend","distension",
"distil","distill","distillation","distiller","distillery",
"distinct","distinction","distinctive","distinguish","distinguishable",
"distinguished","distort","distortion","distract","distracted",
"distraction","distrain","distraint","distrait","distraught",
"distress","distressing","distribute","distribution","distributive",
"distributor","district","distrust","distrustful","disturb",
"disturbance","disturbed","disunion","disunite","disunity",
"disuse","disused","disyllabic","disyllable","ditch",
"dither","dithers","ditto","ditty","diuretic",
"diurnal","divagate","divan","dive","diver",
"diverge","divergence","divers","diverse","diversify",
"diversion","diversionary","diversity","divert","divertimento",
"divertissement","divest","divide","dividend","dividers",
"divination","divine","diviner","divingboard","divinity",
"divisible","division","divisive","divisor","divorce",
"divot","divulge","divvy","dixie","dixieland",
"dizzy","djinn","dna","do","dobbin",
"doc","docile","dock","docker","docket",
"dockyard","doctor","doctoral","doctorate","doctrinaire",
"doctrinal","doctrine","document","documentary","documentation",
"dodder","doddering","doddle","dodge","dodgems",
"dodger","dodgy","dodo","doe","doer",
"doeskin","doff","dog","dogcart","dogcatcher",
"dogfight","dogfish","dogged","doggerel","doggie",
"doggo","doggone","doggy","doghouse","dogie",
"dogleg","dogma","dogmatic","dogmatics","dogmatism",
"dogs","dogsbody","dogtooth","dogtrot","dogwood",
"doh","doily","doings","doldrums","dole",
"doleful","doll","dollar","dollop","dolly",
"dolmen","dolor","dolorous","dolour","dolphin",
"dolt","domain","dome","domed","domestic",
"domesticate","domesticity","domicile","domiciliary","dominance",
"dominant","dominate","domination","domineer","dominican",
"dominion","domino","dominoes","don","donate",
"donation","donjon","donkey","donkeywork","donnish",
"donor","doodle","doodlebug","doom","doomsday",
"door","doorbell","doorframe","doorkeeper","doorknob",
"doorknocker","doorman","doormat","doornail","doorplate",
"doorscraper","doorstep","doorstopper","doorway","dope",
"dopey","dopy","doric","dormant","dormer",
"dormitory","dormouse","dorsal","dory","dosage",
"dose","doss","dosser","dosshouse","dossier",
"dost","dot","dotage","dote","doth",
"doting","dottle","dotty","double","doubles",
"doublet","doublethink","doubloon","doubly","doubt",
"doubtful","doubtless","douche","dough","doughnut",
"doughty","doughy","dour","douse","dove",
"dovecote","dovetail","dowager","dowdy","dowel",
"dower","down","downbeat","downcast","downdraft",
"downdraught","downer","downfall","downgrade","downhearted",
"downhill","downpour","downright","downstage","downstairs",
"downstream","downtown","downtrodden","downward","downwards",
"downwind","downy","dowry","dowse","doxology",
"doyen","doyley","doze","dozen","dozy",
"dpt","drab","drabs","drachm","drachma",
"draconian","draft","draftee","draftsman","drafty",
"drag","draggled","draggy","dragnet","dragoman",
"dragon","dragonfly","dragoon","drain","drainage",
"drainpipe","drake","dram","drama","dramatic",
"dramatics","dramatise","dramatist","dramatize","drank",
"drape","draper","drapery","drastic","drat",
"draught","draughtboard","draughts","draughtsman","draughty",
"draw","drawback","drawbridge","drawer","drawers",
"drawing","drawl","drawn","drawstring","dray",
"dread","dreadful","dreadfully","dreadnaught","dreadnought",
"dream","dreamboat","dreamer","dreamland","dreamless",
"dreamlike","dreamy","drear","dreary","dredge",
"dredger","dregs","drench","dress","dressage",
"dresser","dressing","dressmaker","dressy","drew",
"dribble","driblet","dribs","drier","drift",
"driftage","drifter","driftnet","driftwood","drill",
"drily","drink","drinkable","drinker","drip",
"dripping","drive","drivel","driver","driveway",
"driving","drizzle","drogue","droll","drollery",
"dromedary","drone","drool","droop","drop",
"dropkick","droplet","dropout","dropper","droppings",
"drops","dropsy","dross","drought","drove",
"drover","drown","drowse","drowsy","drub",
"drudge","drudgery","drug","drugget","druggist",
"drugstore","druid","drum","drumbeat","drumfire",
"drumhead","drummer","drumstick","drunk","drunkard",
"drunken","drupe","dry","dryad","dryer",
"dual","dub","dubbin","dubiety","dubious",
"ducal","ducat","duchess","duchy","duck",
"duckboards","duckling","ducks","duckweed","ducky",
"duct","ductile","dud","dude","dudgeon",
"duds","due","duel","duenna","dues",
"duet","duff","duffel","duffer","duffle",
"dug","dugout","duke","dukedom","dukes",
"dulcet","dulcimer","dull","dullard","duly",
"dumb","dumbbell","dumbfound","dumbwaiter","dumfound",
"dummy","dump","dumper","dumpling","dumps",
"dumpy","dun","dunce","dunderhead","dung",
"dungaree","dungarees","dungeon","dunghill","dunk",
"duo","duodecimal","duodenum","duologue","dupe",
"duplex","duplicate","duplicator","duplicity","durable",
"duration","durbar","duress","durex","during",
"durst","dusk","dusky","dust","dustbin",
"dustbowl","dustcart","dustcoat","duster","dustman",
"dustpan","dustsheet","dustup","dusty","dutch",
"dutiable","dutiful","duty","duvet","dwarf",
"dwell","dwelling","dwindle","dyarchy","dye",
"dyestuff","dyeworks","dyke","dynamic","dynamics",
"dynamism","dynamite","dynamo","dynasty","dysentery",
"dyslexia","dyspepsia","dyspeptic","each","eager",
"eagle","eaglet","ear","earache","eardrum",
"eared","earful","earl","earliest","earlobe",
"early","earmark","earmuff","earn","earnest",
"earnings","earphone","earpiece","earplug","earring",
"earshot","earth","earthbound","earthen","earthenware",
"earthling","earthly","earthnut","earthquake","earthshaking",
"earthwork","earthworm","earthy","earwax","earwig",
"ease","easel","easily","east","eastbound",
"easter","easterly","eastern","easterner","easternmost",
"easy","easygoing","eat","eatable","eatables",
"eater","eats","eaves","eavesdrop","ebb",
"ebony","ebullience","ebullient","eccentric","eccentricity",
"ecclesiastic","ecclesiastical","ecg","echelon","echo",
"eclectic","eclipse","ecliptic","eclogue","ecological",
"ecologically","ecology","economic","economical","economically",
"economics","economise","economist","economize","economy",
"ecosystem","ecstasy","ecstatic","ect","ectoplasm",
"ecumenical","ecumenicalism","eczema","edam","eddy",
"edelweiss","eden","edge","edgeways","edging",
"edgy","edible","edibles","edict","edification",
"edifice","edify","edit","edition","editor",
"editorial","editorialise","editorialize","educate","educated",
"education","educational","educationist","educator","educe",
"eec","eeg","eel","eerie","efface",
"effect","effective","effectively","effectiveness","effectives",
"effects","effectual","effectually","effectuate","effeminacy",
"effeminate","effendi","effervesce","effete","efficacious",
"efficacy","efficiency","efficient","effigy","efflorescence",
"effluent","efflux","effort","effortless","effrontery",
"effulgence","effulgent","effusion","effusive","eft",
"egalitarian","egg","eggcup","egghead","eggnog",
"eggplant","eggshell","egis","eglantine","ego",
"egocentric","egoism","egoist","egotism","egotist",
"egregious","egress","egret","eiderdown","eight",
"eighteen","eightsome","eighty","eisteddfod","either",
"ejaculate","ejaculation","eject","ejector","eke",
"ekg","elaborate","elaboration","eland","elapse",
"elastic","elasticity","elastoplast","elate","elated",
"elation","elbow","elbowroom","elder","elderberry",
"elderflower","elderly","eldest","elect","election",
"electioneer","electioneering","elective","elector","electoral",
"electorate","electric","electrical","electrician","electricity",
"electrify","electrocardiogram","electrocardiograph","electrocute","electrode",
"electroencephalogram","electroencephalograph","electrolysis","electrolyte","electron",
"electronic","electronics","electroplate","eleemosynary","elegant",
"elegiac","elegy","element","elemental","elementary",
"elements","elephant","elephantiasis","elephantine","elevate",
"elevated","elevation","elevator","eleven","elevenses",
"elf","elfin","elfish","elicit","elide",
"eligible","eliminate","elite","elitism","elixir",
"elizabethan","elk","elkhound","ellipse","ellipsis",
"elliptic","elm","elocution","elocutionary","elocutionist",
"elongate","elongation","elope","eloquence","eloquent",
"else","elsewhere","elucidate","elucidatory","elude",
"elusive","elver","elves","elvish","elysian",
"elysium","emaciate","emanate","emancipate","emancipation",
"emasculate","embalm","embankment","embargo","embark",
"embarkation","embarrass","embarrassment","embassy","embattled",
"embed","embellish","ember","embezzle","embitter",
"emblazon","emblem","emblematic","embodiment","embody",
"embolden","embolism","embonpoint","embosomed","emboss",
"embowered","embrace","embrasure","embrocation","embroider",
"embroidery","embroil","embryo","embryonic","emend",
"emendation","emerald","emerge","emergence","emergency",
"emergent","emeritus","emery","emetic","emigrant",
"emigrate","eminence","eminent","eminently","emir",
"emirate","emissary","emission","emit","emmentaler",
"emmenthaler","emollient","emolument","emote","emotion",
"emotional","emotionalism","emotionally","emotive","empanel",
"empathy","emperor","emphasis","emphasise","emphasize",
"emphatic","emphatically","emphysema","empire","empirical",
"empiricism","emplacement","emplane","employ","employable",
"employee","employer","employment","emporium","empower",
"empress","emptily","empty","empurpled","empyreal",
"empyrean","emu","emulate","emulation","emulsify",
"emulsion","enable","enabling","enact","enactment",
"enamel","enamelware","enamored","enamoured","encamp",
"encampment","encapsulate","encase","encaustic","encephalitis",
"enchain","enchant","enchanter","enchanting","enchantment",
"encipher","encircle","enclave","enclose","enclosure",
"encode","encomium","encompass","encore","encounter",
"encourage","encouragement","encroach","encroachment","encrust",
"encumber","encumbrance","encyclical","encyclopaedia","encyclopaedic",
"encyclopedia","encyclopedic","end","endanger","endear",
"endearing","endearment","endeavor","endeavour","endemic",
"ending","endive","endless","endocrine","endorse",
"endow","endowment","endpaper","endurance","endure",
"enduring","endways","enema","enemy","energetic",
"energize","energy","enervate","enfeeble","enfilade",
"enfold","enforce","enfranchise","engage","engaged",
"engagement","engaging","engender","engine","engineer",
"engineering","english","englishman","engraft","engrave",
"engraving","engross","engrossing","engulf","enhance",
"enigma","enigmatic","enjoin","enjoy","enjoyable",
"enjoyment","enkindle","enlarge","enlargement","enlighten",
"enlightened","enlightenment","enlist","enliven","enmesh",
"enmity","ennoble","ennui","enormity","enormous",
"enormously","enough","enplane","enquire","enquiring",
"enquiry","enrage","enrapture","enrich","enrol",
"enroll","enrollment","enrolment","ensanguined","ensconce",
"ensemble","enshrine","enshroud","ensign","enslave",
"ensnare","ensue","ensure","entail","entangle",
"entanglement","entente","enter","enteritis","enterprise",
"enterprising","entertain","entertainer","entertaining","entertainment",
"enthral","enthrall","enthrone","enthroned","enthuse",
"enthusiasm","enthusiast","entice","enticement","entire",
"entirety","entitle","entity","entomb","entomology",
"entourage","entrails","entrain","entrance","entrant",
"entrap","entreat","entreaty","entrench","entrenched",
"entrenchment","entrepreneur","entresol","entropy","entrust",
"entry","entwine","enumerate","enunciate","enunciation",
"envelop","envenom","enviable","envious","environed",
"environment","environmental","environmentalist","environs","envisage",
"envoi","envoy","envy","enzyme","eon",
"epaulet","epaulette","ephemeral","epic","epicenter",
"epicentre","epicure","epicurean","epidemic","epidermis",
"epidiascope","epiglottis","epigram","epigrammatic","epilepsy",
"epileptic","epilogue","epiphany","episcopacy","episcopal",
"episcopalian","episode","episodic","epistle","epistolary",
"epitaph","epithet","epitome","epitomise","epitomize",
"epoch","eponymous","equability","equable","equal",
"equalise","equalitarian","equality","equalize","equally",
"equanimity","equate","equation","equator","equatorial",
"equerry","equestrian","equidistant","equilateral","equilibrium",
"equine","equinoctial","equinox","equip","equipage",
"equipment","equipoise","equitable","equitation","equities",
"equity","equivalence","equivalent","equivocal","equivocate",
"equivocation","era","eradicate","eradicator","erase",
"eraser","erasure","ere","erect","erectile",
"erection","eremite","erg","ergo","ergonomics",
"ermine","erode","erogenous","erosion","erotic",
"erotica","eroticism","err","errand","errant",
"erratic","erratum","erroneous","error","ersatz",
"erse","eructation","erudite","erupt","eruption",
"erysipelas","escalate","escalator","escalope","escapade",
"escape","escapee","escapement","escapism","escapology",
"escarpment","eschatology","eschew","escort","escritoire",
"escutcheon","eskimo","esophagus","esoteric","esp",
"espalier","especial","especially","esperanto","espionage",
"esplanade","espousal","espouse","espresso","espy",
"essay","essence","essential","essentially","establish",
"establishment","estaminet","estate","esteem","esthete",
"esthetic","esthetics","estimable","estimate","estimation",
"estimator","estrange","estrangement","estrogen","estuary",
"etch","etching","eternal","eternity","ether",
"ethereal","ethic","ethical","ethically","ethics",
"ethnic","ethnically","ethnographer","ethnography","ethnologist",
"ethnology","ethos","ethyl","etiolate","etiology",
"etiquette","etymologist","etymology","eucalyptus","eucharist",
"euclidean","euclidian","eugenic","eugenics","eulogise",
"eulogist","eulogistic","eulogize","eulogy","eunuch",
"euphemism","euphemistic","euphonious","euphonium","euphony",
"euphoria","euphuism","eurasian","eureka","eurhythmic",
"eurhythmics","eurocrat","eurodollar","eurythmic","eurythmics",
"euthanasia","evacuate","evacuee","evade","evaluate",
"evanescent","evangelic","evangelical","evangelise","evangelist",
"evangelize","evaporate","evasion","evasive","eve",
"even","evening","evenings","evens","evensong",
"event","eventful","eventide","eventual","eventuality",
"eventually","eventuate","ever","evergreen","everlasting",
"everlastingly","evermore","every","everybody","everyday",
"everything","everywhere","evict","evidence","evident",
"evidently","evil","evildoer","evince","eviscerate",
"evocative","evoke","evolution","evolutionary","evolve",
"ewe","ewer","exacerbate","exact","exacting",
"exaction","exactly","exaggerate","exaggeration","exalt",
"exaltation","exalted","exam","examination","examine",
"example","exasperate","exasperation","excavate","excavation",
"excavator","exceed","exceedingly","excel","excellence",
"excellency","excellent","excelsior","except","excepted",
"excepting","exception","exceptionable","exceptional","excerpt",
"excess","excesses","excessive","exchange","exchequer",
"excise","excision","excitable","excite","excited",
"excitement","exciting","exclaim","exclamation","exclamatory",
"exclude","excluding","exclusion","exclusive","exclusively",
"excogitate","excommunicate","excommunication","excoriate","excrement",
"excrescence","excreta","excrete","excretion","excruciating",
"exculpate","excursion","excursionist","excusable","excuse",
"execrable","execrate","executant","execute","execution",
"executioner","executive","executor","exegesis","exemplary",
"exemplification","exemplify","exempt","exemption","exercise",
"exercises","exert","exertion","exeunt","exhalation",
"exhale","exhaust","exhaustion","exhaustive","exhibit",
"exhibition","exhibitionism","exhibitor","exhilarate","exhilarating",
"exhort","exhortation","exhume","exigency","exigent",
"exiguous","exile","exist","existence","existent",
"existential","existentialism","existing","exit","exodus",
"exogamy","exonerate","exorbitant","exorcise","exorcism",
"exorcist","exorcize","exotic","expand","expanse",
"expansion","expansive","expatiate","expatriate","expect",
"expectancy","expectant","expectation","expectations","expectorate",
"expediency","expedient","expedite","expedition","expeditionary",
"expeditious","expel","expend","expendable","expenditure",
"expense","expenses","expensive","experience","experienced",
"experiment","experimental","experimentation","expert","expertise",
"expiate","expiration","expire","explain","explanation",
"explanatory","expletive","explicable","explicate","explicit",
"explode","exploded","exploit","exploration","exploratory",
"explore","explosion","explosive","expo","exponent",
"exponential","export","exportation","exporter","expose",
"exposition","expostulate","exposure","expound","express",
"expression","expressionism","expressionless","expressive","expressly",
"expressway","expropriate","expulsion","expunge","expurgate",
"exquisite","extant","extemporaneous","extempore","extemporise",
"extemporize","extend","extension","extensive","extent",
"extenuate","extenuation","exterior","exteriorise","exteriorize",
"exterminate","external","externalise","externalize","externally",
"externals","exterritorial","extinct","extinction","extinguish",
"extinguisher","extirpate","extol","extort","extortion",
"extortionate","extortions","extra","extract","extraction",
"extracurricular","extraditable","extradite","extrajudicial","extramarital",
"extramural","extraneous","extraordinarily","extraordinary","extrapolate",
"extraterrestrial","extraterritorial","extravagance","extravagant","extravaganza",
"extravert","extreme","extremely","extremism","extremities",
"extremity","extricate","extrinsic","extrovert","extrude",
"exuberance","exuberant","exude","exult","exultant",
"exultation","eye","eyeball","eyebrow","eyecup",
"eyeful","eyeglass","eyeglasses","eyelash","eyelet",
"eyelid","eyeliner","eyepiece","eyes","eyeshot",
"eyesight","eyesore","eyestrain","eyetooth","eyewash",
"eyewitness","eyot","eyrie","eyry","fabian",
"fable","fabled","fabric","fabricate","fabrication",
"fabulous","fabulously","face","facecloth","faceless",
"facet","facetious","facial","facile","facilitate",
"facilities","facility","facing","facings","facsimile",
"fact","faction","factious","factitious","factor",
"factorial","factorise","factorize","factory","factotum",
"factual","faculty","fad","fade","faeces",
"faerie","faery","fag","fagged","faggot",
"fagot","fahrenheit","faience","fail","failing",
"failure","fain","faint","fair","fairground",
"fairly","fairway","fairy","fairyland","faith",
"faithful","faithfully","faithless","fake","fakir",
"falcon","falconer","falconry","fall","fallacious",
"fallacy","fallen","fallible","fallout","fallow",
"falls","false","falsehood","falsetto","falsies",
"falsify","falsity","falter","fame","famed",
"familial","familiar","familiarise","familiarity","familiarize",
"familiarly","family","famine","famish","famished",
"famous","famously","fan","fanatic","fanaticism",
"fancier","fancies","fanciful","fancy","fancywork",
"fandango","fanfare","fang","fanlight","fanny",
"fantasia","fantastic","fantasy","far","faraway",
"farce","fare","farewell","farfetched","farinaceous",
"farm","farmer","farmhand","farmhouse","farming",
"farmyard","farrago","farrier","farrow","farsighted",
"fart","farther","farthest","farthing","fascia",
"fascinate","fascinating","fascination","fascism","fascist",
"fashion","fashionable","fast","fasten","fastener",
"fastening","fastidious","fastness","fat","fatal",
"fatalism","fatalist","fatality","fatally","fate",
"fated","fateful","fates","fathead","father",
"fatherhood","fatherly","fathom","fathomless","fatigue",
"fatigues","fatless","fatted","fatten","fatty",
"fatuity","fatuous","faucet","fault","faultfinding",
"faultless","faulty","faun","fauna","favor",
"favorable","favored","favorite","favoritism","favour",
"favourable","favoured","favourite","favouritism","favours",
"fawn","fay","faze","fbi","fealty",
"fear","fearful","fearless","fearsome","feasible",
"feast","feat","feather","featherbed","featherbrained",
"featherweight","feathery","feature","featureless","features",
"febrile","february","feces","feckless","fecund",
"fed","federal","federalism","federalist","federate",
"federation","fee","feeble","feebleminded","feed",
"feedback","feedbag","feeder","feel","feeler",
"feeling","feelings","feet","feign","feint",
"feldspar","felicitate","felicitous","felicity","feline",
"fell","fellah","fellatio","fellow","fellowship",
"felon","felony","felspar","felt","felucca",
"fem","female","feminine","femininity","feminism",
"feminist","femur","fen","fence","fencer",
"fencing","fend","fender","fennel","feoff",
"feral","ferment","fermentation","fern","ferocious",
"ferocity","ferret","ferroconcrete","ferrous","ferrule",
"ferry","ferryboat","ferryman","fertile","fertilise",
"fertility","fertilize","fertilizer","ferule","fervent",
"fervid","fervor","fervour","festal","fester",
"festival","festive","festivity","festoon","fetal",
"fetch","fetching","fete","fetid","fetish",
"fetishism","fetishist","fetlock","fetter","fettle",
"fetus","feud","feudal","feudalism","feudatory",
"fever","fevered","feverish","feverishly","few",
"fey","fez","fiasco","fiat","fib",
"fiber","fiberboard","fiberglass","fibre","fibreboard",
"fibreglass","fibrositis","fibrous","fibula","fichu",
"fickle","fiction","fictional","fictionalisation","fictionalization",
"fictitious","fiddle","fiddler","fiddlesticks","fiddling",
"fidelity","fidget","fidgets","fidgety","fie",
"fief","field","fielder","fieldwork","fiend",
"fiendish","fiendishly","fierce","fiery","fiesta",
"fife","fifteen","fifth","fifty","fig",
"fight","fighter","figment","figurative","figure",
"figured","figurehead","figures","figurine","filament",
"filbert","filch","file","filet","filial",
"filibuster","filigree","filings","fill","filler",
"fillet","filling","fillip","filly","film",
"filmable","filmstrip","filmy","filter","filth",
"filthy","fin","finable","final","finale",
"finalise","finalist","finality","finalize","finally",
"finance","finances","financial","financially","financier",
"finch","find","finder","finding","fine",
"fineable","finely","finery","finesse","finger",
"fingerboard","fingering","fingernail","fingerplate","fingerpost",
"fingerprint","fingerstall","fingertip","finicky","finis",
"finish","finished","finite","fink","fiord",
"fir","fire","firearm","fireball","firebomb",
"firebox","firebrand","firebreak","firebrick","firebug",
"fireclay","firecracker","firedamp","firedog","firefly",
"fireguard","firelight","firelighter","fireman","fireplace",
"firepower","fireproof","fireside","firestorm","firetrap",
"firewalking","firewatcher","firewater","firewood","firework",
"fireworks","firkin","firm","firmament","first",
"firstborn","firstfruits","firsthand","firstly","firth",
"firtree","fiscal","fish","fishcake","fisherman",
"fishery","fishing","fishmonger","fishplate","fishwife",
"fishy","fissile","fission","fissionable","fissure",
"fist","fisticuffs","fistula","fit","fitful",
"fitment","fitness","fitted","fitter","fitting",
"five","fiver","fives","fix","fixation",
"fixative","fixed","fixedly","fixity","fixture",
"fizz","fizzle","fizzy","fjord","flabbergast",
"flabby","flaccid","flag","flagellant","flagellate",
"flageolet","flagon","flagpole","flagrancy","flagrant",
"flagship","flagstaff","flagstone","flail","flair",
"flak","flake","flaky","flambeau","flamboyant",
"flame","flamenco","flaming","flamingo","flammable",
"flan","flange","flank","flannel","flannelette",
"flannels","flap","flapjack","flapper","flare",
"flared","flares","flash","flashback","flashbulb",
"flashcube","flasher","flashgun","flashlight","flashy",
"flask","flat","flatcar","flatfish","flatfoot",
"flatiron","flatlet","flatly","flatten","flatter",
"flattery","flattop","flatulence","flaunt","flautist",
"flavor","flavoring","flavour","flavouring","flaw",
"flawless","flax","flaxen","flay","flea",
"fleabag","fleabite","fleapit","fleck","fledged",
"fledgling","flee","fleece","fleecy","fleet",
"fleeting","flesh","fleshings","fleshly","fleshpot",
"fleshy","flew","flex","flexible","flibbertigibbet",
"flick","flicker","flicks","flier","flies",
"flight","flightless","flighty","flimsy","flinch",
"fling","flint","flintlock","flinty","flip",
"flippancy","flippant","flipper","flipping","flirt",
"flirtation","flirtatious","flit","flitch","flivver",
"float","floatation","floating","flock","floe",
"flog","flogging","flood","floodgate","floodlight",
"floor","floorboard","flooring","floorwalker","floosy",
"floozy","flop","floppy","flora","floral",
"floriculture","florid","florin","florist","floss",
"flotation","flotilla","flounce","flounder","flour",
"flourish","flourmill","floury","flout","flow",
"flower","flowerbed","flowered","flowering","flowerless",
"flowerpot","flowery","flowing","flown","flu",
"fluctuate","flue","fluency","fluent","fluff",
"fluffy","fluid","fluidity","fluke","flukey",
"fluky","flume","flummery","flummox","flung",
"flunk","flunkey","flunky","fluorescent","fluoridate",
"fluoride","fluorine","flurry","flush","flushed",
"fluster","flute","fluting","flutist","flutter",
"fluvial","flux","fly","flyaway","flyblown",
"flyby","flycatcher","flyer","flying","flyleaf",
"flyover","flypaper","flypast","flysheet","flyswatter",
"flytrap","flyweight","flywheel","flywhisk","foal",
"foam","fob","focal","focus","fodder",
"foe","foeman","foetal","foetus","fog",
"fogbank","fogbound","fogey","foggy","foghorn",
"fogy","foible","foil","foist","fold",
"foldaway","folder","foliage","folio","folk",
"folklore","folklorist","folks","folksy","folktale",
"folkway","follicle","follow","follower","following",
"folly","foment","fomentation","fond","fondant",
"fondle","fondly","fondu","fondue","font",
"food","foodstuff","fool","foolery","foolhardy",
"foolish","foolproof","foolscap","foot","footage",
"football","footbath","footboard","footbridge","footer",
"footfall","foothill","foothold","footing","footle",
"footlights","footling","footloose","footman","footnote",
"footpad","footpath","footplate","footprint","footrace",
"footsie","footslog","footsore","footstep","footstool",
"footsure","footwear","footwork","fop","foppish",
"for","forage","foray","forbear","forbearance",
"forbearing","forbid","forbidden","forbidding","force",
"forced","forceful","forcemeat","forceps","forces",
"forcible","forcibly","ford","fore","forearm",
"forebode","foreboding","forecast","forecastle","foreclose",
"foreclosure","forecourt","foredoomed","forefather","forefinger",
"forefoot","forefront","forego","foregoing","foreground",
"forehand","forehead","foreign","foreigner","foreknowledge",
"foreland","foreleg","forelock","foreman","foremost",
"forename","forenoon","forensic","foreordain","forepart",
"foreplay","forerunner","foresail","foresee","foreseeable",
"foreshadow","foreshore","foreshorten","foresight","foreskin",
"forest","forestall","forester","forestry","foreswear",
"foretaste","foretell","forethought","forever","forewarn",
"forewent","forewoman","foreword","forfeit","forfeiture",
"forgather","forgave","forge","forger","forgery",
"forget","forgetful","forging","forgivable","forgive",
"forgiveable","forgiveness","forgiving","forgo","fork",
"forked","forkful","forklift","forlorn","form",
"formal","formaldehyde","formalin","formalise","formalism",
"formality","formalize","format","formation","formative",
"formbook","former","formerly","formica","formidable",
"formless","formula","formulaic","formulate","formulation",
"fornicate","fornication","forrader","forsake","forsooth",
"forswear","forsythia","fort","forte","forth",
"forthcoming","forthright","forthwith","fortieth","fortification",
"fortify","fortissimo","fortitude","fortnight","fortnightly",
"fortress","fortuitous","fortunate","fortunately","fortune",
"forty","forum","forward","forwarding","forwardly",
"forwardness","forwent","foss","fosse","fossil",
"fossilise","fossilize","foster","fought","foul",
"found","foundation","foundations","founder","foundling",
"foundry","fount","fountain","fountainhead","four",
"foureyes","fourpenny","fours","foursquare","fourteen",
"fourth","fowl","fox","foxglove","foxhole",
"foxhound","foxhunt","foxtrot","foxy","foyer",
"fracas","fraction","fractional","fractionally","fractious",
"fracture","fragile","fragment","fragmentary","fragmentation",
"fragrance","fragrant","frail","frailty","frame",
"frames","framework","franc","franchise","franciscan",
"frank","frankfurter","frankincense","franklin","frankly",
"frantic","fraternal","fraternise","fraternity","fraternize",
"fratricide","frau","fraud","fraudulence","fraudulent",
"fraught","fraulein","fray","frazzle","freak",
"freakish","freckle","free","freebee","freebie",
"freeboard","freebooter","freeborn","freedman","freedom",
"freehand","freehanded","freehold","freeholder","freelance",
"freeload","freely","freeman","freemason","freemasonry",
"freepost","freesia","freestanding","freestone","freestyle",
"freethinker","freeway","freewheel","freewheeling","freewill",
"freeze","freezer","freezing","freight","freighter",
"freightliner","frenchman","frenetic","frenzied","frenzy",
"frequency","frequent","fresco","fresh","freshen",
"fresher","freshet","freshly","freshwater","fret",
"fretful","fretsaw","fretwork","freudian","friable",
"friar","friary","fricassee","fricative","friction",
"friday","fridge","friend","friendless","friendly",
"friends","friendship","frier","frieze","frig",
"frigate","frigging","fright","frighten","frightened",
"frightful","frightfully","frigid","frigidity","frill",
"frilled","frills","frilly","fringe","frippery",
"frisbee","frisian","frisk","frisky","frisson",
"fritter","frivolity","frivolous","frizz","frizzle",
"frizzy","fro","frock","frog","frogged",
"frogman","frogmarch","frogspawn","frolic","frolicsome",
"from","frond","front","frontage","frontal",
"frontbench","frontier","frontiersman","frontispiece","frost",
"frostbite","frostbitten","frostbound","frosting","frosty",
"froth","frothy","frown","frowst","frowsty",
"frowsy","frowzy","froze","frozen","frs",
"fructification","fructify","frugal","frugality","fruit",
"fruitcake","fruiterer","fruitful","fruition","fruitless",
"fruits","fruity","frump","frustrate","frustration",
"fry","fryer","fuchsia","fuck","fucker",
"fucking","fuddle","fudge","fuehrer","fuel",
"fug","fugitive","fugue","fuhrer","fulcrum",
"fulfil","fulfill","fulfillment","fulfilment","full",
"fullback","fuller","fully","fulmar","fulminate",
"fulmination","fulness","fulsome","fumble","fume",
"fumes","fumigate","fun","function","functional",
"functionalism","functionalist","functionary","fund","fundamental",
"fundamentalism","fundamentally","funds","funeral","funerary",
"funereal","funfair","fungicide","fungoid","fungous",
"fungus","funicular","funk","funky","funnel",
"funnies","funnily","funny","fur","furbelow",
"furbish","furious","furiously","furl","furlong",
"furlough","furnace","furnish","furnishings","furniture",
"furore","furrier","furrow","furry","further",
"furtherance","furthermore","furthermost","furthest","furtive",
"fury","furze","fuse","fused","fuselage",
"fusilier","fusillade","fusion","fuss","fusspot",
"fussy","fustian","fusty","futile","futility",
"future","futureless","futures","futurism","futuristic",
"futurity","fuzz","fuzzy","gab","gabardine",
"gabble","gaberdine","gable","gabled","gad",
"gadabout","gadfly","gadget","gadgetry","gaelic",
"gaff","gaffe","gaffer","gag","gaga",
"gaggle","gaiety","gaily","gain","gainful",
"gainfully","gainsay","gait","gaiter","gal",
"gala","galactic","galantine","galaxy","gale",
"gall","gallant","gallantry","galleon","gallery",
"galley","gallic","gallicism","gallivant","gallon",
"gallop","galloping","gallows","gallstone","galore",
"galosh","galumph","galvanic","galvanise","galvanism",
"galvanize","gambit","gamble","gamboge","gambol",
"game","gamecock","gamekeeper","games","gamesmanship",
"gamey","gamma","gammon","gammy","gamp",
"gamut","gamy","gander","gang","ganger",
"gangling","ganglion","gangplank","gangrene","gangster",
"gangway","gannet","gantry","gaol","gaolbird",
"gaoler","gap","gape","gapes","garage",
"garb","garbage","garble","garden","gardenia",
"gardening","gargantuan","gargle","gargoyle","garish",
"garland","garlic","garment","garner","garnet",
"garnish","garret","garrison","garrote","garrotte",
"garrulity","garrulous","garter","gas","gasbag",
"gaseous","gash","gasholder","gasify","gasket",
"gaslight","gasman","gasolene","gasoline","gasp",
"gassy","gastric","gastritis","gastroenteritis","gastronomy",
"gasworks","gat","gate","gatecrash","gatehouse",
"gatekeeper","gatepost","gateway","gather","gathering",
"gauche","gaucherie","gaucho","gaudy","gauge",
"gaunt","gauntlet","gauze","gave","gavel",
"gavotte","gawk","gawky","gawp","gay",
"gayness","gaze","gazebo","gazelle","gazette",
"gazetteer","gazump","gce","gear","gearbox",
"gecko","gee","geese","geezer","geisha",
"gel","gelatine","gelatinous","geld","gelding",
"gelignite","gem","gemini","gen","gendarme",
"gender","gene","genealogist","genealogy","genera",
"general","generalisation","generalise","generalissimo","generality",
"generalization","generalize","generally","generate","generation",
"generative","generator","generic","generous","genesis",
"genetic","geneticist","genetics","genial","geniality",
"genie","genital","genitals","genitive","genius",
"genocide","genre","gent","genteel","gentian",
"gentile","gentility","gentle","gentlefolk","gentleman",
"gentlemanly","gentlewoman","gently","gentry","gents",
"genuflect","genuine","genus","geocentric","geographer",
"geography","geologist","geology","geometric","geometry",
"geophysics","geopolitics","georgette","geranium","geriatric",
"geriatrician","geriatrics","germ","germane","germanic",
"germicide","germinal","germinate","gerontology","gerrymander",
"gerund","gestalt","gestapo","gestation","gesticulate",
"gesture","get","getaway","getup","geum",
"gewgaw","geyser","gharry","ghastly","ghat",
"ghaut","ghee","gherkin","ghetto","ghi",
"ghost","ghostly","ghoul","ghoulish","ghq",
"ghyll","giant","giantess","gibber","gibberish",
"gibbet","gibbon","gibbous","gibe","giblets",
"giddy","gift","gifted","gig","gigantic",
"giggle","gigolo","gild","gilded","gilding",
"gill","gillie","gilly","gilt","gimcrack",
"gimlet","gimmick","gimmicky","gin","ginger",
"gingerbread","gingerly","gingham","gingivitis","gingko",
"ginkgo","ginseng","gipsy","giraffe","gird",
"girder","girdle","girl","girlfriend","girlhood",
"girlie","girlish","girly","giro","girt",
"girth","gist","give","giveaway","given",
"gizzard","glacial","glacier","glad","gladden",
"glade","gladiator","gladiolus","gladly","glamor",
"glamorise","glamorize","glamorous","glamour","glamourous",
"glance","glancing","gland","glandular","glare",
"glaring","glass","glassblower","glasscutter","glasses",
"glasshouse","glassware","glassworks","glassy","glaucoma",
"glaucous","glaze","glazier","glazing","glc",
"gleam","glean","gleaner","gleanings","glebe",
"glee","gleeful","glen","glengarry","glib",
"glide","glider","gliding","glimmer","glimmerings",
"glimpse","glint","glissade","glissando","glisten",
"glister","glitter","glittering","gloaming","gloat",
"global","globe","globefish","globetrotter","globular",
"globule","glockenspiel","gloom","gloomy","gloria",
"glorification","glorify","glorious","glory","gloss",
"glossary","glossy","glottal","glottis","glove",
"glow","glower","glowing","glucose","glue",
"gluey","glum","glut","gluten","glutinous",
"glutton","gluttonous","gluttony","glycerin","glycerine",
"gnarled","gnash","gnat","gnaw","gnawing",
"gneiss","gnocchi","gnome","gnp","gnu",
"goad","goal","goalkeeper","goalmouth","goalpost",
"goat","goatee","goatherd","goatskin","gob",
"gobbet","gobble","gobbledegook","gobbledygook","gobbler",
"goblet","goblin","god","godchild","goddam",
"goddamn","goddie","godforsaken","godhead","godless",
"godlike","godly","godown","godparent","gods",
"godsend","godspeed","goer","goggle","goggles",
"goings","goiter","goitre","gold","goldbeater",
"golden","goldfield","goldfinch","goldfish","goldmine",
"goldsmith","golf","goliath","golliwog","golly",
"gollywog","gonad","gondola","gondolier","gone",
"goner","gong","gonna","gonorrhea","gonorrhoea",
"goo","good","goodbye","goodish","goodly",
"goodness","goodnight","goods","goodwill","goody",
"gooey","goof","goofy","googly","goon",
"goose","gooseberry","gooseflesh","goosestep","gopher",
"gore","gorge","gorgeous","gorgon","gorgonzola",
"gorilla","gormandise","gormandize","gormless","gorse",
"gory","gosh","gosling","gospel","gossamer",
"gossip","gossipy","got","gothic","gotta",
"gotten","gouache","gouda","gouge","goulash",
"gourd","gourmand","gourmet","gout","gouty",
"govern","governance","governess","governing","government",
"governor","gown","gpo","grab","grace",
"graceful","graceless","graces","gracious","gradation",
"grade","gradient","gradual","graduate","graduation",
"graffiti","graft","grafter","grail","grain",
"gram","grammar","grammarian","grammatical","gramme",
"gramophone","grampus","gran","granary","grand",
"grandad","grandchild","granddad","granddaughter","grandee",
"grandeur","grandfather","grandiloquent","grandiose","grandma",
"grandmother","grandpa","grandparent","grandson","grandstand",
"grange","granite","grannie","granny","grant",
};
}
} | 63.217795 | 99 | 0.578073 | [
"Apache-2.0"
] | 10088/lucenenet | src/Lucene.Net.Analysis.Common/Analysis/En/KStemData3.cs | 47,604 | C# |
using ReactiveUI;
namespace ModernControlsForAvalonia.SampleApp.ViewModels
{
public class MainWindowViewModel : ViewModelBase
{
public MainWindowViewModel()
{
LowerSelected = 25d;
UpperSelected = 75d;
}
public double LowerSelected
{
get => lowerSelected;
set
{
this.RaiseAndSetIfChanged(ref lowerSelected, value);
LowerSelectedStr = lowerSelected.ToString("0.00");
}
}
public double UpperSelected
{
get => upperSelected;
set
{
this.RaiseAndSetIfChanged(ref upperSelected, value);
UpperSelectedStr = upperSelected.ToString("0.00");
}
}
public string? LowerSelectedStr
{
get => lowerSelectedStr;
set => this.RaiseAndSetIfChanged(ref lowerSelectedStr, value);
}
public string? UpperSelectedStr
{
get => upperSelectedStr;
set => this.RaiseAndSetIfChanged(ref upperSelectedStr, value);
}
double lowerSelected;
double upperSelected;
string? lowerSelectedStr;
string? upperSelectedStr;
}
}
| 24.75 | 74 | 0.547009 | [
"MIT"
] | DmitryNizhebovsky/ModernControlsForAvalonia | ModernControlsForAvalonia.SampleApp/ViewModels/MainWindowViewModel.cs | 1,287 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Http;
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;
namespace MyApp
{
// Note: For instructions on enabling IIS6 or IIS7 classic mode,
// visit http://go.microsoft.com/?LinkId=9394801
public class WebApiApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
WebApiConfig.Register(GlobalConfiguration.Configuration);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
}
}
} | 29.037037 | 70 | 0.709184 | [
"MIT"
] | AzureMentor/20487-DevelopingWindowsAzureAndWebServices | Allfiles/20487C/Mod03/Democode/FirstWebApiService/End/MyApp/Global.asax.cs | 786 | C# |
using ReactiveUI;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using UaLayman.ViewModels;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
namespace UaLayman.Views
{
public sealed partial class SettingsView : UserControl, IViewFor<SettingsViewModel>
{
public SettingsViewModel ViewModel
{
get { return (SettingsViewModel)GetValue(ViewModelProperty); }
set { SetValue(ViewModelProperty, value); }
}
// Using a DependencyProperty as the backing store for ViewModel. This enables animation, styling, binding, etc...
public static readonly DependencyProperty ViewModelProperty =
DependencyProperty.Register(nameof(ViewModel), typeof(SettingsViewModel), typeof(SettingsView), new PropertyMetadata(null));
object IViewFor.ViewModel
{
get => ViewModel;
set => ViewModel = (SettingsViewModel)value;
}
public SettingsView()
{
this.InitializeComponent();
}
}
}
| 30.772727 | 136 | 0.704579 | [
"MIT"
] | quinmars/UaLayman | UaLayman/Views/SettingsView.xaml.cs | 1,356 | C# |
namespace System.IO.BACnet
{
public enum BacnetPtpDisconnectReasons : byte
{
PTP_DISCONNECT_NO_MORE_DATA = 0,
PTP_DISCONNECT_PREEMPTED = 1,
PTP_DISCONNECT_INVALID_PASSWORD = 2,
PTP_DISCONNECT_OTHER = 3,
}
} | 25.1 | 49 | 0.673307 | [
"MIT"
] | 355911097/BACnet | Base/BacnetPtpDisconnectReasons.cs | 253 | C# |
using System;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
// 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("AWSSDK.DatabaseMigrationService")]
#if BCL35
[assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (3.5) - AWS Database Migration Service. AWS Database Migration Service (AWS DMS) can migrate your data to and from most widely used commercial and open-source databases such as Oracle, PostgreSQL, Microsoft SQL Server, Amazon Aurora, MariaDB, and MySQL. The service supports homogeneous migrations such as Oracle to Oracle, and also heterogeneous migrations between different database platforms, such as Oracle to MySQL or MySQL to Amazon Aurora.")]
#elif BCL45
[assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (4.5) - AWS Database Migration Service. AWS Database Migration Service (AWS DMS) can migrate your data to and from most widely used commercial and open-source databases such as Oracle, PostgreSQL, Microsoft SQL Server, Amazon Aurora, MariaDB, and MySQL. The service supports homogeneous migrations such as Oracle to Oracle, and also heterogeneous migrations between different database platforms, such as Oracle to MySQL or MySQL to Amazon Aurora.")]
#elif PCL
[assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (PCL) - AWS Database Migration Service. AWS Database Migration Service (AWS DMS) can migrate your data to and from most widely used commercial and open-source databases such as Oracle, PostgreSQL, Microsoft SQL Server, Amazon Aurora, MariaDB, and MySQL. The service supports homogeneous migrations such as Oracle to Oracle, and also heterogeneous migrations between different database platforms, such as Oracle to MySQL or MySQL to Amazon Aurora.")]
#elif UNITY
[assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (Unity) - AWS Database Migration Service. AWS Database Migration Service (AWS DMS) can migrate your data to and from most widely used commercial and open-source databases such as Oracle, PostgreSQL, Microsoft SQL Server, Amazon Aurora, MariaDB, and MySQL. The service supports homogeneous migrations such as Oracle to Oracle, and also heterogeneous migrations between different database platforms, such as Oracle to MySQL or MySQL to Amazon Aurora.")]
#elif CORECLR
[assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (CoreCLR)- AWS Database Migration Service. AWS Database Migration Service (AWS DMS) can migrate your data to and from most widely used commercial and open-source databases such as Oracle, PostgreSQL, Microsoft SQL Server, Amazon Aurora, MariaDB, and MySQL. The service supports homogeneous migrations such as Oracle to Oracle, and also heterogeneous migrations between different database platforms, such as Oracle to MySQL or MySQL to Amazon Aurora.")]
#else
#error Unknown platform constant - unable to set correct AssemblyDescription
#endif
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyProduct("Amazon Web Services SDK for .NET")]
[assembly: AssemblyCompany("Amazon.com, Inc")]
[assembly: AssemblyCopyright("Copyright 2009-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.")]
[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)]
// 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("3.3")]
[assembly: AssemblyFileVersion("3.3.13.1")]
#if WINDOWS_PHONE || UNITY
[assembly: System.CLSCompliant(false)]
# else
[assembly: System.CLSCompliant(true)]
#endif
#if BCL
[assembly: System.Security.AllowPartiallyTrustedCallers]
#endif | 75.122807 | 521 | 0.790051 | [
"Apache-2.0"
] | woellij/aws-sdk-net | sdk/src/Services/DatabaseMigrationService/Properties/AssemblyInfo.cs | 4,282 | C# |
/*
* Bungie.Net API
*
* These endpoints constitute the functionality exposed by Bungie.net, both for more traditional website functionality and for connectivity to Bungie video games and their related functionality.
*
* OpenAPI spec version: 2.1.1
* Contact: support@bungie.com
* Generated by: https://github.com/swagger-api/swagger-codegen.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;
using SwaggerDateConverter = BungieNetPlatform.Client.SwaggerDateConverter;
namespace BungieNetPlatform.Model
{
/// <summary>
/// ForumPollResult
/// </summary>
[DataContract]
public partial class ForumPollResult : IEquatable<ForumPollResult>, IValidatableObject
{
/// <summary>
/// Initializes a new instance of the <see cref="ForumPollResult" /> class.
/// </summary>
/// <param name="AnswerText">AnswerText.</param>
/// <param name="AnswerSlot">AnswerSlot.</param>
/// <param name="LastVoteDate">LastVoteDate.</param>
/// <param name="Votes">Votes.</param>
/// <param name="RequestingUserVoted">RequestingUserVoted.</param>
public ForumPollResult(string AnswerText = default(string), int? AnswerSlot = default(int?), DateTime? LastVoteDate = default(DateTime?), int? Votes = default(int?), bool? RequestingUserVoted = default(bool?))
{
this.AnswerText = AnswerText;
this.AnswerSlot = AnswerSlot;
this.LastVoteDate = LastVoteDate;
this.Votes = Votes;
this.RequestingUserVoted = RequestingUserVoted;
}
/// <summary>
/// Gets or Sets AnswerText
/// </summary>
[DataMember(Name="answerText", EmitDefaultValue=false)]
public string AnswerText { get; set; }
/// <summary>
/// Gets or Sets AnswerSlot
/// </summary>
[DataMember(Name="answerSlot", EmitDefaultValue=false)]
public int? AnswerSlot { get; set; }
/// <summary>
/// Gets or Sets LastVoteDate
/// </summary>
[DataMember(Name="lastVoteDate", EmitDefaultValue=false)]
public DateTime? LastVoteDate { get; set; }
/// <summary>
/// Gets or Sets Votes
/// </summary>
[DataMember(Name="votes", EmitDefaultValue=false)]
public int? Votes { get; set; }
/// <summary>
/// Gets or Sets RequestingUserVoted
/// </summary>
[DataMember(Name="requestingUserVoted", EmitDefaultValue=false)]
public bool? RequestingUserVoted { 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 ForumPollResult {\n");
sb.Append(" AnswerText: ").Append(AnswerText).Append("\n");
sb.Append(" AnswerSlot: ").Append(AnswerSlot).Append("\n");
sb.Append(" LastVoteDate: ").Append(LastVoteDate).Append("\n");
sb.Append(" Votes: ").Append(Votes).Append("\n");
sb.Append(" RequestingUserVoted: ").Append(RequestingUserVoted).Append("\n");
sb.Append("}\n");
return sb.ToString();
}
/// <summary>
/// Returns the JSON string presentation of the object
/// </summary>
/// <returns>JSON string presentation of the object</returns>
public string ToJson()
{
return JsonConvert.SerializeObject(this, Formatting.Indented);
}
/// <summary>
/// Returns true if objects are equal
/// </summary>
/// <param name="input">Object to be compared</param>
/// <returns>Boolean</returns>
public override bool Equals(object input)
{
return this.Equals(input as ForumPollResult);
}
/// <summary>
/// Returns true if ForumPollResult instances are equal
/// </summary>
/// <param name="input">Instance of ForumPollResult to be compared</param>
/// <returns>Boolean</returns>
public bool Equals(ForumPollResult input)
{
if (input == null)
return false;
return
(
this.AnswerText == input.AnswerText ||
(this.AnswerText != null &&
this.AnswerText.Equals(input.AnswerText))
) &&
(
this.AnswerSlot == input.AnswerSlot ||
(this.AnswerSlot != null &&
this.AnswerSlot.Equals(input.AnswerSlot))
) &&
(
this.LastVoteDate == input.LastVoteDate ||
(this.LastVoteDate != null &&
this.LastVoteDate.Equals(input.LastVoteDate))
) &&
(
this.Votes == input.Votes ||
(this.Votes != null &&
this.Votes.Equals(input.Votes))
) &&
(
this.RequestingUserVoted == input.RequestingUserVoted ||
(this.RequestingUserVoted != null &&
this.RequestingUserVoted.Equals(input.RequestingUserVoted))
);
}
/// <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.AnswerText != null)
hashCode = hashCode * 59 + this.AnswerText.GetHashCode();
if (this.AnswerSlot != null)
hashCode = hashCode * 59 + this.AnswerSlot.GetHashCode();
if (this.LastVoteDate != null)
hashCode = hashCode * 59 + this.LastVoteDate.GetHashCode();
if (this.Votes != null)
hashCode = hashCode * 59 + this.Votes.GetHashCode();
if (this.RequestingUserVoted != null)
hashCode = hashCode * 59 + this.RequestingUserVoted.GetHashCode();
return hashCode;
}
}
/// <summary>
/// To validate all properties of the instance
/// </summary>
/// <param name="validationContext">Validation context</param>
/// <returns>Validation Result</returns>
IEnumerable<System.ComponentModel.DataAnnotations.ValidationResult> IValidatableObject.Validate(ValidationContext validationContext)
{
yield break;
}
}
}
| 37.507937 | 217 | 0.563831 | [
"MIT"
] | xlxCLUxlx/BungieNetPlatform | src/BungieNetPlatform/Model/ForumPollResult.cs | 7,089 | C# |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using OfficeWebUI.Common;
using OfficeWebUI.Button;
using System.Web.UI.HtmlControls;
namespace OfficeWebUI
{
[DefaultProperty("Text")]
[ParseChildren(true, "Items")]
[ToolboxData("<{0}:OfficeCombobox runat=server></{0}:OfficeCombobox>")]
public class OfficeCombobox : ControlAncestor, INamingContainer, IPostBackEventHandler
{
#region Private
private Panel _panel;
private Panel _dropDown;
private Panel _selectedItem;
private List<ListItem> _items = new List<ListItem>();
private Unit _width = 200;
private HiddenField _selectedValue;
private HiddenField _selectedText;
#endregion
#region Public
public event EventHandler Click;
[Browsable(true)]
[PersistenceMode(PersistenceMode.InnerProperty)]
public List<ListItem> Items
{
get { return this._items; }
}
[Browsable(true)]
public Unit Width
{
get { return this._width; }
set { this._width = value; }
}
public String SelectedValue
{
get { return this._selectedValue.Value; }
}
public String SelectedText
{
get { return this._selectedText.Value; }
}
#endregion
protected override void OnInit(EventArgs e)
{
if (!HttpContext.Current.Items.Contains("OfficeWebUI_Manager"))
throw new Exception("You must include an OfficeWebUIManager on your page to use OfficeWebUI components");
Page.ClientScript.RegisterClientScriptResource(this.GetType(), "OfficeWebUI.Resources.Common.Javascript.Combobox.js");
PostBackOptions p = new PostBackOptions(this);
this._panel = new Panel();
_panel.ID = this.ID + "_panel";
_panel.CssClass = "OfficeWebUI_Combobox";
_panel.Width = this._width;
this.Controls.Add(_panel);
this._selectedText = new HiddenField();
_selectedText.ID = this.ID + "_selectedText";
_panel.Controls.Add(_selectedText);
this._selectedValue = new HiddenField();
_selectedValue.ID = this.ID + "_selectedValue";
_panel.Controls.Add(_selectedValue);
_panel.Attributes.Add("Internal_SelectedTextID", _selectedText.ClientID);
_panel.Attributes.Add("Internal_SelectedValueID", _selectedValue.ClientID);
this._selectedItem = new Panel();
_selectedItem.CssClass = "OfficeWebUI_Combobox_Selected";
_panel.Controls.Add(_selectedItem);
this._dropDown = new Panel();
_dropDown.ID = this.ID + "_dropdown";
_dropDown.Width = this._width;
_dropDown.CssClass = "OfficeWebUI_Combobox_DropDown";
_panel.Controls.Add(_dropDown);
if (_items.Count != 0)
{
Boolean isFirstSelected = false;
foreach (ListItem lItem in this._items)
{
if ((isFirstSelected == false) && (lItem.Selected))
{
_selectedItem.Controls.Add(new Literal { Text = lItem.Text });
this._selectedValue.Value = lItem.Value;
this._selectedText.Value = lItem.Text;
isFirstSelected = true;
}
Panel lItemPanel = new Panel();
lItemPanel.Attributes.Add("InternalValue", lItem.Value);
lItemPanel.Attributes.Add("InternalText", lItem.Text);
lItemPanel.CssClass = "OfficeWebUI_Combobox_Item";
_dropDown.Controls.Add(lItemPanel);
lItemPanel.Controls.Add(new Literal { Text = lItem.Text });
}
if (!isFirstSelected)
{
_selectedItem.Controls.Add(new Literal { Text = this.Items[0].Text });
this._selectedValue.Value = this.Items[0].Value;
this._selectedText.Value = this.Items[0].Text;
isFirstSelected = true;
}
}
base.OnInit(e);
}
protected override void OnLoad(EventArgs e)
{
if (Page.IsPostBack)
{
foreach (ListItem lItem in this._items)
{
if (lItem.Value == this._selectedValue.Value)
{
_selectedItem.Controls.Clear();
_selectedItem.Controls.Add(new Literal { Text = lItem.Text });
}
}
}
base.OnLoad(e);
}
#region IPostBackEventHandler Membres
public void RaisePostBackEvent(string eventArgument)
{
if (this.Click != null)
{
Click(this, new EventArgs());
}
}
#endregion
}
}
| 30.028409 | 130 | 0.549101 | [
"MIT"
] | cschen1205/myob-accounting-plugin | OfficeWebUI/Combobox/Combobox.cs | 5,285 | C# |
/* License
* --------------------------------------------------------------------------------------------------------------------
* This file is part of the AI4E distribution.
* (https://github.com/AI4E/AI4E.AspNetCore.Components.Extensions)
*
* MIT License
*
* Copyright (c) 2019 Andreas Truetschel and contributors.
*
* 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.
* --------------------------------------------------------------------------------------------------------------------
*/
/* Based on
* --------------------------------------------------------------------------------------------------------------------
* Asp.Net Blazor
* Copyright (c) .NET Foundation. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use
* these files except in compliance with the License. You may obtain a copy of the
* License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed
* under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
* --------------------------------------------------------------------------------------------------------------------
*/
using System;
using System.IO;
using System.Net.Mime;
using AI4E.AspNetCore.Blazor.Server;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.StaticFiles;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.FileProviders;
using Microsoft.Net.Http.Headers;
namespace Microsoft.AspNetCore.Builder
{
public static class ComponentsModuleServerApplicationBuilderExtension
{
public static IApplicationBuilder UseBlazorModule<TProgram>(this IApplicationBuilder applicationBuilder)
{
if (applicationBuilder == null)
throw new ArgumentNullException(nameof(applicationBuilder));
var clientAssemblyInServerBinDir = typeof(TProgram).Assembly;
return applicationBuilder.UseBlazorModule(new BlazorOptions
{
ClientAssemblyPath = clientAssemblyInServerBinDir.Location,
});
}
// TODO: Test whether publishing works correctly.
public static IApplicationBuilder UseBlazorModule(this IApplicationBuilder applicationBuilder, BlazorOptions options)
{
if (applicationBuilder == null)
throw new ArgumentNullException(nameof(applicationBuilder));
if (options == null)
throw new ArgumentNullException(nameof(options));
// TODO
if (options.ClientAssemblyPath is null)
return applicationBuilder;
// TODO: Make the .blazor.config file contents sane
// Currently the items in it are bizarre and don't relate to their purpose,
// hence all the path manipulation here. We shouldn't be hardcoding 'dist' here either.
var env = applicationBuilder.ApplicationServices.GetService<IHostingEnvironment>();
var config = BlazorConfig.Read(options.ClientAssemblyPath);
//if (env.IsDevelopment() && config.EnableAutoRebuilding)
//{
// if (env.ApplicationName.Equals(DevServerApplicationName, StringComparison.OrdinalIgnoreCase))
// {
// app.UseDevServerAutoRebuild(config);
// }
// else
// {
// app.UseHostedAutoRebuild(config, env.ContentRootPath);
// }
//}
// First, match the request against files in the client app dist directory
if (Directory.Exists(config.DistPath))
{
applicationBuilder.UseStaticFiles(new StaticFileOptions
{
FileProvider = new PhysicalFileProvider(config.DistPath),
ContentTypeProvider = CreateContentTypeProvider(config.EnableDebugging),
OnPrepareResponse = CacheHeaderSettings.SetCacheHeaders,
});
}
// * Before publishing, we serve the wwwroot files directly from source
// (and don't require them to be copied into dist).
// In this case, WebRootPath will be nonempty if that directory exists.
// * After publishing, the wwwroot files are already copied to 'dist' and
// will be served by the above middleware, so we do nothing here.
// In this case, WebRootPath will be empty (the publish process sets this).
if (!string.IsNullOrEmpty(config.WebRootPath))
{
applicationBuilder.UseStaticFiles(new StaticFileOptions
{
FileProvider = new PhysicalFileProvider(config.WebRootPath),
OnPrepareResponse = CacheHeaderSettings.SetCacheHeaders,
});
}
return applicationBuilder;
}
private static IContentTypeProvider CreateContentTypeProvider(bool enableDebugging)
{
var result = new FileExtensionContentTypeProvider();
AddMapping(result, ".dll", MediaTypeNames.Application.Octet);
if (enableDebugging)
{
AddMapping(result, ".pdb", MediaTypeNames.Application.Octet);
}
return result;
}
private static void AddMapping(FileExtensionContentTypeProvider provider, string name, string mimeType)
{
if (!provider.Mappings.ContainsKey(name))
{
provider.Mappings.Add(name, mimeType);
}
}
}
internal static class CacheHeaderSettings
{
internal static void SetCacheHeaders(StaticFileResponseContext ctx)
{
// By setting "Cache-Control: no-cache", we're allowing the browser to store
// a cached copy of the response, but telling it that it must check with the
// server for modifications (based on Etag) before using that cached copy.
// Longer term, we should generate URLs based on content hashes (at least
// for published apps) so that the browser doesn't need to make any requests
// for unchanged files.
var headers = ctx.Context.Response.GetTypedHeaders();
if (headers.CacheControl == null)
{
headers.CacheControl = new CacheControlHeaderValue
{
NoCache = true
};
}
}
}
}
| 43.853933 | 125 | 0.610172 | [
"MIT"
] | AI4E/AI4E.AspNetCore.Components.ExtensibleRouter | src/AI4E.AspNetCore.Blazor.Server/ComponentsModuleServerApplicationBuilderExtension.cs | 7,806 | 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("MVC# Tasks Interaction Example")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("www.MVCSharp.org")]
[assembly: AssemblyProduct("MVC# Tasks Interaction Example")]
[assembly: AssemblyCopyright("Copyright © www.MVCSharp.org 2008")]
[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("259057ea-f56a-4ede-9f38-76ff8542f897")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
[assembly: AssemblyVersion("1.0.0.0")]
// Below attribute is to suppress FxCop warning "CA2232 : Microsoft.Usage : Add STAThreadAttribute to assembly"
// as Device app does not support STA thread.
[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2232:MarkWindowsFormsEntryPointsWithStaThread")]
| 41.891892 | 129 | 0.766452 | [
"MIT"
] | zherar7ordoya/AP3 | (CSharp)/3) MVP Pattern/MVCSharp/Examples/TasksInteraction/Presentation/Mobile/Properties/AssemblyInfo.cs | 1,553 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SGBank.Models.Interfaces
{
public interface IAccountRepository
{
Account LoadAccount(string AccountNumber);
void SaveAccount(Account account);
}
}
| 20.2 | 50 | 0.742574 | [
"Apache-2.0"
] | dtalon42/Portfolio | SGBank.UI/SGBank.Models/Interfaces/IAccountRepository.cs | 305 | 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("EncryptionProvider")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("EncryptionProvider")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("bcaa2358-ad9b-4f4d-a35d-fff58962d2ab")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 38.081081 | 84 | 0.747339 | [
"Apache-2.0"
] | Enzogord/My-FyiReporting | EncryptionProvider/Properties/AssemblyInfo.cs | 1,412 | C# |
using System;
namespace PalindromeIntegers
{
class Program
{
static void Main(string[] args)
{
string input = Console.ReadLine();
while (input != "END")
{
Console.WriteLine(isPalindrome(input));
input = Console.ReadLine();
}
}
static bool isPalindrome(string text)
{
for (int i = 0; i < text.Length / 2; i++)
{
if (text[i] != text[text.Length - 1 - i])
{
return false;
}
}
return true;
}
}
}
| 19.818182 | 57 | 0.402141 | [
"MIT"
] | Siaa17/softuni-csharp-modules | CSharp Fundamentals/CSharpFundamentals - Methods - Exercise/PalindromeIntegers/Program.cs | 656 | C# |
using Microsoft.Extensions.Configuration;
using Microsoft.IdentityModel.Tokens;
using YawlUrl.Infrastructure.AspNetCore.Models;
using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;
namespace YawlUrl.Infrastructure.AspNetCore.Authorization
{
public sealed class JwtTokenBuilder
{
private readonly IConfiguration _configuration;
public JwtTokenBuilder(IConfiguration configuration)
{
_configuration = configuration;
}
public async Task<JwtTokenModel> GenerateJwtToken(string email, ApplicationUser user)
{
var claims = new List<Claim>
{
new Claim(JwtRegisteredClaimNames.NameId, user.UserName),
new Claim(JwtRegisteredClaimNames.Email, email),
new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
new Claim(ClaimTypes.Role, string.Join(';', user.Roles)),
new Claim(ClaimTypes.AuthenticationMethod, AuthConstants.AuthenticationSchemes.Bearer),
new Claim(ClaimTypes.Name, user.UserName),
new Claim(ClaimTypes.NameIdentifier, user.Id),
};
var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_configuration["JwtKey"]));
var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
var expires = DateTime.Now.AddDays(Convert.ToDouble(_configuration["JwtExpireDays"]));
var token = new JwtSecurityToken(
_configuration["JwtIssuer"],
_configuration["JwtIssuer"],
claims,
expires: expires,
signingCredentials: creds
);
var jwtToken = new JwtTokenModel
{
Token = new JwtSecurityTokenHandler().WriteToken(token),
ExpireDateTime = expires,
Type = AuthConstants.AuthenticationSchemes.Bearer
};
return await Task.FromResult(jwtToken);
}
}
}
| 36.322034 | 103 | 0.638357 | [
"MIT"
] | PonyUrl/ponyurl | Src/YawlUrl.Infrastructure.AspNetCore/Authorization/JwtTokenBuilder.cs | 2,145 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.17020
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace ColorImageStream.Properties
{
/// <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", "4.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 ((resourceMan == null))
{
global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("ColorImageStream.Properties.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;
}
}
}
}
| 38.736111 | 182 | 0.604518 | [
"MIT"
] | eyantra/CS308_Kinecsterel_2012 | code/Kinect/K4WStepByStep/ColorImageStream/Properties/Resources.Designer.cs | 2,791 | C# |
/*
Exemplary file for Chapter 3 - MVVM and Data Binding.
Recipe: Using value converters with parameters.
*/
using CH03.Models;
using PropertyChanged;
using System.Windows.Input;
namespace CH03.ViewModels
{
[ImplementPropertyChanged]
public class MainViewModel
{
public bool IsPrimaryColor { get; set; } = true;
public ICommand CmdChangeColor { get; set; }
public MainViewModel()
{
CmdChangeColor = new RelayCommand(() => ChangeColor());
}
private void ChangeColor()
{
IsPrimaryColor = !IsPrimaryColor;
}
}
}
| 21.517241 | 67 | 0.621795 | [
"MIT"
] | PacktPublishing/Windows-Application-Development-Cookbook | Chapter 3/03-05 - Using value converters with parameters/MainViewModel.cs | 624 | C# |
namespace NPitayaTest.Tests.Serializer
{
public class ProtobufSerializerTests
{
}
} | 14.857143 | 40 | 0.663462 | [
"MIT"
] | rodopoulos/pitaya-rs | pitaya-sharp/NPitaya.Tests/Tests/Serializer/ProtobufSerializerTests.cs | 104 | C# |
// MIT License - Copyright (C) The Mono.Xna Team
// This file is subject to the terms and conditions defined in
// file 'LICENSE.txt', which is part of this source code package.
using System;
using System.Diagnostics;
using System.Runtime.CompilerServices;
using System.Runtime.Serialization;
using System.Numerics;
namespace Microsoft.Xna.Framework
{
/// <summary>
/// Describes a 2D-point.
/// </summary>
[DataContract]
[DebuggerDisplay("{DebugDisplayString,nq}")]
public struct Point : IEquatable<Point>
{
#region Private Fields
private static readonly Point zeroPoint = new Point();
#endregion
#region Public Fields
/// <summary>
/// The x coordinate of this <see cref="Point"/>.
/// </summary>
[DataMember]
public int X;
/// <summary>
/// The y coordinate of this <see cref="Point"/>.
/// </summary>
[DataMember]
public int Y;
#endregion
#region Properties
/// <summary>
/// Returns a <see cref="Point"/> with coordinates 0, 0.
/// </summary>
public static Point Zero
{
get { return zeroPoint; }
}
#endregion
#region Internal Properties
internal string DebugDisplayString
{
get
{
return string.Concat(
this.X.ToString(), " ",
this.Y.ToString()
);
}
}
#endregion
#region Constructors
/// <summary>
/// Constructs a point with X and Y from two values.
/// </summary>
/// <param name="x">The x coordinate in 2d-space.</param>
/// <param name="y">The y coordinate in 2d-space.</param>
public Point(int x, int y)
{
this.X = x;
this.Y = y;
}
/// <summary>
/// Constructs a point with X and Y set to the same value.
/// </summary>
/// <param name="value">The x and y coordinates in 2d-space.</param>
public Point(int value)
{
this.X = value;
this.Y = value;
}
#endregion
#region Operators
/// <summary>
/// Adds two points.
/// </summary>
/// <param name="value1">Source <see cref="Point"/> on the left of the add sign.</param>
/// <param name="value2">Source <see cref="Point"/> on the right of the add sign.</param>
/// <returns>Sum of the points.</returns>
public static Point operator +(Point value1, Point value2)
{
return new Point(value1.X + value2.X, value1.Y + value2.Y);
}
/// <summary>
/// Subtracts a <see cref="Point"/> from a <see cref="Point"/>.
/// </summary>
/// <param name="value1">Source <see cref="Point"/> on the left of the sub sign.</param>
/// <param name="value2">Source <see cref="Point"/> on the right of the sub sign.</param>
/// <returns>Result of the subtraction.</returns>
public static Point operator -(Point value1, Point value2)
{
return new Point(value1.X - value2.X, value1.Y - value2.Y);
}
/// <summary>
/// Multiplies the components of two points by each other.
/// </summary>
/// <param name="value1">Source <see cref="Point"/> on the left of the mul sign.</param>
/// <param name="value2">Source <see cref="Point"/> on the right of the mul sign.</param>
/// <returns>Result of the multiplication.</returns>
public static Point operator *(Point value1, Point value2)
{
return new Point(value1.X * value2.X, value1.Y * value2.Y);
}
/// <summary>
/// Divides the components of a <see cref="Point"/> by the components of another <see cref="Point"/>.
/// </summary>
/// <param name="source">Source <see cref="Point"/> on the left of the div sign.</param>
/// <param name="divisor">Divisor <see cref="Point"/> on the right of the div sign.</param>
/// <returns>The result of dividing the points.</returns>
public static Point operator /(Point source, Point divisor)
{
return new Point(source.X / divisor.X, source.Y / divisor.Y);
}
/// <summary>
/// Compares whether two <see cref="Point"/> instances are equal.
/// </summary>
/// <param name="a"><see cref="Point"/> instance on the left of the equal sign.</param>
/// <param name="b"><see cref="Point"/> instance on the right of the equal sign.</param>
/// <returns><c>true</c> if the instances are equal; <c>false</c> otherwise.</returns>
public static bool operator ==(Point a, Point b)
{
return a.Equals(b);
}
/// <summary>
/// Compares whether two <see cref="Point"/> instances are not equal.
/// </summary>
/// <param name="a"><see cref="Point"/> instance on the left of the not equal sign.</param>
/// <param name="b"><see cref="Point"/> instance on the right of the not equal sign.</param>
/// <returns><c>true</c> if the instances are not equal; <c>false</c> otherwise.</returns>
public static bool operator !=(Point a, Point b)
{
return !a.Equals(b);
}
#endregion
#region Public methods
/// <summary>
/// Compares whether current instance is equal to specified <see cref="Object"/>.
/// </summary>
/// <param name="obj">The <see cref="Object"/> to compare.</param>
/// <returns><c>true</c> if the instances are equal; <c>false</c> otherwise.</returns>
public override bool Equals(object obj)
{
return (obj is Point) && Equals((Point)obj);
}
/// <summary>
/// Compares whether current instance is equal to specified <see cref="Point"/>.
/// </summary>
/// <param name="other">The <see cref="Point"/> to compare.</param>
/// <returns><c>true</c> if the instances are equal; <c>false</c> otherwise.</returns>
public bool Equals(Point other)
{
return ((X == other.X) && (Y == other.Y));
}
/// <summary>
/// Gets the hash code of this <see cref="Point"/>.
/// </summary>
/// <returns>Hash code of this <see cref="Point"/>.</returns>
public override int GetHashCode()
{
unchecked
{
var hash = 17;
hash = hash * 23 + X.GetHashCode();
hash = hash * 23 + Y.GetHashCode();
return hash;
}
}
/// <summary>
/// Returns a <see cref="String"/> representation of this <see cref="Point"/> in the format:
/// {X:[<see cref="X"/>] Y:[<see cref="Y"/>]}
/// </summary>
/// <returns><see cref="String"/> representation of this <see cref="Point"/>.</returns>
public override string ToString()
{
return "{X:" + X + " Y:" + Y + "}";
}
/// <summary>
/// Gets a <see cref="Vector2"/> representation for this object.
/// </summary>
/// <returns>A <see cref="Vector2"/> representation for this object.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public Vector2 ToVector2()
{
return new Vector2(X, Y);
}
/// <summary>
/// Deconstruction method for <see cref="Point"/>.
/// </summary>
/// <param name="x"></param>
/// <param name="y"></param>
public void Deconstruct(out int x, out int y)
{
x = X;
y = Y;
}
#endregion
}
}
| 33.12605 | 109 | 0.5293 | [
"MIT"
] | Thin2d/Thin2d | MonoGame.Framework/Point.cs | 7,884 | C# |
using Newtonsoft.Json;
namespace Sora.OnebotModel.OnebotEvent.NoticeEvent
{
/// <summary>
/// 好友消息撤回
/// </summary>
internal sealed class OnebotFriendRecallEventArgs : BaseNoticeEventArgs
{
/// <summary>
/// 被撤回的消息 ID
/// </summary>
[JsonProperty(PropertyName = "message_id")]
internal int MessageId { get; set; }
}
} | 23.875 | 75 | 0.60733 | [
"Apache-2.0"
] | RingoStudio/Sora | Sora/OnebotModel/OnebotEvent/NoticeEvent/OnebotFriendRecallEventArgs.cs | 406 | C# |
using System;
using System.Collections.Generic;
using System.Data;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using MySql.Data.MySqlClient;
using MySqlConnector.Logging;
using MySqlConnector.Protocol.Serialization;
using MySqlConnector.Utilities;
namespace MySqlConnector.Core
{
internal sealed class CachedProcedure
{
public static async Task<CachedProcedure> FillAsync(IOBehavior ioBehavior, MySqlConnection connection, string schema, string component, CancellationToken cancellationToken)
{
// try to use mysql.proc first, as it is much faster
if (connection.Session.ServerVersion.Version < ServerVersions.RemovesMySqlProcTable && !connection.Session.ProcAccessDenied)
{
try
{
using (var cmd = connection.CreateCommand())
{
cmd.Transaction = connection.CurrentTransaction;
cmd.CommandText = @"SELECT param_list, returns FROM mysql.proc WHERE db = @schema AND name = @component";
cmd.Parameters.AddWithValue("@schema", schema);
cmd.Parameters.AddWithValue("@component", component);
using (var reader = (MySqlDataReader) await cmd.ExecuteReaderAsync(CommandBehavior.Default, ioBehavior, cancellationToken).ConfigureAwait(false))
{
var exists = await reader.ReadAsync(cancellationToken).ConfigureAwait(false);
if (!exists)
return null;
var parametersSqlBytes = (byte[]) reader.GetValue(0);
var returnsSqlBytes = (byte[]) reader.GetValue(1);
// ASSUME this is UTF-8 encoded; it's possible that the `character_set_client` column would need to be used?
var parametersSql = Encoding.UTF8.GetString(parametersSqlBytes);
var returnsSql = Encoding.UTF8.GetString(returnsSqlBytes);
var parsedParameters = ParseParameters(parametersSql);
if (returnsSql.Length != 0)
{
var returnDataType = ParseDataType(returnsSql, out var unsigned, out var length);
parsedParameters.Insert(0, CreateCachedParameter(0, null, null, returnDataType, unsigned, length, returnsSql));
}
return new CachedProcedure(schema, component, parsedParameters);
}
}
}
catch (MySqlException ex)
{
Log.Warn("Session{0} failed to retrieve metadata for Schema={1} Component={2}; falling back to INFORMATION_SCHEMA. Error: {3}", connection.Session.Id, schema, component, ex.Message);
if ((MySqlErrorCode) ex.Number == MySqlErrorCode.TableAccessDenied)
connection.Session.ProcAccessDenied = true;
}
}
if (connection.Session.ServerVersion.Version < ServerVersions.SupportsProcedureCache)
{
Log.Warn("Session{0} ServerVersion={1} does not support cached procedures", connection.Session.Id, connection.Session.ServerVersion.OriginalString);
return null;
}
var parameters = new List<CachedParameter>();
int routineCount;
using (var cmd = connection.CreateCommand())
{
cmd.Transaction = connection.CurrentTransaction;
cmd.CommandText = @"SELECT COUNT(*)
FROM information_schema.routines
WHERE ROUTINE_SCHEMA = @schema AND ROUTINE_NAME = @component;
SELECT ORDINAL_POSITION, PARAMETER_MODE, PARAMETER_NAME, DATA_TYPE, DTD_IDENTIFIER
FROM information_schema.parameters
WHERE SPECIFIC_SCHEMA = @schema AND SPECIFIC_NAME = @component
ORDER BY ORDINAL_POSITION";
cmd.Parameters.AddWithValue("@schema", schema);
cmd.Parameters.AddWithValue("@component", component);
using (var reader = (MySqlDataReader) await cmd.ExecuteReaderAsync(CommandBehavior.Default, ioBehavior, cancellationToken).ConfigureAwait(false))
{
await reader.ReadAsync(cancellationToken).ConfigureAwait(false);
routineCount = reader.GetInt32(0);
await reader.NextResultAsync(cancellationToken).ConfigureAwait(false);
while (await reader.ReadAsync(cancellationToken).ConfigureAwait(false))
{
parameters.Add(new CachedParameter(
reader.GetInt32(0),
!reader.IsDBNull(1) ? reader.GetString(1) : null,
!reader.IsDBNull(2) ? reader.GetString(2) : null,
reader.GetString(3),
reader.GetString(4).IndexOf("unsigned", StringComparison.OrdinalIgnoreCase) != -1,
0
));
}
}
}
if (Log.IsInfoEnabled())
Log.Info("Procedure for Schema={0} Component={1} has RoutineCount={2}, ParameterCount={3}", schema, component, routineCount, parameters.Count);
return routineCount == 0 ? null : new CachedProcedure(schema, component, parameters);
}
public IReadOnlyList<CachedParameter> Parameters { get; }
private CachedProcedure(string schema, string component, IReadOnlyList<CachedParameter> parameters)
{
m_schema = schema;
m_component = component;
Parameters = parameters;
}
internal MySqlParameterCollection AlignParamsWithDb(MySqlParameterCollection parameterCollection)
{
var alignedParams = new MySqlParameterCollection();
var returnParam = parameterCollection?.FirstOrDefault(x => x.Direction == ParameterDirection.ReturnValue);
foreach (var cachedParam in Parameters)
{
MySqlParameter alignParam;
if (cachedParam.Direction == ParameterDirection.ReturnValue)
{
alignParam = returnParam ?? throw new InvalidOperationException($"Attempt to call stored function {FullyQualified} without specifying a return parameter");
}
else
{
var index = parameterCollection?.NormalizedIndexOf(cachedParam.Name) ?? -1;
alignParam = index >= 0 ? parameterCollection[index] : throw new ArgumentException($"Parameter '{cachedParam.Name}' not found in the collection.");
}
if (!alignParam.HasSetDirection)
alignParam.Direction = cachedParam.Direction;
if (!alignParam.HasSetDbType)
alignParam.MySqlDbType = cachedParam.MySqlDbType;
// cached parameters are oredered by ordinal position
alignedParams.Add(alignParam);
}
return alignedParams;
}
internal static List<CachedParameter> ParseParameters(string parametersSql)
{
// strip comments
parametersSql = Regex.Replace(parametersSql, @"/\*.*?\*/", "", RegexOptions.Singleline);
parametersSql = Regex.Replace(parametersSql, @"(^|\s)--.*?$", "", RegexOptions.Multiline);
// normalize spaces
parametersSql = Regex.Replace(parametersSql, @"\s+", " ");
if (string.IsNullOrWhiteSpace(parametersSql))
return new List<CachedParameter>();
// strip precision specifier containing comma
parametersSql = Regex.Replace(parametersSql, @"(DECIMAL|DEC|FIXED|NUMERIC|FLOAT|DOUBLE PRECISION|DOUBLE|REAL)\s*\(\d+(,\s*\d+)\)", @"$1", RegexOptions.CultureInvariant | RegexOptions.IgnoreCase);
var parameters = parametersSql.Split(',');
var cachedParameters = new List<CachedParameter>(parameters.Length);
for (var i = 0; i < parameters.Length; i++)
{
var parameter = parameters[i].Trim();
var originalString = parameter;
string direction = "IN";
if (parameter.StartsWith("INOUT ", StringComparison.OrdinalIgnoreCase))
{
direction = "INOUT";
parameter = parameter.Substring(6);
}
else if (parameter.StartsWith("OUT ", StringComparison.OrdinalIgnoreCase))
{
direction = "OUT";
parameter = parameter.Substring(4);
}
else if (parameter.StartsWith("IN ", StringComparison.OrdinalIgnoreCase))
{
direction = "IN";
parameter = parameter.Substring(3);
}
var parts = Regex.Match(parameter, @"^(?:`((?:[\u0001-\u005F\u0061-\uFFFF]+|``)+)`|([A-Za-z0-9$_\u0080-\uFFFF]+)) (.*)$");
var name = parts.Groups[1].Success ? parts.Groups[1].Value.Replace("``", "`") : parts.Groups[2].Value;
var dataType = ParseDataType(parts.Groups[3].Value, out var unsigned, out var length);
cachedParameters.Add(CreateCachedParameter(i + 1, direction, name, dataType, unsigned, length, originalString));
}
return cachedParameters;
}
internal static string ParseDataType(string sql, out bool unsigned, out int length)
{
if (sql.EndsWith(" ZEROFILL", StringComparison.OrdinalIgnoreCase))
sql = sql.Substring(0, sql.Length - 9);
unsigned = false;
if (sql.EndsWith(" UNSIGNED", StringComparison.OrdinalIgnoreCase))
{
unsigned = true;
sql = sql.Substring(0, sql.Length - 9);
}
sql = Regex.Replace(sql, " (CHARSET|CHARACTER SET) [A-Za-z0-9_]+", "", RegexOptions.CultureInvariant | RegexOptions.IgnoreCase);
sql = Regex.Replace(sql, " (COLLATE) [A-Za-z0-9_]+", "", RegexOptions.CultureInvariant | RegexOptions.IgnoreCase);
length = 0;
var match = Regex.Match(sql, @"\s*\(\s*(\d+)\s*(?:,\s*\d+\s*)?\)");
if (match.Success)
{
length = int.Parse(match.Groups[1].Value, CultureInfo.InvariantCulture);
sql = Regex.Replace(sql, @"\s*\(\s*\d+\s*(?:,\s*\d+\s*)?\)", "");
}
sql = sql.Trim();
// normalize alternate data type names
if (sql.Equals("BOOL", StringComparison.OrdinalIgnoreCase) || sql.Equals("BOOLEAN", StringComparison.OrdinalIgnoreCase))
{
sql = "TINYINT";
length = 1;
}
else if (sql.Equals("INTEGER", StringComparison.OrdinalIgnoreCase))
{
sql = "INT";
}
else if (sql.Equals("NUMERIC", StringComparison.OrdinalIgnoreCase) || sql.Equals("FIXED", StringComparison.OrdinalIgnoreCase))
{
sql = "DECIMAL";
}
else if (sql.Equals("REAL", StringComparison.OrdinalIgnoreCase) || sql.Equals("DOUBLE PRECISION", StringComparison.OrdinalIgnoreCase))
{
sql = "DOUBLE";
}
else if (sql.Equals("NVARCHAR", StringComparison.OrdinalIgnoreCase) || sql.Equals("CHARACTER VARYING", StringComparison.OrdinalIgnoreCase) || sql.Equals("NATIONAL VARCHAR", StringComparison.OrdinalIgnoreCase))
{
sql = "VARCHAR";
}
else if (sql.Equals("NCHAR", StringComparison.OrdinalIgnoreCase) || sql.Equals("CHARACTER", StringComparison.OrdinalIgnoreCase) || sql.Equals("NATIONAL CHAR", StringComparison.OrdinalIgnoreCase))
{
sql = "CHAR";
}
else if (sql.Equals("CHAR BYTE", StringComparison.OrdinalIgnoreCase))
{
sql = "BINARY";
}
return sql;
}
private static CachedParameter CreateCachedParameter(int ordinal, string direction, string name, string dataType, bool unsigned, int length, string originalSql)
{
try
{
return new CachedParameter(ordinal, direction, name, dataType, unsigned, length);
}
catch (NullReferenceException ex)
{
throw new MySqlException("Failed to parse stored procedure parameter '{0}'; extracted data type was {1}".FormatInvariant(originalSql, dataType), ex);
}
}
string FullyQualified => $"`{m_schema}`.`{m_component}`";
static readonly IMySqlConnectorLogger Log = MySqlConnectorLogManager.CreateLogger(nameof(CachedProcedure));
readonly string m_schema;
readonly string m_component;
}
}
| 39.273723 | 212 | 0.708298 | [
"MIT"
] | datatechnology/MySqlConnector | src/MySqlConnector/Core/CachedProcedure.cs | 10,761 | 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.Threading;
namespace Microsoft.VisualStudio.IntegrationTest.Utilities.Input
{
public class SendKeys : AbstractSendKeys
{
private readonly VisualStudioInstance _visualStudioInstance;
public SendKeys(VisualStudioInstance visualStudioInstance)
{
_visualStudioInstance = visualStudioInstance;
}
protected override void ActivateMainWindow()
{
_visualStudioInstance.ActivateMainWindow();
}
protected override void WaitForApplicationIdle(CancellationToken cancellationToken)
{
_visualStudioInstance.WaitForApplicationIdle(cancellationToken);
}
}
}
| 31.444444 | 161 | 0.711425 | [
"Apache-2.0"
] | 20chan/roslyn | src/VisualStudio/IntegrationTest/TestUtilities/Input/SendKeys.cs | 851 | C# |
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
namespace GDGeek
{
public class VoxelRemoveSameVertices
{
private struct Pack
{
public int index;
public VoxelDrawData.Vertice vertice;
public Pack(int i, VoxelDrawData.Vertice v){
index = i;
vertice = v;
}
}
public void build(VoxelProduct.Product main){
var draw = main.draw;
List<VoxelDrawData.Vertice> vertices = draw.vertices;
List<int> triangles = draw.triangles;
List<VoxelDrawData.Vertice> tVertices = new List<VoxelDrawData.Vertice>();
Dictionary<Vector3, Pack> board = new Dictionary<Vector3, Pack>();
List<Pack> temp = new List<Pack> ();
List<int> tTriangles = new List<int>();
Dictionary<int, int> ht = new Dictionary<int, int>();
List<Pack> all = new List<Pack> ();
for(int i =0; i<vertices.Count; ++i){
all.Add (new Pack (i, vertices [i]));
}
while (all.Count != 0) {
for (int i = 0; i < all.Count; ++i) {
if (board.ContainsKey (all [i].vertice.position)) {
Pack ver = board [all[i].vertice.position];
if (ver.vertice.color != all [i].vertice.color || ver.vertice.normal != all [i].vertice.normal) {
temp.Add (all [i]);
} else {
ht [all [i].index] = ht[ver.index];
}
} else {
board [all [i].vertice.position] = all[i];
tVertices.Add (all[i].vertice);
ht [all [i].index] = tVertices.Count - 1;
}
}
board.Clear ();
all = temp;
temp = new List<Pack> ();
}
for(int i = 0; i<triangles.Count; ++i){
int oldIndex = triangles[i];
int newIndex = ht[oldIndex];
tTriangles.Add(newIndex);
}
main.draw.triangles = tTriangles;
main.draw.vertices = tVertices;
}
public void build(VoxelProduct product){
if (product.sub != null) {
for (int i = 0; i < product.sub.Length; ++i) {
build (product.sub [i]);
}
} else {
build (product.main);
}
}
}
} | 19.979798 | 103 | 0.599596 | [
"MIT"
] | gdgeek/GDGeek | Assets/GDGeek/Plugins/Voxel/Mesh/Builder/VoxelRemoveSameVertices.cs | 1,978 | C# |
// c:\program files (x86)\windows kits\10\include\10.0.18362.0\um\dshowasf.h(202,5)
using System;
using System.Runtime.InteropServices;
using REFERENCE_TIME = System.Int64;
namespace DirectN
{
[Guid("b25b8372-d2d2-44b2-8653-1b8dae332489"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
public partial interface IAMWMBufferPassCallback
{
[PreserveSig]
HRESULT Notify(/* [in] __RPC__in_opt */ INSSBuffer3 pNSSBuffer3, /* [in] __RPC__in_opt */ IPin pPin, /* [in] __RPC__in */ ref REFERENCE_TIME prtStart, /* [in] __RPC__in */ ref REFERENCE_TIME prtEnd);
}
}
| 39.733333 | 207 | 0.72651 | [
"MIT"
] | bbday/DirectN | DirectN/DirectN/Generated/IAMWMBufferPassCallback.cs | 598 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using LinqToDB.Extensions;
namespace LinqToDB.Mapping
{
/// <summary>
/// Fluent mapping entity builder.
/// </summary>
/// <typeparam name="T">Entity mapping type.</typeparam>
public class EntityMappingBuilder<T>
{
#region Init
/// <summary>
/// Creates enity mapping builder.
/// </summary>
/// <param name="builder">Fluent mapping builder.</param>
/// <param name="configuration">Optional mapping schema configuration name, for which this entity builder should be taken into account.
/// <see cref="ProviderName"/> for standard configuration names.</param>
public EntityMappingBuilder([JetBrains.Annotations.NotNull] FluentMappingBuilder builder, string configuration)
{
_builder = builder ?? throw new ArgumentNullException(nameof(builder));
Configuration = configuration;
// We'll reset cache here, because there is no need to create builder if you don't want to change something
_builder.MappingSchema.ResetEntityDescriptor(typeof(T));
}
readonly FluentMappingBuilder _builder;
/// <summary>
/// Gets mapping schema configuration name, for which this entity builder should be taken into account.
/// <see cref="ProviderName"/> for standard configuration names.
/// </summary>
public string Configuration { get; }
#endregion
#region GetAttributes
/// <summary>
/// Returns attributes of specified type, applied to current entity type.
/// </summary>
/// <typeparam name="TA">Attribute type.</typeparam>
/// <returns>Returns list of attributes, applied to current entity type.</returns>
public TA[] GetAttributes<TA>()
where TA : Attribute
{
return _builder.GetAttributes<TA>(typeof(T));
}
/// <summary>
/// Returns attributes of specified type, applied to specified entity type.
/// </summary>
/// <typeparam name="TA">Attribute type.</typeparam>
/// <param name="type">Entity type.</param>
/// <returns>Returns list of attributes, applied to specified entity type.</returns>
public TA[] GetAttributes<TA>(Type type)
where TA : Attribute
{
return _builder.GetAttributes<TA>(type);
}
/// <summary>
/// Returns attributes of specified type, applied to specified entity member.
/// Member could be inherited from parent classes.
/// </summary>
/// <typeparam name="TA">Attribute type.</typeparam>
/// <param name="memberInfo">Member info object.</param>
/// <returns>Returns list of attributes, applied to specified entity member.</returns>
public TA[] GetAttributes<TA>(MemberInfo memberInfo)
where TA : Attribute
{
return _builder.GetAttributes<TA>(typeof(T), memberInfo);
}
/// <summary>
/// Returns attributes of specified type, applied to current entity type and active for current configuration.
/// </summary>
/// <typeparam name="TA">Attribute type.</typeparam>
/// <param name="configGetter">Function to extract configuration name from attribute instance.</param>
/// <returns>Returns list of attributes.</returns>
public TA[] GetAttributes<TA>(Func<TA,string> configGetter)
where TA : Attribute
{
var attrs = GetAttributes<TA>();
return string.IsNullOrEmpty(Configuration) ?
attrs.Where(a => string.IsNullOrEmpty(configGetter(a))).ToArray() :
attrs.Where(a => Configuration == configGetter(a)). ToArray();
}
/// <summary>
/// Returns attributes of specified type, applied to specified entity type and active for current configuration.
/// </summary>
/// <typeparam name="TA">Attribute type.</typeparam>
/// <param name="type">Entity type.</param>
/// <param name="configGetter">Function to extract configuration name from attribute instance.</param>
/// <returns>Returns list of attributes.</returns>
public TA[] GetAttributes<TA>(Type type, Func<TA,string> configGetter)
where TA : Attribute
{
var attrs = GetAttributes<TA>(type);
return string.IsNullOrEmpty(Configuration) ?
attrs.Where(a => string.IsNullOrEmpty(configGetter(a))).ToArray() :
attrs.Where(a => Configuration == configGetter(a)). ToArray();
}
/// <summary>
/// Returns attributes of specified type, applied to specified entity member and active for current configuration.
/// </summary>
/// <typeparam name="TA">Attribute type.</typeparam>
/// <param name="memberInfo">Member info object.</param>
/// <param name="configGetter">Function to extract configuration name from attribute instance.</param>
/// <returns>Returns list of attributes.</returns>
public TA[] GetAttributes<TA>(MemberInfo memberInfo, Func<TA,string> configGetter)
where TA : Attribute
{
var attrs = GetAttributes<TA>(memberInfo);
return string.IsNullOrEmpty(Configuration) ?
attrs.Where(a => string.IsNullOrEmpty(configGetter(a))).ToArray() :
attrs.Where(a => Configuration == configGetter(a)). ToArray();
}
#endregion
#region HasAttribute
/// <summary>
/// Adds mapping attribute to current entity.
/// </summary>
/// <param name="attribute">Mapping attribute to add.</param>
/// <returns>Returns current fluent entity mapping builder.</returns>
public EntityMappingBuilder<T> HasAttribute(Attribute attribute)
{
_builder.HasAttribute(typeof(T), attribute);
return this;
}
/// <summary>
/// Adds mapping attribute to specified member.
/// </summary>
/// <param name="memberInfo">Target member.</param>
/// <param name="attribute">Mapping attribute to add to specified member.</param>
/// <returns>Returns current fluent entity mapping builder.</returns>
public EntityMappingBuilder<T> HasAttribute(MemberInfo memberInfo, Attribute attribute)
{
_builder.HasAttribute(memberInfo, attribute);
return this;
}
/// <summary>
/// Adds mapping attribute to a member, specified using lambda expression.
/// </summary>
/// <param name="func">Target member, specified using lambda expression.</param>
/// <param name="attribute">Mapping attribute to add to specified member.</param>
/// <returns>Returns current fluent entity mapping builder.</returns>
public EntityMappingBuilder<T> HasAttribute(LambdaExpression func, Attribute attribute)
{
_builder.HasAttribute(func, attribute);
return this;
}
/// <summary>
/// Adds mapping attribute to a member, specified using lambda expression.
/// </summary>
/// <param name="func">Target member, specified using lambda expression.</param>
/// <param name="attribute">Mapping attribute to add to specified member.</param>
/// <returns>Returns current fluent entity mapping builder.</returns>
public EntityMappingBuilder<T> HasAttribute(Expression<Func<T,object>> func, Attribute attribute)
{
_builder.HasAttribute(func, attribute);
return this;
}
#endregion
/// <summary>
/// Creates entity builder for specified mapping type.
/// </summary>
/// <typeparam name="TE">Mapping type.</typeparam>
/// <param name="configuration">Optional mapping schema configuration name, for which this entity builder should be taken into account.
/// <see cref="ProviderName"/> for standard configuration names.</param>
/// <returns>Returns new fluent entity mapping builder.</returns>
public EntityMappingBuilder<TE> Entity<TE>(string configuration = null)
{
return _builder.Entity<TE>(configuration);
}
/// <summary>
/// Adds column mapping to current entity.
/// </summary>
/// <param name="func">Column mapping property or field getter expression.</param>
/// <returns>Returns fluent property mapping builder.</returns>
public PropertyMappingBuilder<T> Property(Expression<Func<T,object>> func)
{
return (new PropertyMappingBuilder<T>(this, func)).IsColumn();
}
/// <summary>
/// Adds association mapping to current entity.
/// </summary>
/// <typeparam name="S">Association member type.</typeparam>
/// <typeparam name="ID1">This association side key type.</typeparam>
/// <typeparam name="ID2">Other association side key type.</typeparam>
/// <param name="prop">Association member getter expression.</param>
/// <param name="thisKey">This association key getter expression.</param>
/// <param name="otherKey">Other association key getter expression.</param>
/// <param name="canBeNull">Defines type of join. True - left join, False - inner join.</param>
/// <returns>Returns fluent property mapping builder.</returns>
public PropertyMappingBuilder<T> Association<S, ID1, ID2>(
[JetBrains.Annotations.NotNull] Expression<Func<T, S>> prop,
[JetBrains.Annotations.NotNull] Expression<Func<T, ID1>> thisKey,
[JetBrains.Annotations.NotNull] Expression<Func<S, ID2>> otherKey,
bool canBeNull = true)
{
if (prop == null) throw new ArgumentNullException(nameof(prop));
if (thisKey == null) throw new ArgumentNullException(nameof(thisKey));
if (otherKey == null) throw new ArgumentNullException(nameof(otherKey));
var thisKeyName = ((MemberExpression)thisKey.Body).Member.Name;
var otherKeyName = ((MemberExpression)otherKey.Body).Member.Name;
var objProp = Expression.Lambda<Func<T, object>>(Expression.Convert(prop.Body, typeof(object)), prop.Parameters );
return Property( objProp ).HasAttribute( new AssociationAttribute { ThisKey = thisKeyName, OtherKey = otherKeyName, CanBeNull = canBeNull } );
}
/// <summary>
/// Adds one-to-many association mapping to current entity.
/// </summary>
/// <typeparam name="TOther">Other association side type</typeparam>
/// <param name="prop">Association member getter expression.</param>
/// <param name="predicate">Predicate expresssion.</param>
/// <param name="canBeNull">Defines type of join. True - left join, False - inner join.</param>
/// <returns>Returns fluent property mapping builder.</returns>
public PropertyMappingBuilder<T> Association<TOther>(
[JetBrains.Annotations.NotNull] Expression<Func<T, IEnumerable<TOther>>> prop,
[JetBrains.Annotations.NotNull] Expression<Func<T, TOther, bool>> predicate,
bool canBeNull = true)
{
if (prop == null) throw new ArgumentNullException(nameof(prop));
if (predicate == null) throw new ArgumentNullException(nameof(predicate));
var objProp = Expression.Lambda<Func<T, object>>(Expression.Convert(prop.Body, typeof(object)), prop.Parameters );
return Property( objProp ).HasAttribute( new AssociationAttribute { Predicate = predicate, CanBeNull = canBeNull, Relationship = Relationship.OneToMany } );
}
/// <summary>
/// Adds one-to-one association mapping to current entity.
/// </summary>
/// <typeparam name="TOther">Other association side type</typeparam>
/// <param name="prop">Association member getter expression.</param>
/// <param name="predicate">Predicate expresssion</param>
/// <param name="canBeNull">Defines type of join. True - left join, False - inner join.</param>
/// <returns>Returns fluent property mapping builder.</returns>
public PropertyMappingBuilder<T> Association<TOther>(
[JetBrains.Annotations.NotNull] Expression<Func<T, TOther>> prop,
[JetBrains.Annotations.NotNull] Expression<Func<T, TOther, bool>> predicate,
bool canBeNull = true)
{
if (prop == null) throw new ArgumentNullException(nameof(prop));
if (predicate == null) throw new ArgumentNullException(nameof(predicate));
var objProp = Expression.Lambda<Func<T, object>>(Expression.Convert(prop.Body, typeof(object)), prop.Parameters );
return Property( objProp ).HasAttribute( new AssociationAttribute { Predicate = predicate, CanBeNull = canBeNull } );
}
/// <summary>
/// Adds primary key mapping to current entity.
/// </summary>
/// <param name="func">Primary key getter expression.</param>
/// <param name="order">Primary key field order.
/// When multiple fields specified by getter expression, fields will be ordered from first menthioned
/// field to last one starting from provided order with step <c>1</c>.</param>
/// <returns>Returns current fluent entity mapping builder.</returns>
public EntityMappingBuilder<T> HasPrimaryKey(Expression<Func<T,object>> func, int order = -1)
{
var n = 0;
return SetAttribute(
func,
true,
m => new PrimaryKeyAttribute(Configuration, order + n++ + (m && order == -1 ? 1 : 0)),
(m,a) => a.Order = order + n++ + (m && order == -1 ? 1 : 0),
a => a.Configuration);
}
/// <summary>
/// Adds identity column mappping to current entity.
/// </summary>
/// <param name="func">Identity field getter expression.</param>
/// <returns>Returns current fluent entity mapping builder.</returns>
public EntityMappingBuilder<T> HasIdentity(Expression<Func<T,object>> func)
{
return SetAttribute(
func,
false,
_ => new IdentityAttribute(Configuration),
(_,a) => {},
a => a.Configuration);
}
// TODO: V2 - remove unused parameters
/// <summary>
/// Adds column mapping to current entity.
/// </summary>
/// <param name="func">Column member getter expression.</param>
/// <param name="order">Unused.</param>
/// <returns>Returns current fluent entity mapping builder.</returns>
public EntityMappingBuilder<T> HasColumn(Expression<Func<T,object>> func, int order = -1)
{
return SetAttribute(
func,
true,
_ => new ColumnAttribute(Configuration),
(_,a) => a.IsColumn = true,
a => a.Configuration);
}
// TODO: V2 - remove unused parameters
/// <summary>
/// Instruct LINQ to DB to not incude specified member into mapping.
/// </summary>
/// <param name="func">Member getter expression.</param>
/// <param name="order">Unused.</param>
/// <returns>Returns current fluent entity mapping builder.</returns>
public EntityMappingBuilder<T> Ignore(Expression<Func<T,object>> func, int order = -1)
{
return SetAttribute(
func,
true,
_ => new NotColumnAttribute { Configuration = Configuration },
(_,a) => a.IsColumn = false,
a => a.Configuration);
}
/// <summary>
/// Sets database table name for current entity.
/// </summary>
/// <param name="tableName">Table name.</param>
/// <returns>Returns current fluent entity mapping builder.</returns>
public EntityMappingBuilder<T> HasTableName(string tableName)
{
return SetTable(a => a.Name = tableName);
}
/// <summary>
/// Sets database schema/owner name for current entity, to override default name.
/// See <see cref="LinqExtensions.SchemaName{T}(ITable{T}, string)"/> method for support information per provider.
/// </summary>
/// <param name="schemaName">Schema/owner name.</param>
/// <returns>Returns current fluent entity mapping builder.</returns>
public EntityMappingBuilder<T> HasSchemaName(string schemaName)
{
return SetTable(a => a.Schema = schemaName);
}
/// <summary>
/// Sets database name, to override default database name.
/// See <see cref="LinqExtensions.DatabaseName{T}(ITable{T}, string)"/> method for support information per provider.
/// </summary>
/// <param name="databaseName">Database name.</param>
/// <returns>Returns current fluent entity mapping builder.</returns>
public EntityMappingBuilder<T> HasDatabaseName(string databaseName)
{
return SetTable(a => a.Database = databaseName);
}
/// <summary>
/// Adds inheritance mapping for specified discriminator value.
/// </summary>
/// <typeparam name="S">Discriminator value type.</typeparam>
/// <param name="key">Discriminator member getter expression.</param>
/// <param name="value">Discriminator value.</param>
/// <param name="type">Mapping type, used with specified discriminator value.</param>
/// <param name="isDefault">If <c>true</c>, current mapping type used by default.</param>
/// <returns>Returns current fluent entity mapping builder.</returns>
public EntityMappingBuilder<T> Inheritance<S>(Expression<Func<T, S>> key, S value, Type type, bool isDefault = false)
{
HasAttribute(new InheritanceMappingAttribute {Code = value, Type = type, IsDefault = isDefault});
var objProp = Expression.Lambda<Func<T, object>>(Expression.Convert(key.Body, typeof(object)), key.Parameters);
Property(objProp).IsDiscriminator();
return this;
}
EntityMappingBuilder<T> SetTable(Action<TableAttribute> setColumn)
{
return SetAttribute(
() =>
{
var a = new TableAttribute { Configuration = Configuration, IsColumnAttributeRequired = false };
setColumn(a);
return a;
},
setColumn,
a => a.Configuration,
a => new TableAttribute
{
Configuration = a.Configuration,
Name = a.Name,
Schema = a.Schema,
Database = a.Database,
IsColumnAttributeRequired = a.IsColumnAttributeRequired,
});
}
EntityMappingBuilder<T> SetAttribute<TA>(
Func<TA> getNew,
Action<TA> modifyExisting,
Func<TA,string> configGetter,
Func<TA,TA> overrideAttribute)
where TA : Attribute
{
var attrs = GetAttributes(typeof(T), configGetter);
if (attrs.Length == 0)
{
var attr = _builder.MappingSchema.GetAttribute(typeof(T), configGetter);
if (attr != null)
{
var na = overrideAttribute(attr);
modifyExisting(na);
_builder.HasAttribute(typeof(T), na);
return this;
}
_builder.HasAttribute(typeof(T), getNew());
}
else
modifyExisting(attrs[0]);
return this;
}
internal EntityMappingBuilder<T> SetAttribute<TA>(
Expression<Func<T,object>> func,
bool processNewExpression,
Func<bool,TA> getNew,
Action<bool,TA> modifyExisting,
Func<TA,string> configGetter,
Func<TA,TA> overrideAttribute = null,
Func<IEnumerable<TA>, TA> existingGetter = null
)
where TA : Attribute
{
var ex = func.Body;
if (ex is UnaryExpression)
ex = ((UnaryExpression)ex).Operand;
if (existingGetter == null)
existingGetter = GetExisting;
Action<Expression,bool> setAttr = (e,m) =>
{
var memberInfo =
e is MemberExpression ? ((MemberExpression) e).Member :
e is MethodCallExpression ? ((MethodCallExpression)e).Method : null;
if (e is MemberExpression && memberInfo.ReflectedTypeEx() != typeof(T))
memberInfo = typeof(T).GetMemberEx(memberInfo);
if (memberInfo == null)
throw new ArgumentException($"'{e}' cant be converted to a class member.");
var attr = existingGetter(GetAttributes(memberInfo, configGetter));
if (attr == null)
{
if (overrideAttribute != null)
{
attr = existingGetter(_builder.MappingSchema.GetAttributes(typeof(T), memberInfo, configGetter));
if (attr != null)
{
var na = overrideAttribute(attr);
modifyExisting(m, na);
_builder.HasAttribute(memberInfo, na);
return;
}
}
_builder.HasAttribute(memberInfo, getNew(m));
}
else
modifyExisting(m, attr);
};
if (processNewExpression && ex.NodeType == ExpressionType.New)
{
var nex = (NewExpression)ex;
if (nex.Arguments.Count > 0)
{
foreach (var arg in nex.Arguments)
setAttr(arg, true);
return this;
}
}
setAttr(ex, false);
return this;
}
private TA GetExisting<TA>(IEnumerable<TA> attrs)
where TA : Attribute
{
return attrs.FirstOrDefault();
}
}
}
| 38.045283 | 160 | 0.663063 | [
"MIT"
] | Arithmomaniac/linq2db | Source/LinqToDB/Mapping/EntityMappingBuilder.cs | 20,166 | C# |
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Web;
namespace NuGetGallery
{
public static class UriExtensions
{
private static string ExternalLinkAnchorTagFormat = $"<a href=\"{{1}}\" target=\"_blank\">{{0}}</a>";
public static string ToEncodedUrlStringOrNull(this Uri uri)
{
if (uri == null)
{
return null;
}
return uri.AbsoluteUri;
}
public static bool IsHttpsProtocol(this Uri uri)
{
return uri.Scheme == Uri.UriSchemeHttps;
}
public static bool IsHttpProtocol(this Uri uri)
{
return uri.Scheme == Uri.UriSchemeHttp;
}
public static bool IsGitProtocol(this Uri uri)
{
return uri.Scheme == ServicesConstants.GitRepository;
}
public static bool IsDomainWithHttpsSupport(this Uri uri)
{
return IsGitHubUri(uri) || IsGitHubPagerUri(uri) || IsCodeplexUri(uri) || IsMicrosoftUri(uri);
}
public static bool IsGitHubUri(this Uri uri)
{
return string.Equals(uri.Host, "www.github.com", StringComparison.OrdinalIgnoreCase) ||
string.Equals(uri.Host, "github.com", StringComparison.OrdinalIgnoreCase);
}
private static bool IsGitHubPagerUri(this Uri uri)
{
return uri.Authority.EndsWith(".github.com", StringComparison.OrdinalIgnoreCase) ||
uri.Authority.EndsWith(".github.io", StringComparison.OrdinalIgnoreCase);
}
private static bool IsCodeplexUri(this Uri uri)
{
return uri.IsInDomain("codeplex.com");
}
private static bool IsMicrosoftUri(this Uri uri)
{
return uri.IsInDomain("microsoft.com") ||
uri.IsInDomain("asp.net") ||
uri.IsInDomain("msdn.com") ||
string.Equals(uri.Authority, "aka.ms", StringComparison.OrdinalIgnoreCase) ||
string.Equals(uri.Authority, "www.mono-project.com", StringComparison.OrdinalIgnoreCase);
}
private static bool IsInDomain(this Uri uri, string domain)
{
return uri.Authority.EndsWith("." + domain, StringComparison.OrdinalIgnoreCase) ||
string.Equals(uri.Authority, domain, StringComparison.OrdinalIgnoreCase);
}
public static Uri ToHttps(this Uri uri)
{
var uriBuilder = new UriBuilder(uri);
uriBuilder.Scheme = Uri.UriSchemeHttps;
uriBuilder.Port = -1;
return uriBuilder.Uri;
}
public static string AppendQueryStringToRelativeUri(string relativeUrl, IReadOnlyCollection<KeyValuePair<string, string>> queryStringCollection)
{
var tempUri = new Uri("http://www.nuget.org/");
var builder = new UriBuilder(new Uri(tempUri, relativeUrl));
var query = HttpUtility.ParseQueryString(builder.Query);
foreach (var pair in queryStringCollection)
{
query[pair.Key] = pair.Value;
}
builder.Query = query.ToString();
return builder.Uri.PathAndQuery;
}
public static Uri AppendPathToUri(this Uri uri, string pathToAppend, string queryString = null)
{
var builder = new UriBuilder(uri);
builder.Path = builder.Path.TrimEnd('/') + "/" + pathToAppend.TrimStart('/');
if (!string.IsNullOrEmpty(queryString))
{
builder.Query = queryString;
}
return builder.Uri;
}
public static string GetExternalUrlAnchorTag(string data, string link)
{
return string.Format(ExternalLinkAnchorTagFormat, data, link);
}
}
} | 35.104348 | 152 | 0.596235 | [
"Apache-2.0"
] | 304NotModified/NuGetGallery | src/NuGetGallery.Services/Extensions/UriExtensions.cs | 4,039 | C# |
using System;
namespace Caracal.EventBus {
public class Event {
public Guid CorrelationId { get; set; }
public Event() : this(Guid.NewGuid()){}
public Event(Guid correlationId) => CorrelationId = correlationId;
}
public class Event<TData>: Event {
public Event(){ }
public Event(Guid correlationId): base(correlationId) {}
public TData Data { get; set; }
}
} | 23.210526 | 74 | 0.596372 | [
"MIT"
] | Caracal-IT/pay-station | src/Source/Caracal.EventBus/Event.cs | 441 | C# |
namespace MC65SnipeIT
{
partial class StickerLocation
{
/// <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.locationBox = new System.Windows.Forms.ComboBox();
this.KeyStatusInfo = new System.Windows.Forms.Label();
this.PrintBtn = new System.Windows.Forms.Button();
this.ExitBtn = new System.Windows.Forms.Button();
this.SaveBtn = new System.Windows.Forms.Button();
this.GenerateBtn = new System.Windows.Forms.Button();
this.IDText = new System.Windows.Forms.Label();
this.picBarcode = new System.Windows.Forms.PictureBox();
this.NameText = new System.Windows.Forms.Label();
this.panel1 = new System.Windows.Forms.Panel();
this.panel1.SuspendLayout();
this.SuspendLayout();
//
// locationBox
//
this.locationBox.Location = new System.Drawing.Point(39, 12);
this.locationBox.Name = "locationBox";
this.locationBox.Size = new System.Drawing.Size(274, 41);
this.locationBox.TabIndex = 16;
//
// KeyStatusInfo
//
this.KeyStatusInfo.Font = new System.Drawing.Font("Tahoma", 6F, System.Drawing.FontStyle.Regular);
this.KeyStatusInfo.Location = new System.Drawing.Point(10, 570);
this.KeyStatusInfo.Name = "KeyStatusInfo";
this.KeyStatusInfo.Size = new System.Drawing.Size(477, 20);
this.KeyStatusInfo.Text = "Keyboard Shortcuts Disabled! - Use the keypad for data entry!";
this.KeyStatusInfo.TextAlign = System.Drawing.ContentAlignment.TopRight;
//
// PrintBtn
//
this.PrintBtn.Enabled = false;
this.PrintBtn.Location = new System.Drawing.Point(319, 540);
this.PrintBtn.Name = "PrintBtn";
this.PrintBtn.Size = new System.Drawing.Size(144, 30);
this.PrintBtn.TabIndex = 15;
this.PrintBtn.TabStop = false;
this.PrintBtn.Text = "Print";
this.PrintBtn.Visible = false;
this.PrintBtn.Click += new System.EventHandler(this.PrintBtn_Click);
//
// ExitBtn
//
this.ExitBtn.Location = new System.Drawing.Point(77, 540);
this.ExitBtn.Name = "ExitBtn";
this.ExitBtn.Size = new System.Drawing.Size(144, 30);
this.ExitBtn.TabIndex = 14;
this.ExitBtn.Text = "Exit";
this.ExitBtn.Click += new System.EventHandler(this.ExitBtn_Click);
//
// SaveBtn
//
this.SaveBtn.Enabled = false;
this.SaveBtn.Location = new System.Drawing.Point(250, 540);
this.SaveBtn.Name = "SaveBtn";
this.SaveBtn.Size = new System.Drawing.Size(144, 30);
this.SaveBtn.TabIndex = 13;
this.SaveBtn.Text = "Save";
this.SaveBtn.Click += new System.EventHandler(this.SaveBtn_Click);
//
// GenerateBtn
//
this.GenerateBtn.Location = new System.Drawing.Point(319, 13);
this.GenerateBtn.Name = "GenerateBtn";
this.GenerateBtn.Size = new System.Drawing.Size(144, 40);
this.GenerateBtn.TabIndex = 12;
this.GenerateBtn.Text = "Generate";
this.GenerateBtn.Click += new System.EventHandler(this.GenerateBtn_Click);
//
// IDText
//
this.IDText.Location = new System.Drawing.Point(7, 417);
this.IDText.Name = "IDText";
this.IDText.Size = new System.Drawing.Size(398, 40);
this.IDText.Text = "ID";
this.IDText.TextAlign = System.Drawing.ContentAlignment.TopCenter;
//
// picBarcode
//
this.picBarcode.Location = new System.Drawing.Point(53, 9);
this.picBarcode.Name = "picBarcode";
this.picBarcode.Size = new System.Drawing.Size(309, 309);
this.picBarcode.SizeMode = System.Windows.Forms.PictureBoxSizeMode.StretchImage;
//
// NameText
//
this.NameText.Font = new System.Drawing.Font("Tahoma", 8F, System.Drawing.FontStyle.Bold);
this.NameText.Location = new System.Drawing.Point(7, 304);
this.NameText.Name = "NameText";
this.NameText.Size = new System.Drawing.Size(398, 38);
this.NameText.Text = "Name of the Location";
this.NameText.TextAlign = System.Drawing.ContentAlignment.TopCenter;
//
// panel1
//
this.panel1.Controls.Add(this.IDText);
this.panel1.Controls.Add(this.NameText);
this.panel1.Controls.Add(this.picBarcode);
this.panel1.Location = new System.Drawing.Point(36, 62);
this.panel1.Name = "panel1";
this.panel1.Size = new System.Drawing.Size(404, 472);
//
// StickerLocation
//
this.AutoScaleDimensions = new System.Drawing.SizeF(192F, 192F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Dpi;
this.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(240)))), ((int)(((byte)(187)))), ((int)(((byte)(213)))));
this.ClientSize = new System.Drawing.Size(480, 588);
this.Controls.Add(this.locationBox);
this.Controls.Add(this.KeyStatusInfo);
this.Controls.Add(this.PrintBtn);
this.Controls.Add(this.ExitBtn);
this.Controls.Add(this.SaveBtn);
this.Controls.Add(this.GenerateBtn);
this.Controls.Add(this.panel1);
this.Location = new System.Drawing.Point(0, 52);
this.Name = "StickerLocation";
this.Text = "ELW - Loc Sticker Gen";
this.panel1.ResumeLayout(false);
this.ResumeLayout(false);
}
#endregion
private System.Windows.Forms.ComboBox locationBox;
private System.Windows.Forms.Label KeyStatusInfo;
private System.Windows.Forms.Button PrintBtn;
private System.Windows.Forms.Button ExitBtn;
private System.Windows.Forms.Button SaveBtn;
private System.Windows.Forms.Button GenerateBtn;
private System.Windows.Forms.Label IDText;
private System.Windows.Forms.PictureBox picBarcode;
private System.Windows.Forms.Label NameText;
private System.Windows.Forms.Panel panel1;
}
} | 45.184524 | 132 | 0.563957 | [
"Apache-2.0",
"MIT"
] | yaymuffins/EmilyLittleWarehouse | MC65SnipeIT/StickerLocation.Designer.cs | 7,593 | C# |
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using Microsoft.MixedReality.Toolkit.Utilities;
using System.Collections;
using System.Collections.Generic;
using Unity.Profiling;
using UnityEngine;
namespace Microsoft.MixedReality.Toolkit.CameraSystem
{
/// <summary>
/// The Camera system controls the settings of the main camera.
/// </summary>
[HelpURL("https://docs.microsoft.com/windows/mixed-reality/mrtk-unity/configuration/mixed-reality-configuration-guide#camera")]
public class MixedRealityCameraSystem : BaseDataProviderAccessCoreSystem, IMixedRealityCameraSystem
{
/// <summary>
/// Constructor.
/// </summary>
/// <param name="registrar">The <see cref="IMixedRealityServiceRegistrar"/> instance that loaded the service.</param>
/// <param name="profile">The configuration profile for the service.</param>
[System.Obsolete("This constructor is obsolete (registrar parameter is no longer required) and will be removed in a future version of the Microsoft Mixed Reality Toolkit.")]
public MixedRealityCameraSystem(
IMixedRealityServiceRegistrar registrar,
BaseMixedRealityProfile profile = null) : this(profile)
{
Registrar = registrar;
}
/// <summary>
/// Constructor.
/// </summary>
/// <param name="registrar">The <see cref="IMixedRealityServiceRegistrar"/> instance that loaded the service.</param>
/// <param name="profile">The configuration profile for the service.</param>
public MixedRealityCameraSystem(
BaseMixedRealityProfile profile = null) : base(profile)
{ }
/// <inheritdoc/>
public override string Name { get; protected set; } = "Mixed Reality Camera System";
/// <inheritdoc/>
public bool IsOpaque
{
get
{
currentDisplayType = DisplayType.Opaque;
IReadOnlyList<IMixedRealityCameraSettingsProvider> dataProviders = GetDataProviders<IMixedRealityCameraSettingsProvider>();
if (dataProviders.Count > 0)
{
// Takes the first settings provider's setting.
if (!dataProviders[0].IsOpaque)
{
currentDisplayType = DisplayType.Transparent;
}
}
#if UNITY_WSA
else
{
Debug.LogWarning("Windows Mixed Reality specific camera code has been moved into Windows Mixed Reality Camera Settings. Please ensure you have this added under your Camera System's Settings Providers, as this deprecated code path may be removed in a future update.");
#if !UNITY_2020_1_OR_NEWER
// Ensure compatibility with the pre-2019.3 XR architecture for customers / platforms
// with legacy requirements.
#pragma warning disable 0618
if (!UnityEngine.XR.WSA.HolographicSettings.IsDisplayOpaque)
{
currentDisplayType = DisplayType.Transparent;
}
#pragma warning restore 0618
#endif // !UNITY_2020_1_OR_NEWER
}
#endif
return currentDisplayType == DisplayType.Opaque;
}
}
/// <inheritdoc />
public uint SourceId { get; } = 0;
/// <inheritdoc />
public string SourceName { get; } = "Mixed Reality Camera System";
/// <inheritdoc/>
public MixedRealityCameraProfile CameraProfile => ConfigurationProfile as MixedRealityCameraProfile;
private DisplayType currentDisplayType;
private bool cameraOpaqueLastFrame = false;
/// <summary>
/// Specifies whether or not the camera system was able to register a camera settings provider.
/// If so, camera management is not to be performed by the camera system itself. If not, the camera
/// system is to behave as it did in MRTK versions 2.0.0 and 2.1.0.
/// </summary>
private bool useFallbackBehavior = true;
/// <inheritdoc />
public override void Initialize()
{
base.Initialize();
MixedRealityCameraProfile profile = ConfigurationProfile as MixedRealityCameraProfile;
var cameraSettingProviders = GetDataProviders<IMixedRealityCameraSettingsProvider>();
if ((cameraSettingProviders.Count == 0) && (profile != null))
{
// Register the settings providers.
for (int i = 0; i < profile.SettingsConfigurations.Length; i++)
{
MixedRealityCameraSettingsConfiguration configuration = profile.SettingsConfigurations[i];
if (configuration.ComponentType?.Type == null)
{
// Incomplete configuration, do not try to register until a type is set in the profile.
continue;
}
object[] args = { this, configuration.ComponentName, configuration.Priority, configuration.SettingsProfile };
if (RegisterDataProvider<IMixedRealityCameraSettingsProvider>(
configuration.ComponentType.Type,
configuration.ComponentName,
configuration.RuntimePlatform,
args))
{
// Apply the display settings
IMixedRealityCameraSettingsProvider provider = GetDataProvider<IMixedRealityCameraSettingsProvider>(configuration.ComponentName);
provider?.ApplyConfiguration();
// if a camera settings provider was applied, then we will not use the fallback behavior
useFallbackBehavior = false;
}
}
}
if (useFallbackBehavior)
{
cameraOpaqueLastFrame = IsOpaque;
if (IsOpaque)
{
ApplySettingsForOpaqueDisplay();
}
else
{
ApplySettingsForTransparentDisplay();
}
// Ensure the camera is parented to the playspace which starts, unrotated, at the origin.
MixedRealityPlayspace.Position = Vector3.zero;
MixedRealityPlayspace.Rotation = Quaternion.identity;
if (CameraCache.Main.transform.position != Vector3.zero)
{
Debug.LogWarning($"The main camera is not positioned at the origin ({Vector3.zero}), experiences may not behave as expected.");
}
if (CameraCache.Main.transform.rotation != Quaternion.identity)
{
Debug.LogWarning($"The main camera is configured with a non-zero rotation, experiences may not behave as expected.");
}
}
}
/// <inheritdoc />
public override void Enable()
{
base.Enable();
IReadOnlyList<IMixedRealityCameraSettingsProvider> providers = GetDataProviders<IMixedRealityCameraSettingsProvider>();
for (int i = 0; i < providers.Count; i++)
{
providers[i].Enable();
}
}
/// <inheritdoc />
public override void Disable()
{
IReadOnlyList<IMixedRealityCameraSettingsProvider> providers = GetDataProviders<IMixedRealityCameraSettingsProvider>();
for (int i = 0; i < providers.Count; i++)
{
providers[i].Disable();
}
base.Disable();
}
/// <inheritdoc />
public override void Destroy()
{
foreach (var provider in GetDataProviders<IMixedRealityCameraSettingsProvider>())
{
UnregisterDataProvider(provider);
}
useFallbackBehavior = true;
base.Destroy();
}
private static readonly ProfilerMarker UpdatePerfMarker = new ProfilerMarker("[MRTK] MixedRealityCameraSystem.Update");
/// <inheritdoc />
public override void Update()
{
if (!useFallbackBehavior) { return; }
using (UpdatePerfMarker.Auto())
{
base.Update();
if (IsOpaque != cameraOpaqueLastFrame)
{
cameraOpaqueLastFrame = IsOpaque;
if (IsOpaque)
{
ApplySettingsForOpaqueDisplay();
}
else
{
ApplySettingsForTransparentDisplay();
}
}
}
}
private static readonly ProfilerMarker ApplySettingsForOpaquePerfMarker = new ProfilerMarker("[MRTK] MixedRealityCameraSystem.ApplySettingsForOpaqueDisplay");
/// <summary>
/// Applies opaque settings from camera profile.
/// </summary>
private void ApplySettingsForOpaqueDisplay()
{
using (ApplySettingsForOpaquePerfMarker.Auto())
{
CameraCache.Main.clearFlags = CameraProfile.CameraClearFlagsOpaqueDisplay;
CameraCache.Main.nearClipPlane = CameraProfile.NearClipPlaneOpaqueDisplay;
CameraCache.Main.farClipPlane = CameraProfile.FarClipPlaneOpaqueDisplay;
CameraCache.Main.backgroundColor = CameraProfile.BackgroundColorOpaqueDisplay;
QualitySettings.SetQualityLevel(CameraProfile.OpaqueQualityLevel, false);
}
}
private static readonly ProfilerMarker ApplySettingsForTransparentPerfMarker = new ProfilerMarker("[MRTK] MixedRealityCameraSystem.ApplySettingsForTransparentDisplay");
/// <summary>
/// Applies transparent settings from camera profile.
/// </summary>
private void ApplySettingsForTransparentDisplay()
{
using (ApplySettingsForTransparentPerfMarker.Auto())
{
CameraCache.Main.clearFlags = CameraProfile.CameraClearFlagsTransparentDisplay;
CameraCache.Main.backgroundColor = CameraProfile.BackgroundColorTransparentDisplay;
CameraCache.Main.nearClipPlane = CameraProfile.NearClipPlaneTransparentDisplay;
CameraCache.Main.farClipPlane = CameraProfile.FarClipPlaneTransparentDisplay;
QualitySettings.SetQualityLevel(CameraProfile.TransparentQualityLevel, false);
}
}
/// <inheritdoc />
bool IEqualityComparer.Equals(object x, object y)
{
// There shouldn't be other Camera Systems to compare to.
return false;
}
/// <inheritdoc />
int IEqualityComparer.GetHashCode(object obj)
{
return Mathf.Abs(SourceName.GetHashCode());
}
}
}
| 40.003584 | 287 | 0.58794 | [
"MIT"
] | AdsyArena/ARbot | Assets/MRTK/Services/CameraSystem/MixedRealityCameraSystem.cs | 11,163 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace CprBroker.Web.Controls {
public partial class ConfigPropertyGridEditor {
/// <summary>
/// grd control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.GridView grd;
}
}
| 30.96 | 84 | 0.471576 | [
"MPL-2.0",
"MPL-2.0-no-copyleft-exception"
] | OS2CPRbroker/CPRbroker | PART/Source/CprBroker/Web/Pages/Controls/ConfigPropertyGridEditor.ascx.designer.cs | 776 | C# |
using UnityEngine;
public class AudioController : MonoBehaviour
{
public AudioSource gameAudioSource;
public AudioSource palyerAudioSource;
public bool muteOnStart;
public bool mute
{
get;
private set;
}
void Start()
{
if (!muteOnStart) return;
ToggleMute();
}
// Update is called once per frame
void Update()
{
// Mutes-Unmutes the sound from this object each time the user presses space.
if (Input.GetKeyDown(KeyCode.Space))
{
ToggleMute();
}
}
private void ToggleMute()
{
mute = !mute;
if (gameAudioSource != null)
{
gameAudioSource.mute = mute;
}
if (palyerAudioSource != null)
{
palyerAudioSource.mute = mute;
}
}
}
| 19.25 | 85 | 0.547816 | [
"MIT"
] | ApiO/Steroid | Assets/Scripts/AudioController.cs | 849 | C# |
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
namespace cn.vimfung.luascriptcore
{
/// <summary>
/// Lua方法
/// </summary>
public class LuaFunction : LuaBaseObject
{
private LuaContext _context;
/// <summary>
/// 初始化
/// </summary>
/// <param name="decoder">对象解码器</param>
public LuaFunction (LuaObjectDecoder decoder)
: base(decoder)
{
int contextId = decoder.readInt32 ();
_context = LuaContext.getContext (contextId);
luaObjectId = decoder.readString ();
}
/// <summary>
/// 序列化对象
/// </summary>
/// <param name="encoder">对象编码器.</param>
public override void serialization(LuaObjectEncoder encoder)
{
base.serialization (encoder);
encoder.writeInt32 (_context.objectId);
encoder.writeString (luaObjectId);
}
/// <summary>
/// 调用
/// </summary>
/// <param name="arguments">Arguments.</param>
public LuaValue invoke(List<LuaValue> arguments)
{
IntPtr funcPtr = IntPtr.Zero;
IntPtr argsPtr = IntPtr.Zero;
IntPtr resultPtr = IntPtr.Zero;
LuaObjectEncoder funcEncoder = new LuaObjectEncoder ();
funcEncoder.writeObject (this);
byte[] bytes = funcEncoder.bytes;
funcPtr = Marshal.AllocHGlobal (bytes.Length);
Marshal.Copy (bytes, 0, funcPtr, bytes.Length);
if (arguments != null)
{
LuaObjectEncoder argEncoder = new LuaObjectEncoder ();
argEncoder.writeInt32 (arguments.Count);
foreach (LuaValue value in arguments)
{
argEncoder.writeObject (value);
}
bytes = argEncoder.bytes;
argsPtr = Marshal.AllocHGlobal (bytes.Length);
Marshal.Copy (bytes, 0, argsPtr, bytes.Length);
}
int size = NativeUtils.invokeLuaFunction (_context.objectId, funcPtr, argsPtr, out resultPtr);
if (argsPtr != IntPtr.Zero)
{
Marshal.FreeHGlobal (argsPtr);
}
if (funcPtr != IntPtr.Zero)
{
Marshal.FreeHGlobal (funcPtr);
}
if (size > 0)
{
return LuaObjectDecoder.DecodeObject (resultPtr, size) as LuaValue;
}
return new LuaValue ();
}
}
}
| 22.744444 | 97 | 0.670738 | [
"Apache-2.0"
] | Gandaa/LuaScriptCore | Source/Unity3D/UnityProject/Assets/Plugins/LuaScriptCore/LuaFunction.cs | 2,093 | C# |
#nullable enable
using System;
using System.IO;
using Core2D.Model;
using Core2D.Model.Renderer;
using Core2D.Modules.Renderer.PdfSharp;
using Core2D.ViewModels;
using Core2D.ViewModels.Containers;
using Core2D.ViewModels.Data;
namespace Core2D.Modules.FileWriter.PdfSharp;
public sealed class PdfSharpWriter : IFileWriter
{
private readonly IServiceProvider? _serviceProvider;
public PdfSharpWriter(IServiceProvider? serviceProvider)
{
_serviceProvider = serviceProvider;
}
public string Name { get; } = "Pdf (PdfSharp)";
public string Extension { get; } = "pdf";
public void Save(Stream stream, object? item, object? options)
{
if (item is null)
{
return;
}
var ic = options as IImageCache;
if (options is null)
{
return;
}
IProjectExporter exporter = new PdfSharpRenderer(_serviceProvider);
IShapeRenderer renderer = (IShapeRenderer)exporter;
renderer.State.DrawShapeState = ShapeStateFlags.Printable;
renderer.State.ImageCache = ic;
if (item is PageContainerViewModel page)
{
var dataFlow = _serviceProvider.GetService<DataFlow>();
var db = (object)page.Properties;
var record = (object)page.Record;
dataFlow.Bind(page.Template, db, record);
dataFlow.Bind(page, db, record);
exporter.Save(stream, page);
}
else if (item is DocumentContainerViewModel document)
{
var dataFlow = _serviceProvider.GetService<DataFlow>();
dataFlow.Bind(document);
exporter.Save(stream, document);
}
else if (item is ProjectContainerViewModel project)
{
var dataFlow = _serviceProvider.GetService<DataFlow>();
dataFlow.Bind(project);
exporter.Save(stream, project);
}
}
} | 26.60274 | 75 | 0.631308 | [
"MIT"
] | wieslawsoltes/Core2D | src/Core2D/Modules/FileWriter.PdfSharp/PdfSharpWriter.cs | 1,944 | 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/d3d11.h in the Windows SDK for Windows 10.0.19041.0
// Original source is Copyright © Microsoft. All rights reserved.
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
namespace TerraFX.Interop
{
[Guid("DC8E63F3-D12B-4952-B47B-5E45026A862D")]
[NativeTypeName("struct ID3D11Resource : ID3D11DeviceChild")]
public unsafe partial struct ID3D11Resource
{
public void** lpVtbl;
[MethodImpl(MethodImplOptions.AggressiveInlining)]
[return: NativeTypeName("HRESULT")]
public int QueryInterface([NativeTypeName("const IID &")] Guid* riid, [NativeTypeName("void **")] void** ppvObject)
{
return ((delegate* stdcall<ID3D11Resource*, Guid*, void**, int>)(lpVtbl[0]))((ID3D11Resource*)Unsafe.AsPointer(ref this), riid, ppvObject);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
[return: NativeTypeName("ULONG")]
public uint AddRef()
{
return ((delegate* stdcall<ID3D11Resource*, uint>)(lpVtbl[1]))((ID3D11Resource*)Unsafe.AsPointer(ref this));
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
[return: NativeTypeName("ULONG")]
public uint Release()
{
return ((delegate* stdcall<ID3D11Resource*, uint>)(lpVtbl[2]))((ID3D11Resource*)Unsafe.AsPointer(ref this));
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void GetDevice([NativeTypeName("ID3D11Device **")] ID3D11Device** ppDevice)
{
((delegate* stdcall<ID3D11Resource*, ID3D11Device**, void>)(lpVtbl[3]))((ID3D11Resource*)Unsafe.AsPointer(ref this), ppDevice);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
[return: NativeTypeName("HRESULT")]
public int GetPrivateData([NativeTypeName("const GUID &")] Guid* guid, [NativeTypeName("UINT *")] uint* pDataSize, [NativeTypeName("void *")] void* pData)
{
return ((delegate* stdcall<ID3D11Resource*, Guid*, uint*, void*, int>)(lpVtbl[4]))((ID3D11Resource*)Unsafe.AsPointer(ref this), guid, pDataSize, pData);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
[return: NativeTypeName("HRESULT")]
public int SetPrivateData([NativeTypeName("const GUID &")] Guid* guid, [NativeTypeName("UINT")] uint DataSize, [NativeTypeName("const void *")] void* pData)
{
return ((delegate* stdcall<ID3D11Resource*, Guid*, uint, void*, int>)(lpVtbl[5]))((ID3D11Resource*)Unsafe.AsPointer(ref this), guid, DataSize, pData);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
[return: NativeTypeName("HRESULT")]
public int SetPrivateDataInterface([NativeTypeName("const GUID &")] Guid* guid, [NativeTypeName("const IUnknown *")] IUnknown* pData)
{
return ((delegate* stdcall<ID3D11Resource*, Guid*, IUnknown*, int>)(lpVtbl[6]))((ID3D11Resource*)Unsafe.AsPointer(ref this), guid, pData);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void GetType([NativeTypeName("D3D11_RESOURCE_DIMENSION *")] D3D11_RESOURCE_DIMENSION* pResourceDimension)
{
((delegate* stdcall<ID3D11Resource*, D3D11_RESOURCE_DIMENSION*, void>)(lpVtbl[7]))((ID3D11Resource*)Unsafe.AsPointer(ref this), pResourceDimension);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void SetEvictionPriority([NativeTypeName("UINT")] uint EvictionPriority)
{
((delegate* stdcall<ID3D11Resource*, uint, void>)(lpVtbl[8]))((ID3D11Resource*)Unsafe.AsPointer(ref this), EvictionPriority);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
[return: NativeTypeName("UINT")]
public uint GetEvictionPriority()
{
return ((delegate* stdcall<ID3D11Resource*, uint>)(lpVtbl[9]))((ID3D11Resource*)Unsafe.AsPointer(ref this));
}
}
}
| 48.162791 | 164 | 0.671173 | [
"MIT"
] | Ethereal77/terrafx.interop.windows | sources/Interop/Windows/um/d3d11/ID3D11Resource.cs | 4,144 | C# |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TeleSharp.TL;
namespace TeleSharp.TL
{
[TLObject(922273905)]
public class TLDocumentEmpty : TLAbsDocument
{
public override int Constructor
{
get
{
return 922273905;
}
}
public long Id { get; set; }
public void ComputeFlags()
{
}
public override void DeserializeBody(BinaryReader br)
{
Id = br.ReadInt64();
}
public override void SerializeBody(BinaryWriter bw)
{
bw.Write(Constructor);
bw.Write(Id);
}
}
}
| 17.697674 | 61 | 0.549277 | [
"MIT"
] | Vladimir-Novick/TLSharp.NetCore2 | TeleSharp.NetCore2.TL/TL/TLDocumentEmpty.cs | 761 | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.