content stringlengths 5 1.04M | avg_line_length float64 1.75 12.9k | max_line_length int64 2 244k | alphanum_fraction float64 0 0.98 | licenses list | repository_name stringlengths 7 92 | path stringlengths 3 249 | size int64 5 1.04M | lang stringclasses 2 values |
|---|---|---|---|---|---|---|---|---|
using System.Text;
using System.Collections.Generic;
using System.Runtime.Serialization;
namespace Cisco.DnaCenter.Api.Data
{
/// <summary>
/// VlanListResult
/// </summary>
[DataContract]
public class VlanListResult
{
/// <summary>
/// Initializes a new instance of the <see cref="VlanListResult" /> class.
/// </summary>
/// <param name="Response">Response.</param>
/// <param name="_Version">_Version.</param>
public VlanListResult(List<VlanListResultResponse> Response = default, string? _Version = default)
{
this.Response = Response;
this._Version = _Version;
}
/// <summary>
/// Gets or Sets Response
/// </summary>
[DataMember(Name = "response", EmitDefaultValue = false)]
public List<VlanListResultResponse> Response { get; set; }
/// <summary>
/// Gets or Sets _Version
/// </summary>
[DataMember(Name = "version", EmitDefaultValue = false)]
public string? _Version { 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 VlanListResult {\n");
sb.Append(" Response: ").Append(Response).Append("\n");
sb.Append(" _Version: ").Append(_Version).Append("\n");
sb.Append("}\n");
return sb.ToString();
}
}
}
| 26.980392 | 100 | 0.663517 | [
"MIT"
] | panoramicdata/Cisco.DnaCenter.Api | Cisco.DnaCenter.Api/Data/VlanListResult.cs | 1,376 | C# |
using DDaikore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace DDaikontin
{
public class InputMappings
{
public readonly int enterKey;
public readonly int upArrowKey;
public readonly int downArrowKey;
public readonly int leftArrowKey;
public readonly int rightArrowKey;
public readonly int wKey;
public readonly int sKey;
public readonly int aKey;
public readonly int dKey;
public readonly int spaceKey;
public readonly int escapeKey;
public readonly int shiftKey;
protected Core core;
public InputMappings(Core core)
{
this.core = core;
enterKey = core.RegisterInput(Keys.Enter);
upArrowKey = core.RegisterInput(Keys.Up);
downArrowKey = core.RegisterInput(Keys.Down);
leftArrowKey = core.RegisterInput(Keys.Left);
rightArrowKey = core.RegisterInput(Keys.Right);
wKey = core.RegisterInput(Keys.W);
sKey = core.RegisterInput(Keys.S);
aKey = core.RegisterInput(Keys.A);
dKey = core.RegisterInput(Keys.D);
spaceKey = core.RegisterInput(Keys.Space);
escapeKey = core.RegisterInput(Keys.Escape);
shiftKey = core.RegisterInput(Keys.LShiftKey);
}
//TODO: Clone so you can access networked player's most recent known input states
public InputState GetState(int inputIndex)
{
return core.GetInputState(inputIndex);
}
}
}
| 32 | 89 | 0.635216 | [
"MIT"
] | ChaseMelvin/DDaikore | DDaikontin/InputMappings.cs | 1,666 | C# |
// *** WARNING: this file was generated by the Pulumi SDK Generator. ***
// *** Do not edit by hand unless you're certain you know what you are doing! ***
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading.Tasks;
using Pulumi.Serialization;
namespace Pulumi.GoogleNative.Spanner.V1.Outputs
{
/// <summary>
/// Information about the database restore.
/// </summary>
[OutputType]
public sealed class RestoreInfoResponse
{
/// <summary>
/// Information about the backup used to restore the database. The backup may no longer exist.
/// </summary>
public readonly Outputs.BackupInfoResponse BackupInfo;
/// <summary>
/// The type of the restore source.
/// </summary>
public readonly string SourceType;
[OutputConstructor]
private RestoreInfoResponse(
Outputs.BackupInfoResponse backupInfo,
string sourceType)
{
BackupInfo = backupInfo;
SourceType = sourceType;
}
}
}
| 28.128205 | 102 | 0.639927 | [
"Apache-2.0"
] | AaronFriel/pulumi-google-native | sdk/dotnet/Spanner/V1/Outputs/RestoreInfoResponse.cs | 1,097 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Runtime.InteropServices;
using System.Text;
namespace Iot.Device.Ft4222
{
/// <summary>
/// Common static functions for the FT4222
/// </summary>
public class FtCommon
{
/// <summary>
/// Returns the list of FT4222 connected
/// </summary>
/// <returns>A list of devices connected</returns>
public static List<DeviceInformation> GetDevices()
{
List<DeviceInformation> devInfos = new List<DeviceInformation>();
FtStatus ftStatus = 0;
// Check device
uint numOfDevices;
ftStatus = FtFunction.FT_CreateDeviceInfoList(out numOfDevices);
Debug.WriteLine($"Number of devices: {numOfDevices}");
if (numOfDevices == 0)
{
throw new IOException($"No device found");
}
Span<byte> sernum = stackalloc byte[16];
Span<byte> desc = stackalloc byte[64];
for (uint i = 0; i < numOfDevices; i++)
{
uint flags = 0;
FtDevice ftDevice;
uint id;
uint locId;
IntPtr handle;
ftStatus = FtFunction.FT_GetDeviceInfoDetail(i, out flags, out ftDevice, out id, out locId,
in MemoryMarshal.GetReference(sernum), in MemoryMarshal.GetReference(desc), out handle);
if (ftStatus != FtStatus.Ok)
{
throw new IOException($"Can't read device information on device index {i}, error {ftStatus}");
}
var devInfo = new DeviceInformation(
(FtFlag)flags,
ftDevice,
id,
locId,
Encoding.ASCII.GetString(sernum.ToArray(), 0, FindFirstZero(sernum)),
Encoding.ASCII.GetString(desc.ToArray(), 0, FindFirstZero(desc)));
devInfos.Add(devInfo);
}
return devInfos;
}
private static int FindFirstZero(ReadOnlySpan<byte> span)
{
for (int i = 0; i < span.Length; i++)
{
if (span[i] == 0)
{
return i;
}
}
return span.Length;
}
/// <summary>
/// Get the versions of the chipset and dll
/// </summary>
/// <returns>Both the chipset and dll versions</returns>
public static (Version? Chip, Version? Dll) GetVersions()
{
// First, let's find a device
var devices = GetDevices();
if (devices.Count == 0)
{
return (null, null);
}
// Check if the first not open device
int idx = 0;
for (idx = 0; idx < devices.Count; idx++)
{
if ((devices[idx].Flags & FtFlag.PortOpened) != FtFlag.PortOpened)
{
break;
}
}
if (idx == devices.Count)
{
throw new InvalidOperationException($"Can't find any open device to check the versions");
}
var ftStatus = FtFunction.FT_OpenEx(devices[idx].LocId, FtOpenType.OpenByLocation, out SafeFtHandle ftHandle);
if (ftStatus != FtStatus.Ok)
{
throw new IOException($"Can't open the device to check chipset version, status: {ftStatus}");
}
FtVersion ftVersion;
ftStatus = FtFunction.FT4222_GetVersion(ftHandle, out ftVersion);
if (ftStatus != FtStatus.Ok)
{
throw new IOException($"Can't find versions of chipset and FT4222, status: {ftStatus}");
}
ftHandle.Dispose();
Version chip = new Version((int)(ftVersion.ChipVersion >> 24), (int)((ftVersion.ChipVersion >> 16) & 0xFF),
(int)((ftVersion.ChipVersion >> 8) & 0xFF), (int)(ftVersion.ChipVersion & 0xFF));
Version dll = new Version((int)(ftVersion.DllVersion >> 24), (int)((ftVersion.DllVersion >> 16) & 0xFF),
(int)((ftVersion.DllVersion >> 8) & 0xFF), (int)(ftVersion.DllVersion & 0xFF));
return (chip, dll);
}
}
}
| 34.908397 | 122 | 0.520227 | [
"MIT"
] | DazFahy/iot | src/devices/Ft4222/FtCommon.cs | 4,575 | C# |
using Sanakan.DAL.Models;
using Sanakan.Game.Extensions;
namespace Sanakan.Game.Models
{
public enum FightWinner : byte
{
Card1 = 0,
Card2 = 1,
Draw = 2,
}
public static class FightWinnerExtensions
{
public static FightWinner GetFightWinner(Card card1, Card card2)
{
var faCard1 = CardExtensions.GetFA(card1, card2);
var faCard2 = CardExtensions.GetFA(card2, card1);
var c1Health = card1.GetHealthWithPenalty();
var c2Health = card2.GetHealthWithPenalty();
var atkTk1 = c1Health / faCard2;
var atkTk2 = c2Health / faCard1;
var winner = FightWinner.Draw;
if (atkTk1 > atkTk2 + 0.3)
{
winner = FightWinner.Card1;
}
if (atkTk2 > atkTk1 + 0.3)
{
winner = FightWinner.Card2;
}
return winner;
}
}
}
| 24.3 | 72 | 0.532922 | [
"MPL-2.0"
] | Jozpod/sanakan | Game/Models/FightWinner.cs | 974 | C# |
using System;
using System.Collections.Generic;
namespace AspNetCoreOData.Service.Database
{
public partial class AddressType
{
public AddressType()
{
BusinessEntityAddress = new HashSet<BusinessEntityAddress>();
}
public int AddressTypeId { get; set; }
public string Name { get; set; }
public Guid Rowguid { get; set; }
public DateTime ModifiedDate { get; set; }
public virtual ICollection<BusinessEntityAddress> BusinessEntityAddress { get; set; }
}
}
| 26.952381 | 94 | 0.625442 | [
"MIT"
] | CloudBloq/AspNetCoreOData | AspNetCoreOData.Client/Database/AddressType.cs | 568 | C# |
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using System.Collections.Immutable;
using Bicep.Core.Parser;
using Bicep.Core.SemanticModel;
using Bicep.Core.Syntax;
namespace Bicep.LanguageServer.CompilationManager
{
public class CompilationContext
{
public CompilationContext(Compilation compilation)
{
this.Compilation = compilation;
}
public Compilation Compilation { get; }
public ProgramSyntax ProgramSyntax => Compilation.SyntaxTreeGrouping.EntryPoint.ProgramSyntax;
public ImmutableArray<int> LineStarts => Compilation.SyntaxTreeGrouping.EntryPoint.LineStarts;
}
}
| 28.166667 | 102 | 0.736686 | [
"MIT"
] | bhummerstone/bicep | src/Bicep.LangServer/CompilationManager/CompilationContext.cs | 676 | C# |
namespace SeeSharper.Northwind.Scripts
{
using Serenity.ComponentModel;
using Serenity.Data;
using Serenity.Web;
[LookupScript("Northwind.SupplierCountry")]
public class SupplierCountryLookup : RowLookupScript<Entities.SupplierRow>
{
public SupplierCountryLookup()
{
IdField = TextField = "Country";
}
protected override void PrepareQuery(SqlQuery query)
{
var fld = Entities.SupplierRow.Fields;
query.Distinct(true)
.Select(fld.Country)
.Where(
new Criteria(fld.Country) != "" &
new Criteria(fld.Country).IsNotNull());
}
protected override void ApplyOrder(SqlQuery query)
{
}
}
} | 26.433333 | 78 | 0.576293 | [
"MIT"
] | kingajay007/SeeSharper-Master | SeeSharper.Web/Modules/Northwind/Supplier/SupplierCountryLookup.cs | 795 | C# |
namespace Alibi.Plugins.API
{
/// <summary>
/// Represents the protocol state of a client.
/// </summary>
public enum ClientState
{
/// <summary>
/// Brand new client: Has not sent any packets yet
/// </summary>
NewClient,
/// <summary>
/// Has sent the server a protocol-correct handshake, but has not identified yet.
/// </summary>
PostHandshake,
/// <summary>
/// Has told the server their client, we are about to send them server features
/// </summary>
Identified,
/// <summary>
/// The client is fully connected, and has joined an area. Ready to play.
/// </summary>
InArea
}
} | 29.44 | 89 | 0.547554 | [
"MIT"
] | ElijahZAwesome/AO2Sharp | Alibi.Plugins.API/ClientState.cs | 738 | C# |
using System;
using System.Collections.Generic;
namespace hb.SbsdbServer.Model.Entities
{
public partial class Hwkonfig
{
public Hwkonfig()
{
Aussond = new HashSet<Aussond>();
Hw = new HashSet<Hw>();
}
public long Id { get; set; }
public string Bezeichnung { get; set; }
public string Hersteller { get; set; }
public string Hd { get; set; }
public string Prozessor { get; set; }
public string Ram { get; set; }
public string Sonst { get; set; }
public string Video { get; set; }
public long HwtypId { get; set; }
public virtual Hwtyp Hwtyp { get; set; }
public virtual ICollection<Aussond> Aussond { get; set; }
public virtual ICollection<Hw> Hw { get; set; }
}
}
| 28.413793 | 65 | 0.572816 | [
"MIT"
] | hb42/sbsdb-server | SbsdbServer/Model/Entities/Hwkonfig.cs | 826 | C# |
using System.Net.Http;
using System.Reflection;
using System.Threading.Tasks;
using Common;
using Common.Exception;
using Common.Messages;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Newtonsoft.Json;
using Swashbuckle.AspNetCore.Annotations;
using WebAPI_BAL.AuthLogic;
using WebAPI_BAL.JwtGenerator;
using WebAPI_Server.AppStart;
using WebAPI_Service.Identity;
using WebAPI_ViewModel.ConfigSettings;
using WebAPI_ViewModel.Identity;
using WebAPI_ViewModel.Response;
namespace WebAPI_Server.Controllers.v1
{
/// <inheritdoc />
//[Route("api/v{version:apiVersion}/auth")]
[ApiVersion(ApiVersionNumber.V1)]
[Route(ApiEndpoints.AccountControllerPrefix)]
[ApiController]
public class AccountController : BaseController
{
//private readonly ClaimsPrincipal _caller;
private IHttpContextAccessor _httpContextAccessor;
private readonly IAuthentication _auth;
private readonly IAuthorization _authorize;
private readonly FacebookAuthSettings _fbAuthSettings;
private static readonly HttpClient Client = new HttpClient();
private readonly ILogger<AccountController> _logger;
private readonly IAuthenticationService _authService;
/// <inheritdoc />
public AccountController(IAuthentication auth, IOptions<FacebookAuthSettings> fbAuthSettingsAccessor,
IHttpContextAccessor httpContextAccessor, IAuthorization authorize, IAuthenticationService authService, ILogger<AccountController> logger)
{
_fbAuthSettings = fbAuthSettingsAccessor.Value;
_auth = auth;
_authorize = authorize;
_httpContextAccessor = httpContextAccessor;
_authService = authService;
_logger = logger;
}
#region Authentication
/// <summary>
/// Register new user
/// </summary>
/// <param name="data">Information of new user</param>
/// <returns></returns>
[SwaggerResponse(StatusCodes.Status201Created, type: typeof(ApiResponse))]
[SwaggerResponse(StatusCodes.Status409Conflict, type: typeof(ApiResponse))]
[SwaggerResponse(StatusCodes.Status400BadRequest, type: typeof(ApiResponse))]
[RequireCallbackUrlFilter]
[HttpPost(ApiEndpoints.Register)]
[AllowAnonymous]
public async Task<ActionResult<ApiResponse>> RegisterUser([FromBody] RegisterUserViewModel data)
{
var result = await _auth.RegisterUserAsync(data);
if (result)
return StatusCodeResult(StatusCodes.Status201Created, null, InfoMessages.UserRegistered);
return BadRequest(ErrorMessages.CommonErrorMessage);
}
/// <summary>
/// Create new user
/// </summary>
/// <param name="data">Information of new user</param>
/// <returns>New user info</returns>
[SwaggerResponse(StatusCodes.Status201Created, type: typeof(ApiResponse<AddNewUserViewModel>))]
[SwaggerResponse(StatusCodes.Status409Conflict, type: typeof(ApiResponse))]
[SwaggerResponse(StatusCodes.Status400BadRequest, type: typeof(ApiResponse))]
[RequireCallbackUrlFilter]
[HttpPost(ApiEndpoints.AddUser)]
public async Task<ActionResult<ApiResponse<AddNewUserViewModel>>> AddUser([FromBody] AddNewUserViewModel data)
{
var result = await _auth.AddNewUserAsync(User, data);
if (result)
return StatusCodeResult(StatusCodes.Status201Created, null, InfoMessages.CommonInfoMessage);
return BadRequest(ErrorMessages.CommonErrorMessage);
}
/// <summary>
/// Delete user from system
/// </summary>
/// <param name="userId">User Id to delete</param>
/// <returns></returns>
[SwaggerResponse(StatusCodes.Status200OK, type: typeof(ApiResponse))]
[SwaggerResponse(StatusCodes.Status404NotFound, type: typeof(ApiResponse))]
[SwaggerResponse(StatusCodes.Status409Conflict, type: typeof(ApiResponse))]
[SwaggerResponse(StatusCodes.Status400BadRequest, type: typeof(ApiResponse))]
[HttpDelete(ApiEndpoints.RemoveUser)]
public async Task<ActionResult<ApiResponse>> RemoveUser([FromBody] string userId)
{
var result = await _auth.DeleteUserAsync(User, userId);
if (result)
return Ok(null, InfoMessages.CommonInfoMessage);
return BadRequest(ErrorMessages.CommonErrorMessage);
}
/// <summary>
/// Create new user bae on facebook authentication token and login that user.
/// </summary>
/// <param name="model">Facebook access token</param>
/// <returns>User json web token</returns>
[SwaggerResponse(StatusCodes.Status200OK, type: typeof(ApiResponse<JwtToken>))]
[SwaggerResponse(StatusCodes.Status400BadRequest, type: typeof(ApiResponse))]
[SwaggerResponse(StatusCodes.Status409Conflict, type: typeof(ApiResponse))]
[RequireCallbackUrlFilter]
[HttpPost(ApiEndpoints.Facebook)]
[AllowAnonymous]
public async Task<ActionResult<ApiResponse<JwtToken>>> Facebook([FromBody]FacebookAuthViewModel model)
{
// 1.generate an app access token
var appAccessTokenResponse = await Client.GetStringAsync($"https://graph.facebook.com/oauth/access_token?client_id={_fbAuthSettings.AppId}&client_secret={_fbAuthSettings.AppSecret}&grant_type=client_credentials");
var appAccessToken = JsonConvert.DeserializeObject<FacebookAppAccessToken>(appAccessTokenResponse);
// 2. validate the user access token
var userAccessTokenValidationResponse = await Client.GetStringAsync($"https://graph.facebook.com/debug_token?input_token={model.AccessToken}&access_token={appAccessToken.AccessToken}");
var userAccessTokenValidation = JsonConvert.DeserializeObject<FacebookUserAccessTokenValidation>(userAccessTokenValidationResponse);
if (!userAccessTokenValidation.Data.IsValid)
{
throw new WebApiApplicationException(StatusCodes.Status409Conflict, ErrorMessages.InvalidFbToken, MethodBase.GetCurrentMethod().GetParameters());
}
// 3. we've got a valid token so we can request user data from fb
var userInfoResponse = await Client.GetStringAsync($"https://graph.facebook.com/v2.8/me?fields=id,email,first_name,last_name,name,gender,locale,birthday,picture&access_token={model.AccessToken}");
var userInfo = JsonConvert.DeserializeObject<FacebookUserData>(userInfoResponse);
var registerUser = new RegisterUserViewModel()
{
FirstName = userInfo.FirstName,
LastName = userInfo.LastName,
FacebookId = userInfo.Id,
Email = userInfo.Email,
PictureUrl = userInfo.Picture.Data.Url
};
JwtToken result = await _auth.ExternalAuthenticationAsync(registerUser);
if (result == null)
throw new WebApiApplicationException(StatusCodes.Status401Unauthorized, ErrorMessages.InvalidUser);
return Ok(result, InfoMessages.UserSignin);
}
/// <summary>
/// Authenticate and sign in user
/// </summary>
/// <param name="data">Username and password of the user</param>
/// <returns>JWT along with userid</returns>
[SwaggerResponse(StatusCodes.Status200OK, type: typeof(ApiResponse<JwtToken>))]
[SwaggerResponse(StatusCodes.Status401Unauthorized, type: typeof(ApiResponse))]
[SwaggerResponse(StatusCodes.Status403Forbidden, type: typeof(ApiResponse))]
[RequireCallbackUrlFilter]
[HttpPost(ApiEndpoints.Authenticate)]
[AllowAnonymous]
public async Task<ActionResult<ApiResponse<JwtToken>>> Authenticate([FromBody] LoginUserViewModel data)
{
_authService.ValidateLogin(data);
JwtToken result = await _auth.AuthenticateUserAsync(data);
if (result == null)
throw new WebApiApplicationException(StatusCodes.Status401Unauthorized, ErrorMessages.InvalidUser, MethodBase.GetCurrentMethod().GetParameters());
//return StatusCode(StatusCodes.Status401Unauthorized, "Invalid username or password", null);
return Ok(result, InfoMessages.UserSignin);
}
/// <summary>
/// Set new password based on user logged in
/// </summary>
/// <param name="data">New password</param>
/// <returns></returns>
[SwaggerResponse(StatusCodes.Status200OK, type: typeof(ApiResponse))]
[SwaggerResponse(StatusCodes.Status400BadRequest, type: typeof(ApiResponse))]
[HttpPost(ApiEndpoints.SetPassword)]
public async Task<ActionResult<ApiResponse>> SetPassword([FromBody] SetPasswordViewModel data)
{
var result = await _auth.SetPasswordAsync(User, data);
if (result)
return Ok(null, InfoMessages.CommonInfoMessage);
return BadRequest(ErrorMessages.CommonErrorMessage);
}
/// <summary>
/// Change Password based on user logged in and provided with old password
/// </summary>
/// <param name="data">Old and new password</param>
/// <returns></returns>
[SwaggerResponse(StatusCodes.Status200OK, type: typeof(ApiResponse))]
[SwaggerResponse(StatusCodes.Status400BadRequest, type: typeof(ApiResponse))]
[HttpPut(ApiEndpoints.ChangePassword)]
public async Task<ActionResult<ApiResponse>> ChangePassword([FromBody] ChangePasswordViewModel data)
{
var result = await _auth.ChangePasswordAsync(User, data);
if (result)
return Ok(null, InfoMessages.CommonInfoMessage);
return BadRequest(ErrorMessages.CommonErrorMessage);
}
/// <summary>
/// Generate reset password token
/// </summary>
/// <param name="data">user email for reset password</param>
/// <returns></returns>
[SwaggerResponse(StatusCodes.Status200OK, type: typeof(ApiResponse))]
[SwaggerResponse(StatusCodes.Status400BadRequest, type: typeof(ApiResponse))]
[SwaggerResponse(StatusCodes.Status403Forbidden, type: typeof(ApiResponse))]
[RequireCallbackUrlFilter]
[HttpPost(ApiEndpoints.ResetPasswordToken)]
[AllowAnonymous]
public async Task<ActionResult<ApiResponse>> GenerateResetPasswordToken([FromBody] PasswordResetTokenViewModel data)
{
var result = await _auth.GeneratePasswordResetTokenAsync(data.Email);
if (result)
return Ok(null, InfoMessages.CommonInfoMessage);
return BadRequest(ErrorMessages.CommonErrorMessage);
}
/// <summary>
/// Reset password with email token and userid
/// </summary>
/// <param name="data">Data for token, user id and new password</param>
/// <returns></returns>
[SwaggerResponse(StatusCodes.Status200OK, type: typeof(ApiResponse))]
[SwaggerResponse(StatusCodes.Status400BadRequest, type: typeof(ApiResponse))]
[HttpPost(ApiEndpoints.ResetPassword)]
[AllowAnonymous]
public async Task<ActionResult<ApiResponse>> ResetPassword([FromBody] ResetPasswordWithTokenViewModel data)
{
var result = await _auth.ResetPasswordAsync(data);
if (result)
return Ok(null, InfoMessages.CommonInfoMessage);
return BadRequest(ErrorMessages.CommonErrorMessage);
}
/// <summary>
/// Verify email token for registration and new user
/// </summary>
/// <param name="data">Token and user id to verify</param>
/// <returns></returns>
[SwaggerResponse(StatusCodes.Status200OK, type: typeof(ApiResponse))]
[SwaggerResponse(StatusCodes.Status400BadRequest, type: typeof(ApiResponse))]
[SwaggerResponse(StatusCodes.Status404NotFound, type: typeof(ApiResponse))]
[SwaggerResponse(StatusCodes.Status409Conflict, type: typeof(ApiResponse))]
[HttpPost(ApiEndpoints.VerifyEmail)]
[AllowAnonymous]
public async Task<ActionResult<ApiResponse>> VerifyEmailToken([FromBody] VerifyTokenViewModel data)
{
var result = await _auth.VerifyEmailTokenAsync(data.Token, data.UserId);
if (result)
return Ok(null, InfoMessages.CommonInfoMessage);
return BadRequest(ErrorMessages.CommonErrorMessage);
}
//[HttpPost(ApiEndpoints.VerifyResetPassword)]
//[AllowAnonymous]
//public async Task<ActionResult<ApiResponse>> VerifyResetPasswordToken([FromBody] VerifyTokenViewModel data)
//{
// var result = await _auth.VerifyPasswordResetTokenAsync(data.Token, data.UserId);
// if (result)
// return Ok(null, InfoMessages.CommonInfoMessage);
// return BadRequest(ErrorMessages.CommonErrorMessage);
//}
/// <summary>
/// Generate refresh token for logged in user
/// </summary>
/// <param name="data">JWT, refresh token and user id required</param>
/// <returns></returns>
[SwaggerResponse(StatusCodes.Status200OK, type: typeof(ApiResponse))]
[SwaggerResponse(StatusCodes.Status401Unauthorized, type: typeof(ApiResponse))]
[SwaggerResponse(StatusCodes.Status404NotFound, type: typeof(ApiResponse))]
[RequireCallbackUrlFilter]
[HttpPost(ApiEndpoints.RefreshToken)]
[AllowAnonymous]
public async Task<IActionResult> RefreshToken([FromBody] RefreshTokenViewModel data)
{
var result = await _auth.RefreshTokenAsync(data.Token, data.UserId, data.TokenNumber);
if (result == null)
throw new WebApiApplicationException(StatusCodes.Status401Unauthorized, ErrorMessages.InvalidUser, MethodBase.GetCurrentMethod().GetParameters());
return Ok(result, InfoMessages.UserSignin);
}
/// <summary>
/// Log out user (revoke generated JWT)
/// </summary>
/// <returns></returns>
[SwaggerResponse(StatusCodes.Status200OK, type: typeof(ApiResponse))]
[SwaggerResponse(StatusCodes.Status404NotFound, type: typeof(ApiResponse))]
[SwaggerResponse(StatusCodes.Status400BadRequest, type: typeof(ApiResponse))]
[HttpPost(ApiEndpoints.LogOff)]
public async Task<ActionResult<ApiResponse>> Revoke()
{
var result = await _auth.RevokeToken(User);
if (result)
return Ok(null, InfoMessages.CommonInfoMessage);
return BadRequest(ErrorMessages.CommonErrorMessage);
}
#endregion
#region Authorization
/// <summary>
/// Create new role
/// </summary>
/// <param name="data">New role data</param>
/// <returns></returns>
[SwaggerResponse(StatusCodes.Status201Created, type: typeof(ApiResponse))]
[SwaggerResponse(StatusCodes.Status409Conflict, type: typeof(ApiResponse))]
[SwaggerResponse(StatusCodes.Status400BadRequest, type: typeof(ApiResponse))]
[HttpPost(ApiEndpoints.AddRole)]
public async Task<IActionResult> CreateRole([FromBody] ApplicationRoleViewModel data)
{
var result = await _authorize.CreateRole(User, data);
if (result)
return StatusCodeResult(StatusCodes.Status201Created, null, InfoMessages.CommonInfoMessage);
return BadRequest(ErrorMessages.CommonErrorMessage);
}
/// <summary>
/// Update Role
/// </summary>
/// <param name="data">Role data to update with role id</param>
/// <returns></returns>
[SwaggerResponse(StatusCodes.Status200OK, type: typeof(ApiResponse))]
[SwaggerResponse(StatusCodes.Status400BadRequest, type: typeof(ApiResponse))]
[HttpPut(ApiEndpoints.UpdateRole)]
public async Task<IActionResult> UpdateRole([FromBody] ApplicationRoleViewModel data)
{
var result = await _authorize.UpdateRole(User, data);
if (result)
return Ok(null, InfoMessages.CommonInfoMessage);
return BadRequest(ErrorMessages.CommonErrorMessage);
}
/// <summary>
/// Delete role from system
/// </summary>
/// <param name="data">Role data to delete</param>
/// <returns></returns>
[SwaggerResponse(StatusCodes.Status200OK, type: typeof(ApiResponse))]
[SwaggerResponse(StatusCodes.Status400BadRequest, type: typeof(ApiResponse))]
[HttpDelete(ApiEndpoints.DeleteRole)]
public async Task<IActionResult> RemoveRole([FromBody] ApplicationRoleViewModel data)
{
var result = await _authorize.RemoveRole(User, data);
if (result)
return Ok(null, InfoMessages.CommonInfoMessage);
return BadRequest(ErrorMessages.CommonErrorMessage);
}
/// <summary>
/// Check if logged in use has specific role
/// </summary>
/// <param name="roleName">Role name to check for user</param>
/// <returns></returns>
[SwaggerResponse(StatusCodes.Status200OK, type: typeof(ApiResponse))]
[HttpGet(ApiEndpoints.HasRole)]
public async Task<IActionResult> UserIsInRole([FromQuery] string roleName)
{
var result = await _authorize.UserIsInRole(User, roleName);
if (result)
return Ok(new { UserHasRole = true }, InfoMessages.UserHasRole);
return StatusCodeResult(StatusCodes.Status200OK, new { UserHasRole = false }, InfoMessages.UserHasNoRole);
//return BadRequest(ErrorMessages.CommonErrorMessage);
}
/// <summary>
/// Assign role to specific user
/// </summary>
/// <param name="data">role and user data</param>
/// <returns></returns>
[SwaggerResponse(StatusCodes.Status200OK, type: typeof(ApiResponse))]
[SwaggerResponse(StatusCodes.Status400BadRequest, type: typeof(ApiResponse))]
[SwaggerResponse(StatusCodes.Status404NotFound, type: typeof(ApiResponse))]
[HttpPost(ApiEndpoints.AssignRole)]
public async Task<IActionResult> AssignRole([FromBody] AssignRoleViewModel data)
{
var result = await _authorize.AssignRole(User, data.UserId, data.RoleId);
if (result)
return Ok(null, InfoMessages.CommonInfoMessage);
return BadRequest(ErrorMessages.CommonErrorMessage);
}
/// <summary>
/// Remove user from role
/// </summary>
/// <param name="data">role and user data</param>
/// <returns></returns>
[SwaggerResponse(StatusCodes.Status200OK, type: typeof(ApiResponse))]
[SwaggerResponse(StatusCodes.Status400BadRequest, type: typeof(ApiResponse))]
[SwaggerResponse(StatusCodes.Status404NotFound, type: typeof(ApiResponse))]
[HttpDelete(ApiEndpoints.RemoveRole)]
public async Task<IActionResult> RemoveFromRole([FromBody] AssignRoleViewModel data)
{
var result = await _authorize.RemoveFromRole(User, data.UserId, data.RoleId);
if (result)
return Ok(null, InfoMessages.CommonInfoMessage);
return BadRequest(ErrorMessages.CommonErrorMessage);
}
/// <summary>
/// Check if specific user has role
/// </summary>
/// <param name="data">role and user data</param>
/// <returns></returns>
[SwaggerResponse(StatusCodes.Status200OK, type: typeof(ApiResponse))]
[HttpPost(ApiEndpoints.UserRole)]
public async Task<IActionResult> SpecificUserIsInRole([FromBody] UserHasRoleViewModel data)
{
var result = await _authorize.UserIsInRole(data.UserId, data.RoleId);
if (result)
return Ok(new { UserHasRole = true}, InfoMessages.UserHasRole);
return StatusCodeResult(StatusCodes.Status200OK, new { UserHasRole = false }, InfoMessages.UserHasNoRole);
//return BadRequest(ErrorMessages.CommonErrorMessage);
}
#endregion
}
} | 44.512931 | 225 | 0.663165 | [
"MIT"
] | awaisali88/WebApi-Server | WebAPI-Server/Controllers/v1/AccountController.cs | 20,656 | C# |
using System;
using UnityEngine;
namespace UnityEditor.MeshSync {
/// <summary>
/// Basic information about DCCTool
/// </summary>
[Serializable]
public class DCCToolInfo {
internal DCCToolInfo(DCCToolType type, string dccToolVersion) {
Type = type;
DCCToolVersion = dccToolVersion;
}
internal DCCToolInfo(DCCToolInfo other) {
Type = other.Type;
DCCToolVersion = other.DCCToolVersion;
AppPath = other.AppPath;
}
//----------------------------------------------------------------------------------------------------------------------
internal string GetDescription() {
string desc = null;
switch (Type) {
case DCCToolType.AUTODESK_MAYA: {
desc = "Maya " + DCCToolVersion;
break;
}
case DCCToolType.AUTODESK_3DSMAX: {
desc = "3DS Max " + DCCToolVersion;
break;
}
default: {
desc = "";
break;
}
}
return desc;
}
//----------------------------------------------------------------------------------------------------------------------
/// <summary>
/// The type of DCC Tool
/// </summary>
public DCCToolType Type; //DCC Tool Type
/// <summary>
/// The version of DCC Tool
/// </summary>
public string DCCToolVersion; //DCC Tool Version
/// <summary>
/// The path to the DCC Tool application file
/// </summary>
public string AppPath;
/// <summary>
/// The path to the icon of the DCC Tool
/// </summary>
public string IconPath;
[SerializeField] internal readonly int ClassVersion = 1;
}
}
| 24.026667 | 124 | 0.456715 | [
"Apache-2.0"
] | artigee/MeshSync | Editor/Scripts/ProjectSettings/Data/DCCToolInfo.cs | 1,804 | C# |
// CodeContracts
//
// Copyright (c) Microsoft Corporation
//
// All rights reserved.
//
// 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.Diagnostics.Contracts;
using System.Globalization;
using System.Collections;
using System.Collections.Generic;
namespace System
{
public abstract class StringComparer : IComparer, IEqualityComparer, IComparer<string>, IEqualityComparer<string>
{
// Methods
extern protected StringComparer();
extern public int Compare(object x, object y);
public abstract int Compare(string x, string y);
public static StringComparer Create(CultureInfo culture, bool ignoreCase)
{
Contract.Requires(culture != null);
Contract.Ensures(Contract.Result<StringComparer>() != null);
return default(StringComparer);
}
new extern public bool Equals(object x, object y);
public abstract bool Equals(string x, string y);
extern public int GetHashCode(object obj);
public abstract int GetHashCode(string obj);
// Properties
public static StringComparer CurrentCulture
{
get
{
Contract.Ensures(Contract.Result<StringComparer>() != null);
return default(StringComparer);
}
}
public static StringComparer CurrentCultureIgnoreCase
{
get
{
Contract.Ensures(Contract.Result<StringComparer>() != null);
return default(StringComparer);
}
}
public static StringComparer InvariantCulture
{
get
{
Contract.Ensures(Contract.Result<StringComparer>() != null);
return default(StringComparer);
}
}
public static StringComparer InvariantCultureIgnoreCase
{
get
{
Contract.Ensures(Contract.Result<StringComparer>() != null);
return default(StringComparer);
}
}
public static StringComparer Ordinal
{
get
{
Contract.Ensures(Contract.Result<StringComparer>() != null);
return default(StringComparer);
}
}
public static StringComparer OrdinalIgnoreCase
{
get
{
Contract.Ensures(Contract.Result<StringComparer>() != null);
return default(StringComparer);
}
}
}
}
| 35.637363 | 463 | 0.703361 | [
"MIT"
] | Acidburn0zzz/CodeContracts | Microsoft.Research/Contracts/MsCorlib/System.StringComparer.cs | 3,243 | C# |
using it.example.dotnetcore5.dal.ef.sqlite.EfModels;
using System;
using System.Collections.Generic;
using System.Linq;
using ModelPost = it.example.dotnetcore5.domain.Models.Post;
namespace it.example.dotnetcore5.dal.ef.sqlite.Factories
{
/// <summary>
/// Convert Post model domain into a Post Ef entity
/// </summary>
public static class PostFactory
{
/// <summary>
/// Covert
/// </summary>
/// <param name="efModel"></param>
/// <returns></returns>
public static ModelPost ToModelDomain(this Post efEntity)
{
ModelPost model = null;
if (efEntity != null)
{
model = new ModelPost
{
Id = (int)efEntity.Id,
Title = efEntity.Title,
Text = efEntity.Text,
CreateDate = DateTime.Parse(efEntity.CreateDate)
};
}
return model;
}
public static List<ModelPost> ToModelsDomain(this List<Post> efEntities)
{
List<ModelPost> models = null;
if (efEntities != null && efEntities.Any())
{
models = new List<ModelPost>();
efEntities.ForEach(item =>
{
models.Add(item.ToModelDomain());
});
}
return models;
}
public static Post ToEfEntity(this ModelPost model)
{
Post efEntity = null;
if (model != null)
{
efEntity = new Post
{
Id = model.Id,
Title = model.Title,
Text = model.Text,
CreateDate = model.CreateDate.ToString()
};
}
return efEntity;
}
public static List<Post> ToEfEntities(this List<ModelPost> models)
{
List<Post> efEntities = null;
if (models != null && models.Any())
{
efEntities = new List<Post>();
models.ForEach(item =>
{
efEntities.Add(item.ToEfEntity());
});
}
return efEntities;
}
}
}
| 27.702381 | 80 | 0.462828 | [
"MIT"
] | Magicianred/dotnet-core5-webapi-example | it.example.dotnetcore5/it.example.dotnetcore5.dal.ef.sqlite/Factories/PostFactory.cs | 2,329 | C# |
#region Copyright and license information
// Copyright 2001-2009 Stephen Colebourne
// Copyright 2009-2011 Jon Skeet
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#endregion
namespace NodaTime.Testing
{
/// <summary>
/// Clock which can be constructed with an initial instant, and then advanced programmatically.
/// This class is designed to be used when testing classes which take an <see cref="IClock"/> as a dependency.
/// </summary>
public sealed class StubClock : IClock
{
private Instant now;
/// <summary>
/// Creates a stub clock initially set to the given instant.
/// </summary>
public StubClock(Instant initial)
{
now = initial;
}
/// <summary>
/// Returns a fake clock initially set to midnight of the given year/month/day in UTC in the ISO calendar.
/// </summary>
public static StubClock FromUtc(int year, int month, int dayOfMonth)
{
return new StubClock(Instant.FromUtc(year, month, dayOfMonth, 0, 0));
}
/// <summary>
/// Returns a fake clock initially set to the given year/month/day/time in UTC in the ISO calendar.
/// </summary>
public static StubClock FromUtc(int year, int month, int dayOfMonth, int hour, int minute, int second)
{
return new StubClock(Instant.FromUtc(year, month, dayOfMonth, hour, minute, second));
}
/// <summary>
/// Advances the clock by the given duration.
/// </summary>
public void Advance(Duration duration)
{
now += duration;
}
/// <summary>
/// Advances the clock by the given number of ticks.
/// </summary>
public void AdvanceTicks(long ticks)
{
Advance(new Duration(ticks));
}
/// <summary>
/// Advances the clock by the given number of milliseconds.
/// </summary>
public void AdvanceMilliseconds(long milliseconds)
{
Advance(Duration.FromMilliseconds(milliseconds));
}
/// <summary>
/// Advances the clock by the given number of seconds.
/// </summary>
public void AdvanceSeconds(long seconds)
{
Advance(Duration.FromSeconds(seconds));
}
/// <summary>
/// Advances the clock by the given number of minutes.
/// </summary>
public void AdvanceMinutes(long minutes)
{
Advance(Duration.FromMinutes(minutes));
}
/// <summary>
/// Advances the clock by the given number of hours.
/// </summary>
public void AdvanceHours(long hours)
{
now += Duration.FromHours(hours);
}
/// <summary>
/// Advances the clock by the given number of standard (24-hour) days.
/// </summary>
public void AdvanceDays(long days)
{
now += Duration.FromStandardDays(days);
}
/// <summary>
/// Resets the clock to the given instant.
/// </summary>
public void Reset(Instant instant)
{
now = instant;
}
/// <summary>
/// Returns the "current time" for this clock. Unlike a normal clock, this
/// property will return the same value from repeated calls until one of the methods
/// to change the time is called.
/// </summary>
public Instant Now
{
get { return now; }
}
}
}
| 33.507937 | 115 | 0.570109 | [
"Apache-2.0"
] | haf/NodaTime | src/NodaTime.Testing/StubClock.cs | 4,224 | C# |
using Chloe.Infrastructure;
using Chloe.SqlServer;
using Database;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ChloeDemo
{
public static class RegisterMappingTypeDemo
{
/*sql script:
CREATE TABLE [dbo].[ExtensionMappingType](
[Id] [int] IDENTITY(1,1) NOT NULL,
[Name] [nvarchar](100) NULL,
[F_Char] [nvarchar](1) NULL,
[F_Time] [time](7) NULL,
CONSTRAINT [PK_ExtensionMappingType] PRIMARY KEY CLUSTERED
(
[Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
*/
public static void RunDemo()
{
//step 1:
/* 原生 Chloe 不支持 char 和 TimeSpan 类型映射,需要我们自己注册,注册映射类必须在程序启动时进行 */
MappingTypeSystem.Register(typeof(char), DbType.StringFixedLength);
MappingTypeSystem.Register(typeof(TimeSpan), DbType.Time);
//step 2:
/* 因为我们新增了 MappingType,所以需要对原生的 SqlConnection、SqlServerCommand、SqlServerDataReader、SqlServerParameter 包装处理,所以,我们需要自个儿实现 IDbConnectionFactory 工厂 */
SqlServerDbConnectionFactory sqlServerDbConnectionFactory = new SqlServerDbConnectionFactory(DbHelper.ConnectionString);
MsSqlContext context = new MsSqlContext(sqlServerDbConnectionFactory);
/* 经过上述封装,我们就可以支持 char 和 TimeSpan 类型映射了 */
ExtensionMappingType entity = new ExtensionMappingType();
entity.Name = "test";
entity.F_Char = 'A';
entity.F_Time = TimeSpan.FromHours(12);
context.Insert(entity);
Console.WriteLine(entity.Id);
TimeSpan ts = TimeSpan.FromHours(12);
ExtensionMappingType model = context.Query<ExtensionMappingType>().Where(a => a.F_Time == ts && a.Id == entity.Id).First();
Console.WriteLine(model.Id == entity.Id);
Console.WriteLine("Yeah!!");
Console.ReadKey();
}
}
public class ExtensionMappingType
{
public int Id { get; set; }
public string Name { get; set; }
[Chloe.Entity.Column(DbType = DbType.StringFixedLength)]/* 因为 char 是新增的映射类型,必须指定 DbType */
public char? F_Char { get; set; }
[Chloe.Entity.Column(DbType = DbType.Time)]/* 因为 TimeSpan 是新增的映射类型,必须指定 DbType */
public TimeSpan? F_Time { get; set; }
}
/*
* 自定义一个 DbConnectionFactory,实现 CreateConnection 方法,其返回我们自定义的 SqlServerConnection
*/
public class SqlServerDbConnectionFactory : IDbConnectionFactory
{
string _connString;
public SqlServerDbConnectionFactory(string connString)
{
this._connString = connString;
}
public IDbConnection CreateConnection()
{
SqlConnection conn = new SqlConnection(this._connString);
/*
tips:因为我们新增了 MappingType,所以需要对原生的 SqlConnection、SqlServerCommand、SqlServerDataReader、SqlServerParameter 包装处理
*/
return new SqlServerConnection(conn);
}
}
/*
* 对于新增映射类型,需要包装驱动的的 DataParameter,拦截 DbType 和 Value 属性。
*/
public class SqlServerParameter : IDbDataParameter, IDataParameter
{
internal SqlParameter _sqlParameter;
IDbDataParameter Parameter
{
get
{
return (IDbDataParameter)this._sqlParameter;
}
}
public SqlServerParameter(SqlParameter sqlParameter)
{
this._sqlParameter = sqlParameter;
}
public DbType DbType
{
get
{
return this.Parameter.DbType;
}
set
{
DbType dbType = value;
if (value == System.Data.DbType.Time)
{
/* 需要设置 SqlDbType 为 SqlDbType.Time,否则运行会报错 */
this.Parameter.DbType = dbType;
this._sqlParameter.SqlDbType = SqlDbType.Time;
return;
}
this.Parameter.DbType = dbType;
}
}
public object Value
{
get
{
return this.Parameter.Value;
}
set
{
if (value != null)
{
Type valueType = value.GetType();
if (valueType == typeof(TimeSpan))
{
this.DbType = System.Data.DbType.Time;
}
else if (valueType == typeof(char))
{
DbType dbType = this.DbType;
if (dbType != System.Data.DbType.String && dbType != System.Data.DbType.StringFixedLength && dbType != System.Data.DbType.AnsiString && dbType != System.Data.DbType.AnsiStringFixedLength)
{
this.DbType = System.Data.DbType.String;
}
this.Parameter.Value = new string(new char[1] { (char)value });
return;
}
}
this.Parameter.Value = value;
}
}
public byte Precision
{
get
{
return this.Parameter.Precision;
}
set
{
this.Parameter.Precision = value;
}
}
public byte Scale
{
get
{
return this.Parameter.Scale;
}
set
{
this.Parameter.Scale = value;
}
}
public int Size
{
get
{
return this.Parameter.Size;
}
set
{
this.Parameter.Size = value;
}
}
public ParameterDirection Direction
{
get
{
return this.Parameter.Direction;
}
set
{
this.Parameter.Direction = value;
}
}
public bool IsNullable
{
get
{
return this.Parameter.IsNullable;
}
}
public string ParameterName
{
get
{
return this.Parameter.ParameterName;
}
set
{
this.Parameter.ParameterName = value;
}
}
public string SourceColumn
{
get
{
return this.Parameter.SourceColumn;
}
set
{
this.Parameter.SourceColumn = value;
}
}
public DataRowVersion SourceVersion
{
get
{
return this.Parameter.SourceVersion;
}
set
{
this.Parameter.SourceVersion = value;
}
}
}
/*
* 对驱动原生的 DataReader 包装
*/
public class SqlServerDataReader : IDataReader, IDataRecord, IDisposable
{
IDataReader _reader;
public SqlServerDataReader(IDataReader reader)
{
if (reader == null)
throw new ArgumentNullException();
this._reader = reader;
}
#region IDataReader
public int Depth { get { return this._reader.Depth; } }
public bool IsClosed { get { return this._reader.IsClosed; } }
public int RecordsAffected { get { return this._reader.RecordsAffected; } }
public void Close()
{
this._reader.Close();
}
public DataTable GetSchemaTable()
{
return this._reader.GetSchemaTable();
}
public bool NextResult()
{
return this._reader.NextResult();
}
public bool Read()
{
return this._reader.Read();
}
public void Dispose()
{
this._reader.Dispose();
}
#endregion
public int FieldCount { get { return this._reader.FieldCount; } }
public object this[int i] { get { return this._reader[i]; } }
public object this[string name] { get { return this._reader[name]; } }
public bool GetBoolean(int i)
{
return this._reader.GetBoolean(i);
}
public byte GetByte(int i)
{
return this._reader.GetByte(i);
}
public long GetBytes(int i, long fieldOffset, byte[] buffer, int bufferoffset, int length)
{
return this._reader.GetBytes(i, fieldOffset, buffer, bufferoffset, length);
}
/*
*因为 SqlServer 不支持 char 类型,所以,如果我们需要支持 char 类型映射,在数据库里我们只能使用 char、varchar 等字符串类型映射,因此必须拦截 DataReader 的 GetChar() 方法处理
*/
public char GetChar(int i)
{
Type fieldType = this._reader.GetFieldType(i);
if (fieldType == typeof(string))
{
if (this._reader.IsDBNull(i) == false)
{
string str = this._reader.GetString(i);
if (str.Length == 1)
{
return str[0];
}
}
}
return this._reader.GetChar(i);
}
public long GetChars(int i, long fieldoffset, char[] buffer, int bufferoffset, int length)
{
return this._reader.GetChars(i, fieldoffset, buffer, bufferoffset, length);
}
public IDataReader GetData(int i)
{
return this._reader.GetData(i);
}
public string GetDataTypeName(int i)
{
return this._reader.GetDataTypeName(i);
}
public DateTime GetDateTime(int i)
{
return this._reader.GetDateTime(i);
}
public decimal GetDecimal(int i)
{
return this._reader.GetDecimal(i);
}
public double GetDouble(int i)
{
return this._reader.GetDouble(i);
}
public Type GetFieldType(int i)
{
return this._reader.GetFieldType(i);
}
public float GetFloat(int i)
{
return this._reader.GetFloat(i);
}
public Guid GetGuid(int i)
{
return this._reader.GetGuid(i);
}
public short GetInt16(int i)
{
return this._reader.GetInt16(i);
}
public int GetInt32(int i)
{
return this._reader.GetInt32(i);
}
public long GetInt64(int i)
{
return this._reader.GetInt64(i);
}
public string GetName(int i)
{
return this._reader.GetName(i);
}
public int GetOrdinal(string name)
{
return this._reader.GetOrdinal(name);
}
public string GetString(int i)
{
return this._reader.GetString(i);
}
public object GetValue(int i)
{
return this._reader.GetValue(i);
}
public int GetValues(object[] values)
{
return this._reader.GetValues(values);
}
public bool IsDBNull(int i)
{
return this._reader.IsDBNull(i);
}
}
/*
* 对驱动原生的 SqlCommand 包装
*/
public class SqlServerCommand : IDbCommand, IDisposable
{
SqlCommand _dbCommand;
DataParameterCollection _dataParameterCollection;
public SqlServerCommand(SqlCommand dbCommand)
{
if (dbCommand == null)
throw new ArgumentNullException();
this._dbCommand = dbCommand;
this._dataParameterCollection = new DataParameterCollection(dbCommand.Parameters);
}
public string CommandText
{
get
{
return this._dbCommand.CommandText;
}
set
{
this._dbCommand.CommandText = value;
}
}
public int CommandTimeout
{
get
{
return this._dbCommand.CommandTimeout;
}
set
{
this._dbCommand.CommandTimeout = value;
}
}
public CommandType CommandType
{
get
{
return this._dbCommand.CommandType;
}
set
{
this._dbCommand.CommandType = value;
}
}
public IDbConnection Connection
{
get
{
return ((IDbCommand)this._dbCommand).Connection;
}
set
{
((IDbCommand)this._dbCommand).Connection = value;
}
}
public IDataParameterCollection Parameters
{
get
{
return this._dataParameterCollection;
}
}
public IDbTransaction Transaction
{
get
{
return ((IDbCommand)this._dbCommand).Transaction;
}
set
{
((IDbCommand)this._dbCommand).Transaction = value;
}
}
public UpdateRowSource UpdatedRowSource
{
get
{
return this._dbCommand.UpdatedRowSource;
}
set
{
this._dbCommand.UpdatedRowSource = value;
}
}
public void Cancel()
{
this._dbCommand.Cancel();
}
/*
*返回自定义的 SqlServerParameter
*/
public IDbDataParameter CreateParameter()
{
return new SqlServerParameter(this._dbCommand.CreateParameter());
}
public int ExecuteNonQuery()
{
return this._dbCommand.ExecuteNonQuery();
}
public IDataReader ExecuteReader()
{
return new SqlServerDataReader(this._dbCommand.ExecuteReader());
}
public IDataReader ExecuteReader(CommandBehavior behavior)
{
return new SqlServerDataReader(this._dbCommand.ExecuteReader(behavior));
}
public object ExecuteScalar()
{
return this._dbCommand.ExecuteScalar();
}
public void Prepare()
{
this._dbCommand.Prepare();
}
public void Dispose()
{
this._dbCommand.Dispose();
}
public class DataParameterCollection : IDataParameterCollection
{
IDataParameterCollection _parameterCollection;
Dictionary<SqlParameter, SqlServerParameter> _paramters = new Dictionary<SqlParameter, SqlServerParameter>();
public DataParameterCollection(IDataParameterCollection parameterCollection)
{
this._parameterCollection = parameterCollection;
}
public object this[string parameterName]
{
get
{
throw new NotImplementedException();
//SqlParameter sqlParameter = this._parameterCollection[parameterName] as SqlParameter;
//if (sqlParameter != null)
//{
// return this._paramters[sqlParameter];
//}
//return null;
}
set
{
throw new NotImplementedException();
//SqlServerParameter sqlServerParameter = (SqlServerParameter)value;
//if(sqlServerParameter==null)
}
}
public bool Contains(string parameterName)
{
return this._parameterCollection.Contains(parameterName);
}
public int IndexOf(string parameterName)
{
throw new NotImplementedException();
}
public void RemoveAt(string parameterName)
{
throw new NotImplementedException();
}
public bool IsFixedSize { get { return this._parameterCollection.IsFixedSize; } }
public bool IsReadOnly { get { return this._parameterCollection.IsReadOnly; } }
public object this[int index]
{
get
{
throw new NotImplementedException();
}
set
{
throw new NotImplementedException();
}
}
public int Add(object value)
{
SqlServerParameter sqlServerParameter = (SqlServerParameter)value;
int index = this._parameterCollection.Add(sqlServerParameter._sqlParameter);
var xx = this._parameterCollection[sqlServerParameter._sqlParameter.ParameterName];
if (!this._paramters.ContainsKey(sqlServerParameter._sqlParameter))
{
this._paramters.Add(sqlServerParameter._sqlParameter, sqlServerParameter);
}
return index;
throw new NotImplementedException();
}
public void Clear()
{
this._parameterCollection.Clear();
this._paramters.Clear();
}
public bool Contains(object value)
{
throw new NotImplementedException();
}
public int IndexOf(object value)
{
throw new NotImplementedException();
}
public void Insert(int index, object value)
{
throw new NotImplementedException();
}
public void Remove(object value)
{
throw new NotImplementedException();
}
public void RemoveAt(int index)
{
throw new NotImplementedException();
}
public int Count
{
get
{
return this._parameterCollection.Count;
}
}
public bool IsSynchronized
{
get
{
return this._parameterCollection.IsSynchronized;
}
}
public object SyncRoot
{
get
{
return this._parameterCollection.SyncRoot;
}
}
public void CopyTo(Array array, int index)
{
throw new NotImplementedException();
}
public IEnumerator GetEnumerator()
{
foreach (var item in this._parameterCollection)
{
yield return this._paramters[(SqlParameter)item];
}
}
}
}
/*
* 对驱动原生的 SqlConnection 包装
*/
public class SqlServerConnection : IDbConnection, IDisposable, ICloneable
{
SqlConnection _dbConnection;
public SqlServerConnection(SqlConnection dbConnection)
{
if (dbConnection == null)
throw new ArgumentNullException();
this._dbConnection = dbConnection;
}
public string ConnectionString
{
get { return this._dbConnection.ConnectionString; }
set { this._dbConnection.ConnectionString = value; }
}
public int ConnectionTimeout
{
get { return this._dbConnection.ConnectionTimeout; }
}
public string Database
{
get { return this._dbConnection.Database; }
}
public ConnectionState State
{
get { return this._dbConnection.State; }
}
public IDbTransaction BeginTransaction()
{
return this._dbConnection.BeginTransaction();
}
public IDbTransaction BeginTransaction(IsolationLevel il)
{
return this._dbConnection.BeginTransaction(il);
}
public void ChangeDatabase(string databaseName)
{
this._dbConnection.ChangeDatabase(databaseName);
}
public void Close()
{
this._dbConnection.Close();
}
/*
* 返回我们自定义的 SqlServerCommand
*/
public IDbCommand CreateCommand()
{
return new SqlServerCommand(this._dbConnection.CreateCommand());
}
public void Open()
{
this._dbConnection.Open();
}
public void Dispose()
{
this._dbConnection.Dispose();
}
public object Clone()
{
if (this._dbConnection is ICloneable)
{
return new SqlServerConnection((SqlConnection)((ICloneable)this._dbConnection).Clone());
}
throw new NotSupportedException();
}
}
}
| 28.571618 | 211 | 0.502994 | [
"MIT"
] | 1059444127/QueueSystem | Chloe-master/src/DotNet/ChloeDemo/RegisterMappingTypeDemo.cs | 22,141 | C# |
using Kingmaker.Blueprints.Items.Ecnchantments;
using Kingmaker.PubSubSystem;
using Kingmaker.RuleSystem.Rules;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DarkCodex.Components
{
public class ModifyWeaponSize : WeaponEnchantmentLogic, ISubscriber, IInitiatorRulebookSubscriber, IInitiatorRulebookHandler<RuleCalculateWeaponStats>, IRulebookHandler<RuleCalculateWeaponStats>
{
public void OnEventAboutToTrigger(RuleCalculateWeaponStats evt)
{
if (evt.Weapon == base.Owner)
{
evt.IncreaseWeaponSize(SizeCategoryChange);
}
}
public void OnEventDidTrigger(RuleCalculateWeaponStats evt)
{
}
public int SizeCategoryChange;
}
}
| 28.517241 | 198 | 0.719468 | [
"MIT"
] | TheGreatFox1/DarkCodex | DarkCodex/Components/ModifyWeaponSize.cs | 829 | C# |
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using System;
using NLog;
using NLog.Web;
namespace Dukkantek.API
{
public class Program
{
public static void Main(string[] args)
{
var logger = LogManager.Setup()
.LoadConfigurationFromAppSettings()
.GetCurrentClassLogger();
try
{
logger.Debug("init main");
CreateHostBuilder(args).Build().Run();
}
catch (Exception exception)
{
//NLog: catch setup errors
logger.Error(exception, "Stopped program because of exception");
throw;
}
finally
{
// Ensure to flush and stop internal timers/threads before application-exit (Avoid segmentation fault on Linux)
NLog.LogManager.Shutdown();
}
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
})
.ConfigureLogging(logging =>
{
logging.ClearProviders();
logging.SetMinimumLevel(Microsoft.Extensions.Logging.LogLevel.Trace);
})
.UseNLog();
}
}
| 31.04 | 127 | 0.511598 | [
"MIT"
] | AladienSaleh/Dukkantek | Dukkantek.API/Program.cs | 1,552 | C# |
using System.Text.Json.Serialization;
namespace Essensoft.Paylink.Alipay.Domain
{
/// <summary>
/// AlipayEbppIndustryGovHealthcodeQueryModel Data Structure.
/// </summary>
public class AlipayEbppIndustryGovHealthcodeQueryModel : AlipayObject
{
/// <summary>
/// json格式的业务相关信息, 因健康码不同的省市存在个性化的业务参数需求,在本字段内传入
/// </summary>
[JsonPropertyName("biz_info")]
public string BizInfo { get; set; }
/// <summary>
/// 业务类型,医护天使码: MEDIC_ANGEL; 健康码: HEALTHCODE。为空时默认为健康码HEALTHCODE
/// </summary>
[JsonPropertyName("biz_type")]
public string BizType { get; set; }
/// <summary>
/// 市
/// </summary>
[JsonPropertyName("city_code")]
public string CityCode { get; set; }
}
}
| 27.827586 | 73 | 0.60223 | [
"MIT"
] | Frunck8206/payment | src/Essensoft.Paylink.Alipay/Domain/AlipayEbppIndustryGovHealthcodeQueryModel.cs | 933 | C# |
using AutoMapper;
using Landmarks.Common.Models.Admin.BindingModels;
using Landmarks.Interfaces.Admin;
using Landmarks.Web.Common.Constants;
using Landmarks.Web.Common.Extensions;
using Landmarks.Web.Common.Messages;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
namespace Landmarks.Web.Areas.Admin.Pages.Region
{
[Authorize(Roles = NamesConstants.RoleAdmin)]
public class EditModel : PageModel
{
private readonly IRegionService _service;
private readonly IMapper _mapper;
public EditModel(IRegionService service, IMapper mapper)
{
this._service = service;
this._mapper = mapper;
}
[BindProperty]
public AddEditRegionBindingModel EditCategoryBindingModel { get; set; }
public IActionResult OnGet(int? id)
{
if (id == null) return NotFound();
var region = this._service.GetRegion(id.Value);
if (region == null) return NotFound();
this.EditCategoryBindingModel = this._mapper.Map<AddEditRegionBindingModel>(region);
return this.Page();
}
public IActionResult OnPost(int id)
{
if (ModelState.IsValid)
{
this.EditCategoryBindingModel.Id = id;
this._service.SaveEntity(this.EditCategoryBindingModel);
this.TempData.Put(MessageConstants.Name, new MessageModel()
{
Type = MessageType.Warning,
Message = MessageConstants.RegionEditSuccess
});
return RedirectToPage(RedirectURL.ToRegionList, new { Area = NamesConstants.AdminArea });
}
return this.Page();
}
}
} | 30.383333 | 105 | 0.629731 | [
"MIT"
] | stefkavasileva/Project | Landmarks/Landmarks.Web/Areas/Admin/Pages/Region/Edit.cshtml.cs | 1,823 | C# |
using UnityEngine;
using Knockback.Utility;
using UnityStandardAssets.CrossPlatformInput;
namespace Knockback.Helpers
{
/// <summary>
/// This class handles all the inputs from the user
/// </summary>
[System.Serializable]
public class KB_InputSettings
{
//** --ATTRIBUTES--
//** --SERIALIZED ATTRIBUTES--
[SerializeField] private InputType m_inputType = InputType.Touch;
//** --PUBLIC ATTRIBUTES--
public string m_movementXInput;
public string m_movementYInput;
public string m_jumpInput;
public string m_dashInput;
public string m_fireInput;
public string m_interactInput;
public string m_cancelInput;
public string m_readyInput;
[Range(0.6f, 1)] public float m_joystickDeadzone = 0.8f;
//** --METHODS--
//** --PUBLIC METHODS--
public Vector2 MovementInput()
{
if (m_inputType == InputType.MouseAndKeyboard)
return new Vector2(Input.GetAxisRaw(m_movementXInput), Input.GetAxisRaw(m_movementYInput));
else
return new Vector2(CrossPlatformInputManager.GetAxisRaw(m_movementXInput), CrossPlatformInputManager.GetAxisRaw(m_movementYInput));
}
public bool JumpInput()
{
if (m_inputType == InputType.MouseAndKeyboard)
return Input.GetKeyDown(m_jumpInput);
else
return CrossPlatformInputManager.GetButtonDown(m_jumpInput);
}
public bool DashInput()
{
if (m_inputType == InputType.MouseAndKeyboard)
return Input.GetKeyDown(m_dashInput);
else
return CrossPlatformInputManager.GetButtonDown(m_dashInput);
}
public bool FireInput()
{
if (m_inputType == InputType.MouseAndKeyboard)
return Input.GetKey(m_fireInput);
else
return CrossPlatformInputManager.GetButton(m_fireInput);
}
public bool InteractInput()
{
if (m_inputType == InputType.MouseAndKeyboard)
return Input.GetKeyDown(m_interactInput);
else
return CrossPlatformInputManager.GetButtonDown(m_interactInput);
}
public bool CancelInput()
{
if (m_inputType == InputType.MouseAndKeyboard)
return Input.GetKeyDown(m_cancelInput);
else
return CrossPlatformInputManager.GetButtonDown(m_cancelInput);
}
public bool ReadyInput()
{
if (m_inputType == InputType.MouseAndKeyboard)
return Input.GetKeyDown(m_readyInput);
else
return CrossPlatformInputManager.GetButtonDown(m_readyInput);
}
/// <summary>
/// Returns the input type
/// </summary>
public InputType GetInputType() => m_inputType;
/// <summary>
/// Method to set the input type
/// </summary>
/// <param name="inputType">Target input type</param>
public void SetInputType(InputType inputType) => this.m_inputType = inputType;
}
} | 31.940594 | 147 | 0.601364 | [
"MIT"
] | HemanthRj96/Repos-Knockback_version_3 | Knockback/Assets/Internal/Scripts/Helpers/KB_InputSettings.cs | 3,228 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using KERBALISM;
namespace KerbalismFFT
{
class FFTRadioactiveEngine : PartModule
{
[KSPField(isPersistant = true)]
public bool FirstLoad = true;
[KSPField(isPersistant = true)]
public string engineID1;
[KSPField(isPersistant = true)]
public string engineID2;
[KSPField(isPersistant = false)]
public FloatCurve EmissionPercentEngine1 = new FloatCurve();
[KSPField(isPersistant = false)]
public FloatCurve EmissionPercentEngine2 = new FloatCurve();
[KSPField(isPersistant = true)]
public bool EngineHasStarted = false;
[KSPField(isPersistant = true)]
public bool EmitterRunning = true;
[KSPField(isPersistant = true)]
public double GoalEmission = 0d;
[KSPField(isPersistant = true)]
public double EmitterMaxRadiation = 0d;
[KSPField(isPersistant = true)]
public double EmitterRadiationBeforeEngineShutdown = 0d;
[KSPField(isPersistant = true)]
public bool LastEngineState = false;
[KSPField(isPersistant = true)]
public double LastUpdateTime = 0d;
[KSPField(isPersistant = true)]
public double MinEmissionPercent = 0d;
[KSPField(isPersistant = true)]
public double EmissionDecayRate = 1d;
protected ModuleEnginesFX engineModule1;
protected ModuleEnginesFX engineModule2;
protected Emitter emitter;
public virtual void Start()
{
if (Features.Radiation && (Lib.IsFlight() || Lib.IsEditor()))
{
if (engineID1 != null && engineModule1 == null)
{
engineModule1 = FindEngineModule(part, engineID1);
}
if (engineID2 != null && engineModule2 == null)
{
engineModule2 = FindEngineModule(part, engineID2);
}
if (emitter == null)
{
emitter = FindEmitterModule(part);
}
if (FirstLoad)
{
if (emitter != null)
{
EmitterMaxRadiation = emitter.radiation;
if (EmitterMaxRadiation < 0)
{
EmitterMaxRadiation = 0d;
}
}
FirstLoad = false;
}
else
{
EmitterRunning = true;
}
}
}
public virtual void FixedUpdate()
{
if (Lib.IsFlight() && Features.Radiation && emitter != null)
{
bool EngineIgnited = false;
double MinEmission = MinEmissionPercent * EmitterMaxRadiation / 100;
if (engineModule1 != null && engineModule1.EngineIgnited)
{
EngineIgnited = true;
}
if (engineModule2 != null && engineModule2.EngineIgnited)
{
EngineIgnited = true;
}
if (!EngineHasStarted && !EngineIgnited && EmitterRunning)
{
// Disable radiation source, because engine has not started yet
emitter.running = false;
EmitterRunning = false;
}
if (!EngineHasStarted && EngineIgnited)
{
// Engine has started - enable radiation source
EngineHasStarted = true;
emitter.radiation = 0d;
emitter.running = true;
}
if (EngineHasStarted && EngineIgnited)
{
// Update radiation emission value according to engine throttle
double emission1 = 0d;
double emission2 = 0d;
if (engineModule1 != null && engineModule1.EngineIgnited)
{
emission1 = EmitterMaxRadiation * EmissionPercentEngine1.Evaluate(engineModule1.currentThrottle * 100f) / 100d;
}
if (engineModule2 != null && engineModule2.EngineIgnited)
{
emission2 = EmitterMaxRadiation * EmissionPercentEngine2.Evaluate(engineModule2.currentThrottle * 100f) / 100d;
}
GoalEmission = Math.Max(emission1, emission2);
if (GoalEmission < MinEmission)
{
GoalEmission = MinEmission;
}
if (GoalEmission > emitter.radiation)
{
emitter.radiation = GoalEmission;
}
}
if (EngineHasStarted && !EngineIgnited)
{
// Engine was shut down
GoalEmission = MinEmission;
}
if (EngineHasStarted && emitter.radiation > GoalEmission)
{
// Radiation decay
if (EmissionDecayRate <= 0)
{
emitter.radiation = GoalEmission;
}
else
{
double secondsPassed = Planetarium.GetUniversalTime() - LastUpdateTime;
if (secondsPassed > 0)
{
double newEmission = emitter.radiation;
newEmission -= EmitterMaxRadiation * (secondsPassed / EmissionDecayRate) / 100;
if (newEmission < GoalEmission)
{
newEmission = GoalEmission;
}
emitter.radiation = newEmission;
}
}
}
LastUpdateTime = Planetarium.GetUniversalTime();
}
}
// Simulate resources production/consumption for unloaded vessel
public static string BackgroundUpdate(Vessel v, ProtoPartSnapshot part_snapshot, ProtoPartModuleSnapshot module_snapshot, PartModule proto_part_module, Part proto_part, Dictionary<string, double> availableResources, List<KeyValuePair<string, double>> resourceChangeRequest, double elapsed_s)
{
if (Features.Radiation && Lib.Proto.GetBool(module_snapshot, "EngineHasStarted"))
{
ProtoPartModuleSnapshot emitter = KFFTUtils.FindPartModuleSnapshot(part_snapshot, "Emitter");
if (emitter != null)
{
double MinEmissionPercent = Lib.Proto.GetDouble(module_snapshot, "EmitterMaxRadiation");
double EmitterMaxRadiation = Lib.Proto.GetDouble(module_snapshot, "EmitterMaxRadiation");
double EmissionDecayRate = Lib.Proto.GetDouble(module_snapshot, "EmissionDecayRate");
double GoalEmission = MinEmissionPercent * EmitterMaxRadiation / 100;
if (EmissionDecayRate <= 0)
{
Lib.Proto.Set(emitter, "radiation", GoalEmission);
}
else
{
double secondsPassed = Planetarium.GetUniversalTime() - Lib.Proto.GetDouble(module_snapshot, "LastUpdateTime");
if (secondsPassed > 0)
{
double newEmission = Lib.Proto.GetDouble(emitter, "radiation");
newEmission -= EmitterMaxRadiation * (secondsPassed / EmissionDecayRate) / 100;
if (newEmission < GoalEmission)
{
newEmission = GoalEmission;
}
Lib.Proto.Set(emitter, "radiation", newEmission);
}
}
}
}
Lib.Proto.Set(module_snapshot, "LastUpdateTime", Planetarium.GetUniversalTime());
return "radioactive engine";
}
// Find ModuleEnginesFX module
public ModuleEnginesFX FindEngineModule(Part part, string moduleName)
{
ModuleEnginesFX engine = part.GetComponents<ModuleEnginesFX>().ToList().Find(x => x.engineID == moduleName);
if (engine == null)
{
KFFTUtils.LogError($"[FFTRadioactiveEngine][{part}] No ModuleEnginesFX named {moduleName} was found.");
}
return engine;
}
// Find Emitter module on part (Kerbalism radiation source)
public Emitter FindEmitterModule(Part part)
{
Emitter emitter = part.GetComponents<Emitter>().ToList().First();
if (emitter == null)
{
KFFTUtils.LogError($"[FFTRadioactiveEngine][{part}] No radiation Emitter was found.");
}
return emitter;
}
}
}
| 31.072398 | 293 | 0.678025 | [
"Unlicense",
"MIT"
] | judicator/KerbalismFFT | src/Modules/RadioactiveEngine.cs | 6,869 | C# |
namespace BinanceExchange.API.Models.Response.Error
{
/// <summary>
/// This exception is used when malformed requests are sent to the server. Please review the request object
/// </summary>
public class BinanceBadRequestException : BinanceException {
public BinanceBadRequestException(BinanceError errorDetails) : base((string) "Malformed requests are sent to the server. Please review the request object/string", errorDetails)
{
}
}
} | 43.727273 | 184 | 0.719335 | [
"MIT"
] | 1Konto/BinanceDotNet | BinanceExchange.API/Models/Response/Error/BinanceBadRequestException.cs | 483 | C# |
namespace Zsharp.Elysium.Tests
{
using System;
using System.Buffers;
using System.Buffers.Binary;
static class SerializationTesting
{
public static ArrayBufferWriter<byte> CreateWriter(int id, int version)
{
var writer = new ArrayBufferWriter<byte>();
BinaryPrimitives.WriteUInt16BigEndian(writer.GetSpan(2), Convert.ToUInt16(version));
writer.Advance(2);
BinaryPrimitives.WriteUInt16BigEndian(writer.GetSpan(2), Convert.ToUInt16(id));
writer.Advance(2);
return writer;
}
public static SequenceReader<byte> CreateReader(byte[] data)
{
return new SequenceReader<byte>(new ReadOnlySequence<byte>(data));
}
public static SequenceReader<byte> CreateReader(ArrayBufferWriter<byte> writer)
{
return new SequenceReader<byte>(new ReadOnlySequence<byte>(writer.WrittenMemory));
}
}
}
| 29.484848 | 96 | 0.642343 | [
"MIT"
] | firoorg/zsharp | src/Zsharp.Elysium.Tests/SerializationTesting.cs | 973 | C# |
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using System.Threading.Tasks;
using Microsoft.Coyote.Specifications;
using Xunit;
using Xunit.Abstractions;
namespace Microsoft.Coyote.SystematicTesting.Tests.Tasks
{
public class TaskRunConfigureAwaitTrueTests : BaseSystematicTest
{
public TaskRunConfigureAwaitTrueTests(ITestOutputHelper output)
: base(output)
{
}
[Fact(Timeout = 5000)]
public void TestRunParallelTask()
{
this.Test(async () =>
{
SharedEntry entry = new SharedEntry();
await Task.Run(() =>
{
entry.Value = 5;
}).ConfigureAwait(true);
AssertSharedEntryValue(entry, 5);
},
configuration: GetConfiguration().WithTestingIterations(200));
}
[Fact(Timeout = 5000)]
public void TestRunParallelTaskFailure()
{
this.TestWithError(async () =>
{
SharedEntry entry = new SharedEntry();
await Task.Run(() =>
{
entry.Value = 3;
}).ConfigureAwait(true);
AssertSharedEntryValue(entry, 5);
},
configuration: GetConfiguration().WithTestingIterations(200),
expectedError: "Value is 3 instead of 5.",
replay: true);
}
[Fact(Timeout = 5000)]
public void TestRunParallelSynchronousTask()
{
this.Test(async () =>
{
SharedEntry entry = new SharedEntry();
await Task.Run(async () =>
{
await Task.CompletedTask;
entry.Value = 5;
}).ConfigureAwait(true);
AssertSharedEntryValue(entry, 5);
},
configuration: GetConfiguration().WithTestingIterations(200));
}
[Fact(Timeout = 5000)]
public void TestRunParallelSynchronousTaskFailure()
{
this.TestWithError(async () =>
{
SharedEntry entry = new SharedEntry();
await Task.Run(async () =>
{
await Task.CompletedTask;
entry.Value = 3;
}).ConfigureAwait(true);
AssertSharedEntryValue(entry, 5);
},
configuration: GetConfiguration().WithTestingIterations(200),
expectedError: "Value is 3 instead of 5.",
replay: true);
}
[Fact(Timeout = 5000)]
public void TestRunParallelAsynchronousTask()
{
this.Test(async () =>
{
SharedEntry entry = new SharedEntry();
await Task.Run(async () =>
{
await Task.Delay(1).ConfigureAwait(true);
entry.Value = 5;
}).ConfigureAwait(true);
AssertSharedEntryValue(entry, 5);
},
configuration: GetConfiguration().WithTestingIterations(200));
}
[Fact(Timeout = 5000)]
public void TestRunParallelAsynchronousTaskFailure()
{
this.TestWithError(async () =>
{
SharedEntry entry = new SharedEntry();
await Task.Run(async () =>
{
await Task.Delay(1).ConfigureAwait(true);
entry.Value = 3;
}).ConfigureAwait(true);
AssertSharedEntryValue(entry, 5);
},
configuration: GetConfiguration().WithTestingIterations(200),
expectedError: "Value is 3 instead of 5.",
replay: true);
}
[Fact(Timeout = 5000)]
public void TestRunNestedParallelSynchronousTask()
{
this.Test(async () =>
{
SharedEntry entry = new SharedEntry();
await Task.Run(async () =>
{
await Task.Run(async () =>
{
await Task.CompletedTask;
entry.Value = 3;
}).ConfigureAwait(true);
entry.Value = 5;
}).ConfigureAwait(true);
AssertSharedEntryValue(entry, 5);
},
configuration: GetConfiguration().WithTestingIterations(200));
}
[Fact(Timeout = 5000)]
public void TestAwaitNestedParallelSynchronousTaskFailure()
{
this.TestWithError(async () =>
{
SharedEntry entry = new SharedEntry();
await Task.Run(async () =>
{
await Task.Run(async () =>
{
await Task.CompletedTask;
entry.Value = 5;
}).ConfigureAwait(true);
entry.Value = 3;
}).ConfigureAwait(true);
AssertSharedEntryValue(entry, 5);
},
configuration: GetConfiguration().WithTestingIterations(200),
expectedError: "Value is 3 instead of 5.",
replay: true);
}
[Fact(Timeout = 5000)]
public void TestAwaitNestedParallelAsynchronousTask()
{
this.Test(async () =>
{
SharedEntry entry = new SharedEntry();
await Task.Run(async () =>
{
await Task.Run(async () =>
{
await Task.Delay(1).ConfigureAwait(true);
entry.Value = 3;
}).ConfigureAwait(true);
entry.Value = 5;
}).ConfigureAwait(true);
AssertSharedEntryValue(entry, 5);
},
configuration: GetConfiguration().WithTestingIterations(200));
}
[Fact(Timeout = 5000)]
public void TestAwaitNestedParallelAsynchronousTaskFailure()
{
this.TestWithError(async () =>
{
SharedEntry entry = new SharedEntry();
await Task.Run(async () =>
{
await Task.Run(async () =>
{
await Task.Delay(1).ConfigureAwait(true);
entry.Value = 5;
}).ConfigureAwait(true);
entry.Value = 3;
}).ConfigureAwait(true);
AssertSharedEntryValue(entry, 5);
},
configuration: GetConfiguration().WithTestingIterations(200),
expectedError: "Value is 3 instead of 5.",
replay: true);
}
[Fact(Timeout = 5000)]
public void TestRunParallelTaskWithResult()
{
this.Test(async () =>
{
SharedEntry entry = new SharedEntry();
int value = await Task.Run(() =>
{
entry.Value = 5;
return entry.Value;
}).ConfigureAwait(true);
Specification.Assert(value == 5, "Value is {0} instead of 5.", value);
},
configuration: GetConfiguration().WithTestingIterations(200));
}
[Fact(Timeout = 5000)]
public void TestRunParallelTaskWithResultFailure()
{
this.TestWithError(async () =>
{
SharedEntry entry = new SharedEntry();
int value = await Task.Run(() =>
{
entry.Value = 3;
return entry.Value;
}).ConfigureAwait(true);
Specification.Assert(value == 5, "Value is {0} instead of 5.", value);
},
configuration: GetConfiguration().WithTestingIterations(200),
expectedError: "Value is 3 instead of 5.",
replay: true);
}
[Fact(Timeout = 5000)]
public void TestRunParallelSynchronousTaskWithResult()
{
this.Test(async () =>
{
SharedEntry entry = new SharedEntry();
int value = await Task.Run(async () =>
{
await Task.CompletedTask;
entry.Value = 5;
return entry.Value;
}).ConfigureAwait(true);
Specification.Assert(value == 5, "Value is {0} instead of 5.", value);
},
configuration: GetConfiguration().WithTestingIterations(200));
}
[Fact(Timeout = 5000)]
public void TestRunParallelSynchronousTaskWithResultFailure()
{
this.TestWithError(async () =>
{
SharedEntry entry = new SharedEntry();
int value = await Task.Run(async () =>
{
await Task.CompletedTask;
entry.Value = 3;
return entry.Value;
}).ConfigureAwait(true);
Specification.Assert(value == 5, "Value is {0} instead of 5.", value);
},
configuration: GetConfiguration().WithTestingIterations(200),
expectedError: "Value is 3 instead of 5.",
replay: true);
}
[Fact(Timeout = 5000)]
public void TestRunParallelAsynchronousTaskWithResult()
{
this.Test(async () =>
{
SharedEntry entry = new SharedEntry();
int value = await Task.Run(async () =>
{
await Task.Delay(1).ConfigureAwait(true);
entry.Value = 5;
return entry.Value;
}).ConfigureAwait(true);
Specification.Assert(value == 5, "Value is {0} instead of 5.", value);
},
configuration: GetConfiguration().WithTestingIterations(200));
}
[Fact(Timeout = 5000)]
public void TestRunParallelAsynchronousTaskWithResultFailure()
{
this.TestWithError(async () =>
{
SharedEntry entry = new SharedEntry();
int value = await Task.Run(async () =>
{
await Task.Delay(1).ConfigureAwait(true);
entry.Value = 3;
return entry.Value;
}).ConfigureAwait(true);
Specification.Assert(value == 5, "Value is {0} instead of 5.", value);
},
configuration: GetConfiguration().WithTestingIterations(200),
expectedError: "Value is 3 instead of 5.",
replay: true);
}
[Fact(Timeout = 5000)]
public void TestRunNestedParallelSynchronousTaskWithResult()
{
this.Test(async () =>
{
SharedEntry entry = new SharedEntry();
int value = await Task.Run(async () =>
{
return await Task.Run(async () =>
{
await Task.CompletedTask;
entry.Value = 5;
return entry.Value;
}).ConfigureAwait(true);
}).ConfigureAwait(true);
Specification.Assert(value == 5, "Value is {0} instead of 5.", value);
},
configuration: GetConfiguration().WithTestingIterations(200));
}
[Fact(Timeout = 5000)]
public void TestRunNestedParallelSynchronousTaskWithResultFailure()
{
this.TestWithError(async () =>
{
SharedEntry entry = new SharedEntry();
int value = await Task.Run(async () =>
{
return await Task.Run(async () =>
{
await Task.CompletedTask;
entry.Value = 3;
return entry.Value;
}).ConfigureAwait(true);
}).ConfigureAwait(true);
Specification.Assert(value == 5, "Value is {0} instead of 5.", value);
},
configuration: GetConfiguration().WithTestingIterations(200),
expectedError: "Value is 3 instead of 5.",
replay: true);
}
[Fact(Timeout = 5000)]
public void TestRunNestedParallelAsynchronousTaskWithResult()
{
this.Test(async () =>
{
SharedEntry entry = new SharedEntry();
int value = await Task.Run(async () =>
{
return await Task.Run(async () =>
{
await Task.Delay(1).ConfigureAwait(true);
entry.Value = 5;
return entry.Value;
}).ConfigureAwait(true);
}).ConfigureAwait(true);
Specification.Assert(value == 5, "Value is {0} instead of 5.", value);
},
configuration: GetConfiguration().WithTestingIterations(200));
}
[Fact(Timeout = 5000)]
public void TestRunNestedParallelAsynchronousTaskWithResultFailure()
{
this.TestWithError(async () =>
{
SharedEntry entry = new SharedEntry();
int value = await Task.Run(async () =>
{
return await Task.Run(async () =>
{
await Task.Delay(1).ConfigureAwait(true);
entry.Value = 3;
return entry.Value;
}).ConfigureAwait(true);
}).ConfigureAwait(true);
Specification.Assert(value == 5, "Value is {0} instead of 5.", value);
},
configuration: GetConfiguration().WithTestingIterations(200),
expectedError: "Value is 3 instead of 5.",
replay: true);
}
}
}
| 34.045564 | 86 | 0.47348 | [
"MIT"
] | arunt1204/coyote | Tests/Tests.SystematicTesting/Tasks/ConfigureAwait/TaskRunConfigureAwaitTrueTests.cs | 14,199 | 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 networkmanager-2019-07-05.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Text;
using System.Xml.Serialization;
using Amazon.NetworkManager.Model;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
using Amazon.Runtime.Internal.Transform;
using Amazon.Runtime.Internal.Util;
using ThirdParty.Json.LitJson;
namespace Amazon.NetworkManager.Model.Internal.MarshallTransformations
{
/// <summary>
/// DisassociateLink Request Marshaller
/// </summary>
public class DisassociateLinkRequestMarshaller : IMarshaller<IRequest, DisassociateLinkRequest> , IMarshaller<IRequest,AmazonWebServiceRequest>
{
/// <summary>
/// Marshaller the request object to the HTTP request.
/// </summary>
/// <param name="input"></param>
/// <returns></returns>
public IRequest Marshall(AmazonWebServiceRequest input)
{
return this.Marshall((DisassociateLinkRequest)input);
}
/// <summary>
/// Marshaller the request object to the HTTP request.
/// </summary>
/// <param name="publicRequest"></param>
/// <returns></returns>
public IRequest Marshall(DisassociateLinkRequest publicRequest)
{
IRequest request = new DefaultRequest(publicRequest, "Amazon.NetworkManager");
request.Headers[Amazon.Util.HeaderKeys.XAmzApiVersion] = "2019-07-05";
request.HttpMethod = "DELETE";
if (!publicRequest.IsSetGlobalNetworkId())
throw new AmazonNetworkManagerException("Request object does not have required field GlobalNetworkId set");
request.AddPathResource("{globalNetworkId}", StringUtils.FromString(publicRequest.GlobalNetworkId));
if (publicRequest.IsSetDeviceId())
request.Parameters.Add("deviceId", StringUtils.FromString(publicRequest.DeviceId));
if (publicRequest.IsSetLinkId())
request.Parameters.Add("linkId", StringUtils.FromString(publicRequest.LinkId));
request.ResourcePath = "/global-networks/{globalNetworkId}/link-associations";
request.UseQueryString = true;
return request;
}
private static DisassociateLinkRequestMarshaller _instance = new DisassociateLinkRequestMarshaller();
internal static DisassociateLinkRequestMarshaller GetInstance()
{
return _instance;
}
/// <summary>
/// Gets the singleton.
/// </summary>
public static DisassociateLinkRequestMarshaller Instance
{
get
{
return _instance;
}
}
}
} | 36.723404 | 147 | 0.662804 | [
"Apache-2.0"
] | Hazy87/aws-sdk-net | sdk/src/Services/NetworkManager/Generated/Model/Internal/MarshallTransformations/DisassociateLinkRequestMarshaller.cs | 3,452 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.EntityFrameworkCore;
using GameManagerUi.Models;
namespace GameManagerUi.Pages.Players
{
public class IndexModel : PageModel
{
private readonly GameManagerUi.Models.GaMaDbContext _context;
public IndexModel(GameManagerUi.Models.GaMaDbContext context)
{
_context = context;
}
public IList<Player> Player { get;set; }
public async Task OnGetAsync()
{
Player = await _context.Players.ToListAsync();
}
}
}
| 23.965517 | 69 | 0.692086 | [
"Apache-2.0"
] | Hex-Zero/GaMa | GameManagerUi/Pages/Players/Index.cshtml.cs | 697 | C# |
using System;
using Newtonsoft.Json;
namespace Essensoft.AspNetCore.Payment.Alipay.Domain
{
/// <summary>
/// DashboardParam Data Structure.
/// </summary>
[Serializable]
public class DashboardParam : AlipayObject
{
/// <summary>
/// 仪表盘中的字段列名称
/// </summary>
[JsonProperty("key")]
public string Key { get; set; }
/// <summary>
/// 操作计算符,现支持的包括:EQ(等于),GT(大于),LT(小于),LTE(小于或等于),GTE(大于或等于),NOT_EQ(不等于),LIKE(like),NOT_LIKE(not like)
/// </summary>
[JsonProperty("operate")]
public string Operate { get; set; }
/// <summary>
/// 过滤条件值
/// </summary>
[JsonProperty("value")]
public string Value { get; set; }
}
}
| 24.516129 | 109 | 0.546053 | [
"MIT"
] | gebiWangshushu/payment | src/Essensoft.AspNetCore.Payment.Alipay/Domain/DashboardParam.cs | 856 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Configuration;
using Microsoft.Azure.Documents.Client;
using Microsoft.Azure.Documents.Linq;
using Newtonsoft.Json;
using Microsoft.Azure.Documents;
using UrlNotes.Models;
using Microsoft.Extensions.Configuration;
using System.IO;
namespace UrlNotes
{
public static class DocumentDBRepository
{
private static DocumentClient client;
private static Dictionary<string, string> config;
static DocumentDBRepository()
{
GetConfiguration();
client = new DocumentClient(new Uri(config["endpoint"]), config["authkey"]);
}
public static async Task<string> GetAllDocs<T>(string collectionName)
{
var q = client.CreateDocumentQuery<T>(GetCollectionUri(collectionName), new FeedOptions { MaxItemCount = -1, EnableCrossPartitionQuery = true })
.Select(item => item)
.AsDocumentQuery();
List<T> results = new List<T>();
while (q.HasMoreResults)
{
results.AddRange(await q.ExecuteNextAsync<T>());
}
return JsonConvert.SerializeObject(results);
}
public static async Task<List<string>> GetDBCollections()
{
bool dbExists = CheckDBExists();
if (!dbExists)
{
CreateDB().Wait();
await CreateCollections();
InsertDocuments();
}
IEnumerable<string> collectionNames;
try
{
var colls = await client.ReadDocumentCollectionFeedAsync(UriFactory.CreateDatabaseUri(config["database"]));
collectionNames = from x in colls
select x.Id;
}
catch (Exception ex)
{
throw;
}
return collectionNames.ToList<string>();
}
private static async Task CreateCollections()
{
var videoCollection = await client.CreateDocumentCollectionAsync(UriFactory.CreateDatabaseUri(config["database"]), new DocumentCollection { Id = "Videos" });
var docsCollectionn = await client.CreateDocumentCollectionAsync(UriFactory.CreateDatabaseUri(config["database"]), new DocumentCollection { Id = "Docs" });
}
private static bool CheckDBExists()
{
var dbId = config["database"] ?? "NotesDB";
Database database = client.CreateDatabaseQuery().Where(db => db.Id == dbId).ToArray().FirstOrDefault();
if (database != null)
{
return true;
}
else
{
return false;
}
}
public static async void CreateDocument<T>(T item, string collectionName) where T : Item
{
await client.CreateDocumentAsync((GetCollectionUri(collectionName)), item);
}
public static string Search<T>(string collectionName, string searchTerms, string searchText)
{
FeedOptions queryOptions = new FeedOptions { MaxItemCount = -1, EnableCrossPartitionQuery = true };
var terms = searchTerms.Trim().Split(' ');
var contains = terms.Select(x => string.Format("CONTAINS({0}, @{1})", x == "keywords" ? "k.name" : "item." + x, x)).ToArray();
var q = new SqlQuerySpec
{
QueryText = "SELECT VALUE item FROM item JOIN k IN item.keywords WHERE " + contains[0],
Parameters = new SqlParameterCollection()
{
new SqlParameter("@" + terms[0].ToLower(), searchText)
}
};
if (terms.Length > 2 && contains.Length > 2)
{
q.Parameters.Add(new SqlParameter("@" + terms[1], searchText));
q.QueryText += " OR " + contains[1];
}
List<T> queryResult = (client.CreateDocumentQuery<T>(
GetCollectionUri(collectionName),
q,
queryOptions)).ToList();
return JsonConvert.SerializeObject(queryResult);
}
public static async void DeleteDocument(string id, string collectionName)
{
var doc = GetDocumentItem<Item>(id, collectionName);
await client.DeleteDocumentAsync(UriFactory.CreateDocumentUri(config["database"], collectionName, id));
}
public static async void EditDocument(Item item, string collectionName)
{
var doc = GetDocument(item.Id, collectionName);
doc.SetPropertyValue("notes", item.Notes);
doc.SetPropertyValue("tutorial", item.IsTutorial);
Document updated = await client.ReplaceDocumentAsync(doc);
}
public static Document GetDocument(string id, string collectionName)
{
var doc = client.CreateDocumentQuery<Document>(GetCollectionUri(collectionName), new FeedOptions { EnableCrossPartitionQuery = true })
.Where(r => r.Id == id)
.AsEnumerable()
.SingleOrDefault();
return doc;
}
public static T GetDocumentItem<T>(string id, string collectionName) where T : Item
{
var docItem = client.CreateDocumentQuery<T>(GetCollectionUri(collectionName), new FeedOptions { EnableCrossPartitionQuery = true })
.Where(r => r.Id == id)
.AsEnumerable()
.SingleOrDefault();
return docItem;
}
public static void GetConfiguration()
{
var builder = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true);
builder = builder.AddJsonFile($"appsettings.ConnectionStrings.json", optional: true);
builder = builder.AddEnvironmentVariables();
var configBuilder = builder.Build();
config = new Dictionary<string, string>
{
{ "database", configBuilder.GetConnectionString("database") ?? "NotesDB" },
{ "authkey", configBuilder.GetConnectionString("authkey") },
{ "endpoint", configBuilder.GetConnectionString("endpoint") }
};
}
public static Uri GetCollectionUri(string collectionName)
{
return UriFactory.CreateDocumentCollectionUri(config["database"], collectionName);
}
private async static Task CreateDB()
{
try
{
Database database = await client.CreateDatabaseIfNotExistsAsync(new Database { Id = "NotesDB" });
config["database"] = database.Id;
}
catch (Exception)
{
throw;
}
}
private static void InsertDocuments()
{
Video[] starterVideos = {
new Video(new Item() { stringUrl = "https://channel9.msdn.com/Shows/The-Open-Source-Show/Part-1-of-4-Overview-of-existing-tools-to-create-Azure-Container-Service-clusters", IsTutorial = true, Notes = "First of four-part series on Azure Container Service" }),
new Video(new Item() { stringUrl = "https://channel9.msdn.com/Shows/The-Open-Source-Show/Part-2-of-4-Create-an-Azure-Container-Instance-with-the-container-image", IsTutorial = true }),
new Video(new Item() { stringUrl = "https://channel9.msdn.com/Shows/The-Open-Source-Show/Part-3-of-4-Create-a-Web-App-for-Containers-and-set-up-a-web-hook", IsTutorial = true }),
new Video(new Item() { stringUrl = "https://channel9.msdn.com/Shows/The-Open-Source-Show/Part-4-of-4-Use-Azure-Container-Registry", IsTutorial = true }),
new Video(new Item() { stringUrl = "https://channel9.msdn.com/Shows/This+Week+On+Channel+9/TWC9-Windows-Developer-Awards-Voting-Opens-AI-courses-from-Microsoft-Serial-Console-Access-in-Azure-" }),
new Video(new Item() { stringUrl = "https://channel9.msdn.com/Shows/Azure-Friday/Metaparticle", Notes = "Metaparticle sounds cool!" }),
new Video(new Item() { stringUrl = "https://channel9.msdn.com/Shows/XamarinShow/Building-the-New-MSN-News-App-with-Xamarin" }),
new Video(new Item() { stringUrl = "https://channel9.msdn.com/Shows/5-Things/Episode-12-Five-Things-About-Docker", IsTutorial = false }),
new Video(new Item() { stringUrl = "https://channel9.msdn.com/Shows/XamarinShow/Scalable--Service-Data-with-CosmosDB-for-Mobile", IsTutorial = false }),
new Video(new Item() { stringUrl = "https://channel9.msdn.com/Shows/Tech-Crumbs/Starting-with-CosmosDB", IsTutorial = true }),
new Video(new Item() { stringUrl = "https://channel9.msdn.com/Shows/Visual-Studio-Toolbox/CosmosDB-Serverless-NoSQL-for-the-NET-Developer" }),
new Video(new Item() { stringUrl = "https://channel9.msdn.com/Shows/On-NET/Jeremy-Likness-CosmosDB-and-NET-Core", IsTutorial = true }),
new Video(new Item() { stringUrl = "https://channel9.msdn.com/Shows/Azure-Friday/Whats-New-in-Azure-Cosmos-DB", Notes = "Info on what's happening with CosmosDB!" }),
new Video(new Item() { stringUrl = "https://channel9.msdn.com/Shows/Level-Up/Azure-Cosmos-DB-Comprehensive-Overview", IsTutorial = false }),
new Video(new Item() { stringUrl = "https://channel9.msdn.com/Shows/Level-Up/Azure-Container-Instances-for-Multiplayer-Gaming-Theater", Notes = "Info on how to use containers with games" }),
new Video(new Item() { stringUrl = "https://channel9.msdn.com/Shows/Level-Up/Planning-and-building-games-using-the-full-power-of-VSTS-Agile-CI--CD-end-to-end-demo" }),
new Video(new Item() { stringUrl = "https://channel9.msdn.com/Shows/Internet-of-Things-Show/Azure-IoT-Toolkit-extension-for-Visual-Studio-Code" }),
new Video(new Item() { stringUrl = "https://channel9.msdn.com/Shows/This+Week+On+Channel+9/TWC9-Connect-Next-Week-Picking-the-Right-Azure-VM-Star-Wars-Video-Cards-Life-After-the-Uniform-and-m" }),
new Video(new Item() { stringUrl = "https://channel9.msdn.com/Blogs/Azure/Log-Alerts-for-Application-Insights-Preview" }),
new Video(new Item() { stringUrl = "https://channel9.msdn.com/Shows/AI-Show/The-Simplest-Machine-Learning" })
};
foreach (var item in starterVideos)
{
CreateDocument(item, "Videos");
}
var Docs = new List<Doc>();
Doc[] starterDocs = {
new Doc(new Item() { stringUrl = "https://docs.microsoft.com/en-us/azure/event-grid", IsTutorial = false, Notes = "Event Grid is very interesting! Look at this later"}),
new Doc(new Item() { stringUrl = "https://docs.microsoft.com/en-us/azure/cosmos-db/create-sql-api-dotnet", IsTutorial = true}),
new Doc(new Item() { stringUrl = "https://docs.microsoft.com/en-us/azure/app-service/app-service-web-tutorial-rest-api", IsTutorial = true}),
new Doc(new Item() { stringUrl = "https://docs.microsoft.com/en-us/azure/app-service/scripts/app-service-cli-backup-onetime", IsTutorial = true}),
new Doc(new Item() { stringUrl = "https://azure.microsoft.com/en-us/overview/serverless-computing", IsTutorial = false, Notes = "Intro to serverless computing"}),
new Doc(new Item() { stringUrl = "https://docs.microsoft.com/en-us/azure/app-service/app-service-web-overview", IsTutorial = false}),
new Doc(new Item() { stringUrl = "https://docs.microsoft.com/en-us/azure/cosmos-db/query-cheat-sheet"}),
new Doc(new Item() { stringUrl = "https://docs.microsoft.com/en-us/azure/cosmos-db/20-days-of-tips", IsTutorial = true}),
new Doc(new Item() { stringUrl = "https://docs.microsoft.com/en-us/azure/cosmos-db/faq"}),
new Doc(new Item() { stringUrl = "https://docs.microsoft.com/en-us/azure/cosmos-db/manage-account"}),
new Doc(new Item() { stringUrl = "https://docs.microsoft.com/en-us/azure/azure-functions/functions-twitter-email"}),
new Doc(new Item() { stringUrl = "https://docs.microsoft.com/en-us/azure/azure-functions/functions-create-github-webhook-triggered-function", IsTutorial = true, Notes = "GitHub webhook triggered Azure Functions"}),
new Doc(new Item() { stringUrl = "https://docs.microsoft.com/en-us/azure/azure-functions/scripts/functions-cli-create-function-app-vsts-continuous", IsTutorial = true}),
new Doc(new Item() { stringUrl = "https://docs.microsoft.com/en-us/azure/azure-functions/durable-functions-overview"}),
new Doc(new Item() { stringUrl = "https://docs.microsoft.com/en-us/azure/azure-functions/functions-app-settings"}),
new Doc(new Item() { stringUrl = "https://docs.microsoft.com/en-us/azure/event-grid/resize-images-on-storage-blob-upload-event", IsTutorial = true}),
new Doc(new Item() { stringUrl = "https://docs.microsoft.com/en-us/azure/event-grid/concepts", Notes = "Basic concepts on event grid.", IsTutorial = false}),
new Doc(new Item() { stringUrl = "https://docs.microsoft.com/en-us/azure/cognitive-services/computer-vision/quickstarts/csharp", Notes = "Quickstarts to get started with Azure Cognitive Services", IsTutorial = true}),
new Doc(new Item() { stringUrl = "https://docs.microsoft.com/en-us/azure/azure-functions/functions-create-serverless-api", IsTutorial = true}),
new Doc(new Item() { stringUrl = "https://docs.microsoft.com/en-us/azure/cosmos-db/sql-api-dotnetcore-get-started", IsTutorial = true})
};
foreach (var item in starterDocs)
{
CreateDocument(item, "Docs");
}
}
}
}
| 54.725191 | 274 | 0.605663 | [
"Apache-2.0"
] | AzureAdvocateBit/AzureSample-UrlNotes-1 | DocumentDBRepository.cs | 14,340 | C# |
using Microsoft.EntityFrameworkCore.Migrations;
namespace FinalPoint.Data.Migrations
{
public partial class UserProtocolsNavigationalPropertyfix : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
}
protected override void Down(MigrationBuilder migrationBuilder)
{
}
}
}
| 20.111111 | 73 | 0.69337 | [
"MIT"
] | nikolaynikolaev013/FinalPoint | Data/FinalPoint.Data/Migrations/20210605105249_UserProtocolsNavigationalPropertyfix.cs | 364 | C# |
using System;
using System.Linq.Expressions;
using LinqToDB.SqlQuery;
namespace LinqToDB.Linq.Builder
{
using SqlProvider;
class ContextParser : ISequenceBuilder
{
public int BuildCounter { get; set; }
public bool CanBuild(ExpressionBuilder builder, BuildInfo buildInfo)
{
var call = buildInfo.Expression as MethodCallExpression;
return call != null && call.Method.Name == "GetContext";
}
public IBuildContext BuildSequence(ExpressionBuilder builder, BuildInfo buildInfo)
{
var call = (MethodCallExpression)buildInfo.Expression;
return new Context(builder.BuildSequence(new BuildInfo(buildInfo, call.Arguments[0])));
}
public SequenceConvertInfo Convert(ExpressionBuilder builder, BuildInfo buildInfo, ParameterExpression param)
{
return null;
}
public bool IsSequence(ExpressionBuilder builder, BuildInfo buildInfo)
{
return builder.IsSequence(new BuildInfo(buildInfo, ((MethodCallExpression)buildInfo.Expression).Arguments[0]));
}
public class Context : PassThroughContext
{
public Context(IBuildContext context) : base(context)
{
}
public ISqlOptimizer SqlOptimizer;
public Action SetParameters;
public override void BuildQuery<T>(Query<T> query, ParameterExpression queryParameter)
{
query.DoNotCache = true;
QueryRunner.SetNonQueryQuery(query);
SqlOptimizer = query.SqlOptimizer;
SetParameters = () => QueryRunner.SetParameters(query, Builder.DataContext, query.Expression, null, 0);
query.GetElement = (db, expr, ps) => this;
}
}
}
}
| 27.862069 | 115 | 0.717203 | [
"MIT"
] | Arithmomaniac/linq2db | Source/LinqToDB/Linq/Builder/ContextParser.cs | 1,618 | C# |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Microsoft.Diagnostics.Runtime;
using Shared;
namespace Lab3
{
class Program
{
static void Main(string[] args)
{
// args[0] is supposed to be the dump filename
if (args.Length != 1)
{
Console.WriteLine("A dump filename must be provided.");
return;
}
var dumpFilename = args[0];
if (!File.Exists(dumpFilename))
{
Console.WriteLine($"{dumpFilename} does not exist.");
return;
}
ProcessDumpFile(args[0]);
}
private static void ProcessDumpFile(string dumpFilename)
{
using (var target = Utils.GetTarget(dumpFilename))
{
ClrRuntime clr = target.ClrVersions[0].CreateRuntime();
Dictionary<string, TimerStat> stats = new Dictionary<string, TimerStat>(64);
int totalCount = 0;
foreach (var timer in EnumerateTimers(clr).OrderBy(t => t.Period))
{
totalCount++;
string line = string.Intern(GetTimerString(timer));
string key = string.Intern(string.Format(
"@{0,8} ms every {1,8} ms | {2} ({3}) -> {4}",
timer.DueTime.ToString(),
(timer.Period == 4294967295) ? " ------" : timer.Period.ToString(),
timer.StateAddress.ToString("X16"),
timer.StateTypeName,
timer.MethodName
));
TimerStat stat;
if (!stats.ContainsKey(key))
{
stat = new TimerStat()
{
Count = 0,
Line = line,
Period = timer.Period
};
stats[key] = stat;
}
else
{
stat = stats[key];
}
stat.Count = stat.Count + 1;
Console.WriteLine(line);
}
// create a summary
Console.WriteLine("\r\n " + totalCount.ToString() + " timers\r\n-----------------------------------------------");
foreach (var stat in stats.OrderBy(kvp => kvp.Value.Count))
{
Console.WriteLine(string.Format(
"{0,4} | {1}",
stat.Value.Count.ToString(),
stat.Value.Line
));
}
}
}
private static IEnumerable<TimerInfo> EnumerateTimers(ClrRuntime clr)
{
var timerQueueType = Utils.GetMscorlib(clr).GetTypeByName("System.Threading.TimerQueue");
if (timerQueueType == null)
yield break;
ClrStaticField instanceField = timerQueueType.GetStaticFieldByName("s_queue");
if (instanceField == null)
yield break;
var heap = clr.Heap;
foreach (ClrAppDomain domain in clr.AppDomains)
{
ulong? timerQueue = (ulong?)instanceField.GetValue(domain);
if (!timerQueue.HasValue || timerQueue.Value == 0)
continue;
ClrType t = heap.GetObjectType(timerQueue.Value);
if (t == null)
continue;
// m_timers is the start of the list of TimerQueueTimer
var currentPointer = Utils.GetFieldValue(heap, timerQueue.Value, "m_timers");
while ((currentPointer != null) && (((ulong)currentPointer) != 0))
{
// currentPointer points to a TimerQueueTimer instance
ulong currentTimerQueueTimerRef = (ulong)currentPointer;
TimerInfo ti = new TimerInfo()
{
TimerQueueTimerAddress = currentTimerQueueTimerRef
};
var val = Utils.GetFieldValue(heap, currentTimerQueueTimerRef, "m_dueTime");
ti.DueTime = (uint)val;
val = Utils.GetFieldValue(heap, currentTimerQueueTimerRef, "m_period");
ti.Period = (uint)val;
val = Utils.GetFieldValue(heap, currentTimerQueueTimerRef, "m_canceled");
ti.Cancelled = (bool)val;
val = Utils.GetFieldValue(heap, currentTimerQueueTimerRef, "m_state");
ti.StateTypeName = "";
if (val == null)
{
ti.StateAddress = 0;
}
else
{
ti.StateAddress = (ulong)val;
var stateType = heap.GetObjectType(ti.StateAddress);
if (stateType != null)
{
ti.StateTypeName = stateType.Name;
}
}
// decypher the callback details
val = Utils.GetFieldValue(heap, currentTimerQueueTimerRef, "m_timerCallback");
if (val != null)
{
ulong elementAddress = (ulong)val;
if (elementAddress == 0)
continue;
var elementType = heap.GetObjectType(elementAddress);
if (elementType != null)
{
if (elementType.Name == "System.Threading.TimerCallback")
{
ti.MethodName = Utils.BuildTimerCallbackMethodName(clr, heap, elementAddress);
}
else
{
ti.MethodName = "<" + elementType.Name + ">";
}
}
else
{
ti.MethodName = "{no callback type?}";
}
}
else
{
ti.MethodName = "???";
}
yield return ti;
currentPointer = Utils.GetFieldValue(heap, currentTimerQueueTimerRef, "m_next");
}
}
}
private static string GetTimerString(TimerInfo timer)
{
return string.Format(
"0x{0} @{1,8} ms every {2,8} ms | {3} ({4}) -> {5}",
timer.TimerQueueTimerAddress.ToString("X16"),
timer.DueTime.ToString(),
(timer.Period == 4294967295) ? " ------" : timer.Period.ToString(),
timer.StateAddress.ToString("X16"),
timer.StateTypeName,
timer.MethodName
);
}
}
class TimerStat
{
public uint Period { get; set; }
public String Line { get; set; }
public int Count { get; set; }
}
class TimerInfo
{
public ulong TimerQueueTimerAddress { get; set; }
public uint DueTime { get; set; }
public uint Period { get; set; }
public bool Cancelled { get; set; }
public ulong StateAddress { get; set; }
public string StateTypeName { get; set; }
public ulong ThisAddress { get; set; }
public string MethodName { get; set; }
}
}
| 36.437209 | 130 | 0.436048 | [
"MIT"
] | chrisnas/EffectiveDebugging | Labs/ClrMD/Labs-Completed/Lab3 - List Timers/Solution/Lab3/Program.cs | 7,836 | C# |
using OfficeDevPnP.Core.Framework.Provisioning.Model;
using OfficeDevPnP.Core.Utilities;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Xml;
using System.Xml.Linq;
using System.Xml.Schema;
using System.Xml.Serialization;
using OfficeDevPnP.Core.Framework.Provisioning.Providers.Xml.V201605;
using ContentType = OfficeDevPnP.Core.Framework.Provisioning.Model.ContentType;
using OfficeDevPnP.Core.Extensions;
using Microsoft.SharePoint.Client;
using FileLevel = OfficeDevPnP.Core.Framework.Provisioning.Model.FileLevel;
namespace OfficeDevPnP.Core.Framework.Provisioning.Providers.Xml
{
internal class XMLPnPSchemaV201605Formatter :
IXMLSchemaFormatter, ITemplateFormatter
{
private TemplateProviderBase _provider;
public void Initialize(TemplateProviderBase provider)
{
this._provider = provider;
}
string IXMLSchemaFormatter.NamespaceUri
{
get { return (XMLConstants.PROVISIONING_SCHEMA_NAMESPACE_2016_05); }
}
string IXMLSchemaFormatter.NamespacePrefix
{
get { return (XMLConstants.PROVISIONING_SCHEMA_PREFIX); }
}
public bool IsValid(Stream template)
{
if (template == null)
{
throw new ArgumentNullException(nameof(template));
}
// Load the template into an XDocument
XDocument xml = XDocument.Load(template);
// Load the XSD embedded resource
Stream stream = typeof(XMLPnPSchemaV201605Formatter)
.Assembly
.GetManifestResourceStream("OfficeDevPnP.Core.Framework.Provisioning.Providers.Xml.ProvisioningSchema-2016-05.xsd");
// Prepare the XML Schema Set
XmlSchemaSet schemas = new XmlSchemaSet();
schemas.Add(XMLConstants.PROVISIONING_SCHEMA_NAMESPACE_2016_05,
new XmlTextReader(stream));
Boolean result = true;
xml.Validate(schemas, (o, e) =>
{
Diagnostics.Log.Error(e.Exception, "SchemaFormatter", "Template is not valid: {0}", e.Message);
result = false;
});
return (result);
}
Stream ITemplateFormatter.ToFormattedTemplate(Model.ProvisioningTemplate template)
{
if (template == null)
{
throw new ArgumentNullException(nameof(template));
}
V201605.ProvisioningTemplate result = new V201605.ProvisioningTemplate();
V201605.Provisioning wrappedResult = new V201605.Provisioning();
wrappedResult.Preferences = new V201605.Preferences
{
Generator = this.GetType().Assembly.FullName
};
wrappedResult.Templates = new V201605.Templates[] {
new V201605.Templates
{
ID = $"CONTAINER-{template.Id}",
ProvisioningTemplate = new V201605.ProvisioningTemplate[]
{
result
}
}
};
#region Basic Properties
// Translate basic properties
result.ID = template.Id;
result.Version = (Decimal)template.Version;
result.VersionSpecified = true;
result.SitePolicy = template.SitePolicy;
result.ImagePreviewUrl = template.ImagePreviewUrl;
result.DisplayName = template.DisplayName;
result.Description = template.Description;
result.BaseSiteTemplate = template.BaseSiteTemplate;
if (template.Properties != null && template.Properties.Any())
{
result.Properties =
(from p in template.Properties
select new V201605.StringDictionaryItem
{
Key = p.Key,
Value = p.Value,
}).ToArray();
}
else
{
result.Properties = null;
}
#endregion
#region Localizations
if (template.Localizations != null && template.Localizations.Count > 0)
{
wrappedResult.Localizations =
(from l in template.Localizations
select new LocalizationsLocalization
{
LCID = l.LCID,
Name = l.Name,
ResourceFile = l.ResourceFile,
}).ToArray();
}
#endregion
#region Property Bag
// Translate PropertyBagEntries, if any
if (template.PropertyBagEntries != null && template.PropertyBagEntries.Count > 0)
{
result.PropertyBagEntries =
(from bag in template.PropertyBagEntries
select new V201605.PropertyBagEntry()
{
Key = bag.Key,
Value = bag.Value,
Indexed = bag.Indexed,
Overwrite = bag.Overwrite,
OverwriteSpecified = true,
}).ToArray();
}
else
{
result.PropertyBagEntries = null;
}
#endregion
#region Web Settings
if (template.WebSettings != null)
{
result.WebSettings = new V201605.WebSettings
{
NoCrawl = template.WebSettings.NoCrawl,
NoCrawlSpecified = true,
RequestAccessEmail = template.WebSettings.RequestAccessEmail,
Title = template.WebSettings.Title,
Description = template.WebSettings.Description,
SiteLogo = template.WebSettings.SiteLogo,
AlternateCSS = template.WebSettings.AlternateCSS,
MasterPageUrl = template.WebSettings.MasterPageUrl,
CustomMasterPageUrl = template.WebSettings.CustomMasterPageUrl,
WelcomePage = template.WebSettings.WelcomePage
};
}
#endregion
#region Regional Settings
if (template.RegionalSettings != null)
{
result.RegionalSettings = new V201605.RegionalSettings()
{
AdjustHijriDays = template.RegionalSettings.AdjustHijriDays,
AdjustHijriDaysSpecified = true,
AlternateCalendarType = template.RegionalSettings.AlternateCalendarType.FromTemplateToSchemaCalendarTypeV201605(),
AlternateCalendarTypeSpecified = true,
CalendarType = template.RegionalSettings.CalendarType.FromTemplateToSchemaCalendarTypeV201605(),
CalendarTypeSpecified = true,
Collation = template.RegionalSettings.Collation,
CollationSpecified = true,
FirstDayOfWeek = (V201605.DayOfWeek)Enum.Parse(typeof(V201605.DayOfWeek), template.RegionalSettings.FirstDayOfWeek.ToString()),
FirstDayOfWeekSpecified = true,
FirstWeekOfYear = template.RegionalSettings.FirstWeekOfYear,
FirstWeekOfYearSpecified = true,
LocaleId = template.RegionalSettings.LocaleId,
LocaleIdSpecified = true,
ShowWeeks = template.RegionalSettings.ShowWeeks,
ShowWeeksSpecified = true,
Time24 = template.RegionalSettings.Time24,
Time24Specified = true,
TimeZone = template.RegionalSettings.TimeZone.ToString(),
WorkDayEndHour = template.RegionalSettings.WorkDayEndHour.FromTemplateToSchemaWorkHourV201605(),
WorkDayEndHourSpecified = true,
WorkDays = template.RegionalSettings.WorkDays,
WorkDaysSpecified = true,
WorkDayStartHour = template.RegionalSettings.WorkDayStartHour.FromTemplateToSchemaWorkHourV201605(),
WorkDayStartHourSpecified = true,
};
}
else
{
result.RegionalSettings = null;
}
#endregion
#region Supported UI Languages
if (template.SupportedUILanguages != null && template.SupportedUILanguages.Count > 0)
{
result.SupportedUILanguages =
(from l in template.SupportedUILanguages
select new V201605.SupportedUILanguagesSupportedUILanguage
{
LCID = l.LCID,
}).ToArray();
}
else
{
result.SupportedUILanguages = null;
}
#endregion
#region Audit Settings
if (template.AuditSettings != null)
{
result.AuditSettings = new V201605.AuditSettings
{
AuditLogTrimmingRetention = template.AuditSettings.AuditLogTrimmingRetention,
AuditLogTrimmingRetentionSpecified = true,
TrimAuditLog = template.AuditSettings.TrimAuditLog,
TrimAuditLogSpecified = true,
Audit = template.AuditSettings.AuditFlags.FromTemplateToSchemaAuditsV201605(),
};
}
else
{
result.AuditSettings = null;
}
#endregion
#region Security
// Translate Security configuration, if any
if (template.Security != null)
{
result.Security = new V201605.Security();
result.Security.BreakRoleInheritance = template.Security.BreakRoleInheritance;
result.Security.CopyRoleAssignments = template.Security.CopyRoleAssignments;
result.Security.ClearSubscopes = template.Security.ClearSubscopes;
if (template.Security.AdditionalAdministrators != null && template.Security.AdditionalAdministrators.Count > 0)
{
result.Security.AdditionalAdministrators =
(from user in template.Security.AdditionalAdministrators
select new V201605.User
{
Name = user.Name,
}).ToArray();
}
else
{
result.Security.AdditionalAdministrators = null;
}
if (template.Security.AdditionalOwners != null && template.Security.AdditionalOwners.Count > 0)
{
result.Security.AdditionalOwners =
(from user in template.Security.AdditionalOwners
select new V201605.User
{
Name = user.Name,
}).ToArray();
}
else
{
result.Security.AdditionalOwners = null;
}
if (template.Security.AdditionalMembers != null && template.Security.AdditionalMembers.Count > 0)
{
result.Security.AdditionalMembers =
(from user in template.Security.AdditionalMembers
select new V201605.User
{
Name = user.Name,
}).ToArray();
}
else
{
result.Security.AdditionalMembers = null;
}
if (template.Security.AdditionalVisitors != null && template.Security.AdditionalVisitors.Count > 0)
{
result.Security.AdditionalVisitors =
(from user in template.Security.AdditionalVisitors
select new V201605.User
{
Name = user.Name,
}).ToArray();
}
else
{
result.Security.AdditionalVisitors = null;
}
if (template.Security.SiteGroups != null && template.Security.SiteGroups.Count > 0)
{
result.Security.SiteGroups =
(from g in template.Security.SiteGroups
select new V201605.SiteGroup
{
AllowMembersEditMembership = g.AllowMembersEditMembership,
AllowMembersEditMembershipSpecified = true,
AllowRequestToJoinLeave = g.AllowRequestToJoinLeave,
AllowRequestToJoinLeaveSpecified = true,
AutoAcceptRequestToJoinLeave = g.AutoAcceptRequestToJoinLeave,
AutoAcceptRequestToJoinLeaveSpecified = true,
Description = g.Description,
Members = g.Members.Any() ? (from m in g.Members
select new V201605.User
{
Name = m.Name,
}).ToArray() : null,
OnlyAllowMembersViewMembership = g.OnlyAllowMembersViewMembership,
OnlyAllowMembersViewMembershipSpecified = true,
Owner = g.Owner,
RequestToJoinLeaveEmailSetting = g.RequestToJoinLeaveEmailSetting,
Title = g.Title,
}).ToArray();
}
else
{
result.Security.SiteGroups = null;
}
result.Security.Permissions = new SecurityPermissions();
if (template.Security.SiteSecurityPermissions != null)
{
if (template.Security.SiteSecurityPermissions.RoleAssignments != null && template.Security.SiteSecurityPermissions.RoleAssignments.Count > 0)
{
result.Security.Permissions.RoleAssignments =
(from ra in template.Security.SiteSecurityPermissions.RoleAssignments
select new V201605.RoleAssignment
{
Principal = ra.Principal,
RoleDefinition = ra.RoleDefinition,
}).ToArray();
}
else
{
result.Security.Permissions.RoleAssignments = null;
}
if (template.Security.SiteSecurityPermissions.RoleDefinitions != null && template.Security.SiteSecurityPermissions.RoleDefinitions.Count > 0)
{
result.Security.Permissions.RoleDefinitions =
(from rd in template.Security.SiteSecurityPermissions.RoleDefinitions
select new V201605.RoleDefinition
{
Description = rd.Description,
Name = rd.Name,
Permissions =
(from p in rd.Permissions
select (RoleDefinitionPermission)Enum.Parse(typeof(RoleDefinitionPermission), p.ToString())).ToArray(),
}).ToArray();
}
else
{
result.Security.Permissions.RoleDefinitions = null;
}
}
if (
result.Security.AdditionalAdministrators == null &&
result.Security.AdditionalMembers == null &&
result.Security.AdditionalOwners == null &&
result.Security.AdditionalVisitors == null &&
result.Security.Permissions.RoleAssignments == null &&
result.Security.Permissions.RoleDefinitions == null &&
result.Security.SiteGroups == null)
{
result.Security = null;
}
}
#endregion
#region Navigation
if (template.Navigation != null)
{
result.Navigation = new V201605.Navigation {
GlobalNavigation =
template.Navigation.GlobalNavigation != null ?
new NavigationGlobalNavigation {
NavigationType = (NavigationGlobalNavigationNavigationType)Enum.Parse(typeof(NavigationGlobalNavigationNavigationType), template.Navigation.GlobalNavigation.NavigationType.ToString()),
StructuralNavigation =
template.Navigation.GlobalNavigation.StructuralNavigation != null ?
new V201605.StructuralNavigation
{
RemoveExistingNodes = template.Navigation.GlobalNavigation.StructuralNavigation.RemoveExistingNodes,
NavigationNode = (from n in template.Navigation.GlobalNavigation.StructuralNavigation.NavigationNodes
select n.FromModelNavigationNodeToSchemaNavigationNodeV201605()).ToArray()
} : null,
ManagedNavigation =
template.Navigation.GlobalNavigation.ManagedNavigation != null ?
new V201605.ManagedNavigation
{
TermSetId = template.Navigation.GlobalNavigation.ManagedNavigation.TermSetId,
TermStoreId = template.Navigation.GlobalNavigation.ManagedNavigation.TermStoreId,
} : null
}
: null,
CurrentNavigation =
template.Navigation.CurrentNavigation != null ?
new NavigationCurrentNavigation
{
NavigationType = (NavigationCurrentNavigationNavigationType)Enum.Parse(typeof(NavigationCurrentNavigationNavigationType), template.Navigation.CurrentNavigation.NavigationType.ToString()),
StructuralNavigation =
template.Navigation.CurrentNavigation.StructuralNavigation != null ?
new V201605.StructuralNavigation
{
RemoveExistingNodes = template.Navigation.CurrentNavigation.StructuralNavigation.RemoveExistingNodes,
NavigationNode = (from n in template.Navigation.CurrentNavigation.StructuralNavigation.NavigationNodes
select n.FromModelNavigationNodeToSchemaNavigationNodeV201605()).ToArray()
} : null,
ManagedNavigation =
template.Navigation.CurrentNavigation.ManagedNavigation != null ?
new V201605.ManagedNavigation
{
TermSetId = template.Navigation.CurrentNavigation.ManagedNavigation.TermSetId,
TermStoreId = template.Navigation.CurrentNavigation.ManagedNavigation.TermStoreId,
} : null
}
: null
};
}
#endregion
#region Site Columns
// Translate Site Columns (Fields), if any
if (template.SiteFields != null && template.SiteFields.Count > 0)
{
result.SiteFields = new V201605.ProvisioningTemplateSiteFields
{
Any =
(from field in template.SiteFields
select field.SchemaXml.ToXmlElement()).ToArray(),
};
}
else
{
result.SiteFields = null;
}
#endregion
#region Content Types
// Translate ContentTypes, if any
if (template.ContentTypes != null && template.ContentTypes.Count > 0)
{
result.ContentTypes =
(from ct in template.ContentTypes
select new V201605.ContentType
{
ID = ct.Id,
Description = ct.Description,
Group = ct.Group,
Name = ct.Name,
Hidden = ct.Hidden,
Sealed = ct.Sealed,
ReadOnly = ct.ReadOnly,
FieldRefs = ct.FieldRefs.Count > 0 ?
(from fieldRef in ct.FieldRefs
select new V201605.ContentTypeFieldRef
{
Name = fieldRef.Name,
ID = fieldRef.Id.ToString(),
Hidden = fieldRef.Hidden,
Required = fieldRef.Required
}).ToArray() : null,
DocumentTemplate = !String.IsNullOrEmpty(ct.DocumentTemplate) ? new ContentTypeDocumentTemplate { TargetName = ct.DocumentTemplate } : null,
DocumentSetTemplate = ct.DocumentSetTemplate != null ?
new V201605.DocumentSetTemplate
{
AllowedContentTypes = ct.DocumentSetTemplate.AllowedContentTypes.Count > 0 ?
(from act in ct.DocumentSetTemplate.AllowedContentTypes
select new DocumentSetTemplateAllowedContentType
{
ContentTypeID = act
}).ToArray() : null,
DefaultDocuments = ct.DocumentSetTemplate.DefaultDocuments.Count > 0 ?
(from dd in ct.DocumentSetTemplate.DefaultDocuments
select new DocumentSetTemplateDefaultDocument
{
ContentTypeID = dd.ContentTypeId,
FileSourcePath = dd.FileSourcePath,
Name = dd.Name,
}).ToArray() : null,
SharedFields = ct.DocumentSetTemplate.SharedFields.Count > 0 ?
(from sf in ct.DocumentSetTemplate.SharedFields
select new DocumentSetFieldRef
{
ID = sf.ToString(),
}).ToArray() : null,
WelcomePage = ct.DocumentSetTemplate.WelcomePage,
WelcomePageFields = ct.DocumentSetTemplate.WelcomePageFields.Count > 0 ?
(from wpf in ct.DocumentSetTemplate.WelcomePageFields
select new DocumentSetFieldRef
{
ID = wpf.ToString(),
}).ToArray() : null,
} : null,
DisplayFormUrl = ct.DisplayFormUrl,
EditFormUrl = ct.EditFormUrl,
NewFormUrl = ct.NewFormUrl,
}).ToArray();
}
else
{
result.ContentTypes = null;
}
#endregion
#region List Instances
// Translate Lists Instances, if any
if (template.Lists != null && template.Lists.Count > 0)
{
result.Lists =
(from list in template.Lists
select new V201605.ListInstance
{
ContentTypesEnabled = list.ContentTypesEnabled,
Description = list.Description,
DocumentTemplate = list.DocumentTemplate,
EnableVersioning = list.EnableVersioning,
EnableMinorVersions = list.EnableMinorVersions,
EnableModeration = list.EnableModeration,
DraftVersionVisibility = list.DraftVersionVisibility,
DraftVersionVisibilitySpecified = true,
Hidden = list.Hidden,
MinorVersionLimit = list.MinorVersionLimit,
MinorVersionLimitSpecified = true,
MaxVersionLimit = list.MaxVersionLimit,
MaxVersionLimitSpecified = true,
OnQuickLaunch = list.OnQuickLaunch,
EnableAttachments = list.EnableAttachments,
EnableFolderCreation = list.EnableFolderCreation,
ForceCheckout = list.ForceCheckout,
RemoveExistingContentTypes = list.RemoveExistingContentTypes,
TemplateFeatureID = list.TemplateFeatureID != Guid.Empty ? list.TemplateFeatureID.ToString() : null,
TemplateType = list.TemplateType,
Title = list.Title,
Url = list.Url,
ContentTypeBindings = list.ContentTypeBindings.Count > 0 ?
(from contentTypeBinding in list.ContentTypeBindings
select new V201605.ContentTypeBinding
{
ContentTypeID = contentTypeBinding.ContentTypeId,
Default = contentTypeBinding.Default,
Remove = contentTypeBinding.Remove,
}).ToArray() : null,
Views = list.Views.Count > 0 ?
new V201605.ListInstanceViews
{
Any =
(from view in list.Views
select view.SchemaXml.ToXmlElement()).ToArray(),
RemoveExistingViews = list.RemoveExistingViews,
} : null,
Fields = list.Fields.Count > 0 ?
new V201605.ListInstanceFields
{
Any =
(from field in list.Fields
select field.SchemaXml.ToXmlElement()).ToArray(),
} : null,
FieldDefaults = list.FieldDefaults.Count > 0 ?
(from value in list.FieldDefaults
select new FieldDefault { FieldName = value.Key, Value = value.Value }).ToArray() : null,
FieldRefs = list.FieldRefs.Count > 0 ?
(from fieldRef in list.FieldRefs
select new V201605.ListInstanceFieldRef
{
Name = fieldRef.Name,
DisplayName = fieldRef.DisplayName,
Hidden = fieldRef.Hidden,
Required = fieldRef.Required,
ID = fieldRef.Id.ToString(),
}).ToArray() : null,
DataRows = list.DataRows.Count > 0 ?
(from dr in list.DataRows
select new ListInstanceDataRow
{
DataValue = dr.Values.Count > 0 ?
(from value in dr.Values
select new DataValue { FieldName = value.Key, Value = value.Value }).ToArray() : null,
Security = dr.Security.FromTemplateToSchemaObjectSecurityV201605()
}).ToArray() : null,
Security = list.Security.FromTemplateToSchemaObjectSecurityV201605(),
Folders = list.Folders.Count > 0 ?
(from folder in list.Folders
select folder.FromTemplateToSchemaFolderV201605()).ToArray() : null,
UserCustomActions = list.UserCustomActions.Count > 0 ?
(from customAction in list.UserCustomActions
select new V201605.CustomAction
{
CommandUIExtension = new CustomActionCommandUIExtension
{
Any = customAction.CommandUIExtension != null ?
(from x in customAction.CommandUIExtension.Elements() select x.ToXmlElement()).ToArray() : null,
},
Description = customAction.Description,
Enabled = customAction.Enabled,
Group = customAction.Group,
ImageUrl = customAction.ImageUrl,
Location = customAction.Location,
Name = customAction.Name,
Rights = customAction.Rights.FromBasePermissionsToStringV201605(),
RegistrationId = customAction.RegistrationId,
RegistrationType = (RegistrationType)Enum.Parse(typeof(RegistrationType), customAction.RegistrationType.ToString(), true),
RegistrationTypeSpecified = true,
Remove = customAction.Remove,
ScriptBlock = customAction.ScriptBlock,
ScriptSrc = customAction.ScriptSrc,
Sequence = customAction.Sequence,
SequenceSpecified = true,
Title = customAction.Title,
Url = customAction.Url,
}).ToArray() : null,
}).ToArray();
}
else
{
result.Lists = null;
}
#endregion
#region Features
// Translate Features, if any
if (template.Features != null)
{
result.Features = new V201605.Features();
// TODO: This nullability check could be useless, because
// the SiteFeatures property is initialized in the Features
// constructor
if (template.Features.SiteFeatures != null && template.Features.SiteFeatures.Count > 0)
{
result.Features.SiteFeatures =
(from feature in template.Features.SiteFeatures
select new V201605.Feature
{
ID = feature.Id.ToString(),
Deactivate = feature.Deactivate,
}).ToArray();
}
else
{
result.Features.SiteFeatures = null;
}
// TODO: This nullability check could be useless, because
// the WebFeatures property is initialized in the Features
// constructor
if (template.Features.WebFeatures != null && template.Features.WebFeatures.Count > 0)
{
result.Features.WebFeatures =
(from feature in template.Features.WebFeatures
select new V201605.Feature
{
ID = feature.Id.ToString(),
Deactivate = feature.Deactivate,
}).ToArray();
}
else
{
result.Features.WebFeatures = null;
}
if ((template.Features.WebFeatures == null && template.Features.SiteFeatures == null) || (template.Features.WebFeatures.Count == 0 && template.Features.SiteFeatures.Count == 0))
{
result.Features = null;
}
}
#endregion
#region Custom Actions
// Translate CustomActions, if any
if (template.CustomActions != null && (template.CustomActions.SiteCustomActions.Any() || template.CustomActions.WebCustomActions.Any()))
{
result.CustomActions = new V201605.CustomActions();
if (template.CustomActions.SiteCustomActions != null && template.CustomActions.SiteCustomActions.Count > 0)
{
result.CustomActions.SiteCustomActions =
(from customAction in template.CustomActions.SiteCustomActions
select new V201605.CustomAction
{
CommandUIExtension = new CustomActionCommandUIExtension
{
Any = customAction.CommandUIExtension != null ?
(from x in customAction.CommandUIExtension.Elements() select x.ToXmlElement()).ToArray() : null,
},
Description = customAction.Description,
Enabled = customAction.Enabled,
Group = customAction.Group,
ImageUrl = customAction.ImageUrl,
Location = customAction.Location,
Name = customAction.Name,
Rights = customAction.Rights.FromBasePermissionsToStringV201605(),
RegistrationId = customAction.RegistrationId,
RegistrationType = (RegistrationType)Enum.Parse(typeof(RegistrationType), customAction.RegistrationType.ToString(), true),
RegistrationTypeSpecified = true,
Remove = customAction.Remove,
ScriptBlock = customAction.ScriptBlock,
ScriptSrc = customAction.ScriptSrc,
Sequence = customAction.Sequence,
SequenceSpecified = true,
Title = customAction.Title,
Url = customAction.Url,
}).ToArray();
}
else
{
result.CustomActions.SiteCustomActions = null;
}
if (template.CustomActions.WebCustomActions != null && template.CustomActions.WebCustomActions.Count > 0)
{
result.CustomActions.WebCustomActions =
(from customAction in template.CustomActions.WebCustomActions
select new V201605.CustomAction
{
CommandUIExtension = new CustomActionCommandUIExtension
{
Any = customAction.CommandUIExtension != null ?
(from x in customAction.CommandUIExtension.Elements() select x.ToXmlElement()).ToArray() : null,
},
Description = customAction.Description,
Enabled = customAction.Enabled,
Group = customAction.Group,
ImageUrl = customAction.ImageUrl,
Location = customAction.Location,
Name = customAction.Name,
Rights = customAction.Rights.FromBasePermissionsToStringV201605(),
RegistrationId = customAction.RegistrationId,
RegistrationType = (RegistrationType)Enum.Parse(typeof(RegistrationType), customAction.RegistrationType.ToString(), true),
RegistrationTypeSpecified = true,
Remove = customAction.Remove,
ScriptBlock = customAction.ScriptBlock,
ScriptSrc = customAction.ScriptSrc,
Sequence = customAction.Sequence,
SequenceSpecified = true,
Title = customAction.Title,
Url = customAction.Url,
}).ToArray();
}
else
{
result.CustomActions.WebCustomActions = null;
}
}
#endregion
#region Files
// Translate Files, if any
if (template.Files != null && template.Files.Count > 0)
{
result.Files = new ProvisioningTemplateFiles();
result.Files.File =
(from file in template.Files
select new V201605.File
{
Overwrite = file.Overwrite,
Src = file.Src,
Level = (V201605.FileLevel)Enum.Parse(typeof(V201605.FileLevel),file.Level.ToString()),
LevelSpecified = file.Level != FileLevel.Draft,
Folder = file.Folder,
WebParts = file.WebParts.Count > 0 ?
(from wp in file.WebParts
select new V201605.WebPartPageWebPart
{
Zone = wp.Zone,
Order = (int)wp.Order,
Contents = XElement.Parse(wp.Contents).ToXmlElement(),
Title = wp.Title,
}).ToArray() : null,
Properties = file.Properties != null && file.Properties.Count > 0 ?
(from p in file.Properties
select new V201605.StringDictionaryItem
{
Key = p.Key,
Value = p.Value
}).ToArray() : null,
Security = file.Security.FromTemplateToSchemaObjectSecurityV201605()
}).ToArray();
}
else
{
result.Files = null;
}
#endregion
#region Pages
// Translate Pages, if any
if (template.Pages != null && template.Pages.Count > 0)
{
var pages = new List<V201605.Page>();
foreach (var page in template.Pages)
{
var schemaPage = new V201605.Page();
var pageLayout = V201605.WikiPageLayout.OneColumn;
switch (page.Layout)
{
case WikiPageLayout.OneColumn:
pageLayout = V201605.WikiPageLayout.OneColumn;
break;
case WikiPageLayout.OneColumnSideBar:
pageLayout = V201605.WikiPageLayout.OneColumnSidebar;
break;
case WikiPageLayout.TwoColumns:
pageLayout = V201605.WikiPageLayout.TwoColumns;
break;
case WikiPageLayout.TwoColumnsHeader:
pageLayout = V201605.WikiPageLayout.TwoColumnsHeader;
break;
case WikiPageLayout.TwoColumnsHeaderFooter:
pageLayout = V201605.WikiPageLayout.TwoColumnsHeaderFooter;
break;
case WikiPageLayout.ThreeColumns:
pageLayout = V201605.WikiPageLayout.ThreeColumns;
break;
case WikiPageLayout.ThreeColumnsHeader:
pageLayout = V201605.WikiPageLayout.ThreeColumnsHeader;
break;
case WikiPageLayout.ThreeColumnsHeaderFooter:
pageLayout = V201605.WikiPageLayout.ThreeColumnsHeaderFooter;
break;
case WikiPageLayout.Custom:
pageLayout = V201605.WikiPageLayout.Custom;
break;
}
schemaPage.Layout = pageLayout;
schemaPage.Overwrite = page.Overwrite;
schemaPage.Security = (page.Security != null) ? page.Security.FromTemplateToSchemaObjectSecurityV201605() : null;
schemaPage.WebParts = page.WebParts.Count > 0 ?
(from wp in page.WebParts
select new V201605.WikiPageWebPart
{
Column = (int)wp.Column,
Row = (int)wp.Row,
Contents = XElement.Parse(wp.Contents).ToXmlElement(),
Title = wp.Title,
}).ToArray() : null;
schemaPage.Url = page.Url;
schemaPage.Fields = (page.Fields != null && page.Fields.Count > 0) ?
(from f in page.Fields
select new V201605.BaseFieldValue
{
FieldName = f.Key,
Value = f.Value,
}).ToArray() : null;
pages.Add(schemaPage);
}
result.Pages = pages.ToArray();
}
#endregion
#region Taxonomy
// Translate Taxonomy elements, if any
if (template.TermGroups != null && template.TermGroups.Count > 0)
{
result.TermGroups =
(from grp in template.TermGroups
select new V201605.TermGroup
{
Name = grp.Name,
ID = grp.Id != Guid.Empty ? grp.Id.ToString() : null,
Description = grp.Description,
SiteCollectionTermGroup = grp.SiteCollectionTermGroup,
SiteCollectionTermGroupSpecified = grp.SiteCollectionTermGroup,
Contributors = (from c in grp.Contributors
select new V201605.User { Name = c.Name }).ToArray(),
Managers = (from m in grp.Managers
select new V201605.User { Name = m.Name }).ToArray(),
TermSets = (
from termSet in grp.TermSets
select new V201605.TermSet
{
ID = termSet.Id != Guid.Empty ? termSet.Id.ToString() : null,
Name = termSet.Name,
IsAvailableForTagging = termSet.IsAvailableForTagging,
IsOpenForTermCreation = termSet.IsOpenForTermCreation,
Description = termSet.Description,
Language = termSet.Language.HasValue ? termSet.Language.Value : 0,
LanguageSpecified = termSet.Language.HasValue,
Terms = termSet.Terms.FromModelTermsToSchemaTermsV201605(),
CustomProperties = termSet.Properties.Count > 0 ?
(from p in termSet.Properties
select new V201605.StringDictionaryItem
{
Key = p.Key,
Value = p.Value
}).ToArray() : null,
}).ToArray(),
}).ToArray();
}
#endregion
#region Composed Looks
// Translate ComposedLook, if any
if (template.ComposedLook != null && !template.ComposedLook.Equals(Model.ComposedLook.Empty))
{
result.ComposedLook = new V201605.ComposedLook
{
BackgroundFile = template.ComposedLook.BackgroundFile,
ColorFile = template.ComposedLook.ColorFile,
FontFile = template.ComposedLook.FontFile,
Name = template.ComposedLook.Name,
Version = template.ComposedLook.Version,
VersionSpecified = true,
};
if (
template.ComposedLook.BackgroundFile == null &&
template.ComposedLook.ColorFile == null &&
template.ComposedLook.FontFile == null &&
template.ComposedLook.Name == null &&
template.ComposedLook.Version == 0)
{
result.ComposedLook = null;
}
}
#endregion
#region Workflows
if (template.Workflows != null &&
(template.Workflows.WorkflowDefinitions.Any() || template.Workflows.WorkflowSubscriptions.Any()))
{
result.Workflows = new V201605.Workflows
{
WorkflowDefinitions = template.Workflows.WorkflowDefinitions.Count > 0 ?
(from wd in template.Workflows.WorkflowDefinitions
select new WorkflowsWorkflowDefinition
{
AssociationUrl = wd.AssociationUrl,
Description = wd.Description,
DisplayName = wd.DisplayName,
DraftVersion = wd.DraftVersion,
FormField = (wd.FormField != null) ? wd.FormField.ToXmlElement() : null,
Id = wd.Id.ToString(),
InitiationUrl = wd.InitiationUrl,
Properties = (wd.Properties != null && wd.Properties.Count > 0) ?
(from p in wd.Properties
select new V201605.StringDictionaryItem
{
Key = p.Key,
Value = p.Value,
}).ToArray() : null,
Published = wd.Published,
PublishedSpecified = true,
RequiresAssociationForm = wd.RequiresAssociationForm,
RequiresAssociationFormSpecified = true,
RequiresInitiationForm = wd.RequiresInitiationForm,
RequiresInitiationFormSpecified = true,
RestrictToScope = wd.RestrictToScope,
RestrictToType = (V201605.WorkflowsWorkflowDefinitionRestrictToType)Enum.Parse(typeof(V201605.WorkflowsWorkflowDefinitionRestrictToType), wd.RestrictToType),
RestrictToTypeSpecified = true,
XamlPath = wd.XamlPath,
}).ToArray() : null,
WorkflowSubscriptions = template.Workflows.WorkflowSubscriptions.Count > 0 ?
(from ws in template.Workflows.WorkflowSubscriptions
select new WorkflowsWorkflowSubscription
{
DefinitionId = ws.DefinitionId.ToString(),
Enabled = ws.Enabled,
EventSourceId = ws.EventSourceId,
ItemAddedEvent = ws.EventTypes.Contains("ItemAdded"),
ItemUpdatedEvent = ws.EventTypes.Contains("ItemUpdated"),
WorkflowStartEvent = ws.EventTypes.Contains("WorkflowStart"),
ListId = ws.ListId,
ManualStartBypassesActivationLimit = ws.ManualStartBypassesActivationLimit,
ManualStartBypassesActivationLimitSpecified = true,
Name = ws.Name,
ParentContentTypeId = ws.ParentContentTypeId,
PropertyDefinitions = (ws.PropertyDefinitions != null && ws.PropertyDefinitions.Count > 0) ?
(from pd in ws.PropertyDefinitions
select new V201605.StringDictionaryItem
{
Key = pd.Key,
Value = pd.Value,
}).ToArray() : null,
StatusFieldName = ws.StatusFieldName,
}).ToArray() : null,
};
}
else
{
result.Workflows = null;
}
#endregion
#region Search Settings
if (!String.IsNullOrEmpty(template.SiteSearchSettings))
{
if (result.SearchSettings== null)
{
result.SearchSettings = new ProvisioningTemplateSearchSettings();
}
result.SearchSettings.SiteSearchSettings = template.SiteSearchSettings.ToXmlElement();
}
if (!String.IsNullOrEmpty(template.WebSearchSettings))
{
if (result.SearchSettings == null)
{
result.SearchSettings = new ProvisioningTemplateSearchSettings();
}
result.SearchSettings.WebSearchSettings = template.WebSearchSettings.ToXmlElement();
}
#endregion
#region Publishing
if (template.Publishing != null)
{
result.Publishing = new V201605.Publishing
{
AutoCheckRequirements = (V201605.PublishingAutoCheckRequirements)Enum.Parse(typeof(V201605.PublishingAutoCheckRequirements), template.Publishing.AutoCheckRequirements.ToString()),
AvailableWebTemplates = template.Publishing.AvailableWebTemplates.Count > 0 ?
(from awt in template.Publishing.AvailableWebTemplates
select new V201605.PublishingWebTemplate
{
LanguageCode = awt.LanguageCode,
LanguageCodeSpecified = true,
TemplateName = awt.TemplateName,
}).ToArray() : null,
DesignPackage = template.Publishing.DesignPackage != null ? new V201605.PublishingDesignPackage
{
DesignPackagePath = template.Publishing.DesignPackage.DesignPackagePath,
MajorVersion = template.Publishing.DesignPackage.MajorVersion,
MajorVersionSpecified = true,
MinorVersion = template.Publishing.DesignPackage.MinorVersion,
MinorVersionSpecified = true,
PackageGuid = template.Publishing.DesignPackage.PackageGuid.ToString(),
PackageName = template.Publishing.DesignPackage.PackageName,
} : null,
PageLayouts = template.Publishing.PageLayouts != null ?
new V201605.PublishingPageLayouts
{
PageLayout = template.Publishing.PageLayouts.Count > 0 ?
(from pl in template.Publishing.PageLayouts
select new V201605.PublishingPageLayoutsPageLayout
{
Path = pl.Path,
}).ToArray() : null,
Default = template.Publishing.PageLayouts.Any(p => p.IsDefault) ?
template.Publishing.PageLayouts.Last(p => p.IsDefault).Path : null,
} : null,
};
}
else
{
result.Publishing = null;
}
#endregion
#region AddIns
if (template.AddIns != null && template.AddIns.Count > 0)
{
result.AddIns =
(from addin in template.AddIns
select new V201605.AddInsAddin
{
PackagePath = addin.PackagePath,
Source = (V201605.AddInsAddinSource)Enum.Parse(typeof(V201605.AddInsAddinSource), addin.Source),
}).ToArray();
}
else
{
result.AddIns = null;
}
#endregion
#region Providers
// Translate Providers, if any
#pragma warning disable 618
if ((template.Providers != null && template.Providers.Count > 0) || (template.ExtensibilityHandlers != null && template.ExtensibilityHandlers.Count > 0))
{
var extensibilityHandlers = template.ExtensibilityHandlers.Union(template.Providers);
result.Providers =
(from provider in extensibilityHandlers
select new V201605.Provider
{
HandlerType = $"{provider.Type}, {provider.Assembly}",
Configuration = provider.Configuration != null ? provider.Configuration.ToXmlNode() : null,
Enabled = provider.Enabled,
}).ToArray();
}
else
{
result.Providers = null;
}
#pragma warning restore 618
#endregion
XmlSerializerNamespaces ns =
new XmlSerializerNamespaces();
ns.Add(((IXMLSchemaFormatter)this).NamespacePrefix,
((IXMLSchemaFormatter)this).NamespaceUri);
var output = XMLSerializer.SerializeToStream<V201605.Provisioning>(wrappedResult, ns);
output.Position = 0;
return (output);
}
public Model.ProvisioningTemplate ToProvisioningTemplate(Stream template)
{
return (this.ToProvisioningTemplate(template, null));
}
public Model.ProvisioningTemplate ToProvisioningTemplate(Stream template, String identifier)
{
if (template == null)
{
throw new ArgumentNullException(nameof(template));
}
// Crate a copy of the source stream
MemoryStream sourceStream = new MemoryStream();
template.CopyTo(sourceStream);
sourceStream.Position = 0;
// Check the provided template against the XML schema
if (!this.IsValid(sourceStream))
{
// TODO: Use resource file
throw new ApplicationException("The provided template is not valid!");
}
sourceStream.Position = 0;
XDocument xml = XDocument.Load(sourceStream);
XNamespace pnp = XMLConstants.PROVISIONING_SCHEMA_NAMESPACE_2016_05;
// Prepare a variable to hold the single source formatted template
V201605.ProvisioningTemplate source = null;
// Prepare a variable to hold the resulting ProvisioningTemplate instance
Model.ProvisioningTemplate result = new Model.ProvisioningTemplate();
// Determine if we're working on a wrapped SharePointProvisioningTemplate or not
if (xml.Root.Name == pnp + "Provisioning")
{
// Deserialize the whole wrapper
V201605.Provisioning wrappedResult = XMLSerializer.Deserialize<V201605.Provisioning>(xml);
// Handle the wrapper schema parameters
if (wrappedResult.Preferences != null &&
wrappedResult.Preferences.Parameters != null &&
wrappedResult.Preferences.Parameters.Length > 0)
{
foreach (var parameter in wrappedResult.Preferences.Parameters)
{
result.Parameters.Add(parameter.Key, parameter.Text != null ? parameter.Text.Aggregate(String.Empty, (acc, i) => acc + i) : null);
}
}
// Handle Localizations
if (wrappedResult.Localizations != null)
{
result.Localizations.AddRange(
from l in wrappedResult.Localizations
select new Localization
{
LCID = l.LCID,
Name = l.Name,
ResourceFile = l.ResourceFile,
});
}
foreach (var templates in wrappedResult.Templates)
{
// Let's see if we have an in-place template with the provided ID or if we don't have a provided ID at all
source = templates.ProvisioningTemplate.FirstOrDefault(spt => spt.ID == identifier || String.IsNullOrEmpty(identifier));
// If we don't have a template, but there are external file references
if (source == null && templates.ProvisioningTemplateFile.Length > 0)
{
// Otherwise let's see if we have an external file for the template
var externalSource = templates.ProvisioningTemplateFile.FirstOrDefault(sptf => sptf.ID == identifier);
Stream externalFileStream = this._provider.Connector.GetFileStream(externalSource.File);
xml = XDocument.Load(externalFileStream);
if (xml.Root.Name != pnp + "ProvisioningTemplate")
{
throw new ApplicationException("Invalid external file format. Expected a ProvisioningTemplate file!");
}
else
{
source = XMLSerializer.Deserialize<V201605.ProvisioningTemplate>(xml);
}
}
if (source != null)
{
break;
}
}
}
else if (xml.Root.Name == pnp + "ProvisioningTemplate")
{
var IdAttribute = xml.Root.Attribute("ID");
// If there is a provided ID, and if it doesn't equal the current ID
if (!String.IsNullOrEmpty(identifier) &&
IdAttribute != null &&
IdAttribute.Value != identifier)
{
// TODO: Use resource file
throw new ApplicationException("The provided template identifier is not available!");
}
else
{
source = XMLSerializer.Deserialize<V201605.ProvisioningTemplate>(xml);
}
}
#region Basic Properties
// Translate basic properties
result.Id = source.ID;
result.Version = (Double)source.Version;
result.SitePolicy = source.SitePolicy;
result.ImagePreviewUrl = source.ImagePreviewUrl;
result.DisplayName = source.DisplayName;
result.Description = source.Description;
result.BaseSiteTemplate = source.BaseSiteTemplate;
if (source.Properties != null && source.Properties.Length > 0)
{
result.Properties.AddRange(
(from p in source.Properties
select p).ToDictionary(i => i.Key, i => i.Value));
}
#endregion
#region Property Bag
// Translate PropertyBagEntries, if any
if (source.PropertyBagEntries != null)
{
result.PropertyBagEntries.AddRange(
from bag in source.PropertyBagEntries
select new Model.PropertyBagEntry
{
Key = bag.Key,
Value = bag.Value,
Indexed = bag.Indexed,
Overwrite = bag.OverwriteSpecified ? bag.Overwrite : false,
});
}
#endregion
#region Web Settings
if (source.WebSettings != null)
{
result.WebSettings = new Model.WebSettings
{
NoCrawl = source.WebSettings.NoCrawlSpecified ? source.WebSettings.NoCrawl : false,
RequestAccessEmail = source.WebSettings.RequestAccessEmail,
WelcomePage = source.WebSettings.WelcomePage,
Title = source.WebSettings.Title,
Description = source.WebSettings.Description,
SiteLogo = source.WebSettings.SiteLogo,
AlternateCSS = source.WebSettings.AlternateCSS,
MasterPageUrl = source.WebSettings.MasterPageUrl,
CustomMasterPageUrl = source.WebSettings.CustomMasterPageUrl,
};
}
#endregion
#region Regional Settings
if (source.RegionalSettings != null)
{
result.RegionalSettings = new Model.RegionalSettings()
{
AdjustHijriDays = source.RegionalSettings.AdjustHijriDaysSpecified ? source.RegionalSettings.AdjustHijriDays : 0,
AlternateCalendarType = source.RegionalSettings.AlternateCalendarTypeSpecified ? source.RegionalSettings.AlternateCalendarType.FromSchemaToTemplateCalendarTypeV201605() : Microsoft.SharePoint.Client.CalendarType.None,
CalendarType = source.RegionalSettings.CalendarTypeSpecified ? source.RegionalSettings.CalendarType.FromSchemaToTemplateCalendarTypeV201605() : Microsoft.SharePoint.Client.CalendarType.None,
Collation = source.RegionalSettings.CollationSpecified ? source.RegionalSettings.Collation : 0,
FirstDayOfWeek = source.RegionalSettings.FirstDayOfWeekSpecified ?
(System.DayOfWeek)Enum.Parse(typeof(System.DayOfWeek), source.RegionalSettings.FirstDayOfWeek.ToString()) : System.DayOfWeek.Sunday,
FirstWeekOfYear = source.RegionalSettings.FirstWeekOfYearSpecified ? source.RegionalSettings.FirstWeekOfYear : 0,
LocaleId = source.RegionalSettings.LocaleIdSpecified ? source.RegionalSettings.LocaleId : 1033,
ShowWeeks = source.RegionalSettings.ShowWeeksSpecified ? source.RegionalSettings.ShowWeeks : false,
Time24 = source.RegionalSettings.Time24Specified ? source.RegionalSettings.Time24 : false,
TimeZone = !String.IsNullOrEmpty(source.RegionalSettings.TimeZone) ? Int32.Parse(source.RegionalSettings.TimeZone) : 0,
WorkDayEndHour = source.RegionalSettings.WorkDayEndHourSpecified ? source.RegionalSettings.WorkDayEndHour.FromSchemaToTemplateWorkHourV201605() : Model.WorkHour.PM0600,
WorkDays = source.RegionalSettings.WorkDaysSpecified ? source.RegionalSettings.WorkDays : 5,
WorkDayStartHour = source.RegionalSettings.WorkDayStartHourSpecified ? source.RegionalSettings.WorkDayStartHour.FromSchemaToTemplateWorkHourV201605() : Model.WorkHour.AM0900,
};
}
else
{
result.RegionalSettings = null;
}
#endregion
#region Supported UI Languages
if (source.SupportedUILanguages != null && source.SupportedUILanguages.Length > 0)
{
result.SupportedUILanguages.AddRange(
from l in source.SupportedUILanguages
select new SupportedUILanguage
{
LCID = l.LCID,
});
}
#endregion
#region Audit Settings
if (source.AuditSettings != null)
{
result.AuditSettings = new Model.AuditSettings
{
AuditLogTrimmingRetention = source.AuditSettings.AuditLogTrimmingRetentionSpecified ? source.AuditSettings.AuditLogTrimmingRetention : 0,
TrimAuditLog = source.AuditSettings.TrimAuditLogSpecified ? source.AuditSettings.TrimAuditLog : false,
AuditFlags = source.AuditSettings.Audit.Aggregate(Microsoft.SharePoint.Client.AuditMaskType.None, (acc, next) => acc |= (Microsoft.SharePoint.Client.AuditMaskType)Enum.Parse(typeof(Microsoft.SharePoint.Client.AuditMaskType), next.AuditFlag.ToString())),
};
}
#endregion
#region Security
// Translate Security configuration, if any
if (source.Security != null)
{
result.Security.BreakRoleInheritance = source.Security.BreakRoleInheritance;
result.Security.CopyRoleAssignments = source.Security.CopyRoleAssignments;
result.Security.ClearSubscopes = source.Security.ClearSubscopes;
if (source.Security.AdditionalAdministrators != null)
{
result.Security.AdditionalAdministrators.AddRange(
from user in source.Security.AdditionalAdministrators
select new Model.User
{
Name = user.Name,
});
}
if (source.Security.AdditionalOwners != null)
{
result.Security.AdditionalOwners.AddRange(
from user in source.Security.AdditionalOwners
select new Model.User
{
Name = user.Name,
});
}
if (source.Security.AdditionalMembers != null)
{
result.Security.AdditionalMembers.AddRange(
from user in source.Security.AdditionalMembers
select new Model.User
{
Name = user.Name,
});
}
if (source.Security.AdditionalVisitors != null)
{
result.Security.AdditionalVisitors.AddRange(
from user in source.Security.AdditionalVisitors
select new Model.User
{
Name = user.Name,
});
}
if (source.Security.SiteGroups != null)
{
result.Security.SiteGroups.AddRange(
from g in source.Security.SiteGroups
select new Model.SiteGroup(g.Members != null ? from m in g.Members select new Model.User { Name = m.Name } : null)
{
AllowMembersEditMembership = g.AllowMembersEditMembershipSpecified ? g.AllowMembersEditMembership : false,
AllowRequestToJoinLeave = g.AllowRequestToJoinLeaveSpecified ? g.AllowRequestToJoinLeave : false,
AutoAcceptRequestToJoinLeave = g.AutoAcceptRequestToJoinLeaveSpecified ? g.AutoAcceptRequestToJoinLeave : false,
Description = g.Description,
OnlyAllowMembersViewMembership = g.OnlyAllowMembersViewMembershipSpecified ? g.OnlyAllowMembersViewMembership : false,
Owner = g.Owner,
RequestToJoinLeaveEmailSetting = g.RequestToJoinLeaveEmailSetting,
Title = g.Title,
});
}
if (source.Security.Permissions != null)
{
if (source.Security.Permissions.RoleAssignments != null && source.Security.Permissions.RoleAssignments.Length > 0)
{
result.Security.SiteSecurityPermissions.RoleAssignments.AddRange
(from ra in source.Security.Permissions.RoleAssignments
select new Model.RoleAssignment
{
Principal = ra.Principal,
RoleDefinition = ra.RoleDefinition,
});
}
if (source.Security.Permissions.RoleDefinitions != null && source.Security.Permissions.RoleDefinitions.Length > 0)
{
result.Security.SiteSecurityPermissions.RoleDefinitions.AddRange
(from rd in source.Security.Permissions.RoleDefinitions
select new Model.RoleDefinition(
from p in rd.Permissions
select (Microsoft.SharePoint.Client.PermissionKind)Enum.Parse(typeof(Microsoft.SharePoint.Client.PermissionKind), p.ToString()))
{
Description = rd.Description,
Name = rd.Name,
});
}
}
}
#endregion
#region Navigation
if (source.Navigation != null)
{
result.Navigation = new Model.Navigation(
source.Navigation.GlobalNavigation != null ?
new GlobalNavigation(
(GlobalNavigationType)Enum.Parse(typeof(GlobalNavigationType), source.Navigation.GlobalNavigation.NavigationType.ToString()),
source.Navigation.GlobalNavigation.StructuralNavigation != null ?
new Model.StructuralNavigation
{
RemoveExistingNodes = source.Navigation.GlobalNavigation.StructuralNavigation.RemoveExistingNodes,
} : null,
source.Navigation.GlobalNavigation.ManagedNavigation != null ?
new Model.ManagedNavigation
{
TermSetId = source.Navigation.GlobalNavigation.ManagedNavigation.TermSetId,
TermStoreId = source.Navigation.GlobalNavigation.ManagedNavigation.TermStoreId,
} : null
)
: null,
source.Navigation.CurrentNavigation != null ?
new CurrentNavigation(
(CurrentNavigationType)Enum.Parse(typeof(CurrentNavigationType), source.Navigation.CurrentNavigation.NavigationType.ToString()),
source.Navigation.CurrentNavigation.StructuralNavigation != null ?
new Model.StructuralNavigation
{
RemoveExistingNodes = source.Navigation.CurrentNavigation.StructuralNavigation.RemoveExistingNodes,
} : null,
source.Navigation.CurrentNavigation.ManagedNavigation != null ?
new Model.ManagedNavigation
{
TermSetId = source.Navigation.CurrentNavigation.ManagedNavigation.TermSetId,
TermStoreId = source.Navigation.CurrentNavigation.ManagedNavigation.TermStoreId,
} : null
)
: null
);
// If I need to update the Global Structural Navigation nodes
if (result.Navigation.GlobalNavigation != null &&
result.Navigation.GlobalNavigation.StructuralNavigation != null &&
source.Navigation.GlobalNavigation != null &&
source.Navigation.GlobalNavigation.StructuralNavigation != null)
{
result.Navigation.GlobalNavigation.StructuralNavigation.NavigationNodes.AddRange(
from n in source.Navigation.GlobalNavigation.StructuralNavigation.NavigationNode
select n.FromSchemaNavigationNodeToModelNavigationNodeV201605()
);
}
// If I need to update the Current Structural Navigation nodes
if (result.Navigation.CurrentNavigation != null &&
result.Navigation.CurrentNavigation.StructuralNavigation != null &&
source.Navigation.CurrentNavigation != null &&
source.Navigation.CurrentNavigation.StructuralNavigation != null)
{
result.Navigation.CurrentNavigation.StructuralNavigation.NavigationNodes.AddRange(
from n in source.Navigation.CurrentNavigation.StructuralNavigation.NavigationNode
select n.FromSchemaNavigationNodeToModelNavigationNodeV201605()
);
}
}
#endregion
#region Site Columns
// Translate Site Columns (Fields), if any
if ((source.SiteFields != null) && (source.SiteFields.Any != null))
{
result.SiteFields.AddRange(
from field in source.SiteFields.Any
select new Model.Field
{
SchemaXml = field.OuterXml,
});
}
#endregion
#region Content Types
// Translate ContentTypes, if any
if ((source.ContentTypes != null) && (source.ContentTypes != null))
{
result.ContentTypes.AddRange(
from contentType in source.ContentTypes
select new ContentType(
contentType.ID,
contentType.Name,
contentType.Description,
contentType.Group,
contentType.Sealed,
contentType.Hidden,
contentType.ReadOnly,
(contentType.DocumentTemplate != null ?
contentType.DocumentTemplate.TargetName : null),
contentType.Overwrite,
(contentType.FieldRefs != null ?
(from fieldRef in contentType.FieldRefs
select new Model.FieldRef(fieldRef.Name)
{
Id = Guid.Parse(fieldRef.ID),
Hidden = fieldRef.Hidden,
Required = fieldRef.Required
}) : null)
)
{
DocumentSetTemplate = contentType.DocumentSetTemplate != null ?
new Model.DocumentSetTemplate(
contentType.DocumentSetTemplate.WelcomePage,
contentType.DocumentSetTemplate.AllowedContentTypes != null ?
(from act in contentType.DocumentSetTemplate.AllowedContentTypes
select act.ContentTypeID) : null,
contentType.DocumentSetTemplate.DefaultDocuments != null ?
(from dd in contentType.DocumentSetTemplate.DefaultDocuments
select new Model.DefaultDocument
{
ContentTypeId = dd.ContentTypeID,
FileSourcePath = dd.FileSourcePath,
Name = dd.Name,
}) : null,
contentType.DocumentSetTemplate.SharedFields != null ?
(from sf in contentType.DocumentSetTemplate.SharedFields
select Guid.Parse(sf.ID)) : null,
contentType.DocumentSetTemplate.WelcomePageFields != null ?
(from wpf in contentType.DocumentSetTemplate.WelcomePageFields
select Guid.Parse(wpf.ID)) : null
) : null,
DisplayFormUrl = contentType.DisplayFormUrl,
EditFormUrl = contentType.EditFormUrl,
NewFormUrl = contentType.NewFormUrl,
}
);
}
#endregion
#region List Instances
// Translate Lists Instances, if any
if (source.Lists != null)
{
result.Lists.AddRange(
from list in source.Lists
select new Model.ListInstance(
(list.ContentTypeBindings != null ?
(from contentTypeBinding in list.ContentTypeBindings
select new Model.ContentTypeBinding
{
ContentTypeId = contentTypeBinding.ContentTypeID,
Default = contentTypeBinding.Default,
Remove = contentTypeBinding.Remove,
}) : null),
(list.Views != null ?
(from view in list.Views.Any
select new Model.View
{
SchemaXml = view.OuterXml,
}) : null),
(list.Fields != null ?
(from field in list.Fields.Any
select new Model.Field
{
SchemaXml = field.OuterXml,
}) : null),
(list.FieldRefs != null ?
(from fieldRef in list.FieldRefs
select new Model.FieldRef(fieldRef.Name)
{
DisplayName = fieldRef.DisplayName,
Hidden = fieldRef.Hidden,
Required = fieldRef.Required,
Id = Guid.Parse(fieldRef.ID)
}) : null),
(list.DataRows != null ?
(from dataRow in list.DataRows
select new Model.DataRow(
(from dataValue in dataRow.DataValue
select dataValue).ToDictionary(k => k.FieldName, v => v.Value),
dataRow.Security.FromSchemaToTemplateObjectSecurityV201605()
)).ToList() : null),
(list.FieldDefaults != null ?
(from fd in list.FieldDefaults
select fd).ToDictionary(k => k.FieldName, v => v.Value) : null),
list.Security.FromSchemaToTemplateObjectSecurityV201605(),
(list.Folders != null ?
(new List<Model.Folder>(from folder in list.Folders
select folder.FromSchemaToTemplateFolderV201605())) : null),
(list.UserCustomActions != null ?
(new List<Model.CustomAction>(
from customAction in list.UserCustomActions
select new Model.CustomAction
{
CommandUIExtension = (customAction.CommandUIExtension != null && customAction.CommandUIExtension.Any != null) ?
(new XElement("CommandUIExtension", from x in customAction.CommandUIExtension.Any select x.ToXElement())) : null,
Description = customAction.Description,
Enabled = customAction.Enabled,
Group = customAction.Group,
ImageUrl = customAction.ImageUrl,
Location = customAction.Location,
Name = customAction.Name,
Rights = customAction.Rights.ToBasePermissionsV201605(),
ScriptBlock = customAction.ScriptBlock,
ScriptSrc = customAction.ScriptSrc,
RegistrationId = customAction.RegistrationId,
RegistrationType = (UserCustomActionRegistrationType)Enum.Parse(typeof(UserCustomActionRegistrationType), customAction.RegistrationType.ToString(), true),
Remove = customAction.Remove,
Sequence = customAction.SequenceSpecified ? customAction.Sequence : 100,
Title = customAction.Title,
Url = customAction.Url,
})) : null)
)
{
ContentTypesEnabled = list.ContentTypesEnabled,
Description = list.Description,
DocumentTemplate = list.DocumentTemplate,
EnableVersioning = list.EnableVersioning,
EnableMinorVersions = list.EnableMinorVersions,
DraftVersionVisibility = list.DraftVersionVisibility,
EnableModeration = list.EnableModeration,
Hidden = list.Hidden,
MinorVersionLimit = list.MinorVersionLimitSpecified ? list.MinorVersionLimit : 0,
MaxVersionLimit = list.MaxVersionLimitSpecified ? list.MaxVersionLimit : 0,
OnQuickLaunch = list.OnQuickLaunch,
EnableAttachments = list.EnableAttachments,
EnableFolderCreation = list.EnableFolderCreation,
ForceCheckout = list.ForceCheckout,
RemoveExistingContentTypes = list.RemoveExistingContentTypes,
TemplateFeatureID = !String.IsNullOrEmpty(list.TemplateFeatureID) ? Guid.Parse(list.TemplateFeatureID) : Guid.Empty,
RemoveExistingViews = list.Views != null ? list.Views.RemoveExistingViews : false,
TemplateType = list.TemplateType,
Title = list.Title,
Url = list.Url,
});
}
#endregion
#region Features
// Translate Features, if any
if (source.Features != null)
{
if (result.Features.SiteFeatures != null && source.Features.SiteFeatures != null)
{
result.Features.SiteFeatures.AddRange(
from feature in source.Features.SiteFeatures
select new Model.Feature
{
Id = new Guid(feature.ID),
Deactivate = feature.Deactivate,
});
}
if (result.Features.WebFeatures != null && source.Features.WebFeatures != null)
{
result.Features.WebFeatures.AddRange(
from feature in source.Features.WebFeatures
select new Model.Feature
{
Id = new Guid(feature.ID),
Deactivate = feature.Deactivate,
});
}
}
#endregion
#region Custom Actions
// Translate CustomActions, if any
if (source.CustomActions != null)
{
if (result.CustomActions.SiteCustomActions != null && source.CustomActions.SiteCustomActions != null)
{
result.CustomActions.SiteCustomActions.AddRange(
from customAction in source.CustomActions.SiteCustomActions
select new Model.CustomAction
{
CommandUIExtension = (customAction.CommandUIExtension != null && customAction.CommandUIExtension.Any != null) ?
(new XElement("CommandUIExtension", from x in customAction.CommandUIExtension.Any select x.ToXElement())) : null,
Description = customAction.Description,
Enabled = customAction.Enabled,
Group = customAction.Group,
ImageUrl = customAction.ImageUrl,
Location = customAction.Location,
Name = customAction.Name,
Rights = customAction.Rights.ToBasePermissionsV201605(),
ScriptBlock = customAction.ScriptBlock,
ScriptSrc = customAction.ScriptSrc,
RegistrationId = customAction.RegistrationId,
RegistrationType = (UserCustomActionRegistrationType)Enum.Parse(typeof(UserCustomActionRegistrationType), customAction.RegistrationType.ToString(), true),
Remove = customAction.Remove,
Sequence = customAction.SequenceSpecified ? customAction.Sequence : 100,
Title = customAction.Title,
Url = customAction.Url,
});
}
if (result.CustomActions.WebCustomActions != null && source.CustomActions.WebCustomActions != null)
{
result.CustomActions.WebCustomActions.AddRange(
from customAction in source.CustomActions.WebCustomActions
select new Model.CustomAction
{
CommandUIExtension = (customAction.CommandUIExtension != null && customAction.CommandUIExtension.Any != null) ?
(new XElement("CommandUIExtension", from x in customAction.CommandUIExtension.Any select x.ToXElement())) : null,
Description = customAction.Description,
Enabled = customAction.Enabled,
Group = customAction.Group,
ImageUrl = customAction.ImageUrl,
Location = customAction.Location,
Name = customAction.Name,
Rights = customAction.Rights.ToBasePermissionsV201605(),
ScriptBlock = customAction.ScriptBlock,
ScriptSrc = customAction.ScriptSrc,
RegistrationId = customAction.RegistrationId,
RegistrationType = (UserCustomActionRegistrationType)Enum.Parse(typeof(UserCustomActionRegistrationType), customAction.RegistrationType.ToString(), true),
Remove = customAction.Remove,
Sequence = customAction.SequenceSpecified ? customAction.Sequence : 100,
Title = customAction.Title,
Url = customAction.Url,
});
}
}
#endregion
#region Files
// Translate Files and Directories, if any
if (source.Files != null)
{
if (source.Files.File != null && source.Files.File.Length > 0)
{
// Handle Files
result.Files.AddRange(
from file in source.Files.File
select new Model.File(file.Src,
file.Folder,
file.Overwrite,
file.WebParts != null ?
(from wp in file.WebParts
select new Model.WebPart
{
Order = (uint)wp.Order,
Zone = wp.Zone,
Title = wp.Title,
Contents = wp.Contents.InnerXml
}) : null,
file.Properties != null ? file.Properties.ToDictionary(k => k.Key, v => v.Value) : null,
file.Security.FromSchemaToTemplateObjectSecurityV201605(),
file.LevelSpecified ?
(Model.FileLevel)Enum.Parse(typeof(Model.FileLevel), file.Level.ToString()) :
Model.FileLevel.Draft
)
);
}
if (source.Files.Directory != null && source.Files.Directory.Length > 0)
{
// Handle Directories of files
result.Directories.AddRange(
from dir in source.Files.Directory
select new Model.Directory(dir.Src,
dir.Folder,
dir.Overwrite,
dir.LevelSpecified ?
(Model.FileLevel)Enum.Parse(typeof(Model.FileLevel), dir.Level.ToString()) :
Model.FileLevel.Draft,
dir.Recursive,
dir.IncludedExtensions,
dir.ExcludedExtensions,
dir.MetadataMappingFile,
dir.Security.FromSchemaToTemplateObjectSecurityV201605()
)
);
}
}
#endregion
#region Pages
// Translate Pages, if any
if (source.Pages != null)
{
foreach (var page in source.Pages)
{
var pageLayout = WikiPageLayout.OneColumn;
switch (page.Layout)
{
case V201605.WikiPageLayout.OneColumn:
pageLayout = WikiPageLayout.OneColumn;
break;
case V201605.WikiPageLayout.OneColumnSidebar:
pageLayout = WikiPageLayout.OneColumnSideBar;
break;
case V201605.WikiPageLayout.TwoColumns:
pageLayout = WikiPageLayout.TwoColumns;
break;
case V201605.WikiPageLayout.TwoColumnsHeader:
pageLayout = WikiPageLayout.TwoColumnsHeader;
break;
case V201605.WikiPageLayout.TwoColumnsHeaderFooter:
pageLayout = WikiPageLayout.TwoColumnsHeaderFooter;
break;
case V201605.WikiPageLayout.ThreeColumns:
pageLayout = WikiPageLayout.ThreeColumns;
break;
case V201605.WikiPageLayout.ThreeColumnsHeader:
pageLayout = WikiPageLayout.ThreeColumnsHeader;
break;
case V201605.WikiPageLayout.ThreeColumnsHeaderFooter:
pageLayout = WikiPageLayout.ThreeColumnsHeaderFooter;
break;
case V201605.WikiPageLayout.Custom:
pageLayout = WikiPageLayout.Custom;
break;
}
result.Pages.Add(new Model.Page(page.Url, page.Overwrite, pageLayout,
(page.WebParts != null ?
(from wp in page.WebParts
select new Model.WebPart
{
Title = wp.Title,
Column = (uint)wp.Column,
Row = (uint)wp.Row,
Contents = wp.Contents.InnerXml
}).ToList() : null),
page.Security.FromSchemaToTemplateObjectSecurityV201605(),
(page.Fields != null && page.Fields.Length > 0) ?
(from f in page.Fields
select f).ToDictionary(i => i.FieldName, i => i.Value) : null
));
}
}
#endregion
#region Taxonomy
// Translate Termgroups, if any
if (source.TermGroups != null)
{
result.TermGroups.AddRange(
from termGroup in source.TermGroups
select new Model.TermGroup(
!string.IsNullOrEmpty(termGroup.ID) ? Guid.Parse(termGroup.ID) : Guid.Empty,
termGroup.Name,
new List<Model.TermSet>(
from termSet in termGroup.TermSets
select new Model.TermSet(
!string.IsNullOrEmpty(termSet.ID) ? Guid.Parse(termSet.ID) : Guid.Empty,
termSet.Name,
termSet.LanguageSpecified ? (int?)termSet.Language : null,
termSet.IsAvailableForTagging,
termSet.IsOpenForTermCreation,
termSet.Terms != null ? termSet.Terms.FromSchemaTermsToModelTermsV201605() : null,
termSet.CustomProperties != null ? termSet.CustomProperties.ToDictionary(k => k.Key, v => v.Value) : null)
{
Description = termSet.Description,
}),
termGroup.SiteCollectionTermGroup,
termGroup.Contributors != null ? (from c in termGroup.Contributors
select new Model.User { Name = c.Name }).ToArray() : null,
termGroup.Managers != null ? (from m in termGroup.Managers
select new Model.User { Name = m.Name }).ToArray() : null
)
{
Description = termGroup.Description,
});
}
#endregion
#region Composed Looks
// Translate ComposedLook, if any
if (source.ComposedLook != null)
{
result.ComposedLook.BackgroundFile = source.ComposedLook.BackgroundFile;
result.ComposedLook.ColorFile = source.ComposedLook.ColorFile;
result.ComposedLook.FontFile = source.ComposedLook.FontFile;
result.ComposedLook.Name = source.ComposedLook.Name;
result.ComposedLook.Version = source.ComposedLook.Version;
}
#endregion
#region Workflows
if (source.Workflows != null)
{
result.Workflows = new Model.Workflows(
(source.Workflows.WorkflowDefinitions != null &&
source.Workflows.WorkflowDefinitions.Length > 0) ?
(from wd in source.Workflows.WorkflowDefinitions
select new Model.WorkflowDefinition(
(wd.Properties != null && wd.Properties.Length > 0) ?
(from p in wd.Properties
select p).ToDictionary(i => i.Key, i => i.Value) : null)
{
AssociationUrl = wd.AssociationUrl,
Description = wd.Description,
DisplayName = wd.DisplayName,
DraftVersion = wd.DraftVersion,
FormField = wd.FormField != null ? wd.FormField.OuterXml : null,
Id = Guid.Parse(wd.Id),
InitiationUrl = wd.InitiationUrl,
Published = wd.PublishedSpecified ? wd.Published : false,
RequiresAssociationForm = wd.RequiresAssociationFormSpecified ? wd.RequiresAssociationForm : false,
RequiresInitiationForm = wd.RequiresInitiationFormSpecified ? wd.RequiresInitiationForm : false,
RestrictToScope = wd.RestrictToScope,
RestrictToType = wd.RestrictToType.ToString(),
XamlPath = wd.XamlPath,
}) : null,
(source.Workflows.WorkflowSubscriptions != null &&
source.Workflows.WorkflowSubscriptions.Length > 0) ?
(from ws in source.Workflows.WorkflowSubscriptions
select new Model.WorkflowSubscription(
(ws.PropertyDefinitions != null && ws.PropertyDefinitions.Length > 0) ?
(from pd in ws.PropertyDefinitions
select pd).ToDictionary(i => i.Key, i => i.Value) : null)
{
DefinitionId = Guid.Parse(ws.DefinitionId),
Enabled = ws.Enabled,
EventSourceId = ws.EventSourceId,
EventTypes = (new String[] {
ws.ItemAddedEvent? "ItemAdded" : null,
ws.ItemUpdatedEvent? "ItemUpdated" : null,
ws.WorkflowStartEvent? "WorkflowStart" : null }).Where(e => e != null).ToList(),
ListId = ws.ListId,
ManualStartBypassesActivationLimit = ws.ManualStartBypassesActivationLimitSpecified ? ws.ManualStartBypassesActivationLimit : false,
Name = ws.Name,
ParentContentTypeId = ws.ParentContentTypeId,
StatusFieldName = ws.StatusFieldName,
}) : null
);
}
#endregion
#region Search Settings
if (source.SearchSettings != null && source.SearchSettings.SiteSearchSettings != null)
{
result.SiteSearchSettings = source.SearchSettings.SiteSearchSettings.OuterXml;
}
if (source.SearchSettings != null && source.SearchSettings.WebSearchSettings != null)
{
result.WebSearchSettings = source.SearchSettings.WebSearchSettings.OuterXml;
}
#endregion
#region Publishing
if (source.Publishing != null)
{
result.Publishing = new Model.Publishing(
(Model.AutoCheckRequirementsOptions)Enum.Parse(typeof(Model.AutoCheckRequirementsOptions), source.Publishing.AutoCheckRequirements.ToString()),
source.Publishing.DesignPackage != null ?
new Model.DesignPackage
{
DesignPackagePath = source.Publishing.DesignPackage.DesignPackagePath,
MajorVersion = source.Publishing.DesignPackage.MajorVersionSpecified ? source.Publishing.DesignPackage.MajorVersion : 0,
MinorVersion = source.Publishing.DesignPackage.MinorVersionSpecified ? source.Publishing.DesignPackage.MinorVersion : 0,
PackageGuid = Guid.Parse(source.Publishing.DesignPackage.PackageGuid),
PackageName = source.Publishing.DesignPackage.PackageName,
} : null,
source.Publishing.AvailableWebTemplates != null && source.Publishing.AvailableWebTemplates.Length > 0 ?
(from awt in source.Publishing.AvailableWebTemplates
select new Model.AvailableWebTemplate
{
LanguageCode = awt.LanguageCodeSpecified ? awt.LanguageCode : 1033,
TemplateName = awt.TemplateName,
}) : null,
source.Publishing.PageLayouts != null && source.Publishing.PageLayouts.PageLayout != null && source.Publishing.PageLayouts.PageLayout.Length > 0 ?
(from pl in source.Publishing.PageLayouts.PageLayout
select new Model.PageLayout
{
IsDefault = pl.Path == source.Publishing.PageLayouts.Default,
Path = pl.Path,
}) : null
);
}
#endregion
#region AddIns
if (source.AddIns != null && source.AddIns.Length > 0)
{
result.AddIns.AddRange(
from addin in source.AddIns
select new Model.AddIn
{
PackagePath = addin.PackagePath,
Source = addin.Source.ToString(),
});
}
#endregion
#region Providers
// Translate Providers, if any
if (source.Providers != null)
{
foreach (var provider in source.Providers)
{
if (!String.IsNullOrEmpty(provider.HandlerType))
{
var handlerType = Type.GetType(provider.HandlerType, false);
if (handlerType != null)
{
result.ExtensibilityHandlers.Add(
new Model.ExtensibilityHandler
{
Assembly = handlerType.Assembly.FullName,
Type = handlerType.FullName,
Configuration = provider.Configuration != null ? provider.Configuration.ToProviderConfiguration() : null,
Enabled = provider.Enabled,
});
}
}
}
}
#endregion
return (result);
}
}
internal static class V201605Extensions
{
public static V201605.Term[] FromModelTermsToSchemaTermsV201605(this TermCollection terms)
{
V201605.Term[] result = terms.Count > 0 ? (
from term in terms
select new V201605.Term
{
ID = term.Id != Guid.Empty ? term.Id.ToString() : null,
Name = term.Name,
Description = term.Description,
Owner = term.Owner,
LanguageSpecified = term.Language.HasValue,
Language = term.Language.HasValue ? term.Language.Value : 1033,
IsAvailableForTagging = term.IsAvailableForTagging,
IsDeprecated = term.IsDeprecated,
IsReused = term.IsReused,
IsSourceTerm = term.IsSourceTerm,
SourceTermId = term.SourceTermId != Guid.Empty ? term.SourceTermId.ToString() : null,
CustomSortOrder = term.CustomSortOrder,
Terms = term.Terms.Count > 0 ? new V201605.TermTerms { Items = term.Terms.FromModelTermsToSchemaTermsV201605() } : null,
CustomProperties = term.Properties.Count > 0 ?
(from p in term.Properties
select new V201605.StringDictionaryItem
{
Key = p.Key,
Value = p.Value
}).ToArray() : null,
LocalCustomProperties = term.LocalProperties.Count > 0 ?
(from p in term.LocalProperties
select new V201605.StringDictionaryItem
{
Key = p.Key,
Value = p.Value
}).ToArray() : null,
Labels = term.Labels.Count > 0 ?
(from l in term.Labels
select new V201605.TermLabelsLabel
{
Language = l.Language,
IsDefaultForLanguage = l.IsDefaultForLanguage,
Value = l.Value,
}).ToArray() : null,
}).ToArray() : null;
return (result);
}
public static List<Model.Term> FromSchemaTermsToModelTermsV201605(this V201605.Term[] terms)
{
List<Model.Term> result = new List<Model.Term>(
from term in terms
select new Model.Term(
!string.IsNullOrEmpty(term.ID) ? Guid.Parse(term.ID) : Guid.Empty,
term.Name,
term.LanguageSpecified ? term.Language : (int?)null,
(term.Terms != null && term.Terms.Items != null) ? term.Terms.Items.FromSchemaTermsToModelTermsV201605() : null,
term.Labels != null ?
(new List<Model.TermLabel>(
from label in term.Labels
select new Model.TermLabel
{
Language = label.Language,
Value = label.Value,
IsDefaultForLanguage = label.IsDefaultForLanguage
}
)) : null,
term.CustomProperties != null ? term.CustomProperties.ToDictionary(k => k.Key, v => v.Value) : null,
term.LocalCustomProperties != null ? term.LocalCustomProperties.ToDictionary(k => k.Key, v => v.Value) : null
)
{
CustomSortOrder = term.CustomSortOrder,
IsAvailableForTagging = term.IsAvailableForTagging,
IsReused = term.IsReused,
IsSourceTerm = term.IsSourceTerm,
SourceTermId = !String.IsNullOrEmpty(term.SourceTermId) ? new Guid(term.SourceTermId) : Guid.Empty,
IsDeprecated = term.IsDeprecated,
Owner = term.Owner,
}
);
return (result);
}
public static V201605.CalendarType FromTemplateToSchemaCalendarTypeV201605(this Microsoft.SharePoint.Client.CalendarType calendarType)
{
switch (calendarType)
{
case Microsoft.SharePoint.Client.CalendarType.ChineseLunar:
return V201605.CalendarType.ChineseLunar;
case Microsoft.SharePoint.Client.CalendarType.Gregorian:
return V201605.CalendarType.Gregorian;
case Microsoft.SharePoint.Client.CalendarType.GregorianArabic:
return V201605.CalendarType.GregorianArabicCalendar;
case Microsoft.SharePoint.Client.CalendarType.GregorianMEFrench:
return V201605.CalendarType.GregorianMiddleEastFrenchCalendar;
case Microsoft.SharePoint.Client.CalendarType.GregorianXLITEnglish:
return V201605.CalendarType.GregorianTransliteratedEnglishCalendar;
case Microsoft.SharePoint.Client.CalendarType.GregorianXLITFrench:
return V201605.CalendarType.GregorianTransliteratedFrenchCalendar;
case Microsoft.SharePoint.Client.CalendarType.Hebrew:
return V201605.CalendarType.Hebrew;
case Microsoft.SharePoint.Client.CalendarType.Hijri:
return V201605.CalendarType.Hijri;
case Microsoft.SharePoint.Client.CalendarType.Japan:
return V201605.CalendarType.Japan;
case Microsoft.SharePoint.Client.CalendarType.Korea:
return V201605.CalendarType.Korea;
case Microsoft.SharePoint.Client.CalendarType.KoreaJapanLunar:
return V201605.CalendarType.KoreaandJapaneseLunar;
case Microsoft.SharePoint.Client.CalendarType.SakaEra:
return V201605.CalendarType.SakaEra;
case Microsoft.SharePoint.Client.CalendarType.Taiwan:
return V201605.CalendarType.Taiwan;
case Microsoft.SharePoint.Client.CalendarType.Thai:
return V201605.CalendarType.Thai;
case Microsoft.SharePoint.Client.CalendarType.UmAlQura:
return V201605.CalendarType.UmmalQura;
case Microsoft.SharePoint.Client.CalendarType.None:
default:
return V201605.CalendarType.None;
}
}
public static Microsoft.SharePoint.Client.CalendarType FromSchemaToTemplateCalendarTypeV201605(this V201605.CalendarType calendarType)
{
switch (calendarType)
{
case V201605.CalendarType.ChineseLunar:
return Microsoft.SharePoint.Client.CalendarType.ChineseLunar;
case V201605.CalendarType.Gregorian:
return Microsoft.SharePoint.Client.CalendarType.Gregorian;
case V201605.CalendarType.GregorianArabicCalendar:
return Microsoft.SharePoint.Client.CalendarType.GregorianArabic;
case V201605.CalendarType.GregorianMiddleEastFrenchCalendar:
return Microsoft.SharePoint.Client.CalendarType.GregorianMEFrench;
case V201605.CalendarType.GregorianTransliteratedEnglishCalendar:
return Microsoft.SharePoint.Client.CalendarType.GregorianXLITEnglish;
case V201605.CalendarType.GregorianTransliteratedFrenchCalendar:
return Microsoft.SharePoint.Client.CalendarType.GregorianXLITFrench;
case V201605.CalendarType.Hebrew:
return Microsoft.SharePoint.Client.CalendarType.Hebrew;
case V201605.CalendarType.Hijri:
return Microsoft.SharePoint.Client.CalendarType.Hijri;
case V201605.CalendarType.Japan:
return Microsoft.SharePoint.Client.CalendarType.Japan;
case V201605.CalendarType.Korea:
return Microsoft.SharePoint.Client.CalendarType.Korea;
case V201605.CalendarType.KoreaandJapaneseLunar:
return Microsoft.SharePoint.Client.CalendarType.KoreaJapanLunar;
case V201605.CalendarType.SakaEra:
return Microsoft.SharePoint.Client.CalendarType.SakaEra;
case V201605.CalendarType.Taiwan:
return Microsoft.SharePoint.Client.CalendarType.Taiwan;
case V201605.CalendarType.Thai:
return Microsoft.SharePoint.Client.CalendarType.Thai;
case V201605.CalendarType.UmmalQura:
return Microsoft.SharePoint.Client.CalendarType.UmAlQura;
case V201605.CalendarType.None:
default:
return Microsoft.SharePoint.Client.CalendarType.None;
}
}
public static V201605.WorkHour FromTemplateToSchemaWorkHourV201605(this Model.WorkHour workHour)
{
switch (workHour)
{
case Model.WorkHour.AM0100:
return V201605.WorkHour.Item100AM;
case Model.WorkHour.AM0200:
return V201605.WorkHour.Item200AM;
case Model.WorkHour.AM0300:
return V201605.WorkHour.Item300AM;
case Model.WorkHour.AM0400:
return V201605.WorkHour.Item400AM;
case Model.WorkHour.AM0500:
return V201605.WorkHour.Item500AM;
case Model.WorkHour.AM0600:
return V201605.WorkHour.Item600AM;
case Model.WorkHour.AM0700:
return V201605.WorkHour.Item700AM;
case Model.WorkHour.AM0800:
return V201605.WorkHour.Item800AM;
case Model.WorkHour.AM0900:
return V201605.WorkHour.Item900AM;
case Model.WorkHour.AM1000:
return V201605.WorkHour.Item1000AM;
case Model.WorkHour.AM1100:
return V201605.WorkHour.Item1100AM;
case Model.WorkHour.AM1200:
return V201605.WorkHour.Item1200AM;
case Model.WorkHour.PM0100:
return V201605.WorkHour.Item100PM;
case Model.WorkHour.PM0200:
return V201605.WorkHour.Item200PM;
case Model.WorkHour.PM0300:
return V201605.WorkHour.Item300PM;
case Model.WorkHour.PM0400:
return V201605.WorkHour.Item400PM;
case Model.WorkHour.PM0500:
return V201605.WorkHour.Item500PM;
case Model.WorkHour.PM0600:
return V201605.WorkHour.Item600PM;
case Model.WorkHour.PM0700:
return V201605.WorkHour.Item700PM;
case Model.WorkHour.PM0800:
return V201605.WorkHour.Item800PM;
case Model.WorkHour.PM0900:
return V201605.WorkHour.Item900PM;
case Model.WorkHour.PM1000:
return V201605.WorkHour.Item1000PM;
case Model.WorkHour.PM1100:
return V201605.WorkHour.Item1100PM;
case Model.WorkHour.PM1200:
return V201605.WorkHour.Item1200PM;
default:
return V201605.WorkHour.Item100AM;
}
}
public static Model.WorkHour FromSchemaToTemplateWorkHourV201605(this V201605.WorkHour workHour)
{
switch (workHour)
{
case V201605.WorkHour.Item100AM:
return Model.WorkHour.AM0100;
case V201605.WorkHour.Item200AM:
return Model.WorkHour.AM0200;
case V201605.WorkHour.Item300AM:
return Model.WorkHour.AM0300;
case V201605.WorkHour.Item400AM:
return Model.WorkHour.AM0400;
case V201605.WorkHour.Item500AM:
return Model.WorkHour.AM0500;
case V201605.WorkHour.Item600AM:
return Model.WorkHour.AM0600;
case V201605.WorkHour.Item700AM:
return Model.WorkHour.AM0700;
case V201605.WorkHour.Item800AM:
return Model.WorkHour.AM0800;
case V201605.WorkHour.Item900AM:
return Model.WorkHour.AM0900;
case V201605.WorkHour.Item1000AM:
return Model.WorkHour.AM1000;
case V201605.WorkHour.Item1100AM:
return Model.WorkHour.AM1100;
case V201605.WorkHour.Item1200AM:
return Model.WorkHour.AM1200;
case V201605.WorkHour.Item100PM:
return Model.WorkHour.PM0100;
case V201605.WorkHour.Item200PM:
return Model.WorkHour.PM0200;
case V201605.WorkHour.Item300PM:
return Model.WorkHour.PM0300;
case V201605.WorkHour.Item400PM:
return Model.WorkHour.PM0400;
case V201605.WorkHour.Item500PM:
return Model.WorkHour.PM0500;
case V201605.WorkHour.Item600PM:
return Model.WorkHour.PM0600;
case V201605.WorkHour.Item700PM:
return Model.WorkHour.PM0700;
case V201605.WorkHour.Item800PM:
return Model.WorkHour.PM0800;
case V201605.WorkHour.Item900PM:
return Model.WorkHour.PM0900;
case V201605.WorkHour.Item1000PM:
return Model.WorkHour.PM1000;
case V201605.WorkHour.Item1100PM:
return Model.WorkHour.PM1100;
case V201605.WorkHour.Item1200PM:
return Model.WorkHour.PM1200;
default:
return Model.WorkHour.AM0100;
}
}
public static V201605.AuditSettingsAudit[] FromTemplateToSchemaAuditsV201605(this Microsoft.SharePoint.Client.AuditMaskType audits)
{
List<V201605.AuditSettingsAudit> result = new List<AuditSettingsAudit>();
if (audits.HasFlag(Microsoft.SharePoint.Client.AuditMaskType.All))
{
result.Add(new AuditSettingsAudit { AuditFlag = AuditSettingsAuditAuditFlag.All });
}
if (audits.HasFlag(Microsoft.SharePoint.Client.AuditMaskType.CheckIn))
{
result.Add(new AuditSettingsAudit { AuditFlag = AuditSettingsAuditAuditFlag.CheckIn });
}
if (audits.HasFlag(Microsoft.SharePoint.Client.AuditMaskType.CheckOut))
{
result.Add(new AuditSettingsAudit { AuditFlag = AuditSettingsAuditAuditFlag.CheckOut });
}
if (audits.HasFlag(Microsoft.SharePoint.Client.AuditMaskType.ChildDelete))
{
result.Add(new AuditSettingsAudit { AuditFlag = AuditSettingsAuditAuditFlag.ChildDelete });
}
if (audits.HasFlag(Microsoft.SharePoint.Client.AuditMaskType.Copy))
{
result.Add(new AuditSettingsAudit { AuditFlag = AuditSettingsAuditAuditFlag.Copy });
}
if (audits.HasFlag(Microsoft.SharePoint.Client.AuditMaskType.Move))
{
result.Add(new AuditSettingsAudit { AuditFlag = AuditSettingsAuditAuditFlag.Move });
}
if (audits.HasFlag(Microsoft.SharePoint.Client.AuditMaskType.None))
{
result.Add(new AuditSettingsAudit { AuditFlag = AuditSettingsAuditAuditFlag.None });
}
if (audits.HasFlag(Microsoft.SharePoint.Client.AuditMaskType.ObjectDelete))
{
result.Add(new AuditSettingsAudit { AuditFlag = AuditSettingsAuditAuditFlag.ObjectDelete });
}
if (audits.HasFlag(Microsoft.SharePoint.Client.AuditMaskType.ProfileChange))
{
result.Add(new AuditSettingsAudit { AuditFlag = AuditSettingsAuditAuditFlag.ProfileChange });
}
if (audits.HasFlag(Microsoft.SharePoint.Client.AuditMaskType.SchemaChange))
{
result.Add(new AuditSettingsAudit { AuditFlag = AuditSettingsAuditAuditFlag.SchemaChange });
}
if (audits.HasFlag(Microsoft.SharePoint.Client.AuditMaskType.Search))
{
result.Add(new AuditSettingsAudit { AuditFlag = AuditSettingsAuditAuditFlag.Search });
}
if (audits.HasFlag(Microsoft.SharePoint.Client.AuditMaskType.SecurityChange))
{
result.Add(new AuditSettingsAudit { AuditFlag = AuditSettingsAuditAuditFlag.SecurityChange });
}
if (audits.HasFlag(Microsoft.SharePoint.Client.AuditMaskType.Undelete))
{
result.Add(new AuditSettingsAudit { AuditFlag = AuditSettingsAuditAuditFlag.Undelete });
}
if (audits.HasFlag(Microsoft.SharePoint.Client.AuditMaskType.Update))
{
result.Add(new AuditSettingsAudit { AuditFlag = AuditSettingsAuditAuditFlag.Update });
}
if (audits.HasFlag(Microsoft.SharePoint.Client.AuditMaskType.View))
{
result.Add(new AuditSettingsAudit { AuditFlag = AuditSettingsAuditAuditFlag.View });
}
if (audits.HasFlag(Microsoft.SharePoint.Client.AuditMaskType.Workflow))
{
result.Add(new AuditSettingsAudit { AuditFlag = AuditSettingsAuditAuditFlag.Workflow });
}
return result.ToArray();
}
public static Model.ObjectSecurity FromSchemaToTemplateObjectSecurityV201605(this V201605.ObjectSecurity objectSecurity)
{
return ((objectSecurity != null && objectSecurity.BreakRoleInheritance != null) ?
new Model.ObjectSecurity(
objectSecurity.BreakRoleInheritance.RoleAssignment != null ?
(from ra in objectSecurity.BreakRoleInheritance.RoleAssignment
select new Model.RoleAssignment
{
Principal = ra.Principal,
RoleDefinition = ra.RoleDefinition,
}) : null
)
{
ClearSubscopes = objectSecurity.BreakRoleInheritance.ClearSubscopes,
CopyRoleAssignments = objectSecurity.BreakRoleInheritance.CopyRoleAssignments,
} : null);
}
public static V201605.ObjectSecurity FromTemplateToSchemaObjectSecurityV201605(this Model.ObjectSecurity objectSecurity)
{
return ((objectSecurity != null && (objectSecurity.ClearSubscopes == true || objectSecurity.CopyRoleAssignments == true || objectSecurity.RoleAssignments.Count > 0)) ?
new V201605.ObjectSecurity
{
BreakRoleInheritance = new V201605.ObjectSecurityBreakRoleInheritance
{
ClearSubscopes = objectSecurity.ClearSubscopes,
CopyRoleAssignments = objectSecurity.CopyRoleAssignments,
RoleAssignment = (objectSecurity.RoleAssignments != null && objectSecurity.RoleAssignments.Count > 0) ?
(from ra in objectSecurity.RoleAssignments
select new V201605.RoleAssignment
{
Principal = ra.Principal,
RoleDefinition = ra.RoleDefinition,
}).ToArray() : null,
}
} : null);
}
public static Model.Folder FromSchemaToTemplateFolderV201605(this V201605.Folder folder)
{
Model.Folder result = new Model.Folder(folder.Name, null, folder.Security.FromSchemaToTemplateObjectSecurityV201605());
if (folder.Folder1 != null && folder.Folder1.Length > 0)
{
result.Folders.AddRange(from child in folder.Folder1 select child.FromSchemaToTemplateFolderV201605());
}
return (result);
}
public static V201605.Folder FromTemplateToSchemaFolderV201605(this Model.Folder folder)
{
V201605.Folder result = new V201605.Folder();
result.Name = folder.Name;
result.Security = folder.Security.FromTemplateToSchemaObjectSecurityV201605();
result.Folder1 = folder.Folders != null ? (from child in folder.Folders select child.FromTemplateToSchemaFolderV201605()).ToArray() : null;
return (result);
}
public static string FromBasePermissionsToStringV201605(this BasePermissions basePermissions)
{
List<string> permissions = new List<string>();
foreach (var pk in (PermissionKind[])Enum.GetValues(typeof(PermissionKind)))
{
if (basePermissions.Has(pk) && pk != PermissionKind.EmptyMask)
{
permissions.Add(pk.ToString());
}
}
return string.Join(",", permissions.ToArray());
}
public static BasePermissions ToBasePermissionsV201605(this string basePermissionString)
{
BasePermissions bp = new BasePermissions();
// Is it an int value (for backwards compability)?
int permissionInt;
if (int.TryParse(basePermissionString, out permissionInt))
{
bp.Set((PermissionKind)permissionInt);
}
else if (!string.IsNullOrEmpty(basePermissionString))
{
foreach (var pk in basePermissionString.Split(','))
{
PermissionKind permissionKind;
if (Enum.TryParse<PermissionKind>(pk, out permissionKind))
{
bp.Set(permissionKind);
}
}
}
return bp;
}
public static Model.NavigationNode FromSchemaNavigationNodeToModelNavigationNodeV201605(
this V201605.NavigationNode node)
{
var result = new Model.NavigationNode
{
IsExternal = node.IsExternal,
Title = node.Title,
Url = node.Url,
};
if (node.ChildNodes != null && node.ChildNodes.Length > 0)
{
result.NavigationNodes.AddRange(
(from n in node.ChildNodes
select n.FromSchemaNavigationNodeToModelNavigationNodeV201605()));
}
return (result);
}
public static V201605.NavigationNode FromModelNavigationNodeToSchemaNavigationNodeV201605(
this Model.NavigationNode node)
{
var result = new V201605.NavigationNode
{
IsExternal = node.IsExternal,
Title = node.Title,
Url = node.Url,
ChildNodes = (from n in node.NavigationNodes
select n.FromModelNavigationNodeToSchemaNavigationNodeV201605()).ToArray()
};
return (result);
}
}
}
| 49.990418 | 273 | 0.495365 | [
"MIT"
] | danielabbuildingi/PnP-Sites-Core | Core/OfficeDevPnP.Core/Framework/Provisioning/Providers/Xml/XMLPnPSchemaV201605Formatter.cs | 130,427 | C# |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using Spectre.Console.Rendering;
namespace Spectre.Console.Cli
{
[Description("Displays diagnostics about CLI configurations")]
[SuppressMessage("Performance", "CA1812: Avoid uninstantiated internal classes")]
internal sealed class ExplainCommand : Command<ExplainCommand.Settings>
{
private readonly CommandModel _commandModel;
private readonly IAnsiConsole _writer;
public ExplainCommand(IConfiguration configuration, CommandModel commandModel)
{
_commandModel = commandModel ?? throw new ArgumentNullException(nameof(commandModel));
_writer = configuration.Settings.Console.GetConsole();
}
public sealed class Settings : CommandSettings
{
public Settings(string[]? commands, bool? detailed, bool includeHidden)
{
Commands = commands;
Detailed = detailed;
IncludeHidden = includeHidden;
}
[CommandArgument(0, "[command]")]
public string[]? Commands { get; }
[Description("Include detailed information about the commands.")]
[CommandOption("-d|--detailed")]
public bool? Detailed { get; }
[Description("Include hidden commands and options.")]
[CommandOption("--hidden")]
public bool IncludeHidden { get; }
}
public override int Execute([NotNull] CommandContext context, [NotNull] Settings settings)
{
var tree = new Tree("CLI Configuration");
tree.AddNode(ValueMarkup("Application Name", _commandModel.ApplicationName, "no application name"));
tree.AddNode(ValueMarkup("Parsing Mode", _commandModel.ParsingMode.ToString()));
if (settings.Commands == null || settings.Commands.Length == 0)
{
// If there is a default command we'll want to include it in the list too.
var commands = _commandModel.DefaultCommand != null
? new[] { _commandModel.DefaultCommand }.Concat(_commandModel.Commands)
: _commandModel.Commands;
AddCommands(
tree.AddNode(ParentMarkup("Commands")),
commands,
settings.Detailed ?? false,
settings.IncludeHidden);
}
else
{
var currentCommandTier = _commandModel.Commands;
CommandInfo? currentCommand = null;
foreach (var command in settings.Commands)
{
currentCommand = currentCommandTier
.SingleOrDefault(i =>
i.Name.Equals(command, StringComparison.CurrentCultureIgnoreCase) ||
i.Aliases
.Any(alias => alias.Equals(command, StringComparison.CurrentCultureIgnoreCase)));
if (currentCommand == null)
{
break;
}
currentCommandTier = currentCommand.Children;
}
if (currentCommand == null)
{
throw new Exception($"Command {string.Join(" ", settings.Commands)} not found");
}
AddCommands(
tree.AddNode(ParentMarkup("Commands")),
new[] { currentCommand },
settings.Detailed ?? true,
settings.IncludeHidden);
}
_writer.Write(tree);
return 0;
}
private IRenderable ValueMarkup(string key, string value)
{
return new Markup($"{key}: [blue]{value.EscapeMarkup()}[/]");
}
private IRenderable ValueMarkup(string key, string? value, string noValueText)
{
if (string.IsNullOrWhiteSpace(value))
{
return new Markup($"{key}: [grey]({noValueText.EscapeMarkup()})[/]");
}
var table = new Table().NoBorder().HideHeaders().AddColumns("key", "value");
table.AddRow($"{key}", $"[blue]{value.EscapeMarkup()}[/]");
return table;
}
private string ParentMarkup(string description)
{
return $"[yellow]{description.EscapeMarkup()}[/]";
}
private void AddStringList(TreeNode node, string description, IList<string>? strings)
{
if (strings == null || strings.Count == 0)
{
return;
}
var parentNode = node.AddNode(ParentMarkup(description));
foreach (var s in strings)
{
parentNode.AddNode(s);
}
}
private void AddCommands(TreeNode node, IEnumerable<CommandInfo> commands, bool detailed, bool includeHidden)
{
foreach (var command in commands)
{
if (!includeHidden && command.IsHidden)
{
continue;
}
var commandName = $"[green]{command.Name}[/]";
if (command.IsDefaultCommand)
{
commandName += " (default)";
}
var commandNode = node.AddNode(commandName);
commandNode.AddNode(ValueMarkup("Description", command.Description, "no description"));
if (command.IsHidden)
{
commandNode.AddNode(ValueMarkup("IsHidden", command.IsHidden.ToString()));
}
if (!command.IsBranch)
{
commandNode.AddNode(ValueMarkup("Type", command.CommandType?.ToString(), "no command type"));
commandNode.AddNode(ValueMarkup("Settings Type", command.SettingsType.ToString()));
}
if (command.Parameters.Count > 0)
{
var parametersNode = commandNode.AddNode(ParentMarkup("Parameters"));
foreach (var parameter in command.Parameters)
{
AddParameter(parametersNode, parameter, detailed, includeHidden);
}
}
AddStringList(commandNode, "Aliases", command.Aliases.ToList());
AddStringList(commandNode, "Examples", command.Examples.Select(i => string.Join(" ", i)).ToList());
if (command.Children.Count > 0)
{
var childNode = commandNode.AddNode(ParentMarkup("Child Commands"));
AddCommands(childNode, command.Children, detailed, includeHidden);
}
}
}
private void AddParameter(TreeNode parametersNode, CommandParameter parameter, bool detailed, bool includeHidden)
{
if (!includeHidden && parameter.IsHidden)
{
return;
}
if (!detailed)
{
parametersNode.AddNode(
$"{parameter.PropertyName} [purple]{GetShortOptions(parameter)}[/] [grey]{parameter.Property.PropertyType.ToString().EscapeMarkup()}[/]");
return;
}
var parameterNode = parametersNode.AddNode(
$"{parameter.PropertyName} [grey]{parameter.Property.PropertyType.ToString().EscapeMarkup()}[/]");
parameterNode.AddNode(ValueMarkup("Description", parameter.Description, "no description"));
parameterNode.AddNode(ValueMarkup("Parameter Kind", parameter.ParameterKind.ToString()));
if (parameter is CommandOption commandOptionParameter)
{
if (commandOptionParameter.IsShadowed)
{
parameterNode.AddNode(ValueMarkup("IsShadowed", commandOptionParameter.IsShadowed.ToString()));
}
if (commandOptionParameter.LongNames.Count > 0)
{
parameterNode.AddNode(ValueMarkup(
"Long Names",
string.Join("|", commandOptionParameter.LongNames.Select(i => $"--{i}"))));
parameterNode.AddNode(ValueMarkup(
"Short Names",
string.Join("|", commandOptionParameter.ShortNames.Select(i => $"-{i}"))));
}
}
else if (parameter is CommandArgument commandArgumentParameter)
{
parameterNode.AddNode(ValueMarkup("Position", commandArgumentParameter.Position.ToString()));
parameterNode.AddNode(ValueMarkup("Value", commandArgumentParameter.Value));
}
parameterNode.AddNode(ValueMarkup("Required", parameter.Required.ToString()));
if (parameter.Converter != null)
{
parameterNode.AddNode(ValueMarkup(
"Converter", $"\"{parameter.Converter.ConverterTypeName}\""));
}
if (parameter.DefaultValue != null)
{
parameterNode.AddNode(ValueMarkup(
"Default Value", $"\"{parameter.DefaultValue.Value}\""));
}
if (parameter.PairDeconstructor != null)
{
parameterNode.AddNode(ValueMarkup("Pair Deconstructor", parameter.PairDeconstructor.Type.ToString()));
}
AddStringList(
parameterNode,
"Validators",
parameter.Validators.Select(i => i.GetType().ToString()).ToList());
}
private static string GetShortOptions(CommandParameter parameter)
{
if (parameter is CommandOption commandOptionParameter)
{
return string.Join(
" | ",
commandOptionParameter.LongNames.Select(i => $"--{i}")
.Concat(commandOptionParameter.ShortNames.Select(i => $"-{i}")));
}
if (parameter is CommandArgument commandArgumentParameter)
{
return $"{commandArgumentParameter.Value} position {commandArgumentParameter.Position}";
}
return string.Empty;
}
}
} | 38.595588 | 158 | 0.537721 | [
"MIT"
] | gordonkratz/spectre.console | src/Spectre.Console/Cli/Internal/Commands/ExplainCommand.cs | 10,500 | C# |
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
namespace AvatarSnow
{
public class UIManager : MonoBehaviour
{
[SerializeField] private EffectManager effectManager;
public void TappedEffectButton(int index)
{
effectManager.SetEffect((EffectType)Enum.ToObject(typeof(EffectType), index));
}
}
} | 22.578947 | 90 | 0.689977 | [
"MIT"
] | YoHana19/AvatarSnow | Assets/Scripts/UIManager.cs | 431 | C# |
using System;
using System.Collections.Generic;
using System.Text;
namespace Entities.Models
{
public class ChartDto
{
public string Label { get; set; }
public int Value { get; set; }
}
}
| 16.769231 | 41 | 0.642202 | [
"MIT"
] | CodeMazeBlog/blazor-wasm-signalr-charts | End/BlazorProducts.Server/Entities/Models/ChartDto.cs | 220 | C# |
using System;
using System.Drawing;
namespace BaSta.Game
{
public class Game
{
private int _id = -1;
private int _gamekind_id = -1;
private DateTime _date_time = DateTime.Now;
private int _period = 1;
private int _home_team_id = -1;
private string _home_team_name = string.Empty;
private int _guest_team_id = -1;
private string _guest_team_name = string.Empty;
private bool _started;
private Image _home_team_logo;
private Image _guest_team_logo;
public int ID
{
get
{
return _id;
}
set
{
_id = value;
}
}
public int GameKindID
{
get
{
return _gamekind_id;
}
set
{
_gamekind_id = value;
}
}
public DateTime DateTime
{
get
{
return _date_time;
}
set
{
_date_time = value;
}
}
public bool Started
{
get
{
return _started;
}
set
{
_started = value;
}
}
public int Period
{
get
{
return _period;
}
set
{
_period = value;
}
}
public int HomeTeamID
{
get
{
return _home_team_id;
}
set
{
_home_team_id = value;
}
}
public string HomeTeamName
{
get
{
return _home_team_name;
}
set
{
_home_team_name = value;
}
}
public Image HomeTeamLogo
{
get
{
return _home_team_logo;
}
set
{
_home_team_logo = value;
}
}
public int GuestTeamID
{
get
{
return _guest_team_id;
}
set
{
_guest_team_id = value;
}
}
public string GuestTeamName
{
get
{
return _guest_team_name;
}
set
{
_guest_team_name = value;
}
}
public Image GuestTeamLogo
{
get
{
return _guest_team_logo;
}
set
{
_guest_team_logo = value;
}
}
}
} | 19.144737 | 55 | 0.350172 | [
"MIT"
] | christianduerselen/BaSta | src/BaSta.Game/Game.cs | 2,912 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using GW2EIParser.EIData;
using GW2EIParser.Parser;
using GW2EIParser.Parser.ParsedData;
using Newtonsoft.Json.Serialization;
using static GW2EIParser.Parser.ParseEnum.TrashIDS;
namespace GW2EIParser
{
public static class GeneralHelper
{
public static int PollingRate = 150;
public static readonly int BuffDigit = 2;
public static readonly int TimeDigit = 3;
public static readonly long ServerDelayConstant = 10;
public static int PhaseTimeLimit = 1000;
public static AgentItem UnknownAgent = new AgentItem();
// use this for "null" in AbstractActor dictionaries
public static NPC NullActor = new NPC(UnknownAgent);
public static UTF8Encoding NoBOMEncodingUTF8 = new UTF8Encoding(false);
public static readonly DefaultContractResolver ContractResolver = new DefaultContractResolver
{
NamingStrategy = new CamelCaseNamingStrategy()
};
public static Exception GetFinalException(this Exception ex)
{
Exception final = ex;
while (final.InnerException != null)
{
final = final.InnerException;
}
return final;
}
public static double Clamp(double value, double lowerLimit, double upperLimit)
{
return Math.Min(Math.Max(value, lowerLimit), upperLimit);
}
public static void Add<K, T>(Dictionary<K, List<T>> dict, K key, T evt)
{
if (dict.TryGetValue(key, out List<T> list))
{
list.Add(evt);
}
else
{
dict[key] = new List<T>()
{
evt
};
}
}
public static string UppercaseFirst(string s)
{
if (string.IsNullOrEmpty(s))
{
return string.Empty;
}
char[] a = s.ToCharArray();
a[0] = char.ToUpper(a[0]);
return new string(a);
}
public static T MaxBy<T, R>(this IEnumerable<T> en, Func<T, R> evaluate) where R : IComparable<R>
{
return en.Select(t => (value: t, eval: evaluate(t)))
.Aggregate((max, next) => next.eval.CompareTo(max.eval) > 0 ? next : max).value;
}
public static T MinBy<T, R>(this IEnumerable<T> en, Func<T, R> evaluate) where R : IComparable<R>
{
return en.Select(t => (value: t, eval: evaluate(t)))
.Aggregate((max, next) => next.eval.CompareTo(max.eval) < 0 ? next : max).value;
}
public static string FindPattern(string source, string regex)
{
if (string.IsNullOrEmpty(source))
{
return null;
}
Match match = Regex.Match(source, regex);
if (match.Success)
{
return match.Groups[1].Value;
}
return null;
}
public static string GetIcon(AbstractSingleActor actor)
{
string res = GetProfIcon(actor.Prof);
if (res.Length == 0)
{
res = GetNPCIcon(actor.ID);
}
return res;
}
private static string GetProfIcon(string prof)
{
switch (prof)
{
case "Warrior":
return "https://wiki.guildwars2.com/images/4/43/Warrior_tango_icon_20px.png";
case "Berserker":
return "https://wiki.guildwars2.com/images/d/da/Berserker_tango_icon_20px.png";
case "Spellbreaker":
return "https://wiki.guildwars2.com/images/e/ed/Spellbreaker_tango_icon_20px.png";
case "Guardian":
return "https://wiki.guildwars2.com/images/8/8c/Guardian_tango_icon_20px.png";
case "Dragonhunter":
return "https://wiki.guildwars2.com/images/c/c9/Dragonhunter_tango_icon_20px.png";
case "DragonHunter":
return "https://wiki.guildwars2.com/images/c/c9/Dragonhunter_tango_icon_20px.png";
case "Firebrand":
return "https://wiki.guildwars2.com/images/0/02/Firebrand_tango_icon_20px.png";
case "Revenant":
return "https://wiki.guildwars2.com/images/b/b5/Revenant_tango_icon_20px.png";
case "Herald":
return "https://wiki.guildwars2.com/images/6/67/Herald_tango_icon_20px.png";
case "Renegade":
return "https://wiki.guildwars2.com/images/7/7c/Renegade_tango_icon_20px.png";
case "Engineer":
return "https://wiki.guildwars2.com/images/2/27/Engineer_tango_icon_20px.png";
case "Scrapper":
return "https://wiki.guildwars2.com/images/3/3a/Scrapper_tango_icon_200px.png";
case "Holosmith":
return "https://wiki.guildwars2.com/images/2/28/Holosmith_tango_icon_20px.png";
case "Ranger":
return "https://wiki.guildwars2.com/images/4/43/Ranger_tango_icon_20px.png";
case "Druid":
return "https://wiki.guildwars2.com/images/d/d2/Druid_tango_icon_20px.png";
case "Soulbeast":
return "https://wiki.guildwars2.com/images/7/7c/Soulbeast_tango_icon_20px.png";
case "Thief":
return "https://wiki.guildwars2.com/images/7/7a/Thief_tango_icon_20px.png";
case "Daredevil":
return "https://wiki.guildwars2.com/images/e/e1/Daredevil_tango_icon_20px.png";
case "Deadeye":
return "https://wiki.guildwars2.com/images/c/c9/Deadeye_tango_icon_20px.png";
case "Elementalist":
return "https://wiki.guildwars2.com/images/a/aa/Elementalist_tango_icon_20px.png";
case "Tempest":
return "https://wiki.guildwars2.com/images/4/4a/Tempest_tango_icon_20px.png";
case "Weaver":
return "https://wiki.guildwars2.com/images/f/fc/Weaver_tango_icon_20px.png";
case "Mesmer":
return "https://wiki.guildwars2.com/images/6/60/Mesmer_tango_icon_20px.png";
case "Chronomancer":
return "https://wiki.guildwars2.com/images/f/f4/Chronomancer_tango_icon_20px.png";
case "Mirage":
return "https://wiki.guildwars2.com/images/d/df/Mirage_tango_icon_20px.png";
case "Necromancer":
return "https://wiki.guildwars2.com/images/4/43/Necromancer_tango_icon_20px.png";
case "Reaper":
return "https://wiki.guildwars2.com/images/1/11/Reaper_tango_icon_20px.png";
case "Scourge":
return "https://wiki.guildwars2.com/images/0/06/Scourge_tango_icon_20px.png";
case "Sword":
return "https://wiki.guildwars2.com/images/0/07/Crimson_Antique_Blade.png";
}
return "";
}
private static string GetNPCIcon(int id)
{
switch (ParseEnum.GetTargetIDS(id))
{
case ParseEnum.TargetIDS.WorldVersusWorld:
return "https://wiki.guildwars2.com/images/d/db/PvP_Server_Browser_%28map_icon%29.png";
case ParseEnum.TargetIDS.ValeGuardian:
return "https://i.imgur.com/MIpP5pK.png";
case ParseEnum.TargetIDS.Gorseval:
return "https://i.imgur.com/5hmMq12.png";
case ParseEnum.TargetIDS.Sabetha:
return "https://i.imgur.com/UqbFp9S.png";
case ParseEnum.TargetIDS.Slothasor:
return "https://i.imgur.com/h1xH3ER.png";
case ParseEnum.TargetIDS.Berg:
return "https://i.imgur.com/tLMXqL7.png";
case ParseEnum.TargetIDS.Narella:
return "https://i.imgur.com/FwMCoR0.png";
case ParseEnum.TargetIDS.Zane:
return "https://i.imgur.com/tkPWMST.png";
case ParseEnum.TargetIDS.Matthias:
return "https://i.imgur.com/3uMMmTS.png";
case ParseEnum.TargetIDS.KeepConstruct:
return "https://i.imgur.com/Kq0kL07.png";
case ParseEnum.TargetIDS.Xera:
return "https://i.imgur.com/lYwJEyV.png";
case ParseEnum.TargetIDS.Cairn:
return "https://i.imgur.com/gQY37Tf.png";
case ParseEnum.TargetIDS.MursaatOverseer:
return "https://i.imgur.com/5LNiw4Y.png";
case ParseEnum.TargetIDS.Samarog:
return "https://i.imgur.com/MPQhKfM.png";
case ParseEnum.TargetIDS.Deimos:
return "https://i.imgur.com/mWfxBaO.png";
case ParseEnum.TargetIDS.SoullessHorror:
case ParseEnum.TargetIDS.Desmina:
return "https://i.imgur.com/jAiRplg.png";
case ParseEnum.TargetIDS.BrokenKing:
return "https://i.imgur.com/FNgUmvL.png";
case ParseEnum.TargetIDS.SoulEater:
return "https://i.imgur.com/Sd6Az8M.png";
case ParseEnum.TargetIDS.EyeOfFate:
case ParseEnum.TargetIDS.EyeOfJudgement:
return "https://i.imgur.com/kAgdoa5.png";
case ParseEnum.TargetIDS.Dhuum:
return "https://i.imgur.com/RKaDon5.png";
case ParseEnum.TargetIDS.ConjuredAmalgamate:
return "https://i.imgur.com/C23rYTl.png";
case ParseEnum.TargetIDS.CALeftArm:
return "https://i.imgur.com/qrkQvEY.png";
case ParseEnum.TargetIDS.CARightArm:
return "https://i.imgur.com/MVwjtH7.png";
case ParseEnum.TargetIDS.Kenut:
return "https://i.imgur.com/6yq45Cc.png";
case ParseEnum.TargetIDS.Nikare:
return "https://i.imgur.com/TLykcrJ.png";
case ParseEnum.TargetIDS.Qadim:
return "https://i.imgur.com/IfoHTHT.png";
case ParseEnum.TargetIDS.Freezie:
return "https://wiki.guildwars2.com/images/d/d9/Mini_Freezie.png";
case ParseEnum.TargetIDS.Adina:
return "https://i.imgur.com/or3m1yb.png";
case ParseEnum.TargetIDS.Sabir:
return "https://i.imgur.com/Q4WUXqw.png";
case ParseEnum.TargetIDS.PeerlessQadim:
return "https://i.imgur.com/47uePpb.png";
case ParseEnum.TargetIDS.IcebroodConstruct:
case ParseEnum.TargetIDS.IcebroodConstructFraenir:
return "https://i.imgur.com/dpaZFa5.png";
case ParseEnum.TargetIDS.ClawOfTheFallen:
return "https://i.imgur.com/HF85QpV.png";
case ParseEnum.TargetIDS.VoiceOfTheFallen:
return "https://i.imgur.com/BdTGXMU.png";
case ParseEnum.TargetIDS.VoiceAndClaw:
return "https://i.imgur.com/V1rJBnq.png";
case ParseEnum.TargetIDS.FraenirOfJormag:
return "https://i.imgur.com/MxudnKp.png";
case ParseEnum.TargetIDS.Boneskinner:
return "https://i.imgur.com/7HPdKDQ.png";
case ParseEnum.TargetIDS.WhisperOfJormag:
return "https://i.imgur.com/lu9ZLVq.png";
case ParseEnum.TargetIDS.MAMA:
return "https://i.imgur.com/1h7HOII.png";
case ParseEnum.TargetIDS.Siax:
return "https://i.imgur.com/5C60cQb.png";
case ParseEnum.TargetIDS.Ensolyss:
return "https://i.imgur.com/GUTNuyP.png";
case ParseEnum.TargetIDS.Skorvald:
return "https://i.imgur.com/IOPAHRE.png";
case ParseEnum.TargetIDS.Artsariiv:
return "https://wiki.guildwars2.com/images/b/b4/Artsariiv.jpg";
case ParseEnum.TargetIDS.Arkk:
return "https://i.imgur.com/u6vv8cW.png";
case ParseEnum.TargetIDS.LGolem:
return "https://wiki.guildwars2.com/images/4/47/Mini_Baron_von_Scrufflebutt.png";
case ParseEnum.TargetIDS.AvgGolem:
return "https://wiki.guildwars2.com/images/c/cb/Mini_Mister_Mittens.png";
case ParseEnum.TargetIDS.StdGolem:
return "https://wiki.guildwars2.com/images/8/8f/Mini_Professor_Mew.png";
case ParseEnum.TargetIDS.MassiveGolem:
return "https://wiki.guildwars2.com/images/3/33/Mini_Snuggles.png";
case ParseEnum.TargetIDS.MedGolem:
return "https://wiki.guildwars2.com/images/c/cb/Mini_Mister_Mittens.png";
case ParseEnum.TargetIDS.TwistedCastle:
return "https://i.imgur.com/ZBm5Uga.png";
}
switch (ParseEnum.GetTrashIDS(id))
{
case Spirit:
case Spirit2:
case ChargedSoul:
case HollowedBomber:
return "https://i.imgur.com/sHmksvO.png";
case Saul:
return "https://i.imgur.com/ck2IsoS.png";
case GamblerClones:
return "https://i.imgur.com/zMsBWEx.png";
case GamblerReal:
return "https://i.imgur.com/J6oMITN.png";
case Pride:
return "https://i.imgur.com/ePTXx23.png";
case OilSlick:
case Oil:
return "https://i.imgur.com/R26VgEr.png";
case Tear:
return "https://i.imgur.com/N9seps0.png";
case Gambler:
case Drunkard:
case Thief:
return "https://i.imgur.com/vINeVU6.png";
case TormentedDead:
case Messenger:
return "https://i.imgur.com/1J2BTFg.png";
case Enforcer:
return "https://i.imgur.com/elHjamF.png";
case Echo:
return "https://i.imgur.com/kcN9ECn.png";
case Core:
case ExquisiteConjunction:
return "https://i.imgur.com/yI34iqw.png";
case Jessica:
case Olson:
case Engul:
case Faerla:
case Caulle:
case Henley:
case Galletta:
case Ianim:
return "https://i.imgur.com/qeYT1Bf.png";
case InsidiousProjection:
return "https://i.imgur.com/9EdItBS.png";
case EnergyOrb:
return "https://i.postimg.cc/NMNvyts0/Power-Ball.png";
case UnstableLeyRift:
return "https://i.imgur.com/YXM3igs.png";
case RadiantPhantasm:
return "https://i.imgur.com/O5VWLyY.png";
case CrimsonPhantasm:
return "https://i.imgur.com/zP7Bvb4.png";
case Storm:
return "https://i.imgur.com/9XtNPdw.png";
case IcePatch:
return "https://i.imgur.com/yxKJ5Yc.png";
case BanditSaboteur:
return "https://i.imgur.com/jUKMEbD.png";
case NarellaTornado:
case Tornado:
return "https://i.imgur.com/e10lZMa.png";
case Jade:
return "https://i.imgur.com/ivtzbSP.png";
case Zommoros:
return "https://i.imgur.com/BxbsRCI.png";
case AncientInvokedHydra:
return "https://i.imgur.com/YABLiBz.png";
case IcebornHydra:
return "https://i.imgur.com/LoYMBRU.png";
case IceElemental:
return "https://i.imgur.com/pEkBeNp.png";
case WyvernMatriarch:
return "https://i.imgur.com/kLKLSfv.png";
case WyvernPatriarch:
return "https://i.imgur.com/vjjNSpI.png";
case ApocalypseBringer:
return "https://i.imgur.com/0LGKCn2.png";
case ConjuredGreatsword:
return "https://i.imgur.com/vHka0QN.png";
case ConjuredShield:
return "https://i.imgur.com/wUiI19S.png";
case GreaterMagmaElemental1:
case GreaterMagmaElemental2:
return "https://i.imgur.com/sr146T6.png";
case LavaElemental1:
case LavaElemental2:
return "https://i.imgur.com/mydwiYy.png";
case PyreGuardian:
case SmallKillerTornado:
case BigKillerTornado:
return "https://i.imgur.com/6zNPTUw.png";
case PyreGuardianRetal:
return "https://i.imgur.com/WC6LRkO.png";
case PyreGuardianStab:
return "https://i.imgur.com/ISa0urR.png";
case PyreGuardianProtect:
return "https://i.imgur.com/jLW7rpV.png";
case ReaperofFlesh:
return "https://i.imgur.com/Notctbt.png";
case Kernan:
return "https://i.imgur.com/WABRQya.png";
case Knuckles:
return "https://i.imgur.com/m1y8nJE.png";
case Karde:
return "https://i.imgur.com/3UGyosm.png";
case Rigom:
return "https://i.imgur.com/REcGMBe.png";
case Guldhem:
return "https://i.imgur.com/xa7Fefn.png";
case Scythe:
return "https://i.imgur.com/INCGLIK.png";
case BanditBombardier:
case SurgingSoul:
case MazeMinotaur:
case Enervator:
case WhisperEcho:
return "https://i.imgur.com/k79t7ZA.png";
case HandOfErosion:
case HandOfEruption:
return "https://i.imgur.com/reGQHhr.png";
case VoltaicWisp:
return "https://i.imgur.com/C1mvNGZ.png";
case ParalyzingWisp:
return "https://i.imgur.com/YBl8Pqo.png";
case Pylon2:
return "https://i.imgur.com/b33vAEQ.png";
case EntropicDistortion:
return "https://i.imgur.com/MIpP5pK.png";
case SmallJumpyTornado:
return "https://i.imgur.com/WBJNgp7.png";
case OrbSpider:
return "https://i.imgur.com/FB5VM9X.png";
case Seekers:
return "https://i.imgur.com/FrPoluz.png";
case BlueGuardian:
return "https://i.imgur.com/6CefnkP.png";
case GreenGuardian:
return "https://i.imgur.com/nauDVYP.png";
case RedGuardian:
return "https://i.imgur.com/73Uj4lG.png";
case UnderworldReaper:
return "https://i.imgur.com/Tq6SYVe.png";
case CagedWarg:
case GreenSpirit1:
case GreenSpirit2:
case BanditSapper:
case ProjectionArkk:
case PrioryExplorer:
case PrioryScholar:
case VigilRecruit:
case VigilTactician:
case Prisoner1:
case Prisoner2:
case Pylon1:
return "https://i.imgur.com/0koP4xB.png";
case FleshWurm:
return "https://i.imgur.com/o3vX9Zc.png";
case Hands:
return "https://i.imgur.com/8JRPEoo.png";
case TemporalAnomaly:
case TemporalAnomaly2:
return "https://i.imgur.com/MIpP5pK.png";
case DOC:
case BLIGHT:
case PLINK:
case CHOP:
return "https://wiki.guildwars2.com/images/4/47/Mini_Baron_von_Scrufflebutt.png";
case FreeziesFrozenHeart:
return "https://wiki.guildwars2.com/images/9/9e/Mini_Freezie%27s_Heart.png";
case RiverOfSouls:
return "https://i.imgur.com/4pXEnaX.png";
case DhuumDesmina:
return "https://i.imgur.com/jAiRplg.png";
//case CastleFountain:
// return "https://i.imgur.com/xV0OPWL.png";
case HauntingStatue:
return "https://i.imgur.com/7IQDyuK.png";
case GreenKnight:
case RedKnight:
case BlueKnight:
return "https://i.imgur.com/lpBm4d6.png";
}
return "https://i.imgur.com/HuJHqRZ.png";
}
public static string GetLink(string name)
{
switch (name)
{
case "Question":
return "https://wiki.guildwars2.com/images/d/de/Sword_slot.png";
case "Sword":
return "https://wiki.guildwars2.com/images/0/07/Crimson_Antique_Blade.png";
case "Axe":
return "https://wiki.guildwars2.com/images/d/d4/Crimson_Antique_Reaver.png";
case "Dagger":
return "https://wiki.guildwars2.com/images/6/65/Crimson_Antique_Razor.png";
case "Mace":
return "https://wiki.guildwars2.com/images/6/6d/Crimson_Antique_Flanged_Mace.png";
case "Pistol":
return "https://wiki.guildwars2.com/images/4/46/Crimson_Antique_Revolver.png";
case "Scepter":
return "https://wiki.guildwars2.com/images/e/e2/Crimson_Antique_Wand.png";
case "Focus":
return "https://wiki.guildwars2.com/images/8/87/Crimson_Antique_Artifact.png";
case "Shield":
return "https://wiki.guildwars2.com/images/b/b0/Crimson_Antique_Bastion.png";
case "Torch":
return "https://wiki.guildwars2.com/images/7/76/Crimson_Antique_Brazier.png";
case "Warhorn":
return "https://wiki.guildwars2.com/images/1/1c/Crimson_Antique_Herald.png";
case "Greatsword":
return "https://wiki.guildwars2.com/images/5/50/Crimson_Antique_Claymore.png";
case "Hammer":
return "https://wiki.guildwars2.com/images/3/38/Crimson_Antique_Warhammer.png";
case "Longbow":
return "https://wiki.guildwars2.com/images/f/f0/Crimson_Antique_Greatbow.png";
case "Shortbow":
return "https://wiki.guildwars2.com/images/1/17/Crimson_Antique_Short_Bow.png";
case "Rifle":
return "https://wiki.guildwars2.com/images/1/19/Crimson_Antique_Musket.png";
case "Staff":
return "https://wiki.guildwars2.com/images/5/5f/Crimson_Antique_Spire.png";
case "Color-Warrior": return "rgb(255,209,102)";
case "Color-Warrior-NonBoss": return "rgb(190,159,84)";
case "Color-Warrior-Total": return "rgb(125,109,66)";
case "Color-Berserker": return "rgb(255,209,102)";
case "Color-Berserker-NonBoss": return "rgb(190,159,84)";
case "Color-Berserker-Total": return "rgb(125,109,66)";
case "Color-Spellbreaker": return "rgb(255,209,102)";
case "Color-Spellbreaker-NonBoss": return "rgb(190,159,84)";
case "Color-Spellbreaker-Total": return "rgb(125,109,66)";
case "Color-Guardian": return "rgb(114,193,217)";
case "Color-Guardian-NonBoss": return "rgb(88,147,165)";
case "Color-Guardian-Total": return "rgb(62,101,113)";
case "Color-Dragonhunter": return "rgb(114,193,217)";
case "Color-Dragonhunter-NonBoss": return "rgb(88,147,165)";
case "Color-Dragonhunter-Total": return "rgb(62,101,113)";
case "Color-Firebrand": return "rgb(114,193,217)";
case "Color-Firebrand-NonBoss": return "rgb(88,147,165)";
case "Color-Firebrand-Total": return "rgb(62,101,113)";
case "Color-Revenant": return "rgb(209,110,90)";
case "Color-Revenant-NonBoss": return "rgb(159,85,70)";
case "Color-Revenant-Total": return "rgb(110,60,50)";
case "Color-Herald": return "rgb(209,110,90)";
case "Color-Herald-NonBoss": return "rgb(159,85,70)";
case "Color-Herald-Total": return "rgb(110,60,50)";
case "Color-Renegade": return "rgb(209,110,90)";
case "Color-Renegade-NonBoss": return "rgb(159,85,70)";
case "Color-Renegade-Total": return "rgb(110,60,50)";
case "Color-Engineer": return "rgb(208,156,89)";
case "Color-Engineer-NonBoss": return "rgb(158,119,68)";
case "Color-Engineer-Total": return "rgb(109,83,48)";
case "Color-Scrapper": return "rgb(208,156,89)";
case "Color-Scrapper-NonBoss": return "rgb(158,119,68)";
case "Color-Scrapper-Total": return "rgb(109,83,48)";
case "Color-Holosmith": return "rgb(208,156,89)";
case "Color-Holosmith-NonBoss": return "rgb(158,119,68)";
case "Color-Holosmith-Total": return "rgb(109,83,48)";
case "Color-Ranger": return "rgb(140,220,130)";
case "Color-Ranger-NonBoss": return "rgb(107,167,100)";
case "Color-Ranger-Total": return "rgb(75,115,70)";
case "Color-Druid": return "rgb(140,220,130)";
case "Color-Druid-NonBoss": return "rgb(107,167,100)";
case "Color-Druid-Total": return "rgb(75,115,70)";
case "Color-Soulbeast": return "rgb(140,220,130)";
case "Color-Soulbeast-NonBoss": return "rgb(107,167,100)";
case "Color-Soulbeast-Total": return "rgb(75,115,70)";
case "Color-Thief": return "rgb(192,143,149)";
case "Color-Thief-NonBoss": return "rgb(146,109,114)";
case "Color-Thief-Total": return "rgb(101,76,79)";
case "Color-Daredevil": return "rgb(192,143,149)";
case "Color-Daredevil-NonBoss": return "rgb(146,109,114)";
case "Color-Daredevil-Total": return "rgb(101,76,79)";
case "Color-Deadeye": return "rgb(192,143,149)";
case "Color-Deadeye-NonBoss": return "rgb(146,109,114)";
case "Color-Deadeye-Total": return "rgb(101,76,79)";
case "Color-Elementalist": return "rgb(246,138,135)";
case "Color-Elementalist-NonBoss": return "rgb(186,106,103)";
case "Color-Elementalist-Total": return "rgb(127,74,72)";
case "Color-Tempest": return "rgb(246,138,135)";
case "Color-Tempest-NonBoss": return "rgb(186,106,103)";
case "Color-Tempest-Total": return "rgb(127,74,72)";
case "Color-Weaver": return "rgb(246,138,135)";
case "Color-Weaver-NonBoss": return "rgb(186,106,103)";
case "Color-Weaver-Total": return "rgb(127,74,72)";
case "Color-Mesmer": return "rgb(182,121,213)";
case "Color-Mesmer-NonBoss": return "rgb(139,90,162)";
case "Color-Mesmer-Total": return "rgb(96,60,111)";
case "Color-Chronomancer": return "rgb(182,121,213)";
case "Color-Chronomancer-NonBoss": return "rgb(139,90,162)";
case "Color-Chronomancer-Total": return "rgb(96,60,111)";
case "Color-Mirage": return "rgb(182,121,213)";
case "Color-Mirage-NonBoss": return "rgb(139,90,162)";
case "Color-Mirage-Total": return "rgb(96,60,111)";
case "Color-Necromancer": return "rgb(82,167,111)";
case "Color-Necromancer-NonBoss": return "rgb(64,127,85)";
case "Color-Necromancer-Total": return "rgb(46,88,60)";
case "Color-Reaper": return "rgb(82,167,111)";
case "Color-Reaper-NonBoss": return "rgb(64,127,85)";
case "Color-Reaper-Total": return "rgb(46,88,60)";
case "Color-Scourge": return "rgb(82,167,111)";
case "Color-Scourge-NonBoss": return "rgb(64,127,85)";
case "Color-Scourge-Total": return "rgb(46,88,60)";
case "Color-Boss": return "rgb(82,167,250)";
case "Color-Boss-NonBoss": return "rgb(92,177,250)";
case "Color-Boss-Total": return "rgb(92,177,250)";
case "Crit":
return "https://wiki.guildwars2.com/images/9/95/Critical_Chance.png";
case "Scholar":
return "https://wiki.guildwars2.com/images/2/2b/Superior_Rune_of_the_Scholar.png";
case "SwS":
return "https://wiki.guildwars2.com/images/1/1c/Bowl_of_Seaweed_Salad.png";
case "Downs":
return "https://wiki.guildwars2.com/images/c/c6/Downed_enemy.png";
case "Resurrect":
return "https://wiki.guildwars2.com/images/3/3d/Downed_ally.png";
case "Dead":
return "https://wiki.guildwars2.com/images/4/4a/Ally_death_%28interface%29.png";
case "Flank":
return "https://wiki.guildwars2.com/images/b/bb/Hunter%27s_Tactics.png";
case "Glance":
return "https://wiki.guildwars2.com/images/f/f9/Weakness.png";
case "Miss":
return "https://wiki.guildwars2.com/images/3/33/Blinded.png";
case "Interupts":
return "https://wiki.guildwars2.com/images/7/79/Daze.png";
case "Invuln":
return "https://wiki.guildwars2.com/images/e/eb/Determined.png";
case "Blinded":
return "https://wiki.guildwars2.com/images/3/33/Blinded.png";
case "Wasted":
return "https://wiki.guildwars2.com/images/b/b3/Out_Of_Health_Potions.png";
case "Saved":
return "https://wiki.guildwars2.com/images/e/eb/Ready.png";
case "Swap":
return "https://wiki.guildwars2.com/images/c/ce/Weapon_Swap_Button.png";
case "Blank":
return "https://wiki.guildwars2.com/images/d/de/Sword_slot.png";
case "Dodge":
return "https://wiki.guildwars2.com/images/archive/b/b2/20150601155307%21Dodge.png";
case "Bandage":
return "https://wiki.guildwars2.com/images/0/0c/Bandage.png";
case "Stack":
return "https://wiki.guildwars2.com/images/e/ef/Commander_arrow_marker.png";
case "Color-Aegis": return "rgb(102,255,255)";
case "Color-Fury": return "rgb(255,153,0)";
case "Color-Might": return "rgb(153,0,0)";
case "Color-Protection": return "rgb(102,255,255)";
case "Color-Quickness": return "rgb(255,0,255)";
case "Color-Regeneration": return "rgb(0,204,0)";
case "Color-Resistance": return "rgb(255, 153, 102)";
case "Color-Retaliation": return "rgb(255, 51, 0)";
case "Color-Stability": return "rgb(153, 102, 0)";
case "Color-Swiftness": return "rgb(255,255,0)";
case "Color-Vigor": return "rgb(102, 153, 0)";
case "Color-Alacrity": return "rgb(0,102,255)";
case "Color-Glyph of Empowerment": return "rgb(204, 153, 0)";
case "Color-Grace of the Land": return "rgb(,,)";
case "Color-Sun Spirit": return "rgb(255, 102, 0)";
case "Color-Banner of Strength": return "rgb(153, 0, 0)";
case "Color-Banner of Discipline": return "rgb(0, 51, 0)";
case "Color-Spotter": return "rgb(0,255,0)";
case "Color-Stone Spirit": return "rgb(204, 102, 0)";
case "Color-Storm Spirit": return "rgb(102, 0, 102)";
case "Color-Empower Allies": return "rgb(255, 153, 0)";
case "Condi": return "https://wiki.guildwars2.com/images/5/54/Condition_Damage.png";
case "Healing": return "https://wiki.guildwars2.com/images/8/81/Healing_Power.png";
case "Tough": return "https://wiki.guildwars2.com/images/1/12/Toughness.png";
default:
return "";
}
}
}
}
| 48.879484 | 107 | 0.52831 | [
"MIT"
] | Flomix/GW2-Elite-Insights-Parser | GW2EIParser/GeneralHelper.cs | 34,071 | C# |
// Copyright (c) .NET Foundation and contributors. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.IO;
using System.Threading.Tasks;
namespace Microsoft.DotNet.Interactive.Extensions
{
public interface IExtensibleKernel
{
Task LoadExtensionsFromDirectoryAsync(
DirectoryInfo directory,
KernelInvocationContext invocationContext);
}
} | 31.333333 | 101 | 0.742553 | [
"MIT"
] | AngelusGi/interactive | src/Microsoft.DotNet.Interactive/Extensions/IExtensibleKernel.cs | 472 | C# |
using System;
using Vlc.DotNet.Core.Interops.Signatures;
namespace Vlc.DotNet.Core.Interops
{
public sealed partial class VlcManager
{
public MediaStates GetMediaState(VlcMediaInstance mediaInstance)
{
if (mediaInstance == IntPtr.Zero)
throw new ArgumentException("Media instance is not initialized.");
return myLibraryLoader.GetInteropDelegate<GetMediaState>().Invoke(mediaInstance);
}
}
}
| 29.3125 | 93 | 0.682303 | [
"MIT"
] | HumJ0218/Vlc.DotNet | src/Vlc.DotNet.Core.Interops/VlcManager.GetMediaState.cs | 471 | C# |
using System;
using Microsoft.EntityFrameworkCore.Migrations;
namespace PersonalBlog.Migrations
{
public partial class InitialCreate : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "CategoryModel",
columns: table => new
{
Id = table.Column<Guid>(nullable: false),
Name = table.Column<string>(nullable: true),
Description = table.Column<string>(nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_CategoryModel", x => x.Id);
});
migrationBuilder.CreateTable(
name: "PostModel",
columns: table => new
{
Id = table.Column<Guid>(nullable: false),
Slug = table.Column<string>(nullable: true),
ShortDescription = table.Column<string>(nullable: true),
MainContent = table.Column<string>(nullable: true),
CreatedDate = table.Column<DateTime>(nullable: false),
UpdatedDate = table.Column<DateTime>(nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_PostModel", x => x.Id);
});
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "CategoryModel");
migrationBuilder.DropTable(
name: "PostModel");
}
}
}
| 34.46 | 76 | 0.502612 | [
"MIT"
] | thuydotp/personal-blog | PersonalBlog/Migrations/20180715153131_InitialCreate.cs | 1,725 | C# |
// <auto-generated />
using System;
using Car.Data;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
namespace Car.Data.Migrations
{
[DbContext(typeof(ApplicationDbContext))]
[Migration("20190408095905_add_CreatedDate")]
partial class add_CreatedDate
{
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.SerialColumn)
.HasAnnotation("ProductVersion", "2.2.3-servicing-35854")
.HasAnnotation("Relational:MaxIdentifierLength", 63);
modelBuilder.Entity("Car.Data.EntityModels.Cooperation", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnName("id");
b.Property<DateTime>("AssignDate")
.HasColumnName("assign_date");
b.Property<string>("BaseModelCode")
.HasColumnName("base_model_code");
b.Property<string>("CompanyName")
.HasColumnName("company_name");
b.Property<string>("ContactPerson")
.HasColumnName("contact_person");
b.Property<string>("Email")
.HasColumnName("email");
b.Property<string>("Fax")
.HasColumnName("fax");
b.Property<string>("MobilePhoneNo")
.HasColumnName("mobile_phone_no");
b.Property<int>("ProspectId")
.HasColumnName("prospect_id");
b.Property<string>("SalesPersonCode")
.HasColumnName("sales_person_code");
b.Property<int>("SourceId")
.HasColumnName("source_id");
b.Property<int>("VehicleId")
.HasColumnName("vehicle_id");
b.HasKey("Id")
.HasName("pk_cooperations");
b.HasIndex("ProspectId")
.HasName("ix_cooperations_prospect_id");
b.HasIndex("SourceId")
.HasName("ix_cooperations_source_id");
b.HasIndex("VehicleId")
.HasName("ix_cooperations_vehicle_id");
b.ToTable("cooperations");
});
modelBuilder.Entity("Car.Data.EntityModels.Customer", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnName("id");
b.Property<string>("BranchAt")
.HasColumnName("branch_at");
b.Property<int?>("CooperationId")
.HasColumnName("cooperation_id");
b.Property<DateTime>("CreatedDate")
.HasColumnName("created_date");
b.Property<string>("CustomerCode")
.HasColumnName("customer_code");
b.Property<string>("CustomerCodeFrom")
.HasColumnName("customer_code_from");
b.Property<Guid>("CustomerGuid")
.HasColumnName("customer_guid");
b.Property<int>("CustomerType")
.HasColumnName("customer_type");
b.Property<int>("EstablishmentType")
.HasColumnName("establishment_type");
b.Property<int?>("GovernmentId")
.HasColumnName("government_id");
b.Property<int?>("PersonalId")
.HasColumnName("personal_id");
b.Property<string>("TaxIdNo")
.HasColumnName("tax_id_no");
b.HasKey("Id")
.HasName("pk_customers");
b.HasIndex("CooperationId")
.HasName("ix_customers_cooperation_id");
b.HasIndex("GovernmentId")
.HasName("ix_customers_government_id");
b.HasIndex("PersonalId")
.HasName("ix_customers_personal_id");
b.ToTable("customers");
});
modelBuilder.Entity("Car.Data.EntityModels.CustomerGroup", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnName("id");
b.Property<string>("Code")
.HasColumnName("code");
b.Property<string>("Description")
.HasColumnName("description");
b.Property<string>("NameEn")
.HasColumnName("name_en");
b.Property<string>("NameTh")
.HasColumnName("name_th");
b.HasKey("Id")
.HasName("pk_customer_groups");
b.ToTable("customer_groups");
});
modelBuilder.Entity("Car.Data.EntityModels.Government", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnName("id");
b.Property<DateTime>("AssignDate")
.HasColumnName("assign_date");
b.Property<string>("ContactPerson")
.HasColumnName("contact_person");
b.Property<string>("Email")
.HasColumnName("email");
b.Property<string>("Fax")
.HasColumnName("fax");
b.Property<string>("MobilePhoneNo")
.HasColumnName("mobile_phone_no");
b.Property<string>("OrganizationName")
.HasColumnName("organization_name");
b.Property<int>("ProspectId")
.HasColumnName("prospect_id");
b.Property<string>("SalesPersonCode")
.HasColumnName("sales_person_code");
b.Property<int>("SourceId")
.HasColumnName("source_id");
b.Property<int>("VehicleId")
.HasColumnName("vehicle_id");
b.HasKey("Id")
.HasName("pk_governments");
b.HasIndex("ProspectId")
.HasName("ix_governments_prospect_id");
b.HasIndex("SourceId")
.HasName("ix_governments_source_id");
b.HasIndex("VehicleId")
.HasName("ix_governments_vehicle_id");
b.ToTable("governments");
});
modelBuilder.Entity("Car.Data.EntityModels.Personal", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnName("id");
b.Property<DateTime>("AssignDate")
.HasColumnName("assign_date");
b.Property<string>("BaseModelCode")
.HasColumnName("base_model_code");
b.Property<int>("CustomerGroupId")
.HasColumnName("customer_group_id");
b.Property<string>("Email")
.HasColumnName("email");
b.Property<int>("GenderType")
.HasColumnName("gender_type");
b.Property<string>("LastName")
.HasColumnName("last_name");
b.Property<string>("MobilePhoneNo")
.HasColumnName("mobile_phone_no");
b.Property<string>("Name")
.HasColumnName("name");
b.Property<int>("ProspectId")
.HasColumnName("prospect_id");
b.Property<string>("SalesPersonCode")
.HasColumnName("sales_person_code");
b.Property<int>("SourceId")
.HasColumnName("source_id");
b.Property<int>("TitleId")
.HasColumnName("title_id");
b.Property<int>("VehicleId")
.HasColumnName("vehicle_id");
b.HasKey("Id")
.HasName("pk_personals");
b.HasIndex("CustomerGroupId")
.HasName("ix_personals_customer_group_id");
b.HasIndex("ProspectId")
.HasName("ix_personals_prospect_id");
b.HasIndex("SourceId")
.HasName("ix_personals_source_id");
b.HasIndex("TitleId")
.HasName("ix_personals_title_id");
b.HasIndex("VehicleId")
.HasName("ix_personals_vehicle_id");
b.ToTable("personals");
});
modelBuilder.Entity("Car.Data.EntityModels.Prospect", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnName("id");
b.Property<string>("Code")
.HasColumnName("code");
b.Property<string>("Description")
.HasColumnName("description");
b.Property<string>("NameEn")
.HasColumnName("name_en");
b.Property<string>("NameTh")
.HasColumnName("name_th");
b.HasKey("Id")
.HasName("pk_prospect");
b.ToTable("prospect");
});
modelBuilder.Entity("Car.Data.EntityModels.Source", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnName("id");
b.Property<string>("Code")
.HasColumnName("code");
b.Property<string>("Description")
.HasColumnName("description");
b.Property<string>("NameEn")
.HasColumnName("name_en");
b.Property<string>("NameTh")
.HasColumnName("name_th");
b.HasKey("Id")
.HasName("pk_source");
b.ToTable("source");
});
modelBuilder.Entity("Car.Data.EntityModels.Title", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnName("id");
b.Property<string>("Code")
.HasColumnName("code");
b.Property<string>("Description")
.HasColumnName("description");
b.Property<string>("Name")
.HasColumnName("name");
b.HasKey("Id")
.HasName("pk_title");
b.ToTable("title");
});
modelBuilder.Entity("Car.Data.EntityModels.Vehicle", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnName("id");
b.Property<string>("Code")
.HasColumnName("code");
b.Property<string>("Description")
.HasColumnName("description");
b.Property<string>("NameEn")
.HasColumnName("name_en");
b.Property<string>("NameTh")
.HasColumnName("name_th");
b.HasKey("Id")
.HasName("pk_vehicle");
b.ToTable("vehicle");
});
modelBuilder.Entity("Car.Data.EntityModels.Cooperation", b =>
{
b.HasOne("Car.Data.EntityModels.Prospect", "Prospect")
.WithMany()
.HasForeignKey("ProspectId")
.HasConstraintName("fk_cooperations_prospect_prospect_id")
.OnDelete(DeleteBehavior.Cascade);
b.HasOne("Car.Data.EntityModels.Source", "Source")
.WithMany()
.HasForeignKey("SourceId")
.HasConstraintName("fk_cooperations_source_source_id")
.OnDelete(DeleteBehavior.Cascade);
b.HasOne("Car.Data.EntityModels.Vehicle", "Vehicle")
.WithMany()
.HasForeignKey("VehicleId")
.HasConstraintName("fk_cooperations_vehicle_vehicle_id")
.OnDelete(DeleteBehavior.Cascade);
});
modelBuilder.Entity("Car.Data.EntityModels.Customer", b =>
{
b.HasOne("Car.Data.EntityModels.Cooperation", "Cooperation")
.WithMany()
.HasForeignKey("CooperationId")
.HasConstraintName("fk_customers_cooperations_cooperation_id");
b.HasOne("Car.Data.EntityModels.Government", "Government")
.WithMany()
.HasForeignKey("GovernmentId")
.HasConstraintName("fk_customers_governments_government_id");
b.HasOne("Car.Data.EntityModels.Personal", "Personal")
.WithMany()
.HasForeignKey("PersonalId")
.HasConstraintName("fk_customers_personals_personal_id");
});
modelBuilder.Entity("Car.Data.EntityModels.Government", b =>
{
b.HasOne("Car.Data.EntityModels.Prospect", "Prospect")
.WithMany()
.HasForeignKey("ProspectId")
.HasConstraintName("fk_governments_prospect_prospect_id")
.OnDelete(DeleteBehavior.Cascade);
b.HasOne("Car.Data.EntityModels.Source", "Source")
.WithMany()
.HasForeignKey("SourceId")
.HasConstraintName("fk_governments_source_source_id")
.OnDelete(DeleteBehavior.Cascade);
b.HasOne("Car.Data.EntityModels.Vehicle", "Vehicle")
.WithMany()
.HasForeignKey("VehicleId")
.HasConstraintName("fk_governments_vehicle_vehicle_id")
.OnDelete(DeleteBehavior.Cascade);
});
modelBuilder.Entity("Car.Data.EntityModels.Personal", b =>
{
b.HasOne("Car.Data.EntityModels.CustomerGroup", "CustomerGroup")
.WithMany()
.HasForeignKey("CustomerGroupId")
.HasConstraintName("fk_personals_customer_groups_customer_group_id")
.OnDelete(DeleteBehavior.Cascade);
b.HasOne("Car.Data.EntityModels.Prospect", "Prospect")
.WithMany()
.HasForeignKey("ProspectId")
.HasConstraintName("fk_personals_prospect_prospect_id")
.OnDelete(DeleteBehavior.Cascade);
b.HasOne("Car.Data.EntityModels.Source", "Source")
.WithMany()
.HasForeignKey("SourceId")
.HasConstraintName("fk_personals_source_source_id")
.OnDelete(DeleteBehavior.Cascade);
b.HasOne("Car.Data.EntityModels.Title", "Title")
.WithMany()
.HasForeignKey("TitleId")
.HasConstraintName("fk_personals_title_title_id")
.OnDelete(DeleteBehavior.Cascade);
b.HasOne("Car.Data.EntityModels.Vehicle", "Vehicle")
.WithMany()
.HasForeignKey("VehicleId")
.HasConstraintName("fk_personals_vehicle_vehicle_id")
.OnDelete(DeleteBehavior.Cascade);
});
#pragma warning restore 612, 618
}
}
}
| 37.251082 | 108 | 0.458571 | [
"MIT"
] | buibup/Car | Car.Data/Migrations/20190408095905_add_CreatedDate.Designer.cs | 17,212 | C# |
using Entidades.Entidades;
using System.Collections.Generic;
namespace Entidades.Dto
{
public class ItemAchadoDto : ItemDto
{
public bool Devolvido { get; set; }
public List<long> ItensPerdidoMatchId { get; set; }
}
}
| 20.666667 | 59 | 0.677419 | [
"MIT"
] | lgmagalhaes88/Achei | backend/Entidades/Dto/ItemAchadoDto.cs | 250 | 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.
*/
using Aliyun.Acs.Core;
using System.Collections.Generic;
namespace Aliyun.Acs.Cms.Model.V20180308
{
public class ProfileGetResponse : AcsResponse
{
private int? errorCode;
private string errorMessage;
private bool? success;
private string requestId;
private long? userId;
private bool? autoInstall;
private bool? enableInstallAgentNewECS;
private string enableActiveAlert;
public int? ErrorCode
{
get
{
return errorCode;
}
set
{
errorCode = value;
}
}
public string ErrorMessage
{
get
{
return errorMessage;
}
set
{
errorMessage = value;
}
}
public bool? Success
{
get
{
return success;
}
set
{
success = value;
}
}
public string RequestId
{
get
{
return requestId;
}
set
{
requestId = value;
}
}
public long? UserId
{
get
{
return userId;
}
set
{
userId = value;
}
}
public bool? AutoInstall
{
get
{
return autoInstall;
}
set
{
autoInstall = value;
}
}
public bool? EnableInstallAgentNewECS
{
get
{
return enableInstallAgentNewECS;
}
set
{
enableInstallAgentNewECS = value;
}
}
public string EnableActiveAlert
{
get
{
return enableActiveAlert;
}
set
{
enableActiveAlert = value;
}
}
}
} | 16.625899 | 63 | 0.615751 | [
"Apache-2.0"
] | brightness007/unofficial-aliyun-openapi-net-sdk | aliyun-net-sdk-cms/Cms/Model/V20180308/ProfileGetResponse.cs | 2,311 | C# |
// This file isn't generated, but this comment is necessary to exclude it from StyleCop analysis.
// <auto-generated/>
/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
* Use of this file is governed by the BSD 3-clause license that
* can be found in the LICENSE.txt file in the project root.
*/
using System.Collections.Generic;
using Antlr4.Runtime.Misc;
namespace Antlr4.Runtime.Dfa
{
/// <author>Sam Harwell</author>
internal interface IEdgeMap<T> : IEnumerable<KeyValuePair<int, T>>
{
int Count
{
get;
}
bool IsEmpty
{
get;
}
bool ContainsKey(int key);
T this[int key]
{
get;
}
[return: NotNull]
IEdgeMap<T> Put(int key, T value);
[return: NotNull]
IEdgeMap<T> Remove(int key);
[return: NotNull]
IEdgeMap<T> PutAll(IEdgeMap<T> m);
[return: NotNull]
IEdgeMap<T> Clear();
#if NET45PLUS
[return: NotNull]
IReadOnlyDictionary<int, T> ToMap();
#else
[return: NotNull]
IDictionary<int, T> ToMap();
#endif
}
}
| 21.592593 | 97 | 0.578902 | [
"MIT"
] | Arithmomaniac/azure-cosmos-dotnet-v3 | Microsoft.Azure.Cosmos/src/OSS/Antlr/Dfa/IEdgeMap.cs | 1,166 | C# |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Snippy.Services;
namespace Snippy.Models
{
public class Manifest
{
public const string FileName = "manifest.yaml";
public static Manifest Load(string workspaceDirectory)
{
var serializer = new Serializer();
var path = Path.Combine(workspaceDirectory, FileName);
try
{
return serializer.DeserializeFromYaml<Manifest>(path) ?? new Manifest();
}
catch (Exception)
{
return new Manifest();
}
}
public OrderBy OrderBy { get; set; }
public SortDirection SortDirection { get; set; }
public List<WorkspaceDefinition> Definitions { get; set; } = new List<WorkspaceDefinition>();
public void Publish(string workspaceDirectory)
{
var oldManifest = Load(workspaceDirectory);
foreach (var old in oldManifest.Definitions.Where(old => Definitions.SingleOrDefault(current => current.FileName == old.FileName) == null))
Definitions.Add(old);
Definitions = Definitions.OrderBy(x => x.FileName).ToList();
var serializer = new Serializer();
var manifestFilePath = Path.Combine(workspaceDirectory, FileName);
serializer.SerializeToYaml(this, manifestFilePath);
}
}
}
| 31.565217 | 151 | 0.608815 | [
"MIT"
] | refactorsaurusrex/snippy | src/Snippy/Models/Manifest.cs | 1,454 | C# |
// *****************************************************************************
//
// © Component Factory Pty Ltd 2017. All rights reserved.
// The software and associated documentation supplied hereunder are the
// proprietary information of Component Factory Pty Ltd, 13 Swallows Close,
// Mornington, Vic 3931, Australia and are supplied subject to licence terms.
//
// Version 4.5.0.0 www.ComponentFactory.com
// *****************************************************************************
using System;
using System.Text;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Collections.Generic;
using System.Windows.Forms;
using System.Diagnostics;
namespace ComponentFactory.Krypton.Toolkit
{
/// <summary>
/// Positions the child within a border that is drawn as the column background color.
/// </summary>
public class ViewDrawMenuColorColumn : ViewComposite
{
#region Identity
/// <summary>
/// Initialize a new instance of the ViewDrawMenuColorColumn class.
/// </summary>
/// <param name="provider">Reference to provider.</param>
/// <param name="colorColumns">Reference to owning color columns entry.</param>
/// <param name="colors">Set of colors to initialize from.</param>\
/// <param name="start">Stating index to use.</param>
/// <param name="end">Ending index to use.</param>
/// <param name="enabled">Is this column enabled</param>
public ViewDrawMenuColorColumn(IContextMenuProvider provider,
KryptonContextMenuColorColumns colorColumns,
Color[] colors,
int start,
int end,
bool enabled)
{
ViewLayoutColorStack vertical = new ViewLayoutColorStack();
for (int i = start; i < end; i++)
vertical.Add(new ViewDrawMenuColorBlock(provider, colorColumns, colors[i],
(i == start), (i == (end - 1)), enabled));
Add(vertical);
}
/// <summary>
/// Obtains the String representation of this instance.
/// </summary>
/// <returns>User readable name of the instance.</returns>
public override string ToString()
{
// Return the class name and instance identifier
return "ViewDrawMenuColorColumn:" + Id;
}
#endregion
#region Layout
/// <summary>
/// Perform a layout of the elements.
/// </summary>
/// <param name="context">Layout context.</param>
public override void Layout(ViewLayoutContext context)
{
Debug.Assert(context != null);
// We take on all the available display area
ClientRectangle = context.DisplayRectangle;
// Let base class layout the children
base.Layout(context);
// Put back the original size before returning
context.DisplayRectangle = ClientRectangle;
}
#endregion
#region Paint
/// <summary>
/// Perform rendering before child elements are rendered.
/// </summary>
/// <param name="context">Rendering context.</param>
public override void RenderBefore(RenderContext context)
{
Debug.Assert(context != null);
// Validate incoming reference
if (context == null) throw new ArgumentNullException("context");
using(SolidBrush brush = new SolidBrush(Color.FromArgb(197, 197, 197)))
context.Graphics.FillRectangle(brush, ClientRectangle);
}
#endregion
}
}
| 36.881188 | 98 | 0.57396 | [
"BSD-3-Clause"
] | ALMMa/Krypton | Source/Krypton Components/ComponentFactory.Krypton.Toolkit/View Draw/ViewDrawMenuColorColumn.cs | 3,728 | C# |
// WARNING
//
// This file has been generated automatically by Xamarin Studio from the outlets and
// actions declared in your storyboard file.
// Manual changes to this file will not be maintained.
//
using Foundation;
using System;
using System.CodeDom.Compiler;
using UIKit;
namespace ManualCameraControls
{
[Register ("BracketedViewController")]
partial class BracketedViewController
{
[Outlet]
[GeneratedCode ("iOS Designer", "1.0")]
UIImageView CameraView { get; set; }
[Outlet]
[GeneratedCode ("iOS Designer", "1.0")]
UIButton CaptureButton { get; set; }
[Outlet]
[GeneratedCode ("iOS Designer", "1.0")]
UILabel NoCamera { get; set; }
[Outlet]
[GeneratedCode ("iOS Designer", "1.0")]
UIScrollView ScrollView { get; set; }
void ReleaseDesignerOutlets ()
{
if (CameraView != null) {
CameraView.Dispose ();
CameraView = null;
}
if (CaptureButton != null) {
CaptureButton.Dispose ();
CaptureButton = null;
}
if (NoCamera != null) {
NoCamera.Dispose ();
NoCamera = null;
}
if (ScrollView != null) {
ScrollView.Dispose ();
ScrollView = null;
}
}
}
}
| 21.222222 | 84 | 0.661431 | [
"MIT"
] | Art-Lav/ios-samples | ManualCameraControls/ManualCameraControls/BracketedViewController.designer.cs | 1,146 | C# |
using System;
using System.Collections.Generic;
using System.Text;
namespace Confluent.Kafka.Examples.SimpleConsumer
{
public class LocationCheckinData
{
public Guid Id { get; set; }
public MemberData Member { get; set; }
public LocationData Location { get; set; }
public DateTime CheckinCompleted { get; set; }
//public LocationCheckinData(Guid id, Guid memberId, Guid locationId, DateTime checkinCompleted
// , string firstName, string lastName, string locationName)
//{
// MemberData mem = new MemberData();
// mem.Id = memberId;
// mem.FirstName = firstName;
// mem.LastName = lastName;
// LocationData loc = new LocationData();
// loc.Id = locationId;
// loc.LocationName = locationName;
// Id = id;
// Member = mem;
// Location = loc;
//}
public class MemberData
{
public Guid Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
}
public class LocationData
{
public Guid Id { get; set; }
public string LocationName { get; set; }
}
}
}
| 27.956522 | 103 | 0.5521 | [
"Apache-2.0"
] | sstaton/daxko-kafka-etl | examples/SimpleConsumer/LocationCheckinData.cs | 1,288 | C# |
// c:\program files (x86)\windows kits\10\include\10.0.18362.0\shared\ksmedia.h(1166,9)
using System.Runtime.InteropServices;
namespace DirectN
{
[StructLayout(LayoutKind.Sequential)]
public partial struct KSDS3D_LISTENER_ORIENTATION
{
public _DS3DVECTOR Front;
public _DS3DVECTOR Top;
}
}
| 24.923077 | 88 | 0.719136 | [
"MIT"
] | bbday/DirectN | DirectN/DirectN/Generated/KSDS3D_LISTENER_ORIENTATION.cs | 326 | C# |
// <auto-generated />
using System;
using System.Collections.Generic;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
using Repositories.Database;
namespace Repositories.Migrations
{
[DbContext(typeof(DatabaseContext))]
partial class DatabaseContextModelSnapshot : ModelSnapshot
{
protected override void BuildModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("Relational:MaxIdentifierLength", 63)
.HasAnnotation("ProductVersion", "5.0.4")
.HasAnnotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn);
modelBuilder.Entity("Repositories.Database.Models.Build", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid");
b.Property<Guid>("BuildConfigId")
.HasColumnType("uuid");
b.Property<int>("BuildStatus")
.HasColumnType("integer");
b.Property<DateTime>("FinishTime")
.HasColumnType("timestamp without time zone");
b.Property<List<string>>("Logs")
.HasColumnType("text[]");
b.HasKey("Id");
b.HasIndex("BuildConfigId");
b.ToTable("Builds");
});
modelBuilder.Entity("Repositories.Database.Models.BuildConfig", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid");
b.Property<string>("Name")
.HasColumnType("text");
b.Property<Guid>("ProjectId")
.HasColumnType("uuid");
b.HasKey("Id");
b.HasIndex("ProjectId");
b.ToTable("BuildConfigs");
});
modelBuilder.Entity("Repositories.Database.Models.BuildStep", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid");
b.Property<Guid>("BuildConfigId")
.HasColumnType("uuid");
b.Property<Guid?>("BuildStepScriptId")
.HasColumnType("uuid");
b.Property<string>("Name")
.HasColumnType("text");
b.HasKey("Id");
b.HasIndex("BuildConfigId");
b.HasIndex("BuildStepScriptId");
b.ToTable("BuildSteps");
});
modelBuilder.Entity("Repositories.Database.Models.BuildStepScript", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid");
b.Property<string>("Arguments")
.HasColumnType("text");
b.Property<string>("Command")
.HasColumnType("text");
b.HasKey("Id");
b.ToTable("BuildStepScript");
});
modelBuilder.Entity("Repositories.Database.Models.Project", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid");
b.Property<string>("GitToken")
.HasColumnType("text");
b.Property<string>("Name")
.HasColumnType("text");
b.Property<string>("ProjectUri")
.HasColumnType("text");
b.HasKey("Id");
b.ToTable("Projects");
});
modelBuilder.Entity("Repositories.Database.Models.User", b =>
{
b.Property<string>("Id")
.HasColumnType("text");
b.Property<string>("Email")
.HasColumnType("text");
b.Property<bool>("IsRegistered")
.HasColumnType("boolean");
b.Property<string>("Name")
.HasColumnType("text");
b.Property<List<string>>("ProjectsWithAdminAccess")
.HasColumnType("text[]");
b.Property<List<string>>("ProjectsWithUserAccess")
.HasColumnType("text[]");
b.HasKey("Id");
b.ToTable("Users");
});
modelBuilder.Entity("Repositories.Database.Models.Build", b =>
{
b.HasOne("Repositories.Database.Models.BuildConfig", null)
.WithMany("Builds")
.HasForeignKey("BuildConfigId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Repositories.Database.Models.BuildConfig", b =>
{
b.HasOne("Repositories.Database.Models.Project", null)
.WithMany("BuildConfigs")
.HasForeignKey("ProjectId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Repositories.Database.Models.BuildStep", b =>
{
b.HasOne("Repositories.Database.Models.BuildConfig", null)
.WithMany("BuildSteps")
.HasForeignKey("BuildConfigId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("Repositories.Database.Models.BuildStepScript", "BuildStepScript")
.WithMany()
.HasForeignKey("BuildStepScriptId");
b.Navigation("BuildStepScript");
});
modelBuilder.Entity("Repositories.Database.Models.BuildConfig", b =>
{
b.Navigation("Builds");
b.Navigation("BuildSteps");
});
modelBuilder.Entity("Repositories.Database.Models.Project", b =>
{
b.Navigation("BuildConfigs");
});
#pragma warning restore 612, 618
}
}
}
| 34.124378 | 120 | 0.46377 | [
"MIT"
] | Elevator-CI/elevator-api | Repositories/Migrations/DatabaseContextModelSnapshot.cs | 6,861 | C# |
namespace MeetingSystem
{
partial class FileChooseForm
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
this.tableLayoutPanel1 = new System.Windows.Forms.TableLayoutPanel();
this.OKButton = new System.Windows.Forms.Button();
this.fileDataGridView = new System.Windows.Forms.DataGridView();
this.Column1 = new System.Windows.Forms.DataGridViewButtonColumn();
this.tableLayoutPanel2 = new System.Windows.Forms.TableLayoutPanel();
this.label1 = new System.Windows.Forms.Label();
this.fileSourceTextBox = new System.Windows.Forms.TextBox();
this.panel1 = new System.Windows.Forms.Panel();
this.addButton = new System.Windows.Forms.Button();
this.filePathDataGridViewTextBoxColumn = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.fileBindingSource = new System.Windows.Forms.BindingSource(this.components);
this.scoreMessageHandlerBindingSource = new System.Windows.Forms.BindingSource(this.components);
this.tableLayoutPanel1.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.fileDataGridView)).BeginInit();
this.tableLayoutPanel2.SuspendLayout();
this.panel1.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.fileBindingSource)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.scoreMessageHandlerBindingSource)).BeginInit();
this.SuspendLayout();
//
// tableLayoutPanel1
//
this.tableLayoutPanel1.ColumnCount = 1;
this.tableLayoutPanel1.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 100F));
this.tableLayoutPanel1.Controls.Add(this.OKButton, 0, 2);
this.tableLayoutPanel1.Controls.Add(this.fileDataGridView, 0, 1);
this.tableLayoutPanel1.Controls.Add(this.tableLayoutPanel2, 0, 0);
this.tableLayoutPanel1.Dock = System.Windows.Forms.DockStyle.Fill;
this.tableLayoutPanel1.Location = new System.Drawing.Point(0, 0);
this.tableLayoutPanel1.Name = "tableLayoutPanel1";
this.tableLayoutPanel1.RowCount = 3;
this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 15F));
this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 75F));
this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 10F));
this.tableLayoutPanel1.Size = new System.Drawing.Size(548, 303);
this.tableLayoutPanel1.TabIndex = 1;
//
// OKButton
//
this.OKButton.Anchor = System.Windows.Forms.AnchorStyles.None;
this.OKButton.Location = new System.Drawing.Point(194, 275);
this.OKButton.Name = "OKButton";
this.OKButton.Size = new System.Drawing.Size(159, 25);
this.OKButton.TabIndex = 1;
this.OKButton.Text = "OK";
this.OKButton.UseVisualStyleBackColor = true;
this.OKButton.Click += new System.EventHandler(this.OKButton_Click);
//
// fileDataGridView
//
this.fileDataGridView.AllowUserToAddRows = false;
this.fileDataGridView.AllowUserToDeleteRows = false;
this.fileDataGridView.AutoGenerateColumns = false;
this.fileDataGridView.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize;
this.fileDataGridView.Columns.AddRange(new System.Windows.Forms.DataGridViewColumn[] {
this.filePathDataGridViewTextBoxColumn,
this.Column1});
this.fileDataGridView.DataMember = "FileLists";
this.fileDataGridView.DataSource = this.fileBindingSource;
this.fileDataGridView.Dock = System.Windows.Forms.DockStyle.Fill;
this.fileDataGridView.Location = new System.Drawing.Point(3, 48);
this.fileDataGridView.Name = "fileDataGridView";
this.fileDataGridView.ReadOnly = true;
this.fileDataGridView.RowHeadersVisible = false;
this.fileDataGridView.RowTemplate.Height = 24;
this.fileDataGridView.Size = new System.Drawing.Size(542, 221);
this.fileDataGridView.TabIndex = 2;
this.fileDataGridView.CellClick += new System.Windows.Forms.DataGridViewCellEventHandler(this.fileDataGridView_CellClick);
//
// Column1
//
this.Column1.HeaderText = "";
this.Column1.Name = "Column1";
this.Column1.ReadOnly = true;
this.Column1.Text = "刪除";
this.Column1.UseColumnTextForButtonValue = true;
//
// tableLayoutPanel2
//
this.tableLayoutPanel2.ColumnCount = 3;
this.tableLayoutPanel2.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 10F));
this.tableLayoutPanel2.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 75F));
this.tableLayoutPanel2.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 15F));
this.tableLayoutPanel2.Controls.Add(this.label1, 0, 0);
this.tableLayoutPanel2.Controls.Add(this.fileSourceTextBox, 1, 0);
this.tableLayoutPanel2.Controls.Add(this.panel1, 2, 0);
this.tableLayoutPanel2.Dock = System.Windows.Forms.DockStyle.Fill;
this.tableLayoutPanel2.Location = new System.Drawing.Point(3, 3);
this.tableLayoutPanel2.Name = "tableLayoutPanel2";
this.tableLayoutPanel2.RowCount = 1;
this.tableLayoutPanel2.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 100F));
this.tableLayoutPanel2.Size = new System.Drawing.Size(542, 39);
this.tableLayoutPanel2.TabIndex = 3;
//
// label1
//
this.label1.Anchor = System.Windows.Forms.AnchorStyles.None;
this.label1.AutoSize = true;
this.label1.Location = new System.Drawing.Point(12, 13);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(29, 12);
this.label1.TabIndex = 1;
this.label1.Text = "檔案";
//
// fileSourceTextBox
//
this.fileSourceTextBox.Anchor = System.Windows.Forms.AnchorStyles.None;
this.fileSourceTextBox.Location = new System.Drawing.Point(63, 8);
this.fileSourceTextBox.Name = "fileSourceTextBox";
this.fileSourceTextBox.Size = new System.Drawing.Size(388, 22);
this.fileSourceTextBox.TabIndex = 2;
this.fileSourceTextBox.Click += new System.EventHandler(this.fileSourceTextBox_Click);
//
// panel1
//
this.panel1.Controls.Add(this.addButton);
this.panel1.Dock = System.Windows.Forms.DockStyle.Fill;
this.panel1.Location = new System.Drawing.Point(463, 3);
this.panel1.Name = "panel1";
this.panel1.Size = new System.Drawing.Size(76, 33);
this.panel1.TabIndex = 3;
//
// addButton
//
this.addButton.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.addButton.Location = new System.Drawing.Point(9, 5);
this.addButton.Name = "addButton";
this.addButton.Size = new System.Drawing.Size(56, 24);
this.addButton.TabIndex = 1;
this.addButton.Text = "增加";
this.addButton.UseVisualStyleBackColor = true;
this.addButton.Click += new System.EventHandler(this.addButton_Click);
//
// filePathDataGridViewTextBoxColumn
//
this.filePathDataGridViewTextBoxColumn.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.Fill;
this.filePathDataGridViewTextBoxColumn.DataPropertyName = "FilePath";
this.filePathDataGridViewTextBoxColumn.HeaderText = "檔案名稱";
this.filePathDataGridViewTextBoxColumn.Name = "filePathDataGridViewTextBoxColumn";
this.filePathDataGridViewTextBoxColumn.ReadOnly = true;
//
// fileBindingSource
//
this.fileBindingSource.DataSource = typeof(MeetingSystem.Message.FileMessageHandler);
//
// scoreMessageHandlerBindingSource
//
this.scoreMessageHandlerBindingSource.DataSource = typeof(MeetingSystem.Message.ScoreMessageHandler);
//
// FileChooseForm
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(548, 303);
this.Controls.Add(this.tableLayoutPanel1);
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.Fixed3D;
this.Name = "FileChooseForm";
this.Text = "FileChooseForm";
this.tableLayoutPanel1.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)(this.fileDataGridView)).EndInit();
this.tableLayoutPanel2.ResumeLayout(false);
this.tableLayoutPanel2.PerformLayout();
this.panel1.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)(this.fileBindingSource)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.scoreMessageHandlerBindingSource)).EndInit();
this.ResumeLayout(false);
}
#endregion
private System.Windows.Forms.TableLayoutPanel tableLayoutPanel1;
private System.Windows.Forms.Button OKButton;
private System.Windows.Forms.DataGridView fileDataGridView;
private System.Windows.Forms.BindingSource fileBindingSource;
private System.Windows.Forms.TableLayoutPanel tableLayoutPanel2;
private System.Windows.Forms.BindingSource scoreMessageHandlerBindingSource;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.TextBox fileSourceTextBox;
private System.Windows.Forms.DataGridViewTextBoxColumn filePathDataGridViewTextBoxColumn;
private System.Windows.Forms.DataGridViewButtonColumn Column1;
private System.Windows.Forms.Panel panel1;
private System.Windows.Forms.Button addButton;
}
} | 54.570776 | 157 | 0.646306 | [
"MIT"
] | peteryu54089/android-meeting | MeetingServer/MeetingSystem/File/FileChooseForm.Designer.cs | 11,973 | C# |
using System;
using System.Linq;
using System.Net.Http;
using System.Security.Cryptography.X509Certificates;
using System.Threading;
using System.Threading.Tasks;
using NUnit.Framework;
namespace Fhi.HelseId.Altinn.Tests
{
[Ignore("Requires setup")]
public class AltinnServiceOwnerClientTests
{
// Service URI and API key for Altinn
const string ServiceUri = "https://tt02.altinn.no/api/serviceowner/";
const string ApiKey = "";
// Service code and service edition code for the service to use during testing of rights/reportees
const string ServiceCode = "";
const int ServiceEditionCode = 1;
// This PID here must be delegated rights to the service above for the organization below
const string Pid = "";
const string Organization = "";
// Store name, location and thumbprint for the enterprise certificate to use during testing
const string CertificateStoreName = "My";
const string CertificateLocation = "CurrentUser";
const string CertificateThumbprint = "";
#pragma warning disable
private AltinnServiceOwnerClient serviceClient;
[SetUp]
public void SetUp()
{
var options = new AltinnOptions
{
AuthenticationCertificateStoreName = Enum.Parse<StoreName>(CertificateStoreName),
AuthenticationCertificateLocation = Enum.Parse<StoreLocation>(CertificateLocation),
AuthenticationCertificateThumbprint = CertificateThumbprint,
ServiceOwnerServiceUri = ServiceUri,
ServiceOwnerApiKey = ApiKey
};
var httpClient = new HttpClient(options.CreateHttpMessageHandler());
options.ConfigureHttpClient(httpClient);
serviceClient = new AltinnServiceOwnerClient(httpClient);
}
[Test]
public async Task SubUnitsExist()
{
var subUnits = serviceClient.GetOrganizationsOfTypes(CancellationToken.None, "BEDR", "AAFY");
Assert.NotNull(await subUnits.FirstOrDefaultAsync());
}
[Test]
public async Task UnitsExist()
{
var subUnits = serviceClient.GetOrganizationsNotOfTypes(CancellationToken.None, "BEDR", "AAFY");
Assert.NotNull(await subUnits.FirstOrDefaultAsync());
}
[Test]
public async Task KnownOrganizationIsPresent()
{
var organization = await serviceClient.GetOrganization(Organization);
Assert.NotNull(organization);
}
[Test]
public async Task MunicipalitiesExist()
{
var municipalities = serviceClient.GetOrganizationsOfTypes(CancellationToken.None, "KOMM");
Assert.NotNull(await municipalities.FirstOrDefaultAsync());
}
[Test]
public async Task KnownDelegationIsPresent()
{
var hasDelegation = await serviceClient.HasDelegation(Pid, Organization, ServiceCode, ServiceEditionCode);
Assert.True(hasDelegation);
}
[Test]
public async Task KnownReporteesArePresent()
{
var reportees = serviceClient.GetReportees(Pid, ServiceCode, ServiceEditionCode);
Assert.NotNull(await reportees.FirstOrDefaultAsync());
}
[Test]
public async Task RightsAreRetrievedForKnownSubjectAndReportee()
{
var rights = serviceClient.GetRights(Pid, Organization);
var any = await rights.AnyAsync();
Assert.True(any);
}
[Test]
public async Task PagingWorksForKnownReportees()
{
var both = await serviceClient.GetReportees(Pid, ServiceCode, ServiceEditionCode, 0, 2);
var first = await serviceClient.GetReportees(Pid, ServiceCode, ServiceEditionCode, 0, 1);
var second = await serviceClient.GetReportees(Pid, ServiceCode, ServiceEditionCode, 1, 1);
Assert.NotNull(both);
Assert.AreEqual(2, both!.Length);
Assert.NotNull(first.Single());
Assert.NotNull(second.Single());
var firstReporteeFromBoth = both[0];
var secondReporteeFromBoth = both[1];
var firstReporteeAlone = first![0];
var secondReporteeAlone = second![0];
Assert.AreNotEqual(firstReporteeAlone.Name, secondReporteeAlone.Name);
Assert.AreEqual(firstReporteeFromBoth.Name, firstReporteeAlone.Name);
Assert.AreEqual(secondReporteeFromBoth.Name, secondReporteeAlone.Name);
}
[Test]
public async Task PagingWorksForKnownRights()
{
var both = await serviceClient.GetRights(Pid, Organization, 0, 2);
var first = await serviceClient.GetRights(Pid, Organization, 0, 1);
var second = await serviceClient.GetRights(Pid, Organization, 1, 1);
Assert.AreEqual(2, both.Rights.Length);
Assert.NotNull(first.Rights.Single());
Assert.NotNull(second.Rights.Single());
var firstRightFromBoth = both.Rights[0];
var secondRightFromBoth = both.Rights[1];
var firstRightAlone = first.Rights[0];
var secondRightAlone = second.Rights[0];
Assert.AreNotEqual(firstRightAlone.RightID, secondRightAlone.RightID);
Assert.AreEqual(firstRightFromBoth.RightID, firstRightAlone.RightID);
Assert.AreEqual(secondRightFromBoth.RightID, secondRightAlone.RightID);
}
}
}
| 38.551724 | 118 | 0.64347 | [
"MIT"
] | folkehelseinstituttet/fhi.helseid | Fhi.HelseId.Altinn.Tests/AltinnServiceOwnerClientTests.cs | 5,592 | C# |
using System;
using Grasshopper.Kernel;
using Grasshopper.Kernel.Parameters;
namespace RhinoInside.Revit.GH.Components.Categories
{
public class CategoryObjectStyle : TransactionalChainComponent
{
public override Guid ComponentGuid => new Guid("CA3C1CF9-BF5D-4B20-ADCE-3307943A1A51");
public CategoryObjectStyle()
: base
(
name: "Category Object Styles",
nickname: "CatStyles",
description: string.Empty,
category: "Revit",
subCategory: "Object Styles"
)
{ }
protected override ParamDefinition[] Inputs => inputs;
static readonly ParamDefinition[] inputs =
{
ParamDefinition.Create<Parameters.Category>("Category", "C"),
ParamDefinition.Create<Param_Integer>("Line Weight [projection]", "LWP", optional: true, relevance: ParamRelevance.Primary),
ParamDefinition.Create<Param_Integer>("Line Weight [cut]", "LWC", optional: true, relevance: ParamRelevance.Primary),
ParamDefinition.Create<Param_Colour>("Line Color", "LC", optional: true, relevance: ParamRelevance.Primary),
ParamDefinition.Create<Parameters.LinePatternElement>("Line Pattern [projection]", "LPP", optional: true, relevance: ParamRelevance.Primary),
ParamDefinition.Create<Parameters.LinePatternElement>("Line Pattern [cut]", "LPC", optional: true, relevance: ParamRelevance.Occasional),
ParamDefinition.Create<Parameters.Material>("Material", "M", optional: true, relevance: ParamRelevance.Primary),
};
protected override ParamDefinition[] Outputs => outputs;
static readonly ParamDefinition[] outputs =
{
ParamDefinition.Create<Parameters.Category>("Category", "C"),
ParamDefinition.Create<Param_Integer>("Line Weight [projection]", "LWP", relevance: ParamRelevance.Primary),
ParamDefinition.Create<Param_Integer>("Line Weight [cut]", "LWC", relevance: ParamRelevance.Primary),
ParamDefinition.Create<Param_Colour>("Line Color", "LC", relevance: ParamRelevance.Primary),
ParamDefinition.Create<Parameters.LinePatternElement>("Line Pattern [projection]", "LPP", relevance: ParamRelevance.Primary),
ParamDefinition.Create<Parameters.LinePatternElement>("Line Pattern [cut]", "LPC", relevance: ParamRelevance.Occasional),
ParamDefinition.Create<Parameters.Material>("Material", "M", relevance: ParamRelevance.Primary),
};
protected override void TrySolveInstance(IGH_DataAccess DA)
{
if (!Params.GetData(DA, "Category", out Types.Category category, x => x.IsValid))
return;
bool update = false;
update |= Params.GetData(DA, "Line Weight [projection]", out int? lwp);
update |= Params.GetData(DA, "Line Weight [cut]", out int? lwc);
update |= Params.GetData(DA, "Line Color", out System.Drawing.Color? color);
update |= Params.GetData(DA, "Line Pattern [projection]", out Types.LinePatternElement lpp);
update |= Params.GetData(DA, "Line Pattern [cut]", out Types.LinePatternElement lpc);
update |= Params.GetData(DA, "Material", out Types.Material material);
if (update)
{
StartTransaction(category.Document);
category.ProjectionLineWeight = lwp;
category.CutLineWeight = lwc;
category.LineColor = color;
category.ProjectionLinePattern = lpp;
category.CutLinePattern = lpc;
category.Material = material;
}
Params.TrySetData(DA, "Category", () => category);
Params.TrySetData(DA, "Line Weight [projection]", () => category.ProjectionLineWeight);
Params.TrySetData(DA, "Line Weight [cut]", () => category.CutLineWeight);
Params.TrySetData(DA, "Line Color", () => category.LineColor);
Params.TrySetData(DA, "Line Pattern [projection]", () => category.ProjectionLinePattern);
Params.TrySetData(DA, "Line Pattern [cut]", () => category.CutLinePattern);
Params.TrySetData(DA, "Material", () => category.Material);
}
}
}
namespace RhinoInside.Revit.GH.Components.Categories.Obsolete
{
[Obsolete("Obsolete since 2020-10-08")]
public class CategoryObjectStyle : Component
{
public override Guid ComponentGuid => new Guid("1DD8AE78-F7DA-4F26-8353-4CCE6B925DC6");
public override GH_Exposure Exposure => GH_Exposure.primary | GH_Exposure.hidden;
public CategoryObjectStyle()
: base("Category ObjectStyle", "ObjectStyle", string.Empty, "Revit", "Category")
{ }
protected override void RegisterInputParams(GH_InputParamManager manager)
{
manager.AddParameter(new Parameters.Category(), "Category", "C", "Category to query", GH_ParamAccess.item);
}
protected override void RegisterOutputParams(GH_OutputParamManager manager)
{
manager.AddIntegerParameter("LineWeight [projection]", "LWP", "Category line weight [projection]", GH_ParamAccess.item);
manager.AddIntegerParameter("LineWeight [cut]", "LWC", "Category line weigth [cut]", GH_ParamAccess.item);
manager.AddColourParameter("LineColor", "LC", "Category line color", GH_ParamAccess.item);
manager.AddParameter(new Parameters.Element(), "LinePattern [projection]", "LPP", "Category line pattern [projection]", GH_ParamAccess.item);
manager.AddParameter(new Parameters.Element(), "LinePattern [cut]", "LPC", "Category line pattern [cut]", GH_ParamAccess.item);
manager.AddParameter(new Parameters.Material(), "Material", "M", "Category material", GH_ParamAccess.item);
manager.AddBooleanParameter("Cuttable", "C", "Indicates if the category is cuttable or not", GH_ParamAccess.item);
}
protected override void TrySolveInstance(IGH_DataAccess DA)
{
Types.Category category = null;
if (!DA.GetData("Category", ref category) || category.APIObject is null)
return;
DA.SetData("LineWeight [projection]", category.ProjectionLineWeight);
DA.SetData("LineWeight [cut]", category.CutLineWeight);
DA.SetData("LineColor", category.LineColor);
DA.SetData("LinePattern [projection]", category.ProjectionLinePattern);
DA.SetData("LinePattern [cut]", category.CutLinePattern);
DA.SetData("Material", category.Material);
DA.SetData("Cuttable", category.APIObject.IsCuttable);
}
}
}
| 46.819549 | 147 | 0.707564 | [
"MIT"
] | ishanshah4343/rhino.inside-revit | src/RhinoInside.Revit.GH/Components/Category/ObjectStyle.cs | 6,227 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.Tracing;
using System.Linq;
using System.Net.Http.Headers;
using System.Net.Test.Common;
using System.Reflection;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.DotNet.RemoteExecutor;
using Xunit;
using Xunit.Abstractions;
namespace System.Net.Http.Functional.Tests
{
public abstract class DiagnosticsTest : HttpClientHandlerTestBase
{
private const string EnableActivityPropagationEnvironmentVariableSettingName = "DOTNET_SYSTEM_NET_HTTP_ENABLEACTIVITYPROPAGATION";
private const string EnableActivityPropagationAppCtxSettingName = "System.Net.Http.EnableActivityPropagation";
private static bool EnableActivityPropagationEnvironmentVariableIsNotSetAndRemoteExecutorSupported =>
string.IsNullOrEmpty(Environment.GetEnvironmentVariable(EnableActivityPropagationEnvironmentVariableSettingName)) && RemoteExecutor.IsSupported;
private static readonly Uri InvalidUri = new("http://nosuchhost.invalid");
public DiagnosticsTest(ITestOutputHelper output) : base(output) { }
[Fact]
public void EventSource_ExistsWithCorrectId()
{
Type esType = typeof(HttpClient).Assembly.GetType("System.Net.NetEventSource", throwOnError: true, ignoreCase: false);
Assert.NotNull(esType);
Assert.Equal("Private.InternalDiagnostics.System.Net.Http", EventSource.GetName(esType));
Assert.Equal(Guid.Parse("a60cec70-947b-5b80-efe2-7c5547b99b3d"), EventSource.GetGuid(esType));
Assert.NotEmpty(EventSource.GenerateManifest(esType, "assemblyPathToIncludeInManifest"));
}
// Diagnostic tests are each invoked in their own process as they enable/disable
// process-wide EventSource-based tracing, and other tests in the same process
// could interfere with the tests, as well as the enabling of tracing interfering
// with those tests.
[ConditionalFact(typeof(RemoteExecutor), nameof(RemoteExecutor.IsSupported))]
public void SendAsync_ExpectedDiagnosticSourceLogging()
{
RemoteExecutor.Invoke(async (useVersion, testAsync) =>
{
HttpRequestMessage requestLogged = null;
HttpResponseMessage responseLogged = null;
Guid requestGuid = Guid.Empty;
Guid responseGuid = Guid.Empty;
bool exceptionLogged = false;
bool activityLogged = false;
TaskCompletionSource responseLoggedTcs = new(TaskCreationOptions.RunContinuationsAsynchronously);
var diagnosticListenerObserver = new FakeDiagnosticListenerObserver(kvp =>
{
if (kvp.Key.Equals("System.Net.Http.Request"))
{
Assert.NotNull(kvp.Value);
requestLogged = GetProperty<HttpRequestMessage>(kvp.Value, "Request");
requestGuid = GetProperty<Guid>(kvp.Value, "LoggingRequestId");
}
else if (kvp.Key.Equals("System.Net.Http.Response"))
{
Assert.NotNull(kvp.Value);
responseLogged = GetProperty<HttpResponseMessage>(kvp.Value, "Response");
responseGuid = GetProperty<Guid>(kvp.Value, "LoggingRequestId");
TaskStatus requestStatus = GetProperty<TaskStatus>(kvp.Value, "RequestTaskStatus");
Assert.Equal(TaskStatus.RanToCompletion, requestStatus);
responseLoggedTcs.SetResult();
}
else if (kvp.Key.Equals("System.Net.Http.Exception"))
{
exceptionLogged = true;
}
else if (kvp.Key.StartsWith("System.Net.Http.HttpRequestOut"))
{
activityLogged = true;
}
});
using (DiagnosticListener.AllListeners.Subscribe(diagnosticListenerObserver))
{
diagnosticListenerObserver.Enable(s => !s.Contains("HttpRequestOut"));
await GetFactoryForVersion(useVersion).CreateClientAndServerAsync(
async uri =>
{
(HttpRequestMessage request, HttpResponseMessage response) = await GetAsync(useVersion, testAsync, uri);
await responseLoggedTcs.Task;
Assert.Same(request, requestLogged);
Assert.Same(response, responseLogged);
},
async server => await server.HandleRequestAsync());
Assert.Equal(requestGuid, responseGuid);
Assert.False(exceptionLogged, "Exception was logged for successful request");
Assert.False(activityLogged, "HttpOutReq was logged while HttpOutReq logging was disabled");
}
}, UseVersion.ToString(), TestAsync.ToString()).Dispose();
}
[ConditionalFact(typeof(RemoteExecutor), nameof(RemoteExecutor.IsSupported))]
public void SendAsync_ExpectedDiagnosticSourceNoLogging()
{
RemoteExecutor.Invoke(async (useVersion, testAsync) =>
{
bool requestLogged = false;
bool responseLogged = false;
bool activityStartLogged = false;
bool activityStopLogged = false;
var diagnosticListenerObserver = new FakeDiagnosticListenerObserver(kvp =>
{
if (kvp.Key.Equals("System.Net.Http.Request"))
{
requestLogged = true;
}
else if (kvp.Key.Equals("System.Net.Http.Response"))
{
responseLogged = true;
}
else if (kvp.Key.Equals("System.Net.Http.HttpRequestOut.Start"))
{
activityStartLogged = true;
}
else if (kvp.Key.Equals("System.Net.Http.HttpRequestOut.Stop"))
{
activityStopLogged = true;
}
});
using (DiagnosticListener.AllListeners.Subscribe(diagnosticListenerObserver))
{
await GetFactoryForVersion(useVersion).CreateClientAndServerAsync(
async uri =>
{
await GetAsync(useVersion, testAsync, uri);
},
async server =>
{
HttpRequestData request = await server.AcceptConnectionSendResponseAndCloseAsync();
AssertNoHeadersAreInjected(request);
});
Assert.False(requestLogged, "Request was logged while logging disabled.");
Assert.False(activityStartLogged, "HttpRequestOut.Start was logged while logging disabled.");
Assert.False(responseLogged, "Response was logged while logging disabled.");
Assert.False(activityStopLogged, "HttpRequestOut.Stop was logged while logging disabled.");
}
}, UseVersion.ToString(), TestAsync.ToString()).Dispose();
}
[ConditionalTheory(typeof(RemoteExecutor), nameof(RemoteExecutor.IsSupported))]
[InlineData(false)]
[InlineData(true)]
public void SendAsync_HttpTracingEnabled_Succeeds(bool useSsl)
{
if (useSsl && UseVersion == HttpVersion.Version20 && !PlatformDetection.SupportsAlpn)
{
return;
}
RemoteExecutor.Invoke(async (useVersion, useSsl, testAsync) =>
{
using (var listener = new TestEventListener("Private.InternalDiagnostics.System.Net.Http", EventLevel.Verbose))
{
var events = new ConcurrentQueue<EventWrittenEventArgs>();
await listener.RunWithCallbackAsync(events.Enqueue, async () =>
{
// Exercise various code paths to get coverage of tracing
await GetFactoryForVersion(useVersion).CreateClientAndServerAsync(
async uri => await GetAsync(useVersion, testAsync, uri),
async server => await server.HandleRequestAsync(),
options: new GenericLoopbackOptions { UseSsl = bool.Parse(useSsl) });
});
// We don't validate receiving specific events, but rather that we do at least
// receive some events, and that enabling tracing doesn't cause other failures
// in processing.
Assert.DoesNotContain(events,
ev => ev.EventId == 0); // make sure there are no event source error messages
Assert.InRange(events.Count, 1, int.MaxValue);
}
}, UseVersion.ToString(), useSsl.ToString(), TestAsync.ToString()).Dispose();
}
[ConditionalFact(typeof(RemoteExecutor), nameof(RemoteExecutor.IsSupported))]
public void SendAsync_ExpectedDiagnosticExceptionLogging()
{
RemoteExecutor.Invoke(async (useVersion, testAsync) =>
{
Exception exceptionLogged = null;
TaskCompletionSource responseLoggedTcs = new(TaskCreationOptions.RunContinuationsAsynchronously);
var diagnosticListenerObserver = new FakeDiagnosticListenerObserver(kvp =>
{
if (kvp.Key.Equals("System.Net.Http.Response"))
{
Assert.NotNull(kvp.Value);
TaskStatus requestStatus = GetProperty<TaskStatus>(kvp.Value, "RequestTaskStatus");
Assert.Equal(TaskStatus.Faulted, requestStatus);
responseLoggedTcs.SetResult();
}
else if (kvp.Key.Equals("System.Net.Http.Exception"))
{
Assert.NotNull(kvp.Value);
exceptionLogged = GetProperty<Exception>(kvp.Value, "Exception");
}
});
using (DiagnosticListener.AllListeners.Subscribe(diagnosticListenerObserver))
{
diagnosticListenerObserver.Enable();
Exception ex = await Assert.ThrowsAsync<HttpRequestException>(() => GetAsync(useVersion, testAsync, InvalidUri));
await responseLoggedTcs.Task;
Assert.Same(ex, exceptionLogged);
}
}, UseVersion.ToString(), TestAsync.ToString()).Dispose();
}
[ConditionalFact(typeof(RemoteExecutor), nameof(RemoteExecutor.IsSupported))]
public void SendAsync_ExpectedDiagnosticCancelledLogging()
{
RemoteExecutor.Invoke(async (useVersion, testAsync) =>
{
TaskCompletionSource responseLoggedTcs = new(TaskCreationOptions.RunContinuationsAsynchronously);
TaskCompletionSource activityStopTcs = new(TaskCreationOptions.RunContinuationsAsynchronously);
var diagnosticListenerObserver = new FakeDiagnosticListenerObserver(kvp =>
{
if (kvp.Key.Equals("System.Net.Http.Response"))
{
Assert.NotNull(kvp.Value);
TaskStatus status = GetProperty<TaskStatus>(kvp.Value, "RequestTaskStatus");
Assert.Equal(TaskStatus.Canceled, status);
responseLoggedTcs.SetResult();
}
else if (kvp.Key == "System.Net.Http.HttpRequestOut.Stop")
{
Assert.NotNull(kvp.Value);
GetProperty<HttpRequestMessage>(kvp.Value, "Request");
TaskStatus status = GetProperty<TaskStatus>(kvp.Value, "RequestTaskStatus");
Assert.Equal(TaskStatus.Canceled, status);
activityStopTcs.SetResult();
}
});
using (DiagnosticListener.AllListeners.Subscribe(diagnosticListenerObserver))
{
diagnosticListenerObserver.Enable();
var cts = new CancellationTokenSource();
await GetFactoryForVersion(useVersion).CreateClientAndServerAsync(
async uri =>
{
await Assert.ThrowsAsync<TaskCanceledException>(() => GetAsync(useVersion, testAsync, uri, cts.Token));
},
async server =>
{
await server.AcceptConnectionAsync(async connection =>
{
cts.Cancel();
await responseLoggedTcs.Task;
await activityStopTcs.Task;
});
});
}
}, UseVersion.ToString(), TestAsync.ToString()).Dispose();
}
[ConditionalTheory(typeof(RemoteExecutor), nameof(RemoteExecutor.IsSupported))]
[InlineData(ActivityIdFormat.Hierarchical)]
[InlineData(ActivityIdFormat.W3C)]
public void SendAsync_ExpectedDiagnosticSourceActivityLogging(ActivityIdFormat idFormat)
{
RemoteExecutor.Invoke(async (useVersion, testAsync, idFormatString) =>
{
ActivityIdFormat idFormat = Enum.Parse<ActivityIdFormat>(idFormatString);
bool requestLogged = false;
bool responseLogged = false;
bool exceptionLogged = false;
HttpRequestMessage activityStartRequestLogged = null;
HttpRequestMessage activityStopRequestLogged = null;
HttpResponseMessage activityStopResponseLogged = null;
TaskCompletionSource activityStopTcs = new(TaskCreationOptions.RunContinuationsAsynchronously);
Activity parentActivity = new Activity("parent");
parentActivity.SetIdFormat(idFormat);
parentActivity.AddBaggage("correlationId", Guid.NewGuid().ToString("N").ToString());
parentActivity.AddBaggage("moreBaggage", Guid.NewGuid().ToString("N").ToString());
parentActivity.AddTag("tag", "tag"); // add tag to ensure it is not injected into request
parentActivity.TraceStateString = "Foo";
parentActivity.Start();
Assert.Equal(idFormat, parentActivity.IdFormat);
var diagnosticListenerObserver = new FakeDiagnosticListenerObserver(kvp =>
{
if (kvp.Key.Equals("System.Net.Http.Request"))
{
requestLogged = true;
}
else if (kvp.Key.Equals("System.Net.Http.Response"))
{
responseLogged = true;
}
else if (kvp.Key.Equals("System.Net.Http.Exception"))
{
exceptionLogged = true;
}
else if (kvp.Key.Equals("System.Net.Http.HttpRequestOut.Start"))
{
Assert.NotNull(kvp.Value);
Assert.NotNull(Activity.Current);
Assert.Equal(parentActivity, Activity.Current.Parent);
activityStartRequestLogged = GetProperty<HttpRequestMessage>(kvp.Value, "Request");
}
else if (kvp.Key.Equals("System.Net.Http.HttpRequestOut.Stop"))
{
Assert.NotNull(kvp.Value);
Assert.NotNull(Activity.Current);
Assert.Equal(parentActivity, Activity.Current.Parent);
Assert.True(Activity.Current.Duration != TimeSpan.Zero);
activityStopRequestLogged = GetProperty<HttpRequestMessage>(kvp.Value, "Request");
activityStopResponseLogged = GetProperty<HttpResponseMessage>(kvp.Value, "Response");
TaskStatus requestStatus = GetProperty<TaskStatus>(kvp.Value, "RequestTaskStatus");
Assert.Equal(TaskStatus.RanToCompletion, requestStatus);
activityStopTcs.SetResult();
}
});
using (DiagnosticListener.AllListeners.Subscribe(diagnosticListenerObserver))
{
diagnosticListenerObserver.Enable(s => s.Contains("HttpRequestOut"));
await GetFactoryForVersion(useVersion).CreateClientAndServerAsync(
async uri =>
{
(HttpRequestMessage request, HttpResponseMessage response) = await GetAsync(useVersion, testAsync, uri);
await activityStopTcs.Task;
Assert.Same(request, activityStartRequestLogged);
Assert.Same(request, activityStopRequestLogged);
Assert.Same(response, activityStopResponseLogged);
},
async server =>
{
HttpRequestData requestData = await server.AcceptConnectionSendResponseAndCloseAsync();
AssertHeadersAreInjected(requestData, parentActivity);
});
Assert.False(requestLogged, "Request was logged when Activity logging was enabled.");
Assert.False(exceptionLogged, "Exception was logged for successful request");
Assert.False(responseLogged, "Response was logged when Activity logging was enabled.");
}
}, UseVersion.ToString(), TestAsync.ToString(), idFormat.ToString()).Dispose();
}
[ConditionalFact(typeof(RemoteExecutor), nameof(RemoteExecutor.IsSupported))]
public void SendAsync_ExpectedDiagnosticSourceActivityLogging_InvalidBaggage()
{
RemoteExecutor.Invoke(async (useVersion, testAsync) =>
{
bool exceptionLogged = false;
TaskCompletionSource activityStopTcs = new(TaskCreationOptions.RunContinuationsAsynchronously);
Activity parentActivity = new Activity("parent");
parentActivity.SetIdFormat(ActivityIdFormat.Hierarchical);
parentActivity.AddBaggage("bad/key", "value");
parentActivity.AddBaggage("goodkey", "bad/value");
parentActivity.AddBaggage("key", "value");
parentActivity.Start();
var diagnosticListenerObserver = new FakeDiagnosticListenerObserver(kvp =>
{
if (kvp.Key.Equals("System.Net.Http.HttpRequestOut.Stop"))
{
Assert.NotNull(kvp.Value);
Assert.NotNull(Activity.Current);
Assert.Equal(parentActivity, Activity.Current.Parent);
Assert.True(Activity.Current.Duration != TimeSpan.Zero);
HttpRequestMessage request = GetProperty<HttpRequestMessage>(kvp.Value, "Request");
Assert.True(request.Headers.TryGetValues("Request-Id", out var requestId));
Assert.True(request.Headers.TryGetValues("Correlation-Context", out var correlationContext));
Assert.Equal("key=value, goodkey=bad%2Fvalue, bad%2Fkey=value", Assert.Single(correlationContext));
TaskStatus requestStatus = GetProperty<TaskStatus>(kvp.Value, "RequestTaskStatus");
Assert.Equal(TaskStatus.RanToCompletion, requestStatus);
activityStopTcs.SetResult();
}
else if (kvp.Key.Equals("System.Net.Http.Exception"))
{
exceptionLogged = true;
}
});
using (DiagnosticListener.AllListeners.Subscribe(diagnosticListenerObserver))
{
diagnosticListenerObserver.Enable(s => s.Contains("HttpRequestOut"));
await GetFactoryForVersion(useVersion).CreateClientAndServerAsync(
async uri =>
{
await GetAsync(useVersion, testAsync, uri);
},
async server => await server.HandleRequestAsync());
await activityStopTcs.Task;
Assert.False(exceptionLogged, "Exception was logged for successful request");
}
}, UseVersion.ToString(), TestAsync.ToString()).Dispose();
}
[ConditionalFact(typeof(RemoteExecutor), nameof(RemoteExecutor.IsSupported))]
public void SendAsync_ExpectedDiagnosticSourceActivityLoggingDoesNotOverwriteHeader()
{
RemoteExecutor.Invoke(async (useVersion, testAsync) =>
{
bool activityStartLogged = false;
TaskCompletionSource activityStopTcs = new(TaskCreationOptions.RunContinuationsAsynchronously);
Activity parentActivity = new Activity("parent");
parentActivity.SetIdFormat(ActivityIdFormat.Hierarchical);
parentActivity.AddBaggage("correlationId", Guid.NewGuid().ToString("N").ToString());
parentActivity.Start();
string customRequestIdHeader = "|foo.bar.";
var diagnosticListenerObserver = new FakeDiagnosticListenerObserver(kvp =>
{
if (kvp.Key.Equals("System.Net.Http.HttpRequestOut.Start"))
{
HttpRequestMessage request = GetProperty<HttpRequestMessage>(kvp.Value, "Request");
request.Headers.Add("Request-Id", customRequestIdHeader);
activityStartLogged = true;
}
else if (kvp.Key.Equals("System.Net.Http.HttpRequestOut.Stop"))
{
HttpRequestMessage request = GetProperty<HttpRequestMessage>(kvp.Value, "Request");
Assert.Single(request.Headers.GetValues("Request-Id"));
Assert.Equal(customRequestIdHeader, request.Headers.GetValues("Request-Id").Single());
Assert.False(request.Headers.TryGetValues("traceparent", out var _));
Assert.False(request.Headers.TryGetValues("tracestate", out var _));
activityStopTcs.SetResult();
}
});
using (DiagnosticListener.AllListeners.Subscribe(diagnosticListenerObserver))
{
diagnosticListenerObserver.Enable();
await GetFactoryForVersion(useVersion).CreateClientAndServerAsync(
async uri =>
{
await GetAsync(useVersion, testAsync, uri);
},
async server => await server.HandleRequestAsync());
await activityStopTcs.Task;
Assert.True(activityStartLogged, "HttpRequestOut.Start was not logged.");
}
}, UseVersion.ToString(), TestAsync.ToString()).Dispose();
}
[ConditionalFact(typeof(RemoteExecutor), nameof(RemoteExecutor.IsSupported))]
public void SendAsync_ExpectedDiagnosticSourceActivityLoggingDoesNotOverwriteW3CTraceParentHeader()
{
RemoteExecutor.Invoke(async (useVersion, testAsync) =>
{
bool activityStartLogged = false;
TaskCompletionSource activityStopTcs = new(TaskCreationOptions.RunContinuationsAsynchronously);
Activity parentActivity = new Activity("parent");
parentActivity.SetParentId(ActivityTraceId.CreateRandom(), ActivitySpanId.CreateRandom());
parentActivity.TraceStateString = "some=state";
parentActivity.Start();
string customTraceParentHeader = "00-abcdef0123456789abcdef0123456789-abcdef0123456789-01";
var diagnosticListenerObserver = new FakeDiagnosticListenerObserver(kvp =>
{
if (kvp.Key.Equals("System.Net.Http.HttpRequestOut.Start"))
{
HttpRequestMessage request = GetProperty<HttpRequestMessage>(kvp.Value, "Request");
Assert.Single(request.Headers.GetValues("traceparent"));
Assert.False(request.Headers.TryGetValues("tracestate", out var _));
Assert.Equal(customTraceParentHeader, request.Headers.GetValues("traceparent").Single());
Assert.False(request.Headers.TryGetValues("Request-Id", out var _));
activityStartLogged = true;
}
else if (kvp.Key.Equals("System.Net.Http.HttpRequestOut.Stop"))
{
activityStopTcs.SetResult();
}
});
using (DiagnosticListener.AllListeners.Subscribe(diagnosticListenerObserver))
{
diagnosticListenerObserver.Enable();
await GetFactoryForVersion(useVersion).CreateClientAndServerAsync(
async uri =>
{
using HttpClient client = CreateHttpClient(useVersion);
var request = new HttpRequestMessage(HttpMethod.Get, uri)
{
Version = Version.Parse(useVersion)
};
request.Headers.Add("traceparent", customTraceParentHeader);
await client.SendAsync(bool.Parse(testAsync), request);
},
async server => await server.HandleRequestAsync());
await activityStopTcs.Task;
Assert.True(activityStartLogged, "HttpRequestOut.Start was not logged.");
}
}, UseVersion.ToString(), TestAsync.ToString()).Dispose();
}
[ConditionalFact(typeof(RemoteExecutor), nameof(RemoteExecutor.IsSupported))]
public void SendAsync_ExpectedDiagnosticSourceUrlFilteredActivityLogging()
{
RemoteExecutor.Invoke(async (useVersion, testAsync) =>
{
bool activityStartLogged = false;
bool activityStopLogged = false;
var diagnosticListenerObserver = new FakeDiagnosticListenerObserver(kvp =>
{
if (kvp.Key.Equals("System.Net.Http.HttpRequestOut.Start"))
{
activityStartLogged = true;
}
else if (kvp.Key.Equals("System.Net.Http.HttpRequestOut.Stop"))
{
activityStopLogged = true;
}
});
using (DiagnosticListener.AllListeners.Subscribe(diagnosticListenerObserver))
{
await GetFactoryForVersion(useVersion).CreateClientAndServerAsync(
async uri =>
{
diagnosticListenerObserver.Enable((s, r, _) =>
{
if (s.StartsWith("System.Net.Http.HttpRequestOut") && r is HttpRequestMessage request)
{
return request.RequestUri != uri;
}
return true;
});
await GetAsync(useVersion, testAsync, uri);
},
async server => await server.HandleRequestAsync());
Assert.False(activityStartLogged, "HttpRequestOut.Start was logged while URL disabled.");
Assert.False(activityStopLogged, "HttpRequestOut.Stop was logged while URL disabled.");
}
}, UseVersion.ToString(), TestAsync.ToString()).Dispose();
}
[ConditionalFact(typeof(RemoteExecutor), nameof(RemoteExecutor.IsSupported))]
public void SendAsync_ExpectedDiagnosticExceptionActivityLogging()
{
RemoteExecutor.Invoke(async (useVersion, testAsync) =>
{
Exception exceptionLogged = null;
TaskCompletionSource activityStopTcs = new(TaskCreationOptions.RunContinuationsAsynchronously);
var diagnosticListenerObserver = new FakeDiagnosticListenerObserver(kvp =>
{
if (kvp.Key.Equals("System.Net.Http.HttpRequestOut.Stop"))
{
Assert.NotNull(kvp.Value);
GetProperty<HttpRequestMessage>(kvp.Value, "Request");
TaskStatus requestStatus = GetProperty<TaskStatus>(kvp.Value, "RequestTaskStatus");
Assert.Equal(TaskStatus.Faulted, requestStatus);
activityStopTcs.SetResult();
}
else if (kvp.Key.Equals("System.Net.Http.Exception"))
{
Assert.NotNull(kvp.Value);
exceptionLogged = GetProperty<Exception>(kvp.Value, "Exception");
}
});
using (DiagnosticListener.AllListeners.Subscribe(diagnosticListenerObserver))
{
diagnosticListenerObserver.Enable();
Exception ex = await Assert.ThrowsAsync<HttpRequestException>(() => GetAsync(useVersion, testAsync, InvalidUri));
await activityStopTcs.Task;
Assert.Same(ex, exceptionLogged);
}
}, UseVersion.ToString(), TestAsync.ToString()).Dispose();
}
[ConditionalFact(typeof(RemoteExecutor), nameof(RemoteExecutor.IsSupported))]
public void SendAsync_ExpectedDiagnosticSynchronousExceptionActivityLogging()
{
RemoteExecutor.Invoke(async (useVersion, testAsync) =>
{
Exception exceptionLogged = null;
TaskCompletionSource activityStopTcs = new(TaskCreationOptions.RunContinuationsAsynchronously);
var diagnosticListenerObserver = new FakeDiagnosticListenerObserver(kvp =>
{
if (kvp.Key.Equals("System.Net.Http.HttpRequestOut.Stop"))
{
Assert.NotNull(kvp.Value);
GetProperty<HttpRequestMessage>(kvp.Value, "Request");
TaskStatus requestStatus = GetProperty<TaskStatus>(kvp.Value, "RequestTaskStatus");
Assert.Equal(TaskStatus.Faulted, requestStatus);
activityStopTcs.SetResult();
}
else if (kvp.Key.Equals("System.Net.Http.Exception"))
{
Assert.NotNull(kvp.Value);
exceptionLogged = GetProperty<Exception>(kvp.Value, "Exception");
}
});
using (DiagnosticListener.AllListeners.Subscribe(diagnosticListenerObserver))
{
diagnosticListenerObserver.Enable();
using (HttpClientHandler handler = CreateHttpClientHandler(useVersion))
using (HttpClient client = CreateHttpClient(handler, useVersion))
{
// Set a https proxy.
// Forces a synchronous exception for SocketsHttpHandler.
// SocketsHttpHandler only allow http scheme for proxies.
handler.Proxy = new WebProxy($"https://foo.bar", false);
var request = new HttpRequestMessage(HttpMethod.Get, InvalidUri)
{
Version = Version.Parse(useVersion)
};
// We cannot use Assert.Throws<Exception>(() => { SendAsync(...); }) to verify the
// synchronous exception here, because DiagnosticsHandler SendAsync() method has async
// modifier, and returns Task. If the call is not awaited, the current test method will continue
// run before the call is completed, thus Assert.Throws() will not capture the exception.
// We need to wait for the Task to complete synchronously, to validate the exception.
Exception exception = null;
if (bool.Parse(testAsync))
{
Task sendTask = client.SendAsync(request);
Assert.True(sendTask.IsFaulted);
exception = sendTask.Exception.InnerException;
}
else
{
try
{
client.Send(request);
}
catch (Exception ex)
{
exception = ex;
}
Assert.NotNull(exception);
}
await activityStopTcs.Task;
Assert.IsType<NotSupportedException>(exception);
Assert.Same(exceptionLogged, exception);
}
}
}, UseVersion.ToString(), TestAsync.ToString()).Dispose();
}
[ConditionalFact(typeof(RemoteExecutor), nameof(RemoteExecutor.IsSupported))]
public void SendAsync_ExpectedDiagnosticSourceNewAndDeprecatedEventsLogging()
{
RemoteExecutor.Invoke(async (useVersion, testAsync) =>
{
bool requestLogged = false;
bool activityStartLogged = false;
bool activityStopLogged = false;
TaskCompletionSource responseLoggedTcs = new(TaskCreationOptions.RunContinuationsAsynchronously);
var diagnosticListenerObserver = new FakeDiagnosticListenerObserver(kvp =>
{
if (kvp.Key.Equals("System.Net.Http.Request"))
{
requestLogged = true;
}
else if (kvp.Key.Equals("System.Net.Http.Response"))
{
responseLoggedTcs.SetResult();
}
else if (kvp.Key.Equals("System.Net.Http.HttpRequestOut.Start"))
{
activityStartLogged = true;
}
else if (kvp.Key.Equals("System.Net.Http.HttpRequestOut.Stop"))
{
activityStopLogged = true;
}
});
using (DiagnosticListener.AllListeners.Subscribe(diagnosticListenerObserver))
{
diagnosticListenerObserver.Enable();
await GetFactoryForVersion(useVersion).CreateClientAndServerAsync(
async uri =>
{
await GetAsync(useVersion, testAsync, uri);
},
async server => await server.HandleRequestAsync());
await responseLoggedTcs.Task;
Assert.True(activityStartLogged, "HttpRequestOut.Start was not logged.");
Assert.True(requestLogged, "Request was not logged.");
Assert.True(activityStopLogged, "HttpRequestOut.Stop was not logged.");
}
}, UseVersion.ToString(), TestAsync.ToString()).Dispose();
}
[ConditionalFact(typeof(RemoteExecutor), nameof(RemoteExecutor.IsSupported))]
public void SendAsync_ExpectedDiagnosticExceptionOnlyActivityLogging()
{
RemoteExecutor.Invoke(async (useVersion, testAsync) =>
{
bool activityLogged = false;
Exception exceptionLogged = null;
TaskCompletionSource exceptionLoggedTcs = new(TaskCreationOptions.RunContinuationsAsynchronously);
var diagnosticListenerObserver = new FakeDiagnosticListenerObserver(kvp =>
{
if (kvp.Key.Equals("System.Net.Http.HttpRequestOut.Stop"))
{
activityLogged = true;
}
else if (kvp.Key.Equals("System.Net.Http.Exception"))
{
Assert.NotNull(kvp.Value);
exceptionLogged = GetProperty<Exception>(kvp.Value, "Exception");
exceptionLoggedTcs.SetResult();
}
});
using (DiagnosticListener.AllListeners.Subscribe(diagnosticListenerObserver))
{
diagnosticListenerObserver.Enable(s => s.Equals("System.Net.Http.Exception"));
Exception ex = await Assert.ThrowsAsync<HttpRequestException>(() => GetAsync(useVersion, testAsync, InvalidUri));
await exceptionLoggedTcs.Task;
Assert.Same(ex, exceptionLogged);
Assert.False(activityLogged, "HttpOutReq was logged when logging was disabled");
}
}, UseVersion.ToString(), TestAsync.ToString()).Dispose();
}
public static IEnumerable<object[]> UseSocketsHttpHandler_WithIdFormat_MemberData()
{
yield return new object[] { true, ActivityIdFormat.Hierarchical };
yield return new object[] { true, ActivityIdFormat.W3C };
yield return new object[] { false, ActivityIdFormat.Hierarchical };
yield return new object[] { false, ActivityIdFormat.W3C };
}
[ConditionalTheory(typeof(PlatformDetection), nameof(PlatformDetection.IsNotBrowser))]
[MemberData(nameof(UseSocketsHttpHandler_WithIdFormat_MemberData))]
public async Task SendAsync_ExpectedActivityPropagationWithoutListener(bool useSocketsHttpHandler, ActivityIdFormat idFormat)
{
Activity parent = new Activity("parent");
parent.SetIdFormat(idFormat);
parent.Start();
await GetFactoryForVersion(UseVersion).CreateClientAndServerAsync(
async uri =>
{
await GetAsync(UseVersion.ToString(), TestAsync.ToString(), uri, useSocketsHttpHandler: useSocketsHttpHandler);
},
async server =>
{
HttpRequestData requestData = await server.HandleRequestAsync();
AssertHeadersAreInjected(requestData, parent);
});
}
[ConditionalTheory(typeof(PlatformDetection), nameof(PlatformDetection.IsNotBrowser))]
[InlineData(true)]
[InlineData(false)]
public async Task SendAsync_ExpectedActivityPropagationWithoutListenerOrParentActivity(bool useSocketsHttpHandler)
{
await GetFactoryForVersion(UseVersion).CreateClientAndServerAsync(
async uri =>
{
await GetAsync(UseVersion.ToString(), TestAsync.ToString(), uri, useSocketsHttpHandler: useSocketsHttpHandler);
},
async server =>
{
HttpRequestData requestData = await server.HandleRequestAsync();
AssertNoHeadersAreInjected(requestData);
});
}
[ConditionalTheory(nameof(EnableActivityPropagationEnvironmentVariableIsNotSetAndRemoteExecutorSupported))]
[InlineData("true")]
[InlineData("1")]
[InlineData("0")]
[InlineData("false")]
[InlineData("FALSE")]
[InlineData("fAlSe")]
[InlineData("helloworld")]
[InlineData("")]
public void SendAsync_SuppressedGlobalStaticPropagationEnvVar(string envVarValue)
{
RemoteExecutor.Invoke(async (useVersion, testAsync, envVarValue) =>
{
Environment.SetEnvironmentVariable(EnableActivityPropagationEnvironmentVariableSettingName, envVarValue);
bool isInstrumentationEnabled = !(envVarValue == "0" || envVarValue.Equals("false", StringComparison.OrdinalIgnoreCase));
bool anyEventLogged = false;
var diagnosticListenerObserver = new FakeDiagnosticListenerObserver(kvp =>
{
anyEventLogged = true;
});
using (DiagnosticListener.AllListeners.Subscribe(diagnosticListenerObserver))
{
diagnosticListenerObserver.Enable();
await GetFactoryForVersion(useVersion).CreateClientAndServerAsync(
async uri =>
{
Activity parent = new Activity("parent").Start();
(HttpRequestMessage request, _) = await GetAsync(useVersion, testAsync, uri);
string headerName = parent.IdFormat == ActivityIdFormat.Hierarchical ? "Request-Id" : "traceparent";
Assert.Equal(isInstrumentationEnabled, request.Headers.Contains(headerName));
},
async server => await server.HandleRequestAsync());
Assert.Equal(isInstrumentationEnabled, anyEventLogged);
}
}, UseVersion.ToString(), TestAsync.ToString(), envVarValue).Dispose();
}
[ConditionalTheory(typeof(PlatformDetection), nameof(PlatformDetection.IsNotBrowser))]
[MemberData(nameof(UseSocketsHttpHandler_WithIdFormat_MemberData))]
public async Task SendAsync_HeadersAreInjectedOnRedirects(bool useSocketsHttpHandler, ActivityIdFormat idFormat)
{
Activity parent = new Activity("parent");
parent.SetIdFormat(idFormat);
parent.TraceStateString = "Foo";
parent.Start();
await GetFactoryForVersion(UseVersion).CreateServerAsync(async (originalServer, originalUri) =>
{
await GetFactoryForVersion(UseVersion).CreateServerAsync(async (redirectServer, redirectUri) =>
{
Task clientTask = GetAsync(UseVersion.ToString(), TestAsync.ToString(), originalUri, useSocketsHttpHandler: useSocketsHttpHandler);
Task<HttpRequestData> serverTask = originalServer.HandleRequestAsync(HttpStatusCode.Redirect, new[] { new HttpHeaderData("Location", redirectUri.AbsoluteUri) });
await Task.WhenAny(clientTask, serverTask);
Assert.False(clientTask.IsCompleted, $"{clientTask.Status}: {clientTask.Exception}");
HttpRequestData firstRequestData = await serverTask;
AssertHeadersAreInjected(firstRequestData, parent);
serverTask = redirectServer.HandleRequestAsync();
await TestHelper.WhenAllCompletedOrAnyFailed(clientTask, serverTask);
HttpRequestData secondRequestData = await serverTask;
AssertHeadersAreInjected(secondRequestData, parent);
if (idFormat == ActivityIdFormat.W3C)
{
string firstParent = GetHeaderValue(firstRequestData, "traceparent");
string firstState = GetHeaderValue(firstRequestData, "tracestate");
Assert.True(ActivityContext.TryParse(firstParent, firstState, out ActivityContext firstContext));
string secondParent = GetHeaderValue(secondRequestData, "traceparent");
string secondState = GetHeaderValue(secondRequestData, "tracestate");
Assert.True(ActivityContext.TryParse(secondParent, secondState, out ActivityContext secondContext));
Assert.Equal(firstContext.TraceId, secondContext.TraceId);
Assert.Equal(firstContext.TraceFlags, secondContext.TraceFlags);
Assert.Equal(firstContext.TraceState, secondContext.TraceState);
Assert.NotEqual(firstContext.SpanId, secondContext.SpanId);
}
else
{
Assert.NotEqual(GetHeaderValue(firstRequestData, "Request-Id"), GetHeaderValue(secondRequestData, "Request-Id"));
}
});
});
}
[ConditionalTheory(typeof(RemoteExecutor), nameof(RemoteExecutor.IsSupported))]
[InlineData(true)]
[InlineData(false)]
public void SendAsync_SuppressedGlobalStaticPropagationNoListenerAppCtx(bool switchValue)
{
RemoteExecutor.Invoke(async (useVersion, testAsync, switchValue) =>
{
AppContext.SetSwitch(EnableActivityPropagationAppCtxSettingName, bool.Parse(switchValue));
await GetFactoryForVersion(useVersion).CreateClientAndServerAsync(
async uri =>
{
Activity parent = new Activity("parent").Start();
(HttpRequestMessage request, _) = await GetAsync(useVersion, testAsync, uri);
string headerName = parent.IdFormat == ActivityIdFormat.Hierarchical ? "Request-Id" : "traceparent";
Assert.Equal(bool.Parse(switchValue), request.Headers.Contains(headerName));
},
async server => await server.HandleRequestAsync());
}, UseVersion.ToString(), TestAsync.ToString(), switchValue.ToString()).Dispose();
}
public static IEnumerable<object[]> SocketsHttpHandlerPropagators_WithIdFormat_MemberData()
{
foreach (var propagator in new[] { null, DistributedContextPropagator.CreateDefaultPropagator(), DistributedContextPropagator.CreateNoOutputPropagator(), DistributedContextPropagator.CreatePassThroughPropagator() })
{
foreach (ActivityIdFormat format in new[] { ActivityIdFormat.Hierarchical, ActivityIdFormat.W3C })
{
yield return new object[] { propagator, format };
}
}
}
[ConditionalTheory(typeof(PlatformDetection), nameof(PlatformDetection.IsNotBrowser))]
[MemberData(nameof(SocketsHttpHandlerPropagators_WithIdFormat_MemberData))]
public async Task SendAsync_CustomSocketsHttpHandlerPropagator_PropagatorIsUsed(DistributedContextPropagator propagator, ActivityIdFormat idFormat)
{
Activity parent = new Activity("parent");
parent.SetIdFormat(idFormat);
parent.Start();
await GetFactoryForVersion(UseVersion).CreateClientAndServerAsync(
async uri =>
{
using var handler = new SocketsHttpHandler { ActivityHeadersPropagator = propagator };
handler.SslOptions.RemoteCertificateValidationCallback = delegate { return true; };
using var client = new HttpClient(handler);
var request = CreateRequest(HttpMethod.Get, uri, UseVersion, exactVersion: true);
await client.SendAsync(TestAsync, request);
},
async server =>
{
HttpRequestData requestData = await server.HandleRequestAsync();
if (propagator is null || ReferenceEquals(propagator, DistributedContextPropagator.CreateNoOutputPropagator()))
{
AssertNoHeadersAreInjected(requestData);
}
else
{
AssertHeadersAreInjected(requestData, parent, ReferenceEquals(propagator, DistributedContextPropagator.CreatePassThroughPropagator()));
}
});
}
private static T GetProperty<T>(object obj, string propertyName)
{
Type t = obj.GetType();
PropertyInfo p = t.GetRuntimeProperty(propertyName);
object propertyValue = p.GetValue(obj);
Assert.NotNull(propertyValue);
Assert.IsAssignableFrom<T>(propertyValue);
return (T)propertyValue;
}
private static string GetHeaderValue(HttpRequestData request, string name)
{
return request.Headers.SingleOrDefault(h => h.Name.Equals(name, StringComparison.OrdinalIgnoreCase)).Value;
}
private static void AssertNoHeadersAreInjected(HttpRequestData request)
{
Assert.Null(GetHeaderValue(request, "Request-Id"));
Assert.Null(GetHeaderValue(request, "traceparent"));
Assert.Null(GetHeaderValue(request, "tracestate"));
Assert.Null(GetHeaderValue(request, "Correlation-Context"));
}
private static void AssertHeadersAreInjected(HttpRequestData request, Activity parent, bool passthrough = false)
{
string requestId = GetHeaderValue(request, "Request-Id");
string traceparent = GetHeaderValue(request, "traceparent");
string tracestate = GetHeaderValue(request, "tracestate");
if (parent.IdFormat == ActivityIdFormat.Hierarchical)
{
Assert.True(requestId != null, "Request-Id was not injected when instrumentation was enabled");
Assert.StartsWith(parent.Id, requestId);
Assert.Equal(passthrough, parent.Id == requestId);
Assert.Null(traceparent);
Assert.Null(tracestate);
}
else if (parent.IdFormat == ActivityIdFormat.W3C)
{
Assert.Null(requestId);
Assert.True(traceparent != null, "traceparent was not injected when W3C instrumentation was enabled");
Assert.StartsWith($"00-{parent.TraceId.ToHexString()}-", traceparent);
Assert.Equal(passthrough, parent.Id == traceparent);
Assert.Equal(parent.TraceStateString, tracestate);
}
List<NameValueHeaderValue> correlationContext = (GetHeaderValue(request, "Correlation-Context") ?? string.Empty)
.Split(',', StringSplitOptions.RemoveEmptyEntries)
.Select(kvp => NameValueHeaderValue.Parse(kvp))
.ToList();
List<KeyValuePair<string, string>> baggage = parent.Baggage.ToList();
Assert.Equal(baggage.Count, correlationContext.Count);
foreach (var kvp in baggage)
{
Assert.Contains(new NameValueHeaderValue(kvp.Key, kvp.Value), correlationContext);
}
}
private static async Task<(HttpRequestMessage, HttpResponseMessage)> GetAsync(string useVersion, string testAsync, Uri uri, CancellationToken cancellationToken = default, bool useSocketsHttpHandler = false)
{
HttpMessageHandler handler;
if (useSocketsHttpHandler)
{
var socketsHttpHandler = new SocketsHttpHandler();
socketsHttpHandler.SslOptions.RemoteCertificateValidationCallback = delegate { return true; };
handler = socketsHttpHandler;
}
else
{
handler = new HttpClientHandler
{
ServerCertificateCustomValidationCallback = TestHelper.AllowAllCertificates
};
}
using var client = new HttpClient(handler);
var request = CreateRequest(HttpMethod.Get, uri, Version.Parse(useVersion), exactVersion: true);
return (request, await client.SendAsync(bool.Parse(testAsync), request, cancellationToken));
}
}
}
| 49.413444 | 227 | 0.562548 | [
"MIT"
] | 333fred/runtime | src/libraries/System.Net.Http/tests/FunctionalTests/DiagnosticsTests.cs | 53,663 | C# |
using NUnit.Framework;
using System.IO;
namespace FftSharp.Tests
{
internal class Readme
{
public static string OUTPUT_FOLDER = Path.GetFullPath(Path.Combine(TestContext.CurrentContext.TestDirectory, "../../../../../dev/quickstart/"));
[Test]
public void Test_Readme_Quickstart()
{
// Begin with an array containing sample data
double[] signal = FftSharp.SampleData.SampleAudio1();
// Shape the signal using a Hanning window
var window = new FftSharp.Windows.Hanning();
window.ApplyInPlace(signal);
// Calculate the FFT as an array of complex numbers
Complex[] fft = FftSharp.Transform.FFT(signal);
// Or get the spectral power (dB) or magnitude (RMS²) as real numbers
double[] fftPwr = FftSharp.Transform.FFTpower(signal);
double[] fftMag = FftSharp.Transform.FFTmagnitude(signal);
}
[Test]
public void Test_Plot_TimeSeries()
{
// sample audio with tones at 2, 10, and 20 kHz plus white noise
double[] signal = FftSharp.SampleData.SampleAudio1();
int sampleRate = 48_000;
// plot the sample audio
var plt = new ScottPlot.Plot(400, 200);
plt.AddSignal(signal, sampleRate / 1000.0);
plt.YLabel("Amplitude");
plt.Margins(0);
plt.SaveFig(Path.Combine(OUTPUT_FOLDER, "time-series.png"));
}
[Test]
public void Test_Plot_MagnitudePowerFreq()
{
// sample audio with tones at 2, 10, and 20 kHz plus white noise
double[] signal = FftSharp.SampleData.SampleAudio1();
int sampleRate = 48_000;
// calculate the power spectral density using FFT
double[] psd = FftSharp.Transform.FFTpower(signal);
double[] freq = FftSharp.Transform.FFTfreq(sampleRate, psd.Length);
// plot the sample audio
var plt = new ScottPlot.Plot(400, 200);
plt.AddScatterLines(freq, psd);
plt.YLabel("Power (dB)");
plt.XLabel("Frequency (Hz)");
plt.Margins(0);
plt.SaveFig(Path.Combine(OUTPUT_FOLDER, "periodogram.png"));
}
[Test]
public void Test_Complex()
{
Complex[] buffer =
{
new Complex(42, 0),
new Complex(96, 0),
new Complex(13, 0),
new Complex(99, 0),
};
FftSharp.Transform.FFT(buffer);
}
[Test]
public void Test_Window()
{
double[] signal = FftSharp.SampleData.SampleAudio1();
var window = new FftSharp.Windows.Hanning();
double[] windowed = window.Apply(signal);
}
}
}
| 32.590909 | 152 | 0.557183 | [
"MIT"
] | swharden/FftSharp | src/FftSharp.Tests/Readme.cs | 2,871 | C# |
using System;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
namespace OpenLaMulana.Entities
{
public class RectangleSprite
{
static Texture2D _pointTexture;
public static void DrawRectangle(SpriteBatch spriteBatch, Rectangle rectangle, Color color, int lineWidth)
{
if (_pointTexture == null)
{
_pointTexture = new Texture2D(spriteBatch.GraphicsDevice, 1, 1);
_pointTexture.SetData<Color>(new Color[] { Color.White });
}
var _x = (int)Math.Round((float)rectangle.X);
var _y = (int)Math.Round((float)rectangle.Y);
spriteBatch.Draw(_pointTexture, new Rectangle(_x, _y, lineWidth, rectangle.Height + lineWidth), color); // bbox left
spriteBatch.Draw(_pointTexture, new Rectangle(_x, _y, rectangle.Width + lineWidth, lineWidth), color); // bbox top
spriteBatch.Draw(_pointTexture, new Rectangle(_x + rectangle.Width, _y, lineWidth, rectangle.Height + lineWidth), color); // bbox right
spriteBatch.Draw(_pointTexture, new Rectangle(_x, _y + rectangle.Height, rectangle.Width + lineWidth, lineWidth), color); // bbox bottom
}
}
}
| 44.178571 | 148 | 0.656427 | [
"MIT"
] | mysterypaint/OpenLaMulana | Graphics/RectangleSprite.cs | 1,239 | C# |
using System;
using System.Collections.Generic;
using Newtonsoft.Json;
namespace Adeotek.DevToolbox.Models
{
public class AppTask
{
public Guid Guid { get; set; }
public string Name { get; set; }
public string Type { get; set; }
public bool IsActive { get; set; }
public bool IsShortcut { get; set; }
public Dictionary<string, string> Arguments { get; set; }
public AppTask()
{
Arguments = new Dictionary<string, string>();
}
[JsonIgnore]
public TaskTypes TypeAsEnum => string.IsNullOrEmpty(Type) ? TaskTypes.Undefined : Enum.Parse<TaskTypes>(Type);
[JsonIgnore]
public string EditButtonText { get; set; } = "Edit";
[JsonIgnore]
public string DeleteButtonText { get; set; } = "Delete";
}
} | 30.178571 | 118 | 0.6 | [
"MIT"
] | adeotek/dev-toolbox | src/Models/AppTask.cs | 847 | C# |
using System;
using System.Collections.Generic;
using System.Text;
namespace SageOne.Entities
{
public class AccountOpeningBalance : Entity<AccountOpeningBalance>
{
}
} | 18.2 | 70 | 0.758242 | [
"MIT"
] | gvanderberg/sageone-dotnet | src/SageOne/Entities/AccountOpeningBalance.cs | 184 | C# |
using Newtonsoft.Json;
namespace SimilarWeb.Api.Connector.Models.Other
{
/// <summary>
/// Базовый класс запроса из метаданных.
/// </summary>
public abstract class BaseRequest
{
#region Свойства
[JsonProperty("domain")]
public string Domain { get; set; }
[JsonProperty("format")]
public string Format { get; set; }
#endregion
}
}
| 19.428571 | 47 | 0.595588 | [
"MIT"
] | wm-russia-software/SimilarWeb.Api.Connector | SimilarWeb.Api.Connector/SimilarWeb.Api.Connector/Models/Other/BaseRequest.cs | 449 | C# |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using WMPLib;
namespace ARApp1
{
public partial class VideoForm : Form
{
public string VideoLink { get; set; }
public VideoForm()
{
InitializeComponent();
}
private void VideoForm_Load(object sender, EventArgs e)
{
axWindowsMediaPlayer1.Margin = new System.Windows.Forms.Padding(0);
axWindowsMediaPlayer1.Padding = new System.Windows.Forms.Padding(0);
axWindowsMediaPlayer1.URL = VideoLink;
axWindowsMediaPlayer1.Ctlcontrols.play();
axWindowsMediaPlayer1.Ctlenabled = false;
axWindowsMediaPlayer1.uiMode = "none";
}
}
}
| 25.323529 | 80 | 0.656214 | [
"Apache-2.0"
] | sankarvema/AIM | archieve/AppMain/ARApp1/VideoForm.cs | 863 | C# |
namespace _05.ExtractAllSongsWithXmlReader
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml;
/// <summary>
/// Write a program, which using XmlReader extracts all song titles from catalog.xml
/// </summary>
public class Program
{
public static void Main(string[] args)
{
var reader = XmlReader.Create("../../../01.CreateXmlRepresentingCatalogue/catalogue.xml");
var titles = new List<string>();
using (reader)
{
while (reader.Read())
{
if (reader.Name == "title")
{
titles.Add(reader.ReadInnerXml());
}
}
}
foreach (var title in titles)
{
Console.WriteLine(title);
}
}
}
}
| 26.314286 | 102 | 0.479913 | [
"Apache-2.0"
] | iliantrifonov/TelerikAcademy | Databases/14.XmlProcessingIn.NET/05.ExtractAllSongsWithXmlReader/Program.cs | 923 | C# |
namespace Sport.Domain.Enums.Tournament
{
public enum TournamentType
{
Charity = 1,
PrizeMoney = 2
}
}
| 14.666667 | 40 | 0.590909 | [
"MIT"
] | TodorNikolov89/Sport | Sport/Sport.Domain/Enums/Tournament/TournamentType.cs | 134 | C# |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Serialization;
namespace JetBrains.TeamCity.NuGet.Tests
{
public class NuGetRunner_ListPackagesCommandTestBase
{
[XmlRoot("nuget-packages")]
public class NuGetPackages
{
[XmlArray("packages")]
[XmlArrayItem("package")]
public Package[] Packages { get; set; }
}
[XmlRoot("package")]
public class Package
{
[XmlAttribute("source")]
public string Source { get; set; }
[XmlAttribute("id")]
public string Id { get; set; }
[XmlAttribute("versions")]
public string Versions { get; set; }
[XmlAttribute("include-prerelease")]
public string IncludePrerelease { get; set; }
}
protected static string Serialize(IEnumerable<Package> pp)
{
return Serialize(pp.ToArray());
}
protected static string Serialize(params Package[] pp)
{
var s = new XmlSerializer(typeof (NuGetPackages));
var ms = new MemoryStream();
using(var tw = new StreamWriter(ms, Encoding.UTF8))
s.Serialize(tw, new NuGetPackages {Packages = pp});
return new string(Encoding.UTF8.GetChars(ms.GetBuffer()));
}
protected static Package p(string source, string id, string version = null, bool? includePrerelease = null)
{
return new Package
{
Source = source,
Id = id,
Versions = version,
IncludePrerelease = includePrerelease == null ? null : includePrerelease.ToString()
};
}
protected static Package p1(string id, string version = null, bool? includePrerelease = null)
{
return p(NuGetConstants.DefaultFeedUrl_v1, id, version, includePrerelease);
}
protected static Package p2(string id, string version = null, bool? includePrerelease = null)
{
return p(NuGetConstants.DefaultFeedUrl_v2, id, version, includePrerelease);
}
protected static Package p3(string id, string version = null, bool? includePrerelease = null)
{
return p(NuGetConstants.DefaultFeedUrl_v3, id, version, includePrerelease);
}
protected static int PackagesCount(XmlDocument doc, string id)
{
var p = doc.SelectNodes("//package[@id='" + id + "']//package-entry");
return p == null ? 0 : p.Count;
}
protected static XmlDocument DoTestWithSpec(NuGetVersion version, string spec)
{
return TempFilesHolder.WithTempFile(
fileOut =>
TempFilesHolder.WithTempFile(
fileIn =>
{
File.WriteAllText(fileIn, spec);
ProcessExecutor.ExecuteProcess(Files.NuGetRunnerExe, Files.GetNuGetExe(version),
"TeamCity.ListPackages", "-Request", fileIn, "-Response", fileOut)
.Dump()
.AssertExitedSuccessfully()
;
Console.Out.WriteLine("Result: " + File.ReadAllText(fileOut));
var doc = new XmlDocument();
doc.Load(fileOut);
return doc;
}));
}
}
}
| 30.925234 | 112 | 0.593835 | [
"ECL-2.0",
"Apache-2.0",
"BSD-3-Clause"
] | JetBrains/teamcity-nuget-support | nuget-extensions/nuget-tests/src/NuGetRunner_ListPackagesCommandTestBase.cs | 3,309 | 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("WastePermits.UIAutomation")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("WastePermits.UIAutomation")]
[assembly: AssemblyCopyright("Copyright © 2019")]
[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("dc63a146-e6f6-47f8-aafa-03de8414df76")]
// 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.459459 | 84 | 0.748419 | [
"Unlicense"
] | DEFRA/license-and-permitting-dynamics | Crm/WastePermits/Defra.Lp.WastePermits/UIAutomation/Properties/AssemblyInfo.cs | 1,426 | C# |
using Ef5TipsTricks.DataAccess.Entities;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
namespace Ef5TipsTricks.DataAccess.Configurations
{
public class PersonConfiguration : IEntityTypeConfiguration<Person>
{
public void Configure(EntityTypeBuilder<Person> builder)
{
builder.ToTable("People");
builder.HasKey(x => x.Id);
builder.Property(x => x.Id).ValueGeneratedOnAdd();
builder.Property(x => x.FirstName).HasMaxLength(30).IsRequired();
builder.Property(x => x.LastName).HasMaxLength(30).IsRequired();
}
}
}
| 32.75 | 77 | 0.682443 | [
"MIT"
] | marcominerva/EntityFrameworkCoreTipsTricks | Ef5TipsTricks/DataAccess/Configurations/PersonConfiguration.cs | 657 | C# |
/*
* _____ ______
* /_ / ____ ____ ____ _________ / __/ /_
* / / / __ \/ __ \/ __ \/ ___/ __ \/ /_/ __/
* / /__/ /_/ / / / / /_/ /\_ \/ /_/ / __/ /_
* /____/\____/_/ /_/\__ /____/\____/_/ \__/
* /____/
*
* Authors:
* 钟峰(Popeye Zhong) <9555843@qq.com>
*
* Copyright (C) 2015-2017 Zongsoft Corporation. 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.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.Web.Http;
using Zongsoft.Data;
using Zongsoft.Web.Http;
using Zongsoft.Security.Membership;
using Zongsoft.Community.Models;
using Zongsoft.Community.Services;
namespace Zongsoft.Community.Web.Http.Controllers
{
[Authorization]
public class MessageController : Zongsoft.Web.Http.HttpControllerBase<Message, MessageConditional, MessageService>
{
#region 构造函数
public MessageController(Zongsoft.Services.IServiceProvider serviceProvider) : base(serviceProvider)
{
}
#endregion
#region 公共方法
[ActionName("Users")]
public object GetUsers(ulong id, [FromUri]bool? isRead = null, [FromUri]Paging paging = null)
{
return this.GetResult(this.DataService.GetUsers(id, isRead, paging));
}
#endregion
}
}
| 30.789474 | 115 | 0.682621 | [
"Apache-2.0"
] | Zongsoft/Zongsoft.Community | src/api/Http/Controllers/MessageController.cs | 1,777 | C# |
// <auto-generated/>
#pragma warning disable 1591
namespace Test
{
#line hidden
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Components;
public class TestComponent : Microsoft.AspNetCore.Components.ComponentBase
{
#pragma warning disable 1998
protected override void BuildRenderTree(Microsoft.AspNetCore.Components.RenderTree.RenderTreeBuilder builder)
{
base.BuildRenderTree(builder);
__Blazor.Test.TestComponent.TypeInference.CreateMyComponent_0(builder, 0, 1, "hi", 2, 17);
}
#pragma warning restore 1998
}
}
namespace __Blazor.Test.TestComponent
{
#line hidden
internal static class TypeInference
{
public static void CreateMyComponent_0<TItem>(global::Microsoft.AspNetCore.Components.RenderTree.RenderTreeBuilder builder, int seq, int __seq0, TItem __arg0, int __seq1, System.Object __arg1)
{
builder.OpenComponent<global::Test.MyComponent<TItem>>(seq);
builder.AddAttribute(__seq0, "Item", __arg0);
builder.AddAttribute(__seq1, "Other", __arg1);
builder.CloseComponent();
}
}
}
#pragma warning restore 1591
| 34.162162 | 200 | 0.701741 | [
"Apache-2.0"
] | 0xced/AspNetCore | src/Components/test/Microsoft.AspNetCore.Components.Build.Test/TestFiles/RuntimeCodeGenerationTest/ChildComponent_GenericWeaklyTypedAttribute_TypeInference/TestComponent.codegen.cs | 1,264 | C# |
using System;
using System.Reflection;
namespace HelloCoreClrApp
{
public static class NetCoreHelper
{
public static string GetNetCoreVersion()
{
var assembly = typeof(System.Runtime.Versioning.FrameworkName).GetTypeInfo().Assembly;
var assemblyPath = assembly.Location.Split(new[] { '/', '\\' }, StringSplitOptions.RemoveEmptyEntries);
var netCoreAppIndex = Array.IndexOf(assemblyPath, "Microsoft.NETCore.App");
if (netCoreAppIndex > 0 && netCoreAppIndex < assemblyPath.Length - 2)
return assemblyPath[netCoreAppIndex + 1];
return null;
}
}
}
| 32.95 | 115 | 0.644917 | [
"MIT"
] | jp7677/hellocoreclr | src/HelloCoreClrApp/NetCoreHelper.cs | 661 | C# |
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
namespace EncompassRest.Loans
{
/// <summary>
/// ElliUCDDetail
/// </summary>
public sealed partial class ElliUCDDetail : DirtyExtensibleObject, IIdentifiable
{
private DirtyDictionary<string, string?>? _cDFields;
private DirtyDictionary<string, string?>? _lEFields;
/// <summary>
/// ElliUCDDetail CDFields
/// </summary>
[AllowNull]
public IDictionary<string, string?> CDFields { get => GetField(ref _cDFields); set => SetField(ref _cDFields, value); }
/// <summary>
/// ElliUCDDetail LEFields
/// </summary>
[AllowNull]
public IDictionary<string, string?> LEFields { get => GetField(ref _lEFields); set => SetField(ref _lEFields, value); }
}
} | 32.423077 | 127 | 0.638197 | [
"MIT"
] | EncompassRest/EncompassREST | src/EncompassRest/Loans/ElliUCDDetail.cs | 843 | C# |
namespace RelaxAndSport.Application.Identity
{
public interface IUser
{
string Id { get; set; }
}
}
| 15.125 | 45 | 0.619835 | [
"MIT"
] | kriskok95/RelaxAndSport | src/Server/RelaxAndSport.Application/Identity/IUser.cs | 123 | C# |
/* ----------------------------------------------------------------------------
* This file was automatically generated by SWIG (http://www.swig.org).
* Version 2.0.4
*
* Do not make changes to this file unless you know what you are doing--modify
* the SWIG interface file instead.
* ----------------------------------------------------------------------------- */
namespace libsbmlcs {
using System;
using System.Runtime.InteropServices;
/**
* @sbmlpackage{core}
*
@htmlinclude pkg-marker-core.html Implementation of SBML's %Unit construct.
*
* The SBML unit definition facility uses two classes of objects,
* UnitDefinition and Unit. The approach to defining units in %SBML is
* compositional; for example, <em>meter second<sup> –2</sup></em> is
* constructed by combining a Unit object representing <em>meter</em> with
* another Unit object representing <em>second<sup> –2</sup></em>.
* The combination is wrapped inside a UnitDefinition, which provides for
* assigning an identifier and optional name to the combination. The
* identifier can then be referenced from elsewhere in a model. Thus, the
* UnitDefinition class is the container, and Unit instances are placed
* inside UnitDefinition instances.
*
* A Unit structure has four attributes named 'kind', 'exponent', 'scale'
* and 'multiplier'. It represents a (possibly transformed) reference to a
* base unit. The attribute 'kind' on Unit indicates the chosen base unit.
* Its value must be one of the text strings listed below; this list
* corresponds to SBML Level 3 Version 1 Core:
*
* *
*
<table border='0' class='centered text-table width80 normal-font code'
style='border: none !important'>
<tr>
<td>ampere</td><td>farad</td><td>joule</td><td>lux</td><td>radian</td><td>volt</td>
</tr>
<tr>
<td>avogadro</td><td>gram</td><td>katal</td><td>metre</td><td>second</td><td>watt</td>
</tr>
<tr>
<td>becquerel</td><td>gray</td><td>kelvin</td><td>mole</td><td>siemens</td><td>weber</td>
</tr>
<tr>
<td>candela</td><td>henry</td><td>kilogram</td><td>newton</td><td>sievert</td>
</tr>
<tr>
<td>coulomb</td><td>hertz</td><td>litre</td><td>ohm</td><td>steradian</td>
</tr>
<tr>
<td>dimensionless</td><td>item</td><td>lumen</td><td>pascal</td><td>tesla</td>
</tr>
</table>
*
*
*
* A few small differences exist between the Level 3 list of base
* units and the list defined in other Level/Version combinations of SBML.
* Specifically, Levels of SBML before Level 3 do not define @c
* avogadro; conversely, Level 2 Version 1 defines @c Celsius,
* and Level 1 defines @c celsius, @c meter, and @c liter, none of
* which are available in Level 3. In libSBML, each of the predefined
* base unit names is represented by an enumeration value @if clike in
* #UnitKind_t@else whose name begins with the characters
* <code>UNIT_KIND_</code>@endif, discussed in a separate section below.
*
* The attribute named 'exponent' on Unit represents an exponent on the
* unit. In SBML Level 2, the attribute is optional and has a default
* value of @c 1 (one); in SBML Level 3, the attribute is mandatory
* and there is no default value. A Unit structure also has an attribute
* called 'scale'; its value must be an integer exponent for a power-of-ten
* multiplier used to set the scale of the unit. For example, a unit
* having a 'kind' value of @c gram and a 'scale' value of @c -3 signifies
* 10<sup> –3</sup> * gram, or milligrams. In SBML
* Level 2, the attribute is optional and has a default value of @c 0
* (zero), because 10<sup> 0</sup> = 1; in SBML Level 3, the attribute
* is mandatory and has no default value. Lastly, the attribute named
* 'multiplier' can be used to multiply the unit by a real-numbered factor;
* this enables the definition of units that are not power-of-ten multiples
* of SI units. For instance, a multiplier of 0.3048 could be used to
* define @c foot as a measure of length in terms of a @c metre. The
* 'multiplier' attribute is optional in SBML Level 2, where it has a
* default value of @c 1 (one); in SBML Level 3, the attribute is
* mandatory and has not default value.
*
* @if clike
* <h3><a class='anchor' name='UnitKind_t'>UnitKind_t</a></h3>
* @else
* <h3><a class='anchor' name='UnitKind_t'>%Unit identification codes</a></h3>
* @endif
*
* As discussed above, SBML defines a set of base units which serves as the
* starting point for new unit definitions. This set of base units
* consists of the SI units and a small number of additional convenience
* units.
*
* @if clike Until SBML Level 2 Version 3, there
* existed a data type in the SBML specifications called @c UnitKind,
* enumerating the possible SBML base units. Although SBML Level 2
* Version 3 removed this type from the language specification,
* libSBML maintains the corresponding enumeration type #UnitKind_t as a
* convenience and as a way to provide backward compatibility to previous
* SBML Level/Version specifications. (The removal in SBML Level 2
* Version 3 of the enumeration @c UnitKind was also accompanied by
* the redefinition of the data type @c UnitSId to include the previous @c
* UnitKind values as reserved symbols in the @c UnitSId space. This
* change has no net effect on permissible models, their representation or
* their syntax. The purpose of the change in the SBML specification was
* simply to clean up an inconsistency about the contexts in which these
* values were usable.)
* @endif@if java In SBML Level 2 Versions before
* Version 3, there existed an enumeration of units called @c
* UnitKind. In Version 3, this enumeration was removed and the
* identifier class @c UnitSId redefined to include the previous @c
* UnitKind values as reserved symbols. This change has no net effect on
* permissible models, their representation or their syntax. The purpose
* of the change in the SBML specification was simply to clean up an
* inconsistency about the contexts in which these values were usable.
* However, libSBML maintains UnitKind in the form of of a set of static
* integer constants whose names begin with the characters
* <code>UNIT_KIND_</code>. These constants are defined in the class
* <code><a href='libsbmlcs.libsbml.html'>libsbmlConstants</a></code>.
* @endif@if python In SBML Level 2 Versions before
* Version 3, there existed an enumeration of units called @c
* UnitKind. In Version 3, this enumeration was removed and the
* identifier class @c UnitSId redefined to include the previous @c
* UnitKind values as reserved symbols. This change has no net effect on
* permissible models, their representation or their syntax. The purpose
* of the change in the SBML specification was simply to clean up an
* inconsistency about the contexts in which these values were usable.
* However, libSBML maintains UnitKind in the form of of a set of static
* integer constants whose names begin with the characters
* <code>UNIT_KIND_</code>. These constants are defined in the class
* @link libsbml libsbml@endlink.
* @endif
*
* As a consequence of the fact that libSBML supports models in all Levels
* and Versions of SBML, libSBML's set of @c UNIT_KIND_ values is a union
* of all the possible base unit names defined in the different SBML
* specifications. However, not every base unit is allowed in every
* Level+Version combination of SBML. Note in particular the following
* exceptions:
* <ul>
* <li> The alternate spelling @c 'meter' is included in
* addition to the official SI spelling @c 'metre'. This spelling is only
* permitted in SBML Level 1 models.
*
* <li> The alternate spelling @c 'liter' is included in addition to the
* official SI spelling @c 'litre'. This spelling is only permitted in
* SBML Level 1 models.
*
* <li> The unit @c 'Celsius' is included because of its presence in
* specifications of SBML prior to SBML Level 2 Version 3.
*
* <li> The unit @c avogadro was introduced in SBML Level 3, and
* is only permitted for use in SBML Level 3 models.
* </ul>
*
* @if clike The table below lists the symbols defined in the
* @c UnitKind_t enumeration, and their
* meanings. @else The table below lists the unit
* constants defined in libSBML, and their meanings. @endif
*
* @htmlinclude unitkind-table.html
*
*
*/
public class Unit : SBase {
private HandleRef swigCPtr;
internal Unit(IntPtr cPtr, bool cMemoryOwn) : base(libsbmlPINVOKE.Unit_SWIGUpcast(cPtr), cMemoryOwn)
{
//super(libsbmlPINVOKE.UnitUpcast(cPtr), cMemoryOwn);
swigCPtr = new HandleRef(this, cPtr);
}
internal static HandleRef getCPtr(Unit obj)
{
return (obj == null) ? new HandleRef(null, IntPtr.Zero) : obj.swigCPtr;
}
internal static HandleRef getCPtrAndDisown (Unit obj)
{
HandleRef ptr = new HandleRef(null, IntPtr.Zero);
if (obj != null)
{
ptr = obj.swigCPtr;
obj.swigCMemOwn = false;
}
return ptr;
}
~Unit() {
Dispose();
}
public override void Dispose() {
lock(this) {
if (swigCPtr.Handle != IntPtr.Zero) {
if (swigCMemOwn) {
swigCMemOwn = false;
libsbmlPINVOKE.delete_Unit(swigCPtr);
}
swigCPtr = new HandleRef(null, IntPtr.Zero);
}
GC.SuppressFinalize(this);
base.Dispose();
}
}
/**
* Creates a new Unit using the given SBML @p level and @p version
* values.
*
* @param level a long integer, the SBML Level to assign to this Unit
*
* @param version a long integer, the SBML Version to assign to this
* Unit
*
* @throws @if python ValueError @else SBMLConstructorException @endif
* Thrown if the given @p level and @p version combination, or this kind
* of SBML object, are either invalid or mismatched with respect to the
* parent SBMLDocument object.
*
* *
* @note Upon the addition of a Unit object to an SBMLDocument, the SBML
* Level, SBML Version and XML namespace of the document @em
* override the values used when creating the Unit object via this
* constructor. This is necessary to ensure that an SBML document is a
* consistent structure. Nevertheless, the ability to supply the values
* at the time of creation of a Unit is an important aid to producing
* valid SBML. Knowledge of the intented SBML Level and Version
* determine whether it is valid to assign a particular value to an
* attribute, or whether it is valid to add an object to an existing
* SBMLDocument.
*
*/ public
Unit(long level, long version) : this(libsbmlPINVOKE.new_Unit__SWIG_0(level, version), true) {
if (libsbmlPINVOKE.SWIGPendingException.Pending) throw libsbmlPINVOKE.SWIGPendingException.Retrieve();
}
/**
* Creates a new Unit using the given SBMLNamespaces object
* @p sbmlns.
*
* *
*
* The SBMLNamespaces object encapsulates SBML Level/Version/namespaces
* information. It is used to communicate the SBML Level, Version, and (in
* Level 3) packages used in addition to SBML Level 3 Core. A
* common approach to using libSBML's SBMLNamespaces facilities is to create an
* SBMLNamespaces object somewhere in a program once, then hand that object
* as needed to object constructors that accept SBMLNamespaces as arguments.
*
*
*
* @param sbmlns an SBMLNamespaces object.
*
* @throws @if python ValueError @else SBMLConstructorException @endif
* Thrown if the given @p level and @p version combination, or this kind
* of SBML object, are either invalid or mismatched with respect to the
* parent SBMLDocument object.
*
* *
* @note Upon the addition of a Unit object to an SBMLDocument, the SBML
* Level, SBML Version and XML namespace of the document @em
* override the values used when creating the Unit object via this
* constructor. This is necessary to ensure that an SBML document is a
* consistent structure. Nevertheless, the ability to supply the values
* at the time of creation of a Unit is an important aid to producing
* valid SBML. Knowledge of the intented SBML Level and Version
* determine whether it is valid to assign a particular value to an
* attribute, or whether it is valid to add an object to an existing
* SBMLDocument.
*
*/ public
Unit(SBMLNamespaces sbmlns) : this(libsbmlPINVOKE.new_Unit__SWIG_1(SBMLNamespaces.getCPtr(sbmlns)), true) {
if (libsbmlPINVOKE.SWIGPendingException.Pending) throw libsbmlPINVOKE.SWIGPendingException.Retrieve();
}
/**
* Copy constructor; creates a copy of this Unit.
*
* @param orig the object to copy.
*
* @throws @if python ValueError @else SBMLConstructorException @endif
* Thrown if the argument @p orig is @c null.
*/ public
Unit(Unit orig) : this(libsbmlPINVOKE.new_Unit__SWIG_2(Unit.getCPtr(orig)), true) {
if (libsbmlPINVOKE.SWIGPendingException.Pending) throw libsbmlPINVOKE.SWIGPendingException.Retrieve();
}
/**
* Creates and returns a deep copy of this Unit.
*
* @return a (deep) copy of this Unit.
*/ public new
Unit clone() {
IntPtr cPtr = libsbmlPINVOKE.Unit_clone(swigCPtr);
Unit ret = (cPtr == IntPtr.Zero) ? null : new Unit(cPtr, true);
return ret;
}
/**
* Initializes the fields of this Unit object to 'typical' default
* values.
*
* The SBML Unit component has slightly different aspects and default
* attribute values in different SBML Levels and Versions. This method
* sets the values to certain common defaults, based mostly on what they
* are in SBML Level 2. Specifically:
* <ul>
* <li> Sets attribute 'exponent' to @c 1
* <li> Sets attribute 'scale' to @c 0
* <li> Sets attribute 'multiplier' to @c 1.0
* </ul>
*
* The 'kind' attribute is left unchanged.
*/ public
void initDefaults() {
libsbmlPINVOKE.Unit_initDefaults(swigCPtr);
}
/**
* Returns the 'kind' of Unit this is.
*
* @if clike
* @return the value of the 'kind' attribute of this Unit as a
* value from the <a class='el' href='#UnitKind_t'>UnitKind_t</a> enumeration.
* @endif@if java
* @return the value of the 'kind' attribute of this Unit as a
* value from the set of constants whose names begin
* with <code>UNIT_KIND_</code> defined in the class
* <code><a href='libsbmlcs.libsbml.html'>libsbmlConstants</a></code>.
* @endif@if python
* @return the value of the 'kind' attribute of this Unit as a
* value from the set of constants whose names begin
* with <code>UNIT_KIND_</code> defined in the class
* @link libsbml libsbml@endlink.
* @endif
*/ public
int getKind() {
int ret = libsbmlPINVOKE.Unit_getKind(swigCPtr);
return ret;
}
/**
* Returns the value of the 'exponent' attribute of this unit.
*
* @return the 'exponent' value of this Unit, as an integer.
*/ public
int getExponent() {
int ret = libsbmlPINVOKE.Unit_getExponent(swigCPtr);
return ret;
}
/**
* Returns the value of the 'exponent' attribute of this unit.
*
* @return the 'exponent' value of this Unit, as a double.
*/ public
double getExponentAsDouble() {
double ret = libsbmlPINVOKE.Unit_getExponentAsDouble(swigCPtr);
return ret;
}
/**
* Returns the value of the 'scale' attribute of this unit.
*
* @return the 'scale' value of this Unit, as an integer.
*/ public
int getScale() {
int ret = libsbmlPINVOKE.Unit_getScale(swigCPtr);
return ret;
}
/**
* Returns the value of the 'multiplier' attribute of this Unit.
*
* @return the 'multiplier' value of this Unit, as a double.
*/ public
double getMultiplier() {
double ret = libsbmlPINVOKE.Unit_getMultiplier(swigCPtr);
return ret;
}
/**
* Returns the value of the 'offset' attribute of this Unit.
*
* @return the 'offset' value of this Unit, as a double.
*
* *
* @warning <span class='warning'>The 'offset' attribute is only available in
* SBML Level 2 Version 1. This attribute is not present in SBML
* Level 2 Version 2 or above. When producing SBML models using
* these later specifications, modelers and software tools need to account
* for units with offsets explicitly. The %SBML specification document
* offers a number of suggestions for how to achieve this. LibSBML methods
* such as this one related to 'offset' are retained for compatibility with
* earlier versions of SBML Level 2, but their use is strongly
* discouraged.</span>
*
*/ public
double getOffset() {
double ret = libsbmlPINVOKE.Unit_getOffset(swigCPtr);
return ret;
}
/**
* Predicate for testing whether this Unit is of the kind @c ampere.
*
* @return @c true if the kind of this Unit is @c ampere, @c false
* otherwise.
*/ public
bool isAmpere() {
bool ret = libsbmlPINVOKE.Unit_isAmpere(swigCPtr);
return ret;
}
/**
* Predicate for testing whether this Unit is of the kind @c avogadro.
*
* @return @c true if the kind of this Unit is @c avogadro, @c false
* otherwise.
*
* @note The unit @c avogadro was introduced in SBML Level 3, and
* is only permitted for use in SBML Level 3 models.
*/ public
bool isAvogadro() {
bool ret = libsbmlPINVOKE.Unit_isAvogadro(swigCPtr);
return ret;
}
/**
* Predicate for testing whether this Unit is of the kind @c becquerel
*
* @return @c true if the kind of this Unit is @c becquerel, @c false
* otherwise.
*/ public
bool isBecquerel() {
bool ret = libsbmlPINVOKE.Unit_isBecquerel(swigCPtr);
return ret;
}
/**
* Predicate for testing whether this Unit is of the kind @c candela
*
* @return @c true if the kind of this Unit is @c candela, @c false
* otherwise.
*/ public
bool isCandela() {
bool ret = libsbmlPINVOKE.Unit_isCandela(swigCPtr);
return ret;
}
/**
* Predicate for testing whether this Unit is of the kind @c Celsius
*
* @return @c true if the kind of this Unit is @c Celsius, @c false
* otherwise.
*
* @warning <span class='warning'>The predefined unit @c Celsius was
* removed from the list of predefined units in SBML Level 2
* Version 2 at the same time that the 'offset' attribute was removed
* from Unit definitions. LibSBML methods such as this one related to @c
* Celsius are retained in order to support SBML Level 2
* Version 1, but their use is strongly discouraged.</span>
*/ public
bool isCelsius() {
bool ret = libsbmlPINVOKE.Unit_isCelsius(swigCPtr);
return ret;
}
/**
* Predicate for testing whether this Unit is of the kind @c coulomb
*
* @return @c true if the kind of this Unit is @c coulomb, @c false
* otherwise.
*/ public
bool isCoulomb() {
bool ret = libsbmlPINVOKE.Unit_isCoulomb(swigCPtr);
return ret;
}
/**
* Predicate for testing whether this Unit is of the kind @c
* dimensionless.
*
* @return @c true if the kind of this Unit is @c dimensionless, @c false
*
* otherwise.
*/ public
bool isDimensionless() {
bool ret = libsbmlPINVOKE.Unit_isDimensionless(swigCPtr);
return ret;
}
/**
* Predicate for testing whether this Unit is of the kind @c farad
*
* @return @c true if the kind of this Unit is @c farad, @c false
* otherwise.
*/ public
bool isFarad() {
bool ret = libsbmlPINVOKE.Unit_isFarad(swigCPtr);
return ret;
}
/**
* Predicate for testing whether this Unit is of the kind @c gram
*
* @return @c true if the kind of this Unit is @c gram, @c false
* otherwise.
*/ public
bool isGram() {
bool ret = libsbmlPINVOKE.Unit_isGram(swigCPtr);
return ret;
}
/**
* Predicate for testing whether this Unit is of the kind @c gray
*
* @return @c true if the kind of this Unit is @c gray, @c false
* otherwise.
*/ public
bool isGray() {
bool ret = libsbmlPINVOKE.Unit_isGray(swigCPtr);
return ret;
}
/**
* Predicate for testing whether this Unit is of the kind @c henry
*
* @return @c true if the kind of this Unit is @c henry, @c false
* otherwise.
*/ public
bool isHenry() {
bool ret = libsbmlPINVOKE.Unit_isHenry(swigCPtr);
return ret;
}
/**
* Predicate for testing whether this Unit is of the kind @c hertz
*
* @return @c true if the kind of this Unit is @c hertz, @c false
* otherwise.
*/ public
bool isHertz() {
bool ret = libsbmlPINVOKE.Unit_isHertz(swigCPtr);
return ret;
}
/**
* Predicate for testing whether this Unit is of the kind @c item
*
* @return @c true if the kind of this Unit is @c item, @c false
* otherwise.
*/ public
bool isItem() {
bool ret = libsbmlPINVOKE.Unit_isItem(swigCPtr);
return ret;
}
/**
* Predicate for testing whether this Unit is of the kind @c joule
*
* @return @c true if the kind of this Unit is @c joule, @c false
* otherwise.
*/ public
bool isJoule() {
bool ret = libsbmlPINVOKE.Unit_isJoule(swigCPtr);
return ret;
}
/**
* Predicate for testing whether this Unit is of the kind @c katal
*
* @return @c true if the kind of this Unit is @c katal, @c false
* otherwise.
*/ public
bool isKatal() {
bool ret = libsbmlPINVOKE.Unit_isKatal(swigCPtr);
return ret;
}
/**
* Predicate for testing whether this Unit is of the kind @c kelvin
*
* @return @c true if the kind of this Unit is @c kelvin, @c false
* otherwise.
*/ public
bool isKelvin() {
bool ret = libsbmlPINVOKE.Unit_isKelvin(swigCPtr);
return ret;
}
/**
* Predicate for testing whether this Unit is of the kind @c kilogram
*
* @return @c true if the kind of this Unit is @c kilogram, @c false
* otherwise.
*/ public
bool isKilogram() {
bool ret = libsbmlPINVOKE.Unit_isKilogram(swigCPtr);
return ret;
}
/**
* Predicate for testing whether this Unit is of the kind @c litre
*
* @return @c true if the kind of this Unit is @c litre or 'liter', @c
* false
* otherwise.
*/ public
bool isLitre() {
bool ret = libsbmlPINVOKE.Unit_isLitre(swigCPtr);
return ret;
}
/**
* Predicate for testing whether this Unit is of the kind @c lumen
*
* @return @c true if the kind of this Unit is @c lumen, @c false
* otherwise.
*/ public
bool isLumen() {
bool ret = libsbmlPINVOKE.Unit_isLumen(swigCPtr);
return ret;
}
/**
* Predicate for testing whether this Unit is of the kind @c lux
*
* @return @c true if the kind of this Unit is @c lux, @c false
* otherwise.
*/ public
bool isLux() {
bool ret = libsbmlPINVOKE.Unit_isLux(swigCPtr);
return ret;
}
/**
* Predicate for testing whether this Unit is of the kind @c metre
*
* @return @c true if the kind of this Unit is @c metre or 'meter', @c
* false
* otherwise.
*/ public
bool isMetre() {
bool ret = libsbmlPINVOKE.Unit_isMetre(swigCPtr);
return ret;
}
/**
* Predicate for testing whether this Unit is of the kind @c mole
*
* @return @c true if the kind of this Unit is @c mole, @c false
* otherwise.
*/ public
bool isMole() {
bool ret = libsbmlPINVOKE.Unit_isMole(swigCPtr);
return ret;
}
/**
* Predicate for testing whether this Unit is of the kind @c newton
*
* @return @c true if the kind of this Unit is @c newton, @c false
* otherwise.
*/ public
bool isNewton() {
bool ret = libsbmlPINVOKE.Unit_isNewton(swigCPtr);
return ret;
}
/**
* Predicate for testing whether this Unit is of the kind @c ohm
*
* @return @c true if the kind of this Unit is @c ohm, @c false
* otherwise.
*/ public
bool isOhm() {
bool ret = libsbmlPINVOKE.Unit_isOhm(swigCPtr);
return ret;
}
/**
* Predicate for testing whether this Unit is of the kind @c pascal
*
* @return @c true if the kind of this Unit is @c pascal, @c false
* otherwise.
*/ public
bool isPascal() {
bool ret = libsbmlPINVOKE.Unit_isPascal(swigCPtr);
return ret;
}
/**
* Predicate for testing whether this Unit is of the kind @c radian
*
* @return @c true if the kind of this Unit is @c radian, @c false
* otherwise.
*/ public
bool isRadian() {
bool ret = libsbmlPINVOKE.Unit_isRadian(swigCPtr);
return ret;
}
/**
* Predicate for testing whether this Unit is of the kind @c second
*
* @return @c true if the kind of this Unit is @c second, @c false
* otherwise.
*/ public
bool isSecond() {
bool ret = libsbmlPINVOKE.Unit_isSecond(swigCPtr);
return ret;
}
/**
* Predicate for testing whether this Unit is of the kind @c siemens
*
* @return @c true if the kind of this Unit is @c siemens, @c false
* otherwise.
*/ public
bool isSiemens() {
bool ret = libsbmlPINVOKE.Unit_isSiemens(swigCPtr);
return ret;
}
/**
* Predicate for testing whether this Unit is of the kind @c sievert
*
* @return @c true if the kind of this Unit is @c sievert, @c false
* otherwise.
*/ public
bool isSievert() {
bool ret = libsbmlPINVOKE.Unit_isSievert(swigCPtr);
return ret;
}
/**
* Predicate for testing whether this Unit is of the kind @c steradian
*
* @return @c true if the kind of this Unit is @c steradian, @c false
* otherwise.
*/ public
bool isSteradian() {
bool ret = libsbmlPINVOKE.Unit_isSteradian(swigCPtr);
return ret;
}
/**
* Predicate for testing whether this Unit is of the kind @c tesla
*
* @return @c true if the kind of this Unit is @c tesla, @c false
* otherwise.
*/ public
bool isTesla() {
bool ret = libsbmlPINVOKE.Unit_isTesla(swigCPtr);
return ret;
}
/**
* Predicate for testing whether this Unit is of the kind @c volt
*
* @return @c true if the kind of this Unit is @c volt, @c false
* otherwise.
*/ public
bool isVolt() {
bool ret = libsbmlPINVOKE.Unit_isVolt(swigCPtr);
return ret;
}
/**
* Predicate for testing whether this Unit is of the kind @c watt
*
* @return @c true if the kind of this Unit is @c watt, @c false
* otherwise.
*/ public
bool isWatt() {
bool ret = libsbmlPINVOKE.Unit_isWatt(swigCPtr);
return ret;
}
/**
* Predicate for testing whether this Unit is of the kind @c weber
*
* @return @c true if the kind of this Unit is @c weber, @c false
* otherwise.
*/ public
bool isWeber() {
bool ret = libsbmlPINVOKE.Unit_isWeber(swigCPtr);
return ret;
}
/**
* Predicate to test whether the 'kind' attribute of this Unit is set.
*
* @return @c true if the 'kind' attribute of this Unit is set, @c
* false otherwise.
*/ public
bool isSetKind() {
bool ret = libsbmlPINVOKE.Unit_isSetKind(swigCPtr);
return ret;
}
/**
* Predicate to test whether the 'exponent' attribute of this Unit
* is set.
*
* @return @c true if the 'exponent' attribute of this Unit is set,
* @c false otherwise.
*/ public
bool isSetExponent() {
bool ret = libsbmlPINVOKE.Unit_isSetExponent(swigCPtr);
return ret;
}
/**
* Predicate to test whether the 'scale' attribute of this Unit
* is set.
*
* @return @c true if the 'scale' attribute of this Unit is set,
* @c false otherwise.
*/ public
bool isSetScale() {
bool ret = libsbmlPINVOKE.Unit_isSetScale(swigCPtr);
return ret;
}
/**
* Predicate to test whether the 'multiplier' attribute of this Unit
* is set.
*
* @return @c true if the 'multiplier' attribute of this Unit is set,
* @c false otherwise.
*/ public
bool isSetMultiplier() {
bool ret = libsbmlPINVOKE.Unit_isSetMultiplier(swigCPtr);
return ret;
}
/**
* Sets the 'kind' attribute value of this Unit.
*
* @if clike
* @param kind a value from the <a class='el'
* href='#UnitKind_t'>UnitKind_t</a> enumeration.
* @endif@if java
* @param kind a unit identifier chosen from the set of constants whose
* names begin with <code>UNIT_KIND_</code> in <code><a
* href='libsbmlcs.libsbml.html'>libsbmlConstants</a></code>.
* @endif@if python
* @param kind a unit identifier chosen from the set of constants whose
* names begin with <code>UNIT_KIND_</code> in @link libsbml libsbml@endlink.
* @endif
*
* @return integer value indicating success/failure of the
* function. The possible values
* returned by this function are:
* @li @link libsbmlcs.libsbml.LIBSBML_OPERATION_SUCCESS LIBSBML_OPERATION_SUCCESS @endlink
* @li @link libsbmlcs.libsbml.LIBSBML_INVALID_ATTRIBUTE_VALUE LIBSBML_INVALID_ATTRIBUTE_VALUE @endlink
*/ public
int setKind(int kind) {
int ret = libsbmlPINVOKE.Unit_setKind(swigCPtr, kind);
return ret;
}
/**
* Sets the 'exponent' attribute value of this Unit.
*
* @param value the integer to which the attribute 'exponent' should be set
*
* @return integer value indicating success/failure of the
* function. The possible values
* returned by this function are:
* @li @link libsbmlcs.libsbml.LIBSBML_OPERATION_SUCCESS LIBSBML_OPERATION_SUCCESS @endlink
* @li @link libsbmlcs.libsbml.LIBSBML_INVALID_ATTRIBUTE_VALUE LIBSBML_INVALID_ATTRIBUTE_VALUE @endlink
*/ public
int setExponent(int value) {
int ret = libsbmlPINVOKE.Unit_setExponent__SWIG_0(swigCPtr, value);
return ret;
}
/**
* Sets the 'exponent' attribute value of this Unit.
*
* @param value the double to which the attribute 'exponent' should be set
*
* @return integer value indicating success/failure of the
* function. The possible values
* returned by this function are:
* @li @link libsbmlcs.libsbml.LIBSBML_OPERATION_SUCCESS LIBSBML_OPERATION_SUCCESS @endlink
*/ public
int setExponent(double value) {
int ret = libsbmlPINVOKE.Unit_setExponent__SWIG_1(swigCPtr, value);
return ret;
}
/**
* Sets the 'scale' attribute value of this Unit.
*
* @param value the integer to which the attribute 'scale' should be set
*
* @return integer value indicating success/failure of the
* function. The possible values
* returned by this function are:
* @li @link libsbmlcs.libsbml.LIBSBML_OPERATION_SUCCESS LIBSBML_OPERATION_SUCCESS @endlink
*/ public
int setScale(int value) {
int ret = libsbmlPINVOKE.Unit_setScale(swigCPtr, value);
return ret;
}
/**
* Sets the 'multipler' attribute value of this Unit.
*
* @param value the floating-point value to which the attribute
* 'multiplier' should be set
*
* @return integer value indicating success/failure of the
* function. The possible values
* returned by this function are:
* @li @link libsbmlcs.libsbml.LIBSBML_OPERATION_SUCCESS LIBSBML_OPERATION_SUCCESS @endlink
* @li @link libsbmlcs.libsbml.LIBSBML_UNEXPECTED_ATTRIBUTE LIBSBML_UNEXPECTED_ATTRIBUTE @endlink
*/ public
int setMultiplier(double value) {
int ret = libsbmlPINVOKE.Unit_setMultiplier(swigCPtr, value);
return ret;
}
/**
* Sets the 'offset' attribute value of this Unit.
*
* @param value the float-point value to which the attribute 'offset'
* should set
*
* @return integer value indicating success/failure of the
* function. The possible values
* returned by this function are:
* @li @link libsbmlcs.libsbml.LIBSBML_OPERATION_SUCCESS LIBSBML_OPERATION_SUCCESS @endlink
* @li @link libsbmlcs.libsbml.LIBSBML_UNEXPECTED_ATTRIBUTE LIBSBML_UNEXPECTED_ATTRIBUTE @endlink
*
* *
* @warning <span class='warning'>The 'offset' attribute is only available in
* SBML Level 2 Version 1. This attribute is not present in SBML
* Level 2 Version 2 or above. When producing SBML models using
* these later specifications, modelers and software tools need to account
* for units with offsets explicitly. The %SBML specification document
* offers a number of suggestions for how to achieve this. LibSBML methods
* such as this one related to 'offset' are retained for compatibility with
* earlier versions of SBML Level 2, but their use is strongly
* discouraged.</span>
*
*/ public
int setOffset(double value) {
int ret = libsbmlPINVOKE.Unit_setOffset(swigCPtr, value);
return ret;
}
/**
* Returns the libSBML type code of this object instance.
*
* *
*
* LibSBML attaches an identifying code to every kind of SBML object. These
* are integer constants known as <em>SBML type codes</em>. The names of all
* the codes begin with the characters “<code>SBML_</code>”.
* @if clike The set of possible type codes for core elements is defined in
* the enumeration #SBMLTypeCode_t, and in addition, libSBML plug-ins for
* SBML Level 3 packages define their own extra enumerations of type
* codes (e.g., #SBMLLayoutTypeCode_t for the Level 3 Layout
* package).@endif@if java In the Java language interface for libSBML, the
* type codes are defined as static integer constants in the interface class
* {@link libsbmlConstants}. @endif@if python In the Python language
* interface for libSBML, the type codes are defined as static integer
* constants in the interface class @link libsbml@endlink.@endif@if csharp In
* the C# language interface for libSBML, the type codes are defined as
* static integer constants in the interface class
* @link libsbmlcs.libsbml@endlink.@endif Note that different Level 3
* package plug-ins may use overlapping type codes; to identify the package
* to which a given object belongs, call the <code>getPackageName()</code>
* method on the object.
*
*
*
* @return the SBML type code for this object:
* @link libsbmlcs.libsbml.SBML_UNIT SBML_UNIT@endlink (default).
*
* *
* @warning <span class='warning'>The specific integer values of the possible
* type codes may be reused by different Level 3 package plug-ins.
* Thus, to identifiy the correct code, <strong>it is necessary to invoke
* both getTypeCode() and getPackageName()</strong>.</span>
*
*
*
* @see getPackageName()
* @see getElementName()
*/ public new
int getTypeCode() {
int ret = libsbmlPINVOKE.Unit_getTypeCode(swigCPtr);
return ret;
}
/**
* Returns the XML element name of this object, which for Unit, is
* always @c 'unit'.
*
* @return the name of this element, i.e., @c 'unit'.
*/ public new
string getElementName() {
string ret = libsbmlPINVOKE.Unit_getElementName(swigCPtr);
return ret;
}
/**
* Predicate to test whether a given string is the name of a
* predefined SBML unit.
*
* @param name a string to be tested against the predefined unit names
*
* @param level the Level of SBML for which the determination should be
* made. This is necessary because there are a few small differences
* in allowed units between SBML Level 1 and Level 2.
*
* @return @c true if @p name is one of the five SBML predefined unit
* identifiers (@c 'substance', @c 'volume', @c 'area', @c 'length' or @c
* 'time'), @c false otherwise.
*
* @note The predefined unit identifiers @c 'length' and @c 'area' were
* added in Level 2 Version 1.
*
* @if notclike @note Because this is a @em static method, the
* non-C++ language interfaces for libSBML will contain two variants. One
* will be a static method on the class (i.e., Unit), and the
* other will be a standalone top-level function with the name
* Unit_isBuiltIn(). They are functionally
* identical. @endif
*/ public
static bool isBuiltIn(string name, long level) {
bool ret = libsbmlPINVOKE.Unit_isBuiltIn(name, level);
if (libsbmlPINVOKE.SWIGPendingException.Pending) throw libsbmlPINVOKE.SWIGPendingException.Retrieve();
return ret;
}
/**
* Predicate to test whether a given string is the name of a valid
* base unit in SBML (such as @c 'gram' or @c 'mole').
*
* This method exists because prior to SBML Level 2 Version 3,
* an enumeration called @c UnitKind was defined by SBML. This enumeration
* was removed in SBML Level 2 Version 3 and its values were
* folded into the space of values of a type called @c UnitSId. This method
* therefore has less significance in SBML Level 2 Version 3
* and Level 2 Version 4, but remains for backward
* compatibility and support for reading models in older Versions of
* Level 2.
*
* @param name a string to be tested
*
* @param level a long integer representing the SBML specification
* Level
*
* @param version a long integer representing the SBML specification
* Version
*
* @return @c true if name is a valid SBML UnitKind, @c false otherwise
*
* @note The allowed unit names differ between SBML Levels 1
* and 2 and again slightly between Level 2 Versions 1
* and 2.
*
* @if notclike @note Because this is a @em static method, the
* non-C++ language interfaces for libSBML will contain two variants. One
* will be a static method on the class (i.e., Unit), and the
* other will be a standalone top-level function with the name
* Unit_isUnitKind(). They are functionally
* identical. @endif
*/ public
static bool isUnitKind(string name, long level, long version) {
bool ret = libsbmlPINVOKE.Unit_isUnitKind(name, level, version);
if (libsbmlPINVOKE.SWIGPendingException.Pending) throw libsbmlPINVOKE.SWIGPendingException.Retrieve();
return ret;
}
/**
* Predicate returning @c true if two
* Unit objects are identical.
*
* Two Unit objects are considered to be @em identical if they match in
* all attributes. (Contrast this to the method areEquivalent(@if java
* Unit u1, %Unit u2@endif), which compares Unit objects only with respect
* to certain attributes.)
*
* @param unit1 the first Unit object to compare
* @param unit2 the second Unit object to compare
*
* @return @c true if all the attributes of unit1 are identical
* to the attributes of unit2, @c false otherwise.
*
* @if notclike @note Because this is a @em static method, the
* non-C++ language interfaces for libSBML will contain two variants. One
* will be a static method on the class (i.e., Unit), and the
* other will be a standalone top-level function with the name
* Unit_areIdentical(). They are functionally
* identical. @endif
*
* @see @if clike areEquivalent() @else Unit::areEquivalent(Unit u1, %Unit u2) @endif
*/ public
static bool areIdentical(Unit unit1, Unit unit2) {
bool ret = libsbmlPINVOKE.Unit_areIdentical(Unit.getCPtr(unit1), Unit.getCPtr(unit2));
return ret;
}
/**
* Predicate returning @c true if
* Unit objects are equivalent.
*
* Two Unit objects are considered to be @em equivalent either if (1) both
* have a 'kind' attribute value of @c dimensionless, or (2) their 'kind',
* 'exponent' and (for SBML Level 2 Version 1) 'offset'
* attribute values are equal. (Contrast this to the method
* areIdentical(@if java Unit u1, %Unit u2@endif), which compares Unit objects with respect to all
* attributes, not just the 'kind' and 'exponent'.)
*
* @param unit1 the first Unit object to compare
* @param unit2 the second Unit object to compare
*
* @return @c true if the 'kind' and 'exponent' attributes of unit1 are
* identical to the kind and exponent attributes of unit2, @c false
* otherwise.
*
* @if notclike @note Because this is a @em static method, the
* non-C++ language interfaces for libSBML will contain two variants. One
* will be a static method on the class (i.e., Unit), and the
* other will be a standalone top-level function with the name
* Unit_areEquivalent(). They are functionally
* identical. @endif
*
* @see @if clike areIdentical() @else Unit::areIdentical(Unit u1, %Unit u2) @endif
*/ public
static bool areEquivalent(Unit unit1, Unit unit2) {
bool ret = libsbmlPINVOKE.Unit_areEquivalent(Unit.getCPtr(unit1), Unit.getCPtr(unit2));
return ret;
}
/**
* Manipulates the attributes of the Unit to express the unit with the
* value of the scale attribute reduced to zero.
*
* For example, 1 millimetre can be expressed as a Unit with kind=@c
* 'metre' multiplier=@c '1' scale=@c '-3' exponent=@c '1'. It can also be
* expressed as a Unit with kind=@c 'metre'
* multiplier=<code>'0.001'</code> scale=@c '0' exponent=@c '1'.
*
* @param unit the Unit object to manipulate.
*
* @return integer value indicating success/failure of the function. The
* possible values returned by this function are:
* @li @link libsbmlcs.libsbml.LIBSBML_OPERATION_SUCCESS LIBSBML_OPERATION_SUCCESS @endlink
*
* @if notclike @note Because this is a @em static method, the
* non-C++ language interfaces for libSBML will contain two variants. One
* will be a static method on the class (i.e., Unit), and the
* other will be a standalone top-level function with the name
* Unit_removeScale(). They are functionally
* identical. @endif
*
* @see @if clike convertToSI() @else Unit::convertToSI(Unit u) @endif
* @see @if clike merge() @else Unit::merge(Unit u1, Unit u2) @endif
*/ public
static int removeScale(Unit unit) {
int ret = libsbmlPINVOKE.Unit_removeScale(Unit.getCPtr(unit));
return ret;
}
/**
* Merges two Unit objects with the same 'kind' attribute value into a
* single Unit.
*
* For example, the following,
* @verbatim
<unit kind='metre' exponent='2'/>
<unit kind='metre' exponent='1'/>
@endverbatim
* would be merged to become
* @verbatim
<unit kind='metre' exponent='3'/>
@endverbatim
*
* @param unit1 the first Unit object; the result of the operation is
* left as a new version of this unit, modified in-place.
*
* @param unit2 the second Unit object to merge with the first
*
* @if notclike @note Because this is a @em static method, the
* non-C++ language interfaces for libSBML will contain two variants. One
* will be a static method on the class (i.e., Unit), and the
* other will be a standalone top-level function with the name
* Unit_merge(). They are functionally
* identical. @endif
*
* @see @if clike convertToSI() @else Unit::convertToSI(Unit u) @endif
* @see @if clike removeScale() @else Unit::removeScale(Unit u) @endif
*/ public
static void merge(Unit unit1, Unit unit2) {
libsbmlPINVOKE.Unit_merge(Unit.getCPtr(unit1), Unit.getCPtr(unit2));
}
/**
* Returns a UnitDefinition object containing the given @p unit converted
* to the appropriate SI unit.
*
* This method exists because some units can be expressed in terms of
* others when the same physical dimension is involved. For example, one
* hertz is identical to 1 sec<sup>-1</sup>, one litre is equivalent
* to 1 cubic decametre, and so on.
*
* @param unit the Unit object to convert to SI
*
* @return a UnitDefinition object containing the SI unit.
*
* @if notclike @note Because this is a @em static method, the
* non-C++ language interfaces for libSBML will contain two variants. One
* will be a static method on the class (i.e., Unit), and the
* other will be a standalone top-level function with the name
* Unit_convertToSI(). They are functionally
* identical. @endif
*
* @see @if clike merge() @else Unit::merge(Unit u1, Unit u2) @endif
*/ public
static UnitDefinition convertToSI(Unit unit) {
IntPtr cPtr = libsbmlPINVOKE.Unit_convertToSI(Unit.getCPtr(unit));
UnitDefinition ret = (cPtr == IntPtr.Zero) ? null : new UnitDefinition(cPtr, true);
return ret;
}
/**
* Predicate returning @c true if
* all the required attributes for this Unit object
* have been set.
*
* @note The required attributes for a Unit object are:
* @li 'kind'
* @li 'exponent' (required in SBML Level 3; optional in Level 2)
* @li 'multiplier' (required in SBML Level 3; optional in Level 2)
* @li 'scale' (required in SBML Level 3; optional in Level 2)
*
* @return a bool value indicating whether all the required
* elements for this object have been defined.
*/ public new
bool hasRequiredAttributes() {
bool ret = libsbmlPINVOKE.Unit_hasRequiredAttributes(swigCPtr);
return ret;
}
}
}
| 33.483146 | 108 | 0.687562 | [
"Apache-2.0"
] | 0u812/roadrunner | third_party/libSBML-5.9.0-Source/src/bindings/csharp/csharp-files/Unit.cs | 44,700 | C# |
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
namespace IoTSharp.Data
{
public static class IoTSharpClaimTypes
{
public const string Customer = "http://schemas.iotsharp.net/ws/2019/01/identity/claims/customer";
public const string Tenant = "http://schemas.iotsharp.net/ws/2019/01/identity/claims/tenant";
}
public enum ApiCode : int
{
Success = 10000,
LoginError = 10001,
Exception = 10002,
AlreadyExists = 10003,
NotFoundTenantOrCustomer = 10004,
NotFoundDevice = 10005,
NotFoundCustomer = 10006,
NothingToDo = 10007,
DoNotAllow = 10008,
NotFoundTenant = 10009,
NotFoundDeviceIdentity = 10010,
RPCFailed = 10011,
RPCTimeout = 10012,
CustomerDoesNotHaveDevice = 10013,
CreateUserFailed = 10014,
CantFindObject = 10015,
InValidData = 10016,
}
public enum DataCatalog
{
None,
AttributeData,
AttributeLatest,
TelemetryData,
TelemetryLatest,
}
[System.Text.Json.Serialization.JsonConverter(typeof(System.Text.Json.Serialization.JsonStringEnumConverter))]
[JsonConverter(typeof(StringEnumConverter))]
public enum DataSide
{
AnySide,
ServerSide,
ClientSide,
}
[System.Text.Json.Serialization.JsonConverter(typeof(System.Text.Json.Serialization.JsonStringEnumConverter))]
[JsonConverter(typeof(StringEnumConverter))]
public enum UserRole
{
Anonymous,
NormalUser,
CustomerAdmin,
TenantAdmin,
SystemAdmin,
}
[System.Text.Json.Serialization.JsonConverter(typeof(System.Text.Json.Serialization.JsonStringEnumConverter))]
[JsonConverter(typeof(StringEnumConverter))]
public enum DataType
{
Boolean,
String,
Long,
Double,
Json,
XML,
Binary,
DateTime
}
[System.Text.Json.Serialization.JsonConverter(typeof(System.Text.Json.Serialization.JsonStringEnumConverter))]
[JsonConverter(typeof(StringEnumConverter))]
public enum DataBaseType
{
PostgreSql,
SqlServer,
MySql ,
Oracle ,
Sqlite,
InMemory
}
[System.Text.Json.Serialization.JsonConverter(typeof(System.Text.Json.Serialization.JsonStringEnumConverter))]
[JsonConverter(typeof(StringEnumConverter))]
public enum IdentityType
{
AccessToken,
DevicePassword,
X509Certificate
}
[System.Text.Json.Serialization.JsonConverter(typeof(System.Text.Json.Serialization.JsonStringEnumConverter))]
[JsonConverter(typeof(StringEnumConverter))]
public enum ObjectType
{
Unknow,
Device,
Tenant,
Customer,
User,
MQTTBroker,
MQTTClient
}
[System.Text.Json.Serialization.JsonConverter(typeof(System.Text.Json.Serialization.JsonStringEnumConverter))]
[JsonConverter(typeof(StringEnumConverter))]
public enum DeviceType
{
Device = 0,
Gateway = 1
}
[System.Text.Json.Serialization.JsonConverter(typeof(System.Text.Json.Serialization.JsonStringEnumConverter))]
[JsonConverter(typeof(StringEnumConverter))]
public enum CoApRes
{
Attributes,
Telemetry,
}
[System.Text.Json.Serialization.JsonConverter(typeof(System.Text.Json.Serialization.JsonStringEnumConverter))]
[JsonConverter(typeof(StringEnumConverter))]
public enum RuleType
{
RuleNode,
RuleSwitcher
}
[System.Text.Json.Serialization.JsonConverter(typeof(System.Text.Json.Serialization.JsonStringEnumConverter))]
[JsonConverter(typeof(StringEnumConverter))]
public enum EventType
{
Normal=1,
TestPurpose=2
}
public enum NodeStatus
{
Abort = -1,
Created = 0,
Processing =1,
Suspend = 2,
Complete = 1,
}
public enum MsgType
{
MQTT,
CoAP,
HTTP
}
public enum MountType
{
RAW = 0,
Telemetry =1,
Attribute=2,
RPC=3,
Online = 4,
Offline=5
}
} | 25.578947 | 114 | 0.642433 | [
"MIT"
] | NanoFabricFX/IoTSharp | IoTSharp.Data/Enums.cs | 4,376 | C# |
#region License
// Copyright 2004-2010 Castle Project - http://www.castleproject.org/
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#endregion
namespace Castle.Facilities.NHibernateIntegration.Util
{
using System;
using System.Collections.Generic;
using System.Reflection;
/// <summary>
/// Utility classes for NHibernate. Contains methods to get properties of an entity etc.
/// </summary>
public class ReflectionUtility
{
/// <summary>
/// Gets the readable (non indexed) properties names and values.
/// The keys holds the names of the properties.
/// The values are the values of the properties
/// </summary>
public static IDictionary<string, object> GetPropertiesDictionary(object obj)
{
IDictionary<string, object> ht = new Dictionary<string, object>();
foreach (PropertyInfo property in obj.GetType().
GetProperties(BindingFlags.Instance |
BindingFlags.GetProperty | BindingFlags.Public |
BindingFlags.NonPublic))
{
if (property.CanRead && property.GetIndexParameters().Length == 0)
{
ht[property.Name] = property.GetValue(obj, null);
}
}
return ht;
}
/// <summary>
/// Determines whether type is simple enough to need just ToString()
/// to show its state.
/// (string,int, bool, enums are simple.
/// Anything else is false.
/// </summary>
public static bool IsSimpleType(Type type)
{
if (type.IsEnum || type.IsPrimitive || type == typeof (string)
|| type == typeof (DateTime))
return true;
else
return false;
}
}
} | 30.882353 | 89 | 0.687143 | [
"Apache-2.0"
] | ByteDecoder/Castle.Facilities.NHibernateIntegration | src/Castle.Facilities.NHibernateIntegration/Util/ReflectionUtility.cs | 2,102 | C# |
using Buildersoft.Andy.X.Data.Model;
using System;
using System.Collections.Generic;
using System.Text;
namespace Buildersoft.Andy.X.Logic.Interfaces.Components
{
public interface IComponentLogic
{
Component CreateComponent(string name);
Component GetComponent(string name);
List<Component> GetAllComponents();
}
}
| 23.533333 | 56 | 0.733711 | [
"Apache-2.0"
] | buildersoftdev/andyx | src/Buildersoft.Andy.X.Logic/Repositories/Interfaces/Components/IComponentLogic.cs | 355 | C# |
#nullable enable
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Maui.Animations;
using Microsoft.Maui.Graphics;
namespace Microsoft.Maui.Controls
{
/// <include file="../../docs/Microsoft.Maui.Controls/ViewExtensions.xml" path="Type[@FullName='Microsoft.Maui.Controls.ViewExtensions']/Docs" />
public static class ViewExtensions
{
/// <include file="../../docs/Microsoft.Maui.Controls/ViewExtensions.xml" path="//Member[@MemberName='CancelAnimations']/Docs" />
public static void CancelAnimations(this VisualElement view)
{
if (view == null)
throw new ArgumentNullException(nameof(view));
view.AbortAnimation(nameof(LayoutTo));
view.AbortAnimation(nameof(TranslateTo));
view.AbortAnimation(nameof(RotateTo));
view.AbortAnimation(nameof(RotateYTo));
view.AbortAnimation(nameof(RotateXTo));
view.AbortAnimation(nameof(ScaleTo));
view.AbortAnimation(nameof(ScaleXTo));
view.AbortAnimation(nameof(ScaleYTo));
view.AbortAnimation(nameof(FadeTo));
}
static Task<bool> AnimateTo(this VisualElement view, double start, double end, string name,
Action<VisualElement, double> updateAction, uint length = 250, Easing? easing = null)
{
if (easing == null)
easing = Easing.Linear;
var tcs = new TaskCompletionSource<bool>();
var weakView = new WeakReference<VisualElement>(view);
void UpdateProperty(double f)
{
if (weakView.TryGetTarget(out VisualElement? v))
{
updateAction(v, f);
}
}
new Animation(UpdateProperty, start, end, easing).Commit(view, name, 16, length, finished: (f, a) => tcs.SetResult(a));
return tcs.Task;
}
/// <include file="../../docs/Microsoft.Maui.Controls/ViewExtensions.xml" path="//Member[@MemberName='FadeTo']/Docs" />
public static Task<bool> FadeTo(this VisualElement view, double opacity, uint length = 250, Easing? easing = null)
{
if (view == null)
throw new ArgumentNullException(nameof(view));
return AnimateTo(view, view.Opacity, opacity, nameof(FadeTo), (v, value) => v.Opacity = value, length, easing);
}
/// <include file="../../docs/Microsoft.Maui.Controls/ViewExtensions.xml" path="//Member[@MemberName='LayoutTo']/Docs" />
public static Task<bool> LayoutTo(this VisualElement view, Rect bounds, uint length = 250, Easing? easing = null)
{
if (view == null)
throw new ArgumentNullException(nameof(view));
Rect start = view.Bounds;
Func<double, Rect> computeBounds = progress =>
{
double x = start.X + (bounds.X - start.X) * progress;
double y = start.Y + (bounds.Y - start.Y) * progress;
double w = start.Width + (bounds.Width - start.Width) * progress;
double h = start.Height + (bounds.Height - start.Height) * progress;
return new Rect(x, y, w, h);
};
return AnimateTo(view, 0, 1, nameof(LayoutTo), (v, value) => v.Layout(computeBounds(value)), length, easing);
}
/// <include file="../../docs/Microsoft.Maui.Controls/ViewExtensions.xml" path="//Member[@MemberName='RelRotateTo']/Docs" />
public static Task<bool> RelRotateTo(this VisualElement view, double drotation, uint length = 250, Easing? easing = null)
{
if (view == null)
throw new ArgumentNullException(nameof(view));
return view.RotateTo(view.Rotation + drotation, length, easing);
}
/// <include file="../../docs/Microsoft.Maui.Controls/ViewExtensions.xml" path="//Member[@MemberName='RelScaleTo']/Docs" />
public static Task<bool> RelScaleTo(this VisualElement view, double dscale, uint length = 250, Easing? easing = null)
{
if (view == null)
throw new ArgumentNullException(nameof(view));
return view.ScaleTo(view.Scale + dscale, length, easing);
}
/// <include file="../../docs/Microsoft.Maui.Controls/ViewExtensions.xml" path="//Member[@MemberName='RotateTo']/Docs" />
public static Task<bool> RotateTo(this VisualElement view, double rotation, uint length = 250, Easing? easing = null)
{
if (view == null)
throw new ArgumentNullException(nameof(view));
return AnimateTo(view, view.Rotation, rotation, nameof(RotateTo), (v, value) => v.Rotation = value, length, easing);
}
/// <include file="../../docs/Microsoft.Maui.Controls/ViewExtensions.xml" path="//Member[@MemberName='RotateXTo']/Docs" />
public static Task<bool> RotateXTo(this VisualElement view, double rotation, uint length = 250, Easing? easing = null)
{
if (view == null)
throw new ArgumentNullException(nameof(view));
return AnimateTo(view, view.RotationX, rotation, nameof(RotateXTo), (v, value) => v.RotationX = value, length, easing);
}
/// <include file="../../docs/Microsoft.Maui.Controls/ViewExtensions.xml" path="//Member[@MemberName='RotateYTo']/Docs" />
public static Task<bool> RotateYTo(this VisualElement view, double rotation, uint length = 250, Easing? easing = null)
{
if (view == null)
throw new ArgumentNullException(nameof(view));
return AnimateTo(view, view.RotationY, rotation, nameof(RotateYTo), (v, value) => v.RotationY = value, length, easing);
}
/// <include file="../../docs/Microsoft.Maui.Controls/ViewExtensions.xml" path="//Member[@MemberName='ScaleTo']/Docs" />
public static Task<bool> ScaleTo(this VisualElement view, double scale, uint length = 250, Easing? easing = null)
{
if (view == null)
throw new ArgumentNullException(nameof(view));
return AnimateTo(view, view.Scale, scale, nameof(ScaleTo), (v, value) => v.Scale = value, length, easing);
}
/// <include file="../../docs/Microsoft.Maui.Controls/ViewExtensions.xml" path="//Member[@MemberName='ScaleXTo']/Docs" />
public static Task<bool> ScaleXTo(this VisualElement view, double scale, uint length = 250, Easing? easing = null)
{
if (view == null)
throw new ArgumentNullException(nameof(view));
return AnimateTo(view, view.ScaleX, scale, nameof(ScaleXTo), (v, value) => v.ScaleX = value, length, easing);
}
/// <include file="../../docs/Microsoft.Maui.Controls/ViewExtensions.xml" path="//Member[@MemberName='ScaleYTo']/Docs" />
public static Task<bool> ScaleYTo(this VisualElement view, double scale, uint length = 250, Easing? easing = null)
{
if (view == null)
throw new ArgumentNullException(nameof(view));
return AnimateTo(view, view.ScaleY, scale, nameof(ScaleYTo), (v, value) => v.ScaleY = value, length, easing);
}
/// <include file="../../docs/Microsoft.Maui.Controls/ViewExtensions.xml" path="//Member[@MemberName='TranslateTo']/Docs" />
public static Task<bool> TranslateTo(this VisualElement view, double x, double y, uint length = 250, Easing? easing = null)
{
if (view == null)
throw new ArgumentNullException(nameof(view));
easing ??= Easing.Linear;
var tcs = new TaskCompletionSource<bool>();
var weakView = new WeakReference<VisualElement>(view);
Action<double> translateX = f =>
{
if (weakView.TryGetTarget(out VisualElement? v))
v.TranslationX = f;
};
Action<double> translateY = f =>
{
if (weakView.TryGetTarget(out VisualElement? v))
v.TranslationY = f;
};
new Animation
{
{ 0, 1, new Animation(translateX, view.TranslationX, x, easing: easing) },
{ 0, 1, new Animation(translateY, view.TranslationY, y, easing: easing) }
}.Commit(view, nameof(TranslateTo), 16, length, null, (f, a) => tcs.SetResult(a));
return tcs.Task;
}
internal static IAnimationManager GetAnimationManager(this IAnimatable animatable)
{
if (animatable is Element e && e.FindMauiContext() is IMauiContext mauiContext)
return mauiContext.GetAnimationManager();
throw new ArgumentException($"Unable to find {nameof(IAnimationManager)} for '{animatable.GetType().FullName}'.", nameof(animatable));
}
internal static IMauiContext RequireMauiContext(this Element element, bool fallbackToAppMauiContext = false)
=> element.FindMauiContext(fallbackToAppMauiContext) ?? throw new InvalidOperationException($"{nameof(IMauiContext)} not found.");
internal static IMauiContext? FindMauiContext(this Element element, bool fallbackToAppMauiContext = false)
{
if (element is Maui.IElement fe && fe.Handler?.MauiContext != null)
return fe.Handler.MauiContext;
foreach (var parent in element.GetParentsPath())
{
if (parent is Maui.IElement parentView && parentView.Handler?.MauiContext != null)
return parentView.Handler.MauiContext;
}
return fallbackToAppMauiContext ? Application.Current?.FindMauiContext() : default;
}
internal static IFontManager RequireFontManager(this Element element, bool fallbackToAppMauiContext = false)
=> element.RequireMauiContext(fallbackToAppMauiContext).Services.GetRequiredService<IFontManager>();
internal static double GetDefaultFontSize(this Element element)
=> element.FindMauiContext()?.Services?.GetService<IFontManager>()?.DefaultFontSize ?? 0d;
internal static Element? FindParentWith(this Element element, Func<Element, bool> withMatch, bool includeThis = false)
{
if (includeThis && withMatch(element))
return element;
foreach (var parent in element.GetParentsPath())
{
if (withMatch(parent))
return parent;
}
return default;
}
internal static T? FindParentOfType<T>(this Element element, bool includeThis = false)
where T : Maui.IElement
{
if (includeThis && element is T view)
return view;
foreach (var parent in element.GetParentsPath())
{
if (parent is T parentView)
return parentView;
}
return default;
}
internal static IEnumerable<Element> GetParentsPath(this Element self)
{
Element current = self;
while (!Application.IsApplicationOrNull(current.RealParent))
{
current = current.RealParent;
yield return current;
}
}
internal static List<Page> GetParentPages(this Page target)
{
var result = new List<Page>();
var parent = target.RealParent as Page;
while (!Application.IsApplicationOrWindowOrNull(parent))
{
result.Add(parent!);
parent = parent!.RealParent as Page;
}
return result;
}
internal static string? GetStringValue(this IView element)
{
string? text = null;
if (element is ILabel label)
text = label.Text;
else if (element is IEntry entry)
text = entry.Text;
else if (element is IEditor editor)
text = editor.Text;
else if (element is ITimePicker tp)
text = tp.Time.ToString();
else if (element is IDatePicker dp)
text = dp.Date.ToString();
else if (element is ICheckBox cb)
text = cb.IsChecked.ToString();
else if (element is ISwitch sw)
text = sw.IsOn.ToString();
else if (element is IRadioButton rb)
text = rb.IsChecked.ToString();
return text;
}
internal static bool TrySetValue(this Element element, string text)
{
if (element is Label label)
{
label.Text = text;
return true;
}
else if (element is Entry entry)
{
entry.Text = text;
return true;
}
else if (element is Editor editor)
{
editor.Text = text;
return true;
}
else if (element is CheckBox cb && bool.TryParse(text, out bool result))
{
cb.IsChecked = result;
return true;
}
else if (element is Switch sw && bool.TryParse(text, out bool swResult))
{
sw.IsToggled = swResult;
return true;
}
else if (element is RadioButton rb && bool.TryParse(text, out bool rbResult))
{
rb.IsChecked = rbResult;
return true;
}
else if (element is TimePicker tp && TimeSpan.TryParse(text, out TimeSpan tpResult))
{
tp.Time = tpResult;
return true;
}
else if (element is DatePicker dp && DateTime.TryParse(text, out DateTime dpResult))
{
dp.Date = dpResult;
return true;
}
return false;
}
}
}
| 34.548387 | 146 | 0.695017 | [
"MIT"
] | AlexanderSemenyak/maui | src/Controls/src/Core/ViewExtensions.cs | 11,781 | C# |
using System.Net;
using System.Threading;
namespace Softfire.MonoGame.NTWK
{
public class NetPeerConfiguration
{
#region MTU
/// <summary>
/// Default MTU.
/// </summary>
public const int DefaultMtu = 1408;
/// <summary>
/// Maximum MTU.
/// </summary>
public int MaximumMtu { get; private set; }
/// <summary>
/// Is Auto Expanding Mtu.
/// </summary>
public bool IsAutoExpandingMtu { get; private set; }
/// <summary>
/// MTU Expansion Interval.
/// </summary>
public float MtuExpansionInterval { get; private set; }
/// <summary>
/// Maximum MTU Expansion Attempts.
/// </summary>
public int MaximumMtuExpansionAttempts { get; private set; }
#endregion
/// <summary>
/// Log File Path.
/// </summary>
public string LogFilePath { get; private set; }
/// <summary>
/// Is Locked.
/// Unable to be editted if locked.
/// </summary>
public bool IsLocked { get; private set; } = false;
/// <summary>
/// Is Accepting Connections.
/// </summary>
public bool IsAcceptingConnections { get; private set; } = false;
/// <summary>
/// Identifier.
/// </summary>
public string Identifier { get; private set; }
/// <summary>
/// Thread Name.
/// </summary>
public Thread Thread { get; private set; }
/// <summary>
/// Thread Name.
/// </summary>
public string ThreadName => Thread?.Name;
/// <summary>
/// Local IP Address.
/// </summary>
public IPAddress LocalAddress { get; private set; }
/// <summary>
/// Broadcast IP Address.
/// </summary>
public IPAddress BroadcastAddress { get; private set; }
/// <summary>
/// Port.
/// </summary>
public int Port { get; private set; }
/// <summary>
/// Receive Buffer Size.
/// </summary>
public int ReceiveBufferSize { get; private set; } = 131071;
/// <summary>
/// Send Buffer Size.
/// </summary>
public int SendBufferSize { get; private set; } = 131071;
/// <summary>
/// Maximum Connections.
/// </summary>
public int MaximumConnections { get; private set; } = 32;
/// <summary>
/// Ping Interval.
/// </summary>
public float PingInterval { get; private set; } = 4.0f;
/// <summary>
/// Connection Time Out.
/// </summary>
public float ConnectionTimeOut { get; private set; } = 25.0f;
/// <summary>
/// Reconnection Interval.
/// </summary>
public float ReconnectionInterval { get; private set; } = 3.0f;
/// <summary>
/// Maximum Reconnection Attempts.
/// </summary>
public int MaximumReconnectionAttempts { get; private set; } = 5;
/// <summary>
/// Peer Type.
/// </summary>
public PeerTypes PeerType { get; private set; }
/// <summary>
/// Peer Types.
/// </summary>
public enum PeerTypes
{
Peer,
Client,
Server
}
/// <summary>
/// Default Constructor.
/// </summary>
public NetPeerConfiguration()
{
Identifier = "Softfire.MonoGame.NTWK";
LogFilePath = @"Config\Logs\";
}
/// <summary>
/// Net Peer Configuration Constructor.
/// </summary>
/// <param name="identifier">A unique identifier. Intaken as a <see cref="string"/>.</param>
/// <param name="logFilePath">The path to store the NetPeer's log file.</param>
/// <param name="peerType">The Type of Peer. Used in LogFilePath to store logs.</param>
public NetPeerConfiguration(string identifier = "Softfire.MonoGame.NTWK", string logFilePath = @"Config\Logs\", PeerTypes peerType = PeerTypes.Peer)
{
Identifier = identifier;
if (logFilePath == @"Config\Logs\")
{
switch (peerType)
{
case PeerTypes.Peer:
LogFilePath = logFilePath + "Peer";
break;
case PeerTypes.Client:
LogFilePath = logFilePath + "Client";
break;
case PeerTypes.Server:
LogFilePath = logFilePath + "Server";
break;
}
}
else
{
LogFilePath = logFilePath;
}
PeerType = peerType;
}
/// <summary>
/// Lock.
/// Locks against edits.
/// Only usable with an Unstarted/Stopped Thread.
/// </summary>
public void Lock()
{
if (Thread != null &&
(Thread.ThreadState == ThreadState.Unstarted ||
Thread.ThreadState == ThreadState.Stopped))
{
IsLocked = true;
}
}
/// <summary>
/// Unlock.
/// Unlocks config for editting.
/// Only usable with an Unstarted/Stopped Thread.
/// </summary>
public void UnLock()
{
if (Thread == null ||
(Thread.ThreadState == ThreadState.Unstarted ||
Thread.ThreadState == ThreadState.Stopped))
{
IsLocked = false;
}
}
/// <summary>
/// Set Identifier.
/// </summary>
/// <param name="identifier">A unique identifier. Peers must have matching identifiers to communicate.</param>
/// <returns>Returns a <see cref="bool"/> indicating whether the Identifier was set.</returns>
public bool SetIdentifier(string identifier)
{
var result = false;
if (!IsLocked)
{
Identifier = identifier;
result = true;
}
return result;
}
/// <summary>
/// Set Local Address And Port.
/// Can only be used if IsLocked is false.
/// </summary>
/// <param name="ipAddress">IPAddress to set to Local Address.</param>
/// <param name="port">The port on which to listen.</param>
/// <returns>Returns a <see cref="bool"/> indicating whether the Local Address and Port were set.</returns>
public bool SetLocalAddressAndPort(IPAddress ipAddress, int port)
{
var result = false;
if (!IsLocked)
{
LocalAddress = ipAddress;
Port = port;
BroadcastAddress = NetCommon.GetIpV4BroadcastAddress(ipAddress).Item2;
result = true;
}
return result;
}
/// <summary>
/// Set Send Buffer Size.
/// </summary>
/// <param name="sendBufferSize">The receive buffer size.</param>
/// <returns>Returns a <see cref="bool"/> indicating whether the Send Buffer was set.</returns>
public bool SetSendBufferSize(int sendBufferSize)
{
var result = false;
if (!IsLocked)
{
SendBufferSize = sendBufferSize;
result = true;
}
return result;
}
/// <summary>
/// Set Receive Buffer Size.
/// </summary>
/// <param name="receiveBufferSize">The receive buffer size.</param>
/// <returns>Returns a <see cref="bool"/> indicating whether the Receive Buffer was set.</returns>
public bool SetReceiveBufferSize(int receiveBufferSize)
{
var result = false;
if (!IsLocked)
{
ReceiveBufferSize = receiveBufferSize;
result = true;
}
return result;
}
/// <summary>
/// Set Thread.
/// </summary>
/// <param name="thread">Intakes the Thread used by the NetPeer.</param>
/// <returns>Returns a <see cref="bool"/> indicating whether the Thread was set.</returns>
public bool SetThread(Thread thread)
{
var result = false;
if (!IsLocked)
{
Thread = thread;
result = true;
}
return result;
}
/// <summary>
/// Set Maximum Connections.
/// </summary>
/// <param name="maximumConnections">The maximum connections allowed.</param>
/// <returns>Returns a <see cref="bool"/> indicating whether the Maximum Connections were set.</returns>
public bool SetMaximumConnections(int maximumConnections)
{
var result = false;
if (!IsLocked)
{
MaximumConnections = maximumConnections;
result = true;
}
return result;
}
/// <summary>
/// Set Maximum MTU.
/// Maximum Transmission Unit.
/// </summary>
/// <param name="maximumMtu">The maximum MTU size.</param>
/// <returns>Returns a <see cref="bool"/> indicating whether the Maximum MTU was set.</returns>
public bool SetMaximumMtu(int maximumMtu)
{
var result = false;
if (!IsLocked)
{
MaximumMtu = maximumMtu;
result = true;
}
return result;
}
/// <summary>
/// Set Ping Interval.
/// </summary>
/// <param name="pingInterval">The amount of time between latency calculations.</param>
/// <returns>Returns a <see cref="bool"/> indicating whether the Pint Interval was set.</returns>
public bool SetPingInterval(float pingInterval)
{
var result = false;
if (!IsLocked)
{
PingInterval = pingInterval;
result = true;
}
return result;
}
/// <summary>
/// Set Connection Time Out.
/// </summary>
/// <param name="connectionTimeOut">The time out period in which to drop connections if unreachable.</param>
/// <returns>Returns a <see cref="bool"/> indicating whether the Connection Time Out was set.</returns>
public bool SetConnectionTimeOut(int connectionTimeOut)
{
var result = false;
if (!IsLocked)
{
ConnectionTimeOut = connectionTimeOut;
result = true;
}
return result;
}
/// <summary>
/// Set Reconnection Interval.
/// </summary>
/// <param name="reconnectionInterval">The time period in which to try reconnecting to peers.</param>
/// <returns>Returns a <see cref="bool"/> indicating whether the Reconnection Interval was set.</returns>
public bool SetReconnectionInterval(float reconnectionInterval)
{
var result = false;
if (!IsLocked)
{
ReconnectionInterval = reconnectionInterval;
result = true;
}
return result;
}
/// <summary>
/// Set Maximum Reconnection Attempts
/// </summary>
/// <param name="maximumReconnectionAttempts">The maximum number of reconnection attempts when reconnecting to peers.</param>
/// <returns>Returns a <see cref="bool"/> indicating whether the Maximum Reconnection Attempts were set.</returns>
public bool SetMaximumReconnectionAttempts(int maximumReconnectionAttempts)
{
var result = false;
if (!IsLocked)
{
MaximumReconnectionAttempts = maximumReconnectionAttempts;
result = true;
}
return result;
}
/// <summary>
/// Set Accepting Connections.
/// </summary>
/// <param name="isAcceptingConnections">A boolean indicating whether the peer is accepting connections.</param>
/// <returns>Returns a <see cref="bool"/> indicating whether the IsAcceptingConnections was set.</returns>
public bool SetAcceptingConnections(bool isAcceptingConnections)
{
var result = false;
if (!IsLocked)
{
IsAcceptingConnections = isAcceptingConnections;
result = true;
}
return result;
}
/// <summary>
/// Set MTU Auto Expansion.
/// </summary>
/// <param name="isAutoExpandingMtu">A boolean indicating whether the MTU is auto expanding.</param>
/// <returns>Returns a <see cref="bool"/> indicating whether the IsAutoExpandingMtu was set.</returns>
public bool SetMtuAutoExpansion(bool isAutoExpandingMtu)
{
var result = false;
if (!IsLocked)
{
IsAutoExpandingMtu = isAutoExpandingMtu;
result = true;
}
return result;
}
/// <summary>
/// Set Maximum MTU Expansion Attempts
/// </summary>
/// <param name="maximumMtuExpansionAttempts">The maximum number of mtu expansion attempts.</param>
/// <returns>Returns a <see cref="bool"/> indicating whether the Maximum MTU Expansion Attempts were set.</returns>
public bool SetMaximumMtuExpansionAttempts(int maximumMtuExpansionAttempts)
{
var result = false;
if (!IsLocked)
{
MaximumMtuExpansionAttempts = maximumMtuExpansionAttempts;
result = true;
}
return result;
}
/// <summary>
/// Set Mtu Expansion Interval.
/// </summary>
/// <param name="mtuExpansionInterval">The time period between MTU expansion attempts.</param>
/// <returns>Returns a <see cref="bool"/> indicating whether the MTU Expansion Interval was set.</returns>
public bool SetMtuExpansionInterval(float mtuExpansionInterval)
{
var result = false;
if (!IsLocked)
{
MtuExpansionInterval = mtuExpansionInterval;
result = true;
}
return result;
}
}
} | 30.53527 | 156 | 0.515559 | [
"MIT"
] | Softfire/softfire-monogame-libraries | Softfire.MonoGame.NTWK/NetPeerConfiguration.cs | 14,720 | C# |
using System;
namespace NetTopologySuite.IO.VectorTiles.Tiles.WebMercator
{
public static class WebMercatorHandler
{
// https://gist.github.com/nagasudhirpulla/9b5a192ccaca3c5992e5d4af0d1e6dc4
private const int EarthRadius = 6378137;
private const double OriginShift = 2 * Math.PI * EarthRadius / 2;
//Converts given lat/lon in WGS84 Datum to XY in Spherical Mercator EPSG:900913
public static (double x, double y) LatLonToMeters(double lat, double lon)
{
var x = lon * OriginShift / 180;
var y = Math.Log(Math.Tan((90 + lat) * Math.PI / 360)) / (Math.PI / 180);
y = y * OriginShift / 180;
return (x, y);
}
//Converts XY point from (Spherical) Web Mercator EPSG:3785 (unofficially EPSG:900913) to lat/lon in WGS84 Datum
public static (double x, double y) MetersToLatLon((double x, double y) m)
{
var x = (m.x / OriginShift) * 180;
var y = (m.y / OriginShift) * 180;
y = 180 / Math.PI * (2 * Math.Atan(Math.Exp(y * Math.PI / 180)) - Math.PI / 2);
return (x, y);
}
//Converts EPSG:900913 to pyramid pixel coordinates in given zoom level
public static (double x, double y) MetersToPixels((double x, double y) m, int zoom, int tileSize)
{
var res = Resolution(zoom, tileSize);
var x = (m.x + OriginShift) / res;
var y = (m.y + OriginShift) / res;
return (x, y);
}
//Converts pixel coordinates in given zoom level of pyramid to EPSG:900913
public static (double x, double y) PixelsToMeters((double x, double y) p, int zoom, int tileSize)
{
var res = Resolution(zoom, tileSize);
var x = p.x * res - OriginShift;
var y = p.y * res - OriginShift;
return (x, y);
}
//Resolution (meters/pixel) for given zoom level (measured at Equator)
public static double Resolution(int zoom, int tileSize)
{
return InitialResolution(tileSize) / (Math.Pow(2, zoom));
}
public static double InitialResolution(int tileSize)
{
return 2 * Math.PI * EarthRadius / tileSize;
}
}
} | 39.711864 | 120 | 0.567222 | [
"MIT"
] | FObermaier/NetTopologySuite.IO.VectorTiles | src/NetTopologySuite.IO.VectorTiles/Tiles/WebMercator/WebMercatorHandler.cs | 2,343 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using Microsoft.AspNetCore.Mvc.ApplicationModels;
namespace ApplicationModelWebSite;
public class ActionDescriptionAttribute : Attribute, IActionModelConvention
{
private readonly object _value;
public ActionDescriptionAttribute(object value)
{
_value = value;
}
public void Apply(ActionModel model)
{
model.Properties["description"] = _value;
}
}
| 23.26087 | 75 | 0.734579 | [
"MIT"
] | Aezura/aspnetcore | src/Mvc/test/WebSites/ApplicationModelWebSite/Conventions/ActionDescriptionAttribute.cs | 535 | C# |
#region License
/* Authors:
* Sebastien Lambla (seb@serialseb.com)
* Copyright:
* (C) 2007-2009 Caffeine IT & naughtyProd Ltd (http://www.caffeine-it.com)
* License:
* This file is distributed under the terms of the MIT License found at the end of this file.
*/
#endregion
// Copyright (c) Microsoft Corporation. All rights reserved.
// This source code is made available under the terms of the Microsoft Public License (MS-PL)
using System;
using System.Collections;
using System.Collections.Generic;
namespace IQ
{
public class ScopedDictionary<TKey, TValue>
{
ScopedDictionary<TKey, TValue> previous;
Dictionary<TKey, TValue> map;
public ScopedDictionary() : this(null)
{
}
public ScopedDictionary(ScopedDictionary<TKey, TValue> previous)
{
this.previous = previous;
this.map = new Dictionary<TKey, TValue>();
}
public ScopedDictionary(ScopedDictionary<TKey, TValue> previous, IEnumerable<KeyValuePair<TKey, TValue>> pairs)
: this(previous)
{
foreach (var p in pairs)
{
this.map.Add(p.Key, p.Value);
}
}
public void Add(TKey key, TValue value)
{
this.map.Add(key, value);
}
public bool TryGetValue(TKey key, out TValue value)
{
for (ScopedDictionary<TKey, TValue> scope = this; scope != null; scope = scope.previous)
{
if (scope.map.TryGetValue(key, out value))
return true;
}
value = default(TValue);
return false;
}
public bool ContainsKey(TKey key)
{
for (ScopedDictionary<TKey, TValue> scope = this; scope != null; scope = scope.previous)
{
if (scope.map.ContainsKey(key))
return true;
}
return false;
}
}
}
#region Full 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.
//
#endregion
| 34.473118 | 120 | 0.61884 | [
"MIT"
] | openrasta/openrasta-core | src/OpenRasta/Reflection/ScopedDictionary.cs | 3,208 | C# |
namespace ConventionTest_
{
using FluentAssertions;
using System;
using TimeWarp.Blazor.Testing;
public class LifecycleExamples
{
public static void AlwaysPass() => true.Should().BeTrue();
[Input(5, 3, 2)]
[Input(8, 5, 3)]
public static void Subtract(int aX, int aY, int aExpectedDifference)
{
// Will run lifecycles around each Input
int result = aX - aY;
result.Should().Be(aExpectedDifference);
}
public static void Setup() => Console.WriteLine("Sample Setup");
public static void Cleanup() => Console.WriteLine("Sample Cleanup");
}
}
| 25.166667 | 72 | 0.665563 | [
"Unlicense"
] | TimeWarpEngineering/timewarp-templates | Source/TimeWarp.Blazor.Template/templates/TimeWarp.Blazor/Tests/TimeWarp.Blazor.Testing/ConventionTests/LifecycleExamples.cs | 606 | C# |
//
// Copyright (C) 2012-2014 DataStax Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
namespace Cassandra
{
internal delegate void CassandraEventHandler(object sender, CassandraEventArgs e);
} | 36.9 | 86 | 0.724932 | [
"Apache-2.0"
] | 902Software/csharp-driver | src/Cassandra/CassandraEventHandler.cs | 738 | C# |
/*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using NUnit.Framework;
using QuantConnect.Indicators;
package com.quantconnect.lean.Tests.Indicators
{
[TestFixture]
public class AbsolutePriceOscillatorTests : CommonIndicatorTests<IndicatorDataPoint>
{
protected @Override IndicatorBase<IndicatorDataPoint> CreateIndicator() {
return new AbsolutePriceOscillator(5, 10);
}
protected @Override String TestFileName
{
get { return "spy_apo.txt"; }
}
protected @Override String TestColumnName
{
get { return "APO_5_10"; }
}
}
}
| 33.410256 | 88 | 0.706063 | [
"Apache-2.0"
] | aricooperman/jLean | orig-src/Tests/Indicators/AbsolutePriceOscillatorTests.cs | 1,305 | C# |
namespace CEvery.Migrations
{
using System;
using System.Data.Entity.Migrations;
public partial class added_fields1 : DbMigration
{
public override void Up()
{
}
public override void Down()
{
}
}
}
| 16.470588 | 52 | 0.539286 | [
"Apache-2.0"
] | bharathkumarms/subscriptionmanager | CEvery/Migrations/201410051424442_added_fields1.cs | 280 | C# |
using ShakerGames.Base.Helpers.Animations;
using TMPro;
namespace ShakerGames.Base.Component
{
using UnityEngine;
using UnityEngine.UI;
using DG.Tweening;
public class AnimationComponent : MonoBehaviour, IComponent
{
public delegate void AnimationComponentDelegate();
public event AnimationComponentDelegate OnIntroAnimationCompleted;
private Tween _tutorialHandAnimationTween;
[SerializeField]private Animator _tryAgain;
public void Initialize(ComponentContainer componentContainer)
{
}
public void PlayIntroAnimation(Image image, float duration)
{
image.DOColor(new Color(255, 255, 255, 1), duration)
.OnComplete(() =>
{
image.DOColor(new Color(255, 255, 255, 0), duration).OnComplete(() =>
{
OnIntroAnimationCompleted?.Invoke();
});
});
}
public void PlayLoadingTextAnimation(float _lastChange, float _loadingTextChangeRate, string[] _loadingStrings,
int _loadingStringsIndex, TMP_Text _loadingText)
{
if (Time.time > _lastChange + _loadingTextChangeRate)
{
if (_loadingStringsIndex == _loadingStrings.Length)
_loadingStringsIndex = 0;
_loadingText.text = _loadingStrings[_loadingStringsIndex];
_loadingStringsIndex++;
_lastChange = Time.time;
}
}
public void PlayTutorialHandAnimation(RectTransform imageTransform, float maxMovementDistance, float duration,
Ease ease)
{
_tutorialHandAnimationTween = imageTransform
.DOMoveX(imageTransform.localPosition.x - maxMovementDistance, duration)
.SetEase(ease)
.SetLoops(-1, LoopType.Yoyo);
}
public void PlayTryAgainAnimation()
{
_tryAgain.SetTrigger("play");
}
public void StopTutorialHandAnimation()
{
_tutorialHandAnimationTween.Kill();
}
}
} | 32.235294 | 119 | 0.592153 | [
"MIT"
] | ilkinmammadzada220/shaker-games-base-setup | Assets/GameAssets/Base/Components/Scripts/AnimationComponent.cs | 2,192 | C# |
using System.Windows;
using System.Windows.Input;
using System.Windows.Interactivity;
namespace Mystique.Views.Behaviors.Actions
{
public class InvokePassThruCommandAction : TriggerAction<DependencyObject>
{
public ICommand Command
{
get { return (ICommand)GetValue(CommandProperty); }
set { SetValue(CommandProperty, value); }
}
// Using a DependencyProperty as the backing store for Command. This enables animation, styling, binding, etc...
public static readonly DependencyProperty CommandProperty =
DependencyProperty.Register("Command", typeof(ICommand), typeof(InvokePassThruCommandAction), new UIPropertyMetadata(null));
protected override void Invoke(object parameter)
{
if(Command != null)
Command.Execute(parameter);
}
}
}
| 32.555556 | 136 | 0.67463 | [
"MIT"
] | fin-alice/Mystique | Mystique/Views/Behaviors/Actions/InvokePassThruCommandAction.cs | 881 | C# |
using Coderingen.Pattern;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Coderingen
{
public class Helper
{
/// <summary>
/// Hulpmethode om meerdere coderingen na elkaar uit te voeren op een gegeven component
/// </summary>
/// <param name="types">de verschillenden coderingen, gescheiden door een spatie (bv. blok wissel blok)</param>
/// <returns>Het resultaat van de verschillende coderingen</returns>
public static ICodering MeerdereCoderingen(string types)
{
ICodering codering = new BasisCodering();
// verschillende coderingen toepassen
foreach (string type in types.Split(' '))
{
// type blok
if (type == "blok")
{
codering = new BlokCodering(codering);
}
else if (type == "wissel")
{
codering = new WisselCodering(codering);
}
else
{
codering = new CijferCodering(codering);
}
}
return codering;
}
static void Main(string[] args)
{
Console.WriteLine("hello world");
string types = Console.ReadLine();
ICodering codering = MeerdereCoderingen(types);
string input = Console.ReadLine();
Console.WriteLine(codering.Codeer(input));
}
}
}
| 29.705882 | 119 | 0.558416 | [
"MIT"
] | LorenzoDeBie/SoftwareOntwikkelingII | Reeks07/FieldValidation/Coderingen/Helper.cs | 1,517 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace entrepot_pharmacie
{
public class Entrepot
{
Caisse caisse;
Article article;
private static int idEntrepot = 1;
public static int IdEntrepot
{
get { return idEntrepot; }
set { idEntrepot = value; }
}
public Fournisseur listeFournisseur
{
get => default;
set
{
}
}
public Client listeClient
{
get => default;
set
{
}
}
public Caisse nomCaisse
{
get => default;
set
{
}
}
public void creer_fournisseur()
{
throw new System.NotImplementedException();
}
public void modifier_fournisseur()
{
throw new System.NotImplementedException();
}
public void supprimer_fournisseur()
{
throw new System.NotImplementedException();
}
public void achat_article()
{
}
public void vente_article()
{
throw new System.NotImplementedException();
}
}
} | 18.788732 | 55 | 0.471514 | [
"MIT"
] | Arizona-dev/entrepot-pharmacie | Pharma-stock/Data/Entrepot.cs | 1,336 | C# |
#region License
/*
Copyright (c) 2010-2020 dxFeed Solutions DE GmbH
This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0.
If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
#endregion
using System;
using System.Runtime.InteropServices;
using com.dxfeed.api;
using com.dxfeed.native.api;
namespace com.dxfeed.native
{
internal class NativeDxException : DxException
{
public int ErrorCode { get; private set; }
public static NativeDxException Create()
{
int error;
IntPtr desc;
C.Instance.dxf_get_last_error(out error, out desc);
var message = Marshal.PtrToStringUni(desc);
return new NativeDxException(error, message);
}
public NativeDxException(int error, string message) : base(message)
{
ErrorCode = error;
}
public NativeDxException(string message) : base(message) { }
}
}
| 26.575 | 108 | 0.630292 | [
"MPL-2.0",
"MPL-2.0-no-copyleft-exception"
] | ttldtor/dxfeed-net-api | dxf_native/src/NativeDxException.cs | 1,065 | 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("SerialPortNet")]
[assembly: AssemblyDescription("An abstraction of serial ports to provide compatibility between .NET Framework and UWP apps.")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Will Graham")]
[assembly: AssemblyProduct("SerialPortNet")]
[assembly: AssemblyCopyright("Copyright © Will Graham 2016")]
[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("0.1.3.0")]
[assembly: AssemblyFileVersion("0.1.3.0")]
[assembly: ComVisible(false)] | 39.896552 | 127 | 0.752809 | [
"MIT"
] | wgraham17/serialportnet | SerialPortNet.UWP/Properties/AssemblyInfo.cs | 1,160 | C# |
using AutoMapper;
using CiSeCase.Core.Interfaces.Manager;
namespace CiSeCase.Infrastructure.Managers.Map
{
public class AutoMapperMapManager : IMapManager
{
private readonly IMapper _mapper;
public AutoMapperMapManager(IMapper mapper)
{
_mapper = mapper;
}
public TDestination Map<TSource, TDestination>(TSource source)
{
return _mapper.Map<TDestination>(source);
}
}
} | 24.368421 | 70 | 0.650108 | [
"MIT"
] | efqanZ/cs-case | src/CiSeCase.Infrastructure/Managers/Map/AutoMapperMapManager.cs | 463 | C# |
// ==========================================================================
// Squidex Headless CMS
// ==========================================================================
// Copyright (c) Squidex UG (haftungsbeschränkt)
// All rights reserved. Licensed under the MIT license.
// ==========================================================================
using System.Collections.ObjectModel;
namespace Squidex.Domain.Apps.Core.Schemas
{
public sealed class AssetsFieldProperties : FieldProperties
{
public bool MustBeImage { get; set; }
public int? MinItems { get; set; }
public int? MaxItems { get; set; }
public int? MinWidth { get; set; }
public int? MaxWidth { get; set; }
public int? MinHeight { get; set; }
public int? MaxHeight { get; set; }
public int? MinSize { get; set; }
public int? MaxSize { get; set; }
public int? AspectWidth { get; set; }
public int? AspectHeight { get; set; }
public ReadOnlyCollection<string> AllowedExtensions { get; set; }
public override T Accept<T>(IFieldPropertiesVisitor<T> visitor)
{
return visitor.Visit(this);
}
public override T Accept<T>(IFieldVisitor<T> visitor, IField field)
{
return visitor.Visit((IField<AssetsFieldProperties>)field);
}
public override RootField CreateRootField(long id, string name, Partitioning partitioning, IFieldSettings settings = null)
{
return Fields.Assets(id, name, partitioning, this, settings);
}
public override NestedField CreateNestedField(long id, string name, IFieldSettings settings = null)
{
return Fields.Assets(id, name, this, settings);
}
}
}
| 30.762712 | 130 | 0.544904 | [
"MIT"
] | niklasise/squidex | src/Squidex.Domain.Apps.Core.Model/Schemas/AssetsFieldProperties.cs | 1,818 | C# |
using System;
namespace _07.SumSeconds
{
class Sum_Second
{
static void Main()
{
var firstTime = int.Parse(Console.ReadLine());
var secondTime = int.Parse(Console.ReadLine());
var thirdTime = int.Parse(Console.ReadLine());
int result = (firstTime + secondTime + thirdTime) * 60;
Console.WriteLine(result);
}
}
}
| 22.631579 | 68 | 0.532558 | [
"MIT"
] | adeto/Simple-Conditions | Sum_Second.cs | 432 | C# |
namespace Vote.Model.DbEntity
{
public class WxAuthorization : EntityExtend
{
/// <summary>
/// 微信OpenId
/// </summary>
public string ExOpenId { get; set; }
/// <summary>
/// 用户Id 可空
/// </summary>
public string MemberId { get; set; }
/// <summary>
/// 平台Id
/// </summary>
public string PlatformId { get; set; }
}
} | 21.3 | 47 | 0.478873 | [
"Apache-2.0"
] | MichealFex/vote | src/model/Vote.Model/DbEntity/Members/WxAuthorization.cs | 442 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using Castle.DynamicProxy;
using Orchard.DisplayManagement.Descriptors;
using Orchard.DisplayManagement.Shapes;
using Orchard.DisplayManagement.Theming;
namespace Orchard.DisplayManagement.Implementation
{
public class DefaultShapeFactory : Composite, IShapeFactory
{
private readonly IEnumerable<IShapeFactoryEvents> _events;
private readonly IShapeTableManager _shapeTableManager;
private readonly IThemeManager _themeManager;
private static readonly ProxyGenerator ProxyGenerator = new ProxyGenerator();
public DefaultShapeFactory(
IEnumerable<IShapeFactoryEvents> events,
IShapeTableManager shapeTableManager,
IThemeManager themeManager)
{
_events = events;
_shapeTableManager = shapeTableManager;
_themeManager = themeManager;
}
public dynamic New { get { return this; } }
public override bool TryInvokeMember(System.Dynamic.InvokeMemberBinder binder, object[] args, out object result)
{
result = Create(binder.Name, Arguments.From(args, binder.CallInfo.ArgumentNames));
return true;
}
private class ShapeImplementation : IShape, IPositioned
{
public ShapeImplementation(string type)
{
Metadata.Type = type;
}
public ShapeMetadata Metadata { get; } = new ShapeMetadata();
public string Position
{
get
{
return Metadata.Position;
}
set
{
Metadata.Position = value;
}
}
}
public T Create<T>(string shapeType) where T : class
{
return (T)Create(typeof(T), shapeType);
}
public object Create(Type baseType, string shapeType)
{
IShape shape;
// Don't generate a proxy for shape types
if (typeof(IShape).IsAssignableFrom(baseType))
{
shape = Activator.CreateInstance(baseType) as IShape;
shape.Metadata.Type = shapeType;
}
else
{
var options = new ProxyGenerationOptions();
options.AddMixinInstance(new ShapeImplementation(shapeType));
shape = ProxyGenerator.CreateClassProxy(baseType, options) as IShape;
}
return shape;
}
public IShape Create(string shapeType)
{
return Create(shapeType, Arguments.Empty, () => new Shape());
}
public IShape Create(string shapeType, INamedEnumerable<object> parameters)
{
return Create(shapeType, parameters, () => new Shape());
}
public T Create<T>(T obj) where T : class
{
return (T)Create(typeof(T).Name, Arguments.Empty, () => obj);
}
public IShape Create(string shapeType, INamedEnumerable<object> parameters, Func<dynamic> createShape)
{
var theme = _themeManager.GetThemeAsync().Result;
var defaultShapeTable = _shapeTableManager.GetShapeTable(theme?.Id);
ShapeDescriptor shapeDescriptor;
defaultShapeTable.Descriptors.TryGetValue(shapeType, out shapeDescriptor);
parameters = parameters ?? Arguments.Empty;
var creatingContext = new ShapeCreatingContext
{
New = this,
ShapeFactory = this,
ShapeType = shapeType,
OnCreated = new List<Action<ShapeCreatedContext>>()
};
IEnumerable<object> positional = parameters.Positional.ToList();
var baseType = positional.FirstOrDefault() as Type;
if (baseType == null)
{
// default to common base class
creatingContext.Create = createShape ?? (() => new Shape());
}
else
{
// consume the first argument
positional = positional.Skip(1);
creatingContext.Create = () => Activator.CreateInstance(baseType);
}
// "creating" events may add behaviors and alter base type)
foreach (var ev in _events)
{
ev.Creating(creatingContext);
}
if (shapeDescriptor != null)
{
foreach (var ev in shapeDescriptor.Creating)
{
ev(creatingContext);
}
}
// create the new instance
var createdContext = new ShapeCreatedContext
{
New = creatingContext.New,
ShapeFactory = creatingContext.ShapeFactory,
ShapeType = creatingContext.ShapeType,
Shape = creatingContext.Create()
};
if (!(createdContext.Shape is IShape))
{
throw new InvalidOperationException("Invalid base type for shape: " + createdContext.Shape.GetType().ToString());
}
if (createdContext.Shape.Metadata == null)
{
createdContext.Shape.Metadata = new ShapeMetadata();
}
ShapeMetadata shapeMetadata = createdContext.Shape.Metadata;
createdContext.Shape.Metadata.Type = shapeType;
// Concatenate wrappers if there are any
if (shapeDescriptor != null &&
shapeMetadata.Wrappers.Count + shapeDescriptor.Wrappers.Count > 0)
{
shapeMetadata.Wrappers = shapeMetadata.Wrappers.Concat(shapeDescriptor.Wrappers).ToList();
}
// only one non-Type, non-named argument is allowed
var initializer = positional.SingleOrDefault();
if (initializer != null)
{
foreach (var prop in initializer.GetType().GetProperties())
{
createdContext.Shape[prop.Name] = prop.GetValue(initializer, null);
}
}
foreach (var kv in parameters.Named)
{
createdContext.Shape[kv.Key] = kv.Value;
}
// "created" events provides default values and new object initialization
foreach (var ev in _events)
{
ev.Created(createdContext);
}
if (shapeDescriptor != null)
{
foreach (var ev in shapeDescriptor.Created)
{
ev(createdContext);
}
}
foreach (var ev in creatingContext.OnCreated)
{
ev(createdContext);
}
return createdContext.Shape;
}
}
} | 32.618605 | 129 | 0.54841 | [
"BSD-3-Clause"
] | CityOfAuburnAL/orchard2 | src/Orchard.DisplayManagement/Implementation/DefaultShapeFactory.cs | 7,015 | 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/ctffunc.h in the Windows SDK for Windows 10.0.20348.0
// Original source is Copyright © Microsoft. All rights reserved.
using NUnit.Framework;
using System;
using System.Runtime.InteropServices;
using static TerraFX.Interop.Windows;
namespace TerraFX.Interop.UnitTests
{
/// <summary>Provides validation of the <see cref="IEnumTfLatticeElements" /> struct.</summary>
public static unsafe class IEnumTfLatticeElementsTests
{
/// <summary>Validates that the <see cref="Guid" /> of the <see cref="IEnumTfLatticeElements" /> struct is correct.</summary>
[Test]
public static void GuidOfTest()
{
Assert.That(typeof(IEnumTfLatticeElements).GUID, Is.EqualTo(IID_IEnumTfLatticeElements));
}
/// <summary>Validates that the <see cref="IEnumTfLatticeElements" /> struct is blittable.</summary>
[Test]
public static void IsBlittableTest()
{
Assert.That(Marshal.SizeOf<IEnumTfLatticeElements>(), Is.EqualTo(sizeof(IEnumTfLatticeElements)));
}
/// <summary>Validates that the <see cref="IEnumTfLatticeElements" /> struct has the right <see cref="LayoutKind" />.</summary>
[Test]
public static void IsLayoutSequentialTest()
{
Assert.That(typeof(IEnumTfLatticeElements).IsLayoutSequential, Is.True);
}
/// <summary>Validates that the <see cref="IEnumTfLatticeElements" /> struct has the correct size.</summary>
[Test]
public static void SizeOfTest()
{
if (Environment.Is64BitProcess)
{
Assert.That(sizeof(IEnumTfLatticeElements), Is.EqualTo(8));
}
else
{
Assert.That(sizeof(IEnumTfLatticeElements), Is.EqualTo(4));
}
}
}
}
| 38.346154 | 145 | 0.649448 | [
"MIT"
] | phizch/terrafx.interop.windows | tests/Interop/Windows/um/ctffunc/IEnumTfLatticeElementsTests.cs | 1,996 | C# |
#region Copyright notice and license
// Copyright 2019 The gRPC Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#endregion
using System;
using System.Buffers;
using System.Text;
using Grpc.AspNetCore.Web.Internal;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Primitives;
using NUnit.Framework;
namespace Grpc.AspNetCore.Server.Tests.Web
{
[TestFixture]
public class GrpcWebProtocolHelpersTests
{
[Test]
public void WriteTrailers_NoTrailers_WrittenToOutput()
{
// Arrange
var trailers = new HeaderDictionary();
var output = new ArrayBufferWriter<byte>();
// Act
GrpcWebProtocolHelpers.WriteTrailers(trailers, output);
// Assert
Assert.AreEqual(5, output.WrittenSpan.Length);
Assert.AreEqual(128, output.WrittenSpan[0]);
Assert.AreEqual(0, output.WrittenSpan[1]);
Assert.AreEqual(0, output.WrittenSpan[2]);
Assert.AreEqual(0, output.WrittenSpan[3]);
Assert.AreEqual(0, output.WrittenSpan[4]);
}
[Test]
public void WriteTrailers_OneTrailer_WrittenToOutput()
{
// Arrange
var trailers = new HeaderDictionary();
trailers.Add("one", "two");
var output = new ArrayBufferWriter<byte>();
// Act
GrpcWebProtocolHelpers.WriteTrailers(trailers, output);
// Assert
Assert.AreEqual(15, output.WrittenSpan.Length);
Assert.AreEqual(128, output.WrittenSpan[0]);
Assert.AreEqual(0, output.WrittenSpan[1]);
Assert.AreEqual(0, output.WrittenSpan[2]);
Assert.AreEqual(0, output.WrittenSpan[3]);
Assert.AreEqual(10, output.WrittenSpan[4]);
var text = Encoding.ASCII.GetString(output.WrittenSpan.Slice(5));
Assert.AreEqual("one: two\r\n", text);
}
[Test]
public void WriteTrailers_OneTrailerMixedCase_WrittenToOutputLowerCase()
{
// Arrange
var trailers = new HeaderDictionary();
trailers.Add("One", "Two");
var output = new ArrayBufferWriter<byte>();
// Act
GrpcWebProtocolHelpers.WriteTrailers(trailers, output);
// Assert
Assert.AreEqual(15, output.WrittenSpan.Length);
Assert.AreEqual(128, output.WrittenSpan[0]);
Assert.AreEqual(0, output.WrittenSpan[1]);
Assert.AreEqual(0, output.WrittenSpan[2]);
Assert.AreEqual(0, output.WrittenSpan[3]);
Assert.AreEqual(10, output.WrittenSpan[4]);
var text = Encoding.ASCII.GetString(output.WrittenSpan.Slice(5));
Assert.AreEqual("one: Two\r\n", text);
}
[Test]
public void WriteTrailers_MultiValueTrailer_WrittenToOutput()
{
// Arrange
var trailers = new HeaderDictionary();
trailers.Add("one", new StringValues(new[] { "two", "three" }));
var output = new ArrayBufferWriter<byte>();
// Act
GrpcWebProtocolHelpers.WriteTrailers(trailers, output);
// Assert
Assert.AreEqual(27, output.WrittenSpan.Length);
Assert.AreEqual(128, output.WrittenSpan[0]);
Assert.AreEqual(0, output.WrittenSpan[1]);
Assert.AreEqual(0, output.WrittenSpan[2]);
Assert.AreEqual(0, output.WrittenSpan[3]);
Assert.AreEqual(22, output.WrittenSpan[4]);
var text = Encoding.ASCII.GetString(output.WrittenSpan.Slice(5));
Assert.AreEqual("one: two\r\none: three\r\n", text);
}
[Test]
public void WriteTrailers_InvalidHeaderName_Error()
{
// Arrange
var trailers = new HeaderDictionary();
trailers.Add("one\r", "two");
var output = new ArrayBufferWriter<byte>();
// Act
var ex = Assert.Throws<InvalidOperationException>(() => GrpcWebProtocolHelpers.WriteTrailers(trailers, output));
// Assert
Assert.AreEqual("Invalid non-ASCII or control character in header: 0x000D", ex.Message);
}
[Test]
public void WriteTrailers_InvalidHeaderValue_Error()
{
// Arrange
var trailers = new HeaderDictionary();
trailers.Add("one", "two:" + (char)127);
var output = new ArrayBufferWriter<byte>();
// Act
var ex = Assert.Throws<InvalidOperationException>(() => GrpcWebProtocolHelpers.WriteTrailers(trailers, output));
// Assert
Assert.AreEqual("Invalid non-ASCII or control character in header: 0x007F", ex.Message);
}
}
}
| 33.810127 | 124 | 0.607638 | [
"Apache-2.0"
] | ManickaP/grpc-dotnet | test/Grpc.AspNetCore.Server.Tests/Web/GrpcWebProtocolHelpersTests.cs | 5,344 | C# |
using Microsoft.AspNetCore.Mvc.Testing;
using Store;
using Store.Contracts.V1;
using Store.Contracts.V1.Responses;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using Xunit;
namespace storeIntegrationTests
{
public class UserControllerTests : IntegrationTest
{
[Fact]
public async Task te4st1()
{
var response = await TestClient.GetAsync(ApiRoutes.Category.GetAll);
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
}
}
}
| 24.16 | 80 | 0.721854 | [
"MIT"
] | Remigiusz-Ruszkiewicz/Store-masterv3 | storeIntegrationTests/ProductControllerTests.cs | 604 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace addressbook_web_tests
{
class Figure
{
private bool colored = false;
public bool Colored
{
get
{
return colored;
}
set
{
colored = value;
}
}
}
}
| 15.703704 | 37 | 0.488208 | [
"Apache-2.0"
] | kamlia/csharp_training | addressbook-web-tests/addressbook-web-tests/Figure.cs | 426 | C# |
namespace WebAPI.Migrations
{
using System;
using System.Data.Entity.Migrations;
public partial class AddBookPageCount : DbMigration
{
public override void Up()
{
AddColumn("public.Books", "PageCount", c => c.Int(nullable: false));
}
public override void Down()
{
DropColumn("public.Books", "PageCount");
}
}
}
| 21.947368 | 80 | 0.553957 | [
"MIT"
] | M1nified/SOA | Zadania6/Library/WebAPI/Migrations/201705021621061_AddBookPageCount.cs | 417 | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.