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 |
|---|---|---|---|---|---|---|---|---|
namespace ProyectoIntegrador4SA
{
partial class Consultar_Resultados
{
/// <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.dataGridView1 = new System.Windows.Forms.DataGridView();
this.label1 = new System.Windows.Forms.Label();
this.Back = new System.Windows.Forms.Button();
((System.ComponentModel.ISupportInitialize)(this.dataGridView1)).BeginInit();
this.SuspendLayout();
//
// dataGridView1
//
this.dataGridView1.BackgroundColor = System.Drawing.Color.Gray;
this.dataGridView1.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize;
this.dataGridView1.Location = new System.Drawing.Point(12, 59);
this.dataGridView1.Name = "dataGridView1";
this.dataGridView1.Size = new System.Drawing.Size(435, 240);
this.dataGridView1.TabIndex = 0;
this.dataGridView1.CellContentClick += new System.Windows.Forms.DataGridViewCellEventHandler(this.dataGridView1_CellContentClick);
//
// label1
//
this.label1.AutoSize = true;
this.label1.Font = new System.Drawing.Font("Times New Roman", 24F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.label1.Location = new System.Drawing.Point(91, 9);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(256, 36);
this.label1.TabIndex = 1;
this.label1.Text = "Resultados Totales ";
//
// Back
//
this.Back.Font = new System.Drawing.Font("Times New Roman", 14.25F, ((System.Drawing.FontStyle)((System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Italic))), System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.Back.Location = new System.Drawing.Point(150, 305);
this.Back.Name = "Back";
this.Back.Size = new System.Drawing.Size(147, 41);
this.Back.TabIndex = 2;
this.Back.Text = "Regresar";
this.Back.UseVisualStyleBackColor = true;
this.Back.Click += new System.EventHandler(this.Back_Click);
//
// Consultar_Resultados
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.BackColor = System.Drawing.Color.White;
this.ClientSize = new System.Drawing.Size(459, 356);
this.Controls.Add(this.Back);
this.Controls.Add(this.label1);
this.Controls.Add(this.dataGridView1);
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.Fixed3D;
this.MaximizeBox = false;
this.Name = "Consultar_Resultados";
this.Opacity = 0.9D;
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
this.Text = "Consultar Resultados";
this.FormClosed += new System.Windows.Forms.FormClosedEventHandler(this.Consultar_Resultados_FormClosed);
((System.ComponentModel.ISupportInitialize)(this.dataGridView1)).EndInit();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.DataGridView dataGridView1;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.Button Back;
}
} | 45.708333 | 225 | 0.608933 | [
"MIT"
] | Tomvargas/VOTOS | votos/Consultar Resultados.Designer.cs | 4,390 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.JsonPatch;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using MongoDB.Driver;
using Newtonsoft.Json;
using RadarTechno.History;
using RadarTechno.Technologies;
using RadarTechno.Users;
namespace RadarTechno.Entities
{
[Authorize]
[Route("api/entities")]
[ApiController]
public class EntityController : Controller
{
readonly IConfiguration configuration;
private readonly Validation _validation = new Validation();
public EntityController(IConfiguration configuration)
{
this.configuration = configuration;
}
[HttpGet("{id}")]
public async Task<IActionResult> GetEntityById([FromServices] IEntityRepository entityRepository, string id)
{
var result = await entityRepository.FindByIdAsync(id);
if (result != null)
{
return Ok(result);
}
return NoContent();
}
[HttpGet]
public async Task<IActionResult> GetAllEntities([FromServices] IEntityRepository entityRepository)
{
var result = await entityRepository.FindAllAsync();
if (result.Any())
{
return Ok(result);
}
return NoContent();
}
[HttpGet("{id}/technologies")]
public async Task<IActionResult> GetEntityTechnologies(
[FromServices] IEntityRepository entityRepository,
[FromServices] ITechnologyRepository technologyRepository,
[FromServices] IEntityService entityService,
string id)
{
var result = await entityRepository.FindTechnologies(technologyRepository, id);
if (result != null && result.Any())
{
var referenceEntityId = configuration.GetSection("ReferenceEntityId");
if (referenceEntityId != null && !String.IsNullOrEmpty(referenceEntityId.Value))
{
var referenceEntityTechnologies =
await entityRepository.FindTechnologies(technologyRepository, referenceEntityId.Value);
if (referenceEntityTechnologies != null && referenceEntityTechnologies.Any())
{
result = entityService.PopulateEntityTechnologiesGroupStatus(result,
referenceEntityTechnologies);
}
}
return Ok(result);
}
return NoContent();
}
[HttpPost]
public async Task<IActionResult> CreateEntity([FromServices] IEntityRepository entityRepository, Entity entity)
{
var user = HttpContext.User;
if (!user.IsInRole("root"))
{
return Unauthorized();
}
if(!_validation.Validate(entity))
{
return BadRequest();
}
await entityRepository.SaveAsync(entity);
return CreatedAtAction(nameof(GetEntityById), new { id = entity.Id }, entity);
}
[HttpPatch("{id}")]
public async Task<IActionResult> PatchEntity(
[FromServices] IEntityRepository entityRepository,
[FromServices] IUserService userService,
string id,
[FromBody]JsonPatchDocument<Entity> entityPatch)
{
var user = HttpContext.User;
if (!user.IsInRole("root")) return Unauthorized();
var entity = await entityRepository.FindByIdAsync(id);
if (entity == null) return BadRequest();
try
{
var oldAdmins = entity.AdminList;
entityPatch.ApplyTo(entity);
if (!_validation.Validate(entity))
{
return BadRequest();
}
var adminsPatch = entityPatch.Operations.Where(o => o.path.Equals("/adminList") || o.path.Equals("/AdminList"));
if (adminsPatch.Any())
{
await userService.HandleNewAdminsRoles(oldAdmins, entity.AdminList, entity.Id);
}
await entityRepository.ReplaceOneAsync(id, entity);
}
catch (UserException ex)
{
return BadRequest(new {message = ex.Message});
}
return NoContent();
}
[HttpPatch("{id}/technology-status")]
public async Task<IActionResult> UpdateTechnologyStatus(
[FromServices] IEntityRepository entityRepository,
[FromServices] IQueue queue,
string id,
[FromBody] EntityTechnology patchEntityTechnology)
{
var user = HttpContext.User;
var claims = user.Claims;
var userEntity = claims.FirstOrDefault(c => c.Type == ClaimTypes.PrimaryGroupSid).Value;
var author = user.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Name).Value;
if ((user.IsInRole("admin") && userEntity != id) && !user.IsInRole("root"))
{
return Unauthorized();
}
var entityTechnology =
await entityRepository.FindTechnologyByIdAsync(id, patchEntityTechnology.TechnologyId);
if (!_validation.Validate(entityTechnology))
{
return BadRequest();
}
entityTechnology.UpdateEntityTechnology(patchEntityTechnology);
var result = await entityRepository.UpdateEntityTechnology(id, entityTechnology);
queue.PublishAsync("history", JsonConvert.SerializeObject(
new HistoryMessage()
{
Id = entityTechnology.Id,
Data = JsonConvert.SerializeObject(
entityTechnology,
new JsonSerializerSettings
{
NullValueHandling = NullValueHandling.Ignore
}
),
Type = "entity-technology",
Author = author
},
new JsonSerializerSettings {NullValueHandling = NullValueHandling.Ignore }
));
return NoContent();
}
[HttpPatch("{id}/technologies")]
public async Task<IActionResult> AddTechnology(
[FromServices] IEntityRepository entityRepository,
[FromServices] IQueue queue,
[FromServices] ITechnologyRepository technologyRepository,
[FromBody] EntityTechnology entityTechnology,
string id)
{
try
{
var user = HttpContext.User;
if (!_validation.Validate(entityTechnology))
{
return BadRequest();
}
await entityRepository.AddTechnology(entityTechnology, id, technologyRepository);
var author = user.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Name).Value;
queue.PublishAsync("history", JsonConvert.SerializeObject(
new HistoryMessage()
{
Id = entityTechnology.Id,
Data = JsonConvert.SerializeObject(
entityTechnology,
new JsonSerializerSettings
{
NullValueHandling = NullValueHandling.Ignore
}
),
Type = "entity-technology",
Author = author
}
));
return NoContent();
}
catch (ArgumentException ex)
{
return BadRequest(new { message = ex.Message });
}
catch (MongoWriteException exception)
{
if (exception.WriteError.Category == ServerErrorCategory.DuplicateKey)
{
return Conflict(new { message = "This technology is already in your entity" });
}
return BadRequest();
}
}
}
} | 38.96789 | 128 | 0.543732 | [
"MIT"
] | axa-group/radar | src/RadarTechno/Entities/EntityController.cs | 8,497 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using SlimDX.DirectWrite;
using VVVV.Core.DirectWrite;
using System.Runtime.InteropServices;
namespace VVVV.DX11.Nodes.Text
{
public unsafe class FWColorStyler : ITextStyler, IDisposable
{
private SharpFontWrapper.ColorRGBA colorStyle;
public bool Enabled;
public SlimDX.Color4 Color;
public SlimDX.DirectWrite.TextRange Range;
public void Apply(TextLayout layout)
{
if (Enabled)
{
var sc = this.Color;
SharpDX.Color4 c = *(SharpDX.Color4*)≻
if (colorStyle == null)
{
var factory = FontWrapperFactory.GetFactory();
colorStyle = factory.CreateColor(c);
}
else
{
colorStyle.SetColor(c.Red, c.Green, c.Blue, c.Alpha);
}
SharpDX.DirectWrite.TextLayout tl = new SharpDX.DirectWrite.TextLayout(layout.ComPointer);
tl.SetDrawingEffect(colorStyle.NativePointer, new SharpDX.DirectWrite.TextRange(Range.StartPosition, Range.Length));
}
}
public void Dispose()
{
if (colorStyle != null)
{
colorStyle.Dispose();
colorStyle = null;
}
}
}
}
| 27.833333 | 132 | 0.546241 | [
"BSD-3-Clause"
] | laurensrinke/dx11-vvvv | Nodes/VVVV.DX11.Nodes.Text/Lib/ColorStyler.cs | 1,505 | C# |
using NSwag.Generation.Processors;
using NSwag.Generation.Processors.Contexts;
using System.Collections.Generic;
namespace Timeline.Swagger
{
/// <summary>
/// Swagger operation processor that adds default description to response.
/// </summary>
public class DefaultDescriptionOperationProcessor : IOperationProcessor
{
private readonly Dictionary<string, string> defaultDescriptionMap = new Dictionary<string, string>
{
["200"] = "Succeeded to perform the operation.",
["304"] = "Item does not change.",
["400"] = "See code and message for error info.",
["401"] = "You need to log in to perform this operation.",
["403"] = "You have no permission to perform the operation.",
["404"] = "Item does not exist. See code and message for error info."
};
/// <inheritdoc/>
public bool Process(OperationProcessorContext context)
{
var responses = context.OperationDescription.Operation.Responses;
foreach (var (httpStatusCode, res) in responses)
{
if (!string.IsNullOrEmpty(res.Description)) continue;
if (defaultDescriptionMap.ContainsKey(httpStatusCode))
{
res.Description = defaultDescriptionMap[httpStatusCode];
}
}
return true;
}
}
}
| 36.8 | 107 | 0.586957 | [
"MIT"
] | crupest/Timeline | BackEnd/Timeline/Swagger/DefaultDescriptionOperationProcessor.cs | 1,474 | C# |
using System;
using System.Linq;
using Microsoft.AspNet.OData;
using Microsoft.AspNet.OData.Query;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.OData;
namespace HBK.Storage.Api.OData
{
/// <summary>
/// 啟用 OData 參數查詢
/// </summary>
public class EnableODataQueryAttribute : EnableQueryAttribute
{
/// <summary>
/// 建立一個新的執行個體
/// </summary>
public EnableODataQueryAttribute()
{
// 預設屬性
base.AllowedFunctions = AllowedFunctions.Contains | AllowedFunctions.Cast | AllowedFunctions.Any | AllowedFunctions.All;
base.MaxTop = 100;
}
/// <inheritdoc/>
public override void OnActionExecuting(ActionExecutingContext context)
{
ODataQueryOptions queryOptions = (ODataQueryOptions)context.ActionArguments.Values
.SingleOrDefault(arg => arg is ODataQueryOptions);
if (queryOptions == null)
{
throw new ArgumentException("No ODataQueryOptions argument in action arguments.", nameof(context));
}
try
{
base.ValidateQuery(context.HttpContext.Request, queryOptions);
}
catch (ODataException ex)
{
var dic = new Microsoft.AspNetCore.Mvc.ModelBinding.ModelStateDictionary();
dic.AddModelError("OData", ex.Message);
context.Result = new BadRequestObjectResult(dic);
}
}
/// <inheritdoc/>
public override void OnActionExecuted(ActionExecutedContext actionExecutedContext)
{
// Do nothing
}
}
}
| 31.75 | 133 | 0.583802 | [
"MIT"
] | nightsoul357/HBK-Storage | HBK.Storage.Api/OData/EnableODataQueryAttribute.cs | 1,820 | C# |
using UnityEngine;
using System.Collections;
public class tk2dTileMapDemoFollowCam : MonoBehaviour {
tk2dCamera cam;
public Transform target;
public float followSpeed = 1.0f;
public float minZoomSpeed = 20.0f;
public float maxZoomSpeed = 40.0f;
public float maxZoomFactor = 0.6f;
void Awake() {
cam = GetComponent<tk2dCamera>();
}
void FixedUpdate() {
Vector3 start = transform.position;
Vector3 end = Vector3.MoveTowards(start, target.position, followSpeed * Time.deltaTime);
end.z = start.z;
transform.position = end;
if (target.rigidbody != null && cam != null) {
float spd = target.rigidbody.velocity.magnitude;
float scl = Mathf.Clamp01((spd - minZoomSpeed) / (maxZoomSpeed - minZoomSpeed));
float targetZoomFactor = Mathf.Lerp(1, maxZoomFactor, scl);
cam.ZoomFactor = Mathf.MoveTowards(cam.ZoomFactor, targetZoomFactor, 0.2f * Time.deltaTime);
}
}
}
| 27.242424 | 95 | 0.726363 | [
"MIT"
] | hazdviel/mathnificat | Assets/TK2DROOT/tk2dTileMap_demo/Demo1/Scripts/tk2dTileMapDemoFollowCam.cs | 899 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class LittleGuyView : MonoBehaviour
{
[SerializeField] private Animator AnimationControl;
public void StartIdleAnimation()
{
AnimationControl.SetTrigger("Idle");
}
public void StartWalkAnimation()
{
AnimationControl.SetTrigger("Walk");
}
}
| 16.52381 | 52 | 0.763689 | [
"MIT"
] | FriedrichWessel/UnityEditorDeviceConnection | Assets/EditorConnectionWindow/Example/LittleGuy/LittleGuyView.cs | 349 | C# |
using System.Text.Json;
using JT808.Protocol.Extensions;
using JT808.Protocol.Formatters;
using JT808.Protocol.Interfaces;
using JT808.Protocol.MessagePack;
namespace JT808.Protocol.MessageBody
{
/// <summary>
/// UDP 消息重传次数
/// 0x8103_0x0005
/// </summary>
public class JT808_0x8103_0x0005 : JT808_0x8103_BodyBase, IJT808MessagePackFormatter<JT808_0x8103_0x0005>, IJT808Analyze
{
/// <summary>
/// 0x0005
/// </summary>
public override uint ParamId { get; set; } = 0x0005;
/// <summary>
/// 数据长度
/// 4 byte
/// </summary>
public override byte ParamLength { get; set; } = 4;
/// <summary>
/// UDP 消息重传次数
/// </summary>
public uint ParamValue { get; set; }
/// <summary>
/// UDP消息重传次数
/// </summary>
public override string Description => "UDP消息重传次数";
/// <summary>
///
/// </summary>
/// <param name="reader"></param>
/// <param name="writer"></param>
/// <param name="config"></param>
public void Analyze(ref JT808MessagePackReader reader, Utf8JsonWriter writer, IJT808Config config)
{
JT808_0x8103_0x0005 jT808_0x8103_0x0005 = new JT808_0x8103_0x0005();
jT808_0x8103_0x0005.ParamId = reader.ReadUInt32();
jT808_0x8103_0x0005.ParamLength = reader.ReadByte();
jT808_0x8103_0x0005.ParamValue = reader.ReadUInt32();
writer.WriteNumber($"[{ jT808_0x8103_0x0005.ParamId.ReadNumber()}]参数ID", jT808_0x8103_0x0005.ParamId);
writer.WriteNumber($"[{jT808_0x8103_0x0005.ParamLength.ReadNumber()}]参数长度", jT808_0x8103_0x0005.ParamLength);
writer.WriteNumber($"[{ jT808_0x8103_0x0005.ParamValue.ReadNumber()}]参数值[UDP消息重传次数]", jT808_0x8103_0x0005.ParamValue);
}
/// <summary>
///
/// </summary>
/// <param name="reader"></param>
/// <param name="config"></param>
/// <returns></returns>
public JT808_0x8103_0x0005 Deserialize(ref JT808MessagePackReader reader, IJT808Config config)
{
JT808_0x8103_0x0005 jT808_0x8103_0x0005 = new JT808_0x8103_0x0005();
jT808_0x8103_0x0005.ParamId = reader.ReadUInt32();
jT808_0x8103_0x0005.ParamLength = reader.ReadByte();
jT808_0x8103_0x0005.ParamValue = reader.ReadUInt32();
return jT808_0x8103_0x0005;
}
/// <summary>
///
/// </summary>
/// <param name="writer"></param>
/// <param name="value"></param>
/// <param name="config"></param>
public void Serialize(ref JT808MessagePackWriter writer, JT808_0x8103_0x0005 value, IJT808Config config)
{
writer.WriteUInt32(value.ParamId);
writer.WriteByte(value.ParamLength);
writer.WriteUInt32(value.ParamValue);
}
}
}
| 37.820513 | 130 | 0.605424 | [
"MIT"
] | jackyzcq/JT808 | src/JT808.Protocol/MessageBody/JT808_0x8103_0x0005.cs | 3,038 | C# |
using HairSalon.Dtos;
using HairSalon.Services;
using System.Collections.Generic;
using System.Web.Http;
using System.Web.Http.Description;
namespace HairSalon.Controllers
{
[Authorize]
[RoutePrefix("api/serviceProvider")]
public class ServiceProviderController : ApiController
{
public ServiceProviderController(IServiceProviderService serviceProviderService)
{
_serviceProviderService = serviceProviderService;
}
[Route("add")]
[HttpPost]
[ResponseType(typeof(ServiceProviderAddOrUpdateResponseDto))]
public IHttpActionResult Add(ServiceProviderAddOrUpdateRequestDto dto) { return Ok(_serviceProviderService.AddOrUpdate(dto)); }
[Route("update")]
[HttpPut]
[ResponseType(typeof(ServiceProviderAddOrUpdateResponseDto))]
public IHttpActionResult Update(ServiceProviderAddOrUpdateRequestDto dto) { return Ok(_serviceProviderService.AddOrUpdate(dto)); }
[Route("get")]
[AllowAnonymous]
[HttpGet]
[ResponseType(typeof(ICollection<ServiceProviderDto>))]
public IHttpActionResult Get() { return Ok(_serviceProviderService.Get()); }
[Route("getById")]
[HttpGet]
[ResponseType(typeof(ServiceProviderDto))]
public IHttpActionResult GetById(int id) { return Ok(_serviceProviderService.GetById(id)); }
[Route("remove")]
[HttpDelete]
[ResponseType(typeof(int))]
public IHttpActionResult Remove(int id) { return Ok(_serviceProviderService.Remove(id)); }
protected readonly IServiceProviderService _serviceProviderService;
}
}
| 33.77551 | 138 | 0.703323 | [
"MIT"
] | QuinntyneBrown/hair-salon | HairSalon/Controllers/ServiceProviderController.cs | 1,655 | 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 securityhub-2018-10-26.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.SecurityHub.Model;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
using Amazon.Runtime.Internal.Transform;
using Amazon.Runtime.Internal.Util;
using ThirdParty.Json.LitJson;
namespace Amazon.SecurityHub.Model.Internal.MarshallTransformations
{
/// <summary>
/// Action Marshaller
/// </summary>
public class ActionMarshaller : IRequestMarshaller<Action, JsonMarshallerContext>
{
/// <summary>
/// Unmarshaller the response from the service to the response class.
/// </summary>
/// <param name="requestObject"></param>
/// <param name="context"></param>
/// <returns></returns>
public void Marshall(Action requestObject, JsonMarshallerContext context)
{
if(requestObject.IsSetActionType())
{
context.Writer.WritePropertyName("ActionType");
context.Writer.Write(requestObject.ActionType);
}
if(requestObject.IsSetAwsApiCallAction())
{
context.Writer.WritePropertyName("AwsApiCallAction");
context.Writer.WriteObjectStart();
var marshaller = AwsApiCallActionMarshaller.Instance;
marshaller.Marshall(requestObject.AwsApiCallAction, context);
context.Writer.WriteObjectEnd();
}
if(requestObject.IsSetDnsRequestAction())
{
context.Writer.WritePropertyName("DnsRequestAction");
context.Writer.WriteObjectStart();
var marshaller = DnsRequestActionMarshaller.Instance;
marshaller.Marshall(requestObject.DnsRequestAction, context);
context.Writer.WriteObjectEnd();
}
if(requestObject.IsSetNetworkConnectionAction())
{
context.Writer.WritePropertyName("NetworkConnectionAction");
context.Writer.WriteObjectStart();
var marshaller = NetworkConnectionActionMarshaller.Instance;
marshaller.Marshall(requestObject.NetworkConnectionAction, context);
context.Writer.WriteObjectEnd();
}
if(requestObject.IsSetPortProbeAction())
{
context.Writer.WritePropertyName("PortProbeAction");
context.Writer.WriteObjectStart();
var marshaller = PortProbeActionMarshaller.Instance;
marshaller.Marshall(requestObject.PortProbeAction, context);
context.Writer.WriteObjectEnd();
}
}
/// <summary>
/// Singleton Marshaller.
/// </summary>
public readonly static ActionMarshaller Instance = new ActionMarshaller();
}
} | 35.264151 | 110 | 0.624666 | [
"Apache-2.0"
] | philasmar/aws-sdk-net | sdk/src/Services/SecurityHub/Generated/Model/Internal/MarshallTransformations/ActionMarshaller.cs | 3,738 | C# |
using System.Data.Common;
using Microsoft.EntityFrameworkCore;
namespace Gsv.EntityFrameworkCore
{
public static class GsvDbContextConfigurer
{
public static void Configure(DbContextOptionsBuilder<GsvDbContext> builder, string connectionString)
{
builder.UseSqlServer(connectionString);
// builder.UseMySql(connectionString);
}
public static void Configure(DbContextOptionsBuilder<GsvDbContext> builder, DbConnection connection)
{
builder.UseSqlServer(connection);
// builder.UseMySql(connection);
}
}
}
| 29.238095 | 108 | 0.687296 | [
"MIT"
] | d2cLabs/Gsv | aspnet-core/src/Gsv.EntityFrameworkCore/EntityFrameworkCore/GsvDbContextConfigurer.cs | 614 | C# |
using Microsoft.EntityFrameworkCore.Migrations;
namespace Caracal.PayStation.Storage.Postgres.Migrations
{
public partial class WorkflowColumn : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.AddColumn<string>(
name: "workflowUrl",
schema: "paystore",
table: "withdrawals",
type: "character varying(2048)",
maxLength: 2048,
nullable: true);
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropColumn(
name: "workflowUrl",
schema: "paystore",
table: "withdrawals");
}
}
}
| 29.074074 | 71 | 0.564331 | [
"MIT"
] | Caracal-IT/pay-station | src/Source/Caracal.PayStation.Storage.Postgres/Migrations/20210430123054_WorkflowColumn.cs | 787 | C# |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
// ---------------------------------------------------------------------------
// TypeHashingAlgorithms.cs
//
// Generic functions to compute the hashcode value of types
// ---------------------------------------------------------------------------
using System;
using System.Diagnostics;
using System.Runtime.CompilerServices;
namespace Internal.NativeFormat
{
static class TypeHashingAlgorithms
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static int _rotl(int value, int shift)
{
return (int)(((uint)value << shift) | ((uint)value >> (32 - shift)));
}
//
// Returns the hashcode value of the 'src' string
//
public static int ComputeNameHashCode(string src)
{
int hash1 = 0x6DA3B944;
int hash2 = 0;
for (int i = 0; i < src.Length; i += 2)
{
hash1 = (hash1 + _rotl(hash1, 5)) ^ src[i];
if ((i + 1) < src.Length)
hash2 = (hash2 + _rotl(hash2, 5)) ^ src[i + 1];
}
hash1 += _rotl(hash1, 8);
hash2 += _rotl(hash2, 8);
return hash1 ^ hash2;
}
public static int ComputeArrayTypeHashCode(int elementTypeHashcode, int rank)
{
// Arrays are treated as generic types in some parts of our system. The array hashcodes are
// carefully crafted to be the same as the hashcodes of their implementation generic types.
int hashCode;
if (rank == 1)
{
hashCode = unchecked((int)0xd5313557u);
Debug.Assert(hashCode == ComputeNameHashCode("System.Array`1"));
}
else
{
hashCode = ComputeNameHashCode("System.MDArrayRank" + rank.ToString() + "`1");
}
hashCode = (hashCode + _rotl(hashCode, 13)) ^ elementTypeHashcode;
return (hashCode + _rotl(hashCode, 15));
}
public static int ComputeArrayTypeHashCode<T>(T elementType, int rank)
{
return ComputeArrayTypeHashCode(elementType.GetHashCode(), rank);
}
public static int ComputePointerTypeHashCode(int pointeeTypeHashcode)
{
return (pointeeTypeHashcode + _rotl(pointeeTypeHashcode, 5)) ^ 0x12D0;
}
public static int ComputePointerTypeHashCode<T>(T pointeeType)
{
return ComputePointerTypeHashCode(pointeeType.GetHashCode());
}
public static int ComputeByrefTypeHashCode(int parameterTypeHashcode)
{
return (parameterTypeHashcode + _rotl(parameterTypeHashcode, 7)) ^ 0x4C85;
}
public static int ComputeByrefTypeHashCode<T>(T parameterType)
{
return ComputeByrefTypeHashCode(parameterType.GetHashCode());
}
public static int ComputeNestedTypeHashCode(int enclosingTypeHashcode, int nestedTypeNameHash)
{
return (enclosingTypeHashcode + _rotl(enclosingTypeHashcode, 11)) ^ nestedTypeNameHash;
}
public static int ComputeGenericInstanceHashCode<ARG>(int genericDefinitionHashCode, ARG[] genericTypeArguments)
{
int hashcode = genericDefinitionHashCode;
for (int i = 0; i < genericTypeArguments.Length; i++)
{
int argumentHashCode = genericTypeArguments[i].GetHashCode();
hashcode = (hashcode + _rotl(hashcode, 13)) ^ argumentHashCode;
}
return (hashcode + _rotl(hashcode, 15));
}
}
}
| 34.108108 | 120 | 0.569995 | [
"MIT"
] | ZZHGit/corert | src/Common/src/Internal/NativeFormat/TypeHashingAlgorithms.cs | 3,788 | 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("Sannel.House.Thermostat.Data")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Sannel.House.Thermostat.Data")]
[assembly: AssemblyCopyright("Copyright © 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("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: ComVisible(false)] | 37 | 84 | 0.743709 | [
"Apache-2.0"
] | holtsoftware/House | Sannel.House.Thermostat/Sannel.House.Thermostat.Data/Properties/AssemblyInfo.cs | 1,076 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
namespace Microsoft.AspNetCore.OutputCaching;
/// <summary>
/// A named policy.
/// </summary>
internal sealed class NamedPolicy : IOutputCachePolicy
{
private readonly string _policyName;
/// <summary>
/// Create a new <see cref="NamedPolicy"/> instance.
/// </summary>
/// <param name="policyName">The name of the profile.</param>
public NamedPolicy(string policyName)
{
_policyName = policyName;
}
/// <inheritdoc />
ValueTask IOutputCachePolicy.ServeResponseAsync(OutputCacheContext context, CancellationToken cancellationToken)
{
var policy = GetProfilePolicy(context);
if (policy == null)
{
return ValueTask.CompletedTask;
}
return policy.ServeResponseAsync(context, cancellationToken);
}
/// <inheritdoc />
ValueTask IOutputCachePolicy.ServeFromCacheAsync(OutputCacheContext context, CancellationToken cancellationToken)
{
var policy = GetProfilePolicy(context);
if (policy == null)
{
return ValueTask.CompletedTask;
}
return policy.ServeFromCacheAsync(context, cancellationToken);
}
/// <inheritdoc />
ValueTask IOutputCachePolicy.CacheRequestAsync(OutputCacheContext context, CancellationToken cancellationToken)
{
var policy = GetProfilePolicy(context);
if (policy == null)
{
return ValueTask.CompletedTask;
}
return policy.CacheRequestAsync(context, cancellationToken); ;
}
internal IOutputCachePolicy? GetProfilePolicy(OutputCacheContext context)
{
var policies = context.Options.NamedPolicies;
return policies != null && policies.TryGetValue(_policyName, out var cacheProfile)
? cacheProfile
: null;
}
}
| 28.057143 | 117 | 0.664969 | [
"Apache-2.0"
] | aspnet/AspNetCore | src/Middleware/OutputCaching/src/Policies/NamedPolicy.cs | 1,964 | C# |
using Photon.Pun;
using Photon.Realtime;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
namespace BNG {
public class NetworkManager : MonoBehaviourPunCallbacks {
/// <summary>
/// Maximum number of players per room. If the room is full, a new radom one will be created.
/// </summary>
[Tooltip("Maximum number of players per room. If the room is full, a new random one will be created. 0 = No Max.")]
[SerializeField]
private byte maxPlayersPerRoom = 0;
[Tooltip("If true, the JoinRoomName will try to be Joined On Start. If false, need to call JoinRoom yourself.")]
public bool JoinRoomOnStart = true;
[Tooltip("If true, do not destroy this object when moving to another scene")]
public bool dontDestroyOnLoad = true;
public string JoinRoomName = "RandomRoom";
[Tooltip("Game Version can be used to separate rooms.")]
public string GameVersion = "1";
[Tooltip("Name of the Player object to spawn. Must be in a /Resources folder.")]
public string RemotePlayerObjectName = "RemotePlayer";
[Tooltip("Optional GUI Text element to output debug information.")]
public Text DebugText;
ScreenFader sf;
void Awake() {
// Required if you want to call PhotonNetwork.LoadLevel()
PhotonNetwork.AutomaticallySyncScene = true;
if (dontDestroyOnLoad) {
DontDestroyOnLoad(this.gameObject);
}
if(Camera.main != null) {
sf = Camera.main.GetComponentInChildren<ScreenFader>(true);
}
}
void Start() {
// Connect to Random Room if Connected to Photon Server
if (PhotonNetwork.IsConnected) {
if (JoinRoomOnStart) {
LogText("Joining Room : " + JoinRoomName);
PhotonNetwork.JoinRoom(JoinRoomName);
}
}
// Otherwise establish a new connection. We can then connect via OnConnectedToMaster
else {
PhotonNetwork.ConnectUsingSettings();
PhotonNetwork.GameVersion = GameVersion;
}
}
void Update() {
// Show Loading Progress
if (PhotonNetwork.LevelLoadingProgress > 0 && PhotonNetwork.LevelLoadingProgress < 1) {
Debug.Log(PhotonNetwork.LevelLoadingProgress);
}
}
public override void OnJoinRoomFailed(short returnCode, string message) {
LogText("Room does not exist. Creating <color=yellow>" + JoinRoomName + "</color>");
PhotonNetwork.CreateRoom(JoinRoomName, new RoomOptions { MaxPlayers = maxPlayersPerRoom }, TypedLobby.Default);
}
public override void OnJoinRandomFailed(short returnCode, string message) {
Debug.Log("OnJoinRandomFailed Failed, Error : " + message);
}
public override void OnConnectedToMaster() {
LogText("Connected to Master Server. \n");
if (JoinRoomOnStart) {
LogText("Joining Room : <color=aqua>" + JoinRoomName + "</color>");
PhotonNetwork.JoinRoom(JoinRoomName);
}
}
public override void OnPlayerEnteredRoom(Player newPlayer) {
base.OnPlayerEnteredRoom(newPlayer);
float playerCount = PhotonNetwork.IsConnected && PhotonNetwork.CurrentRoom != null ? PhotonNetwork.CurrentRoom.PlayerCount : 0;
LogText("Connected players : " + playerCount);
}
public override void OnJoinedRoom() {
LogText("Joined Room. Creating Remote Player Representation.");
// Network Instantiate the object used to represent our player. This will have a View on it and represent the player
GameObject player = PhotonNetwork.Instantiate(RemotePlayerObjectName, new Vector3(0f, 0f, 0f), Quaternion.identity, 0);
NetworkPlayer np = player.GetComponent<NetworkPlayer>();
if (np) {
np.transform.name = "MyRemotePlayer";
np.AssignPlayerObjects();
}
}
public override void OnDisconnected(DisconnectCause cause) {
LogText("Disconnected from PUN due to cause : " + cause);
if (!PhotonNetwork.ReconnectAndRejoin()) {
LogText("Reconnect and Joined.");
}
base.OnDisconnected(cause);
}
public void LoadScene(string sceneName) {
// Fade Screen out
StartCoroutine(doLoadLevelWithFade(sceneName));
}
IEnumerator doLoadLevelWithFade(string sceneName) {
if (sf) {
sf.DoFadeIn();
yield return new WaitForSeconds(sf.SceneFadeInDelay);
}
PhotonNetwork.LoadLevel(sceneName);
yield return null;
}
void LogText(string message) {
// Output to worldspace to help with debugging.
if (DebugText) {
DebugText.text += "\n" + message;
}
Debug.Log(message);
}
}
}
| 34.874172 | 139 | 0.594569 | [
"MIT"
] | CheongHo-Lee/blockcodingVR-unity | Assets/BNG Framework/Integrations/PUN/NetworkManager.cs | 5,268 | C# |
//
// Copyright (c) Microsoft. 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.Globalization;
using Microsoft.Azure.Commands.Common.Authentication;
using Microsoft.Azure.Commands.Common.Authentication.Models;
using Microsoft.WindowsAzure.Commands.Common;
namespace Microsoft.Azure.Commands.ApiManagement.ServiceManagement
{
using AutoMapper;
using Common.Authentication.Abstractions;
using Microsoft.Azure.Commands.ApiManagement.ServiceManagement.Models;
using Microsoft.Azure.Management.ApiManagement;
using Microsoft.Azure.Management.ApiManagement.SmapiModels;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Management.Automation;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
public class ApiManagementClient
{
private const string PeriodGroupName = "period";
private const string ValueGroupName = "value";
private const string ProductIdPathTemplate = "/products/{0}";
private const string UserIdPathTemplate = "/users/{0}";
// pattern: ^(?<period>[DdMmYy]{1})(?<value>\d+)$
internal const string PeriodPattern = "^(?<" + PeriodGroupName + ">[DdMmYy]{1})(?<" + ValueGroupName + @">\d+)$";
static readonly Regex PeriodRegex = new Regex(PeriodPattern, RegexOptions.Compiled);
private readonly IAzureContext _context;
private Management.ApiManagement.ApiManagementClient _client;
private readonly JsonSerializerSettings _jsonSerializerSetting = new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore };
private static IMapper _mapper;
private static readonly object _lock = new object();
public static IMapper Mapper
{
get
{
lock(_lock)
{
if (_mapper == null)
{
ConfigureMappings();
}
return _mapper;
}
}
}
static ApiManagementClient()
{
ConfigureMappings();
}
private static void ConfigureMappings()
{
var config = new MapperConfiguration(cfg =>
{
cfg.CreateMap<PsApiManagementParameter, ParameterContract>();
cfg.CreateMap<PsApiManagementRequest, RequestContract>();
cfg.CreateMap<PsApiManagementResponse, ResponseContract>();
cfg.CreateMap<PsApiManagementRepresentation, RepresentationContract>();
cfg.CreateMap<PsApiManagementAuthorizationHeaderCredential, AuthorizationHeaderCredentialsContract>();
cfg
.CreateMap<ApiContract, PsApiManagementApi>()
.ForMember(dest => dest.ApiId, opt => opt.MapFrom(src => src.Id))
.ForMember(dest => dest.Protocols, opt => opt.MapFrom(src => src.Protocols.ToArray()))
.ForMember(
dest => dest.AuthorizationServerId,
opt => opt.MapFrom(
src => src.AuthenticationSettings != null && src.AuthenticationSettings.OAuth2 != null
? src.AuthenticationSettings.OAuth2.AuthorizationServerId
: null))
.ForMember(
dest => dest.AuthorizationScope,
opt => opt.MapFrom(
src => src.AuthenticationSettings != null && src.AuthenticationSettings.OAuth2 != null
? src.AuthenticationSettings.OAuth2.AuthorizationServerId
: null))
.ForMember(
dest => dest.SubscriptionKeyHeaderName,
opt => opt.MapFrom(
src => src.SubscriptionKeyParameterNames != null
? src.SubscriptionKeyParameterNames.Header
: null))
.ForMember(
dest => dest.SubscriptionKeyQueryParamName,
opt => opt.MapFrom(
src => src.SubscriptionKeyParameterNames != null
? src.SubscriptionKeyParameterNames.Query
: null));
cfg.CreateMap<RequestContract, PsApiManagementRequest>();
cfg.CreateMap<ResponseContract, PsApiManagementResponse>();
cfg.CreateMap<RepresentationContract, PsApiManagementRepresentation>();
cfg.CreateMap<ParameterContract, PsApiManagementParameter>();
cfg.CreateMap<OperationContract, PsApiManagementOperation>();
cfg
.CreateMap<ProductContract, PsApiManagementProduct>()
.ForMember(dest => dest.ProductId, opt => opt.MapFrom(src => src.Id))
.ForMember(dest => dest.Title, opt => opt.MapFrom(src => src.Name))
.ForMember(dest => dest.LegalTerms, opt => opt.MapFrom(src => src.Terms));
cfg
.CreateMap<SubscriptionContract, PsApiManagementSubscription>()
.ForMember(dest => dest.SubscriptionId, opt => opt.MapFrom(src => src.Id));
cfg
.CreateMap<UserContract, PsApiManagementUser>()
.ForMember(dest => dest.UserId, opt => opt.MapFrom(src => src.Id))
.ForMember(dest => dest.Identities, opt => opt.MapFrom(src => src.Identities.ToDictionary(key => key.Id, value => value.Provider)));
cfg
.CreateMap<GroupContract, PsApiManagementGroup>()
.ForMember(dest => dest.GroupId, opt => opt.MapFrom(src => src.Id));
cfg
.CreateMap<CertificateContract, PsApiManagementCertificate>()
.ForMember(dest => dest.CertificateId, opt => opt.MapFrom(src => src.Id));
cfg
.CreateMap<OAuth2AuthorizationServerContract, PsApiManagementOAuth2AuthrozationServer>()
.ForMember(dest => dest.ServerId, opt => opt.MapFrom(src => src.Id))
.ForMember(dest => dest.AccessTokenSendingMethods, opt => opt.MapFrom(src => src.BearerTokenSendingMethods))
.ForMember(dest => dest.TokenEndpointUrl, opt => opt.MapFrom(src => src.TokenEndpoint))
.ForMember(dest => dest.AuthorizationEndpointUrl, opt => opt.MapFrom(src => src.AuthorizationEndpoint))
.ForMember(dest => dest.ClientRegistrationPageUrl, opt => opt.MapFrom(src => src.ClientRegistrationEndpoint))
.ForMember(dest => dest.ClientAuthenticationMethods, opt => opt.MapFrom(src => src.ClientAuthenticationMethod))
.ForMember(dest => dest.AuthorizationRequestMethods, opt => opt.MapFrom(src => src.AuthorizationMethods))
.ForMember(dest => dest.TokenBodyParameters, opt => opt.Ignore())
.AfterMap((src, dest) =>
dest.TokenBodyParameters = src.TokenBodyParameters == null
? (Hashtable)null
: new Hashtable(src.TokenBodyParameters.ToDictionary(key => key.Name, value => value.Value)));
cfg
.CreateMap<LoggerGetContract, PsApiManagementLogger>()
.ForMember(dest => dest.LoggerId, opt => opt.MapFrom(src => src.Id))
.ForMember(dest => dest.Description, opt => opt.MapFrom(src => src.Description))
.ForMember(dest => dest.IsBuffered, opt => opt.MapFrom(src => src.IsBuffered))
.ForMember(dest => dest.Type, opt => opt.MapFrom(src => src.Type));
cfg
.CreateMap<PropertyContract, PsApiManagementProperty>()
.ForMember(dest => dest.PropertyId, opt => opt.MapFrom(src => src.Id))
.ForMember(dest => dest.Name, opt => opt.MapFrom(src => src.Name))
.ForMember(dest => dest.Value, opt => opt.MapFrom(src => src.Value))
.ForMember(dest => dest.Secret, opt => opt.MapFrom(src => src.Secret))
.ForMember(dest => dest.Tags, opt => opt.MapFrom(src => src.Tags == null ? new string[0] : src.Tags.ToArray()));
cfg
.CreateMap<OpenidConnectProviderContract, PsApiManagementOpenIdConnectProvider>()
.ForMember(dest => dest.OpenIdConnectProviderId, opt => opt.MapFrom(src => src.Id))
.ForMember(dest => dest.Name, opt => opt.MapFrom(src => src.Name))
.ForMember(dest => dest.Description, opt => opt.MapFrom(src => src.Description))
.ForMember(dest => dest.ClientId, opt => opt.MapFrom(src => src.ClientId))
.ForMember(dest => dest.ClientSecret, opt => opt.MapFrom(src => src.ClientSecret))
.ForMember(dest => dest.MetadataEndpoint, opt => opt.MapFrom(src => src.MetadataEndpoint));
cfg
.CreateMap<AccessInformationContract, PsApiManagementAccessInformation>()
.ForMember(dest => dest.Enabled, opt => opt.MapFrom(src => src.Enabled))
.ForMember(dest => dest.Id, opt => opt.MapFrom(src => src.Id))
.ForMember(dest => dest.PrimaryKey, opt => opt.MapFrom(src => src.PrimaryKey))
.ForMember(dest => dest.SecondaryKey, opt => opt.MapFrom(src => src.SecondaryKey));
cfg.CreateMap<TenantConfigurationSyncStateContract, PsApiManagementTenantConfigurationSyncState>();
cfg
.CreateMap<IdentityProviderContract, PsApiManagementIdentityProvider>()
.ForMember(dest => dest.ClientId, opt => opt.MapFrom(src => src.ClientId))
.ForMember(dest => dest.ClientSecret, opt => opt.MapFrom(src => src.ClientSecret))
.ForMember(dest => dest.Type, opt => opt.MapFrom(src => src.Type))
.ForMember(dest => dest.AllowedTenants, opt => opt.MapFrom(src => src.AllowedTenants == null ? new string[0] : src.AllowedTenants.ToArray()));
cfg
.CreateMap<BackendProxyContract, PsApiManagementBackendProxy>()
.ForMember(dest => dest.Url, opt => opt.MapFrom(src => src.Url))
.ForMember(dest => dest.ProxyCredentials, opt => opt.MapFrom(src =>
string.IsNullOrEmpty(src.Password) ? PSCredential.Empty :
new PSCredential(src.Username, src.Password.ConvertToSecureString())));
cfg
.CreateMap<PsApiManagementBackendProxy, BackendProxyContract>()
.ForMember(dest => dest.Url, opt => opt.MapFrom(src => src.Url))
.ForMember(dest => dest.Username, opt => opt.MapFrom(src => src.ProxyCredentials == PSCredential.Empty ? null : src.ProxyCredentials.UserName))
.ForMember(dest => dest.Password, opt => opt.MapFrom(src => src.ProxyCredentials == PSCredential.Empty ? null : src.ProxyCredentials.Password.ConvertToString()));
cfg
.CreateMap<BackendCredentialsContract, PsApiManagementBackendCredential>()
.ForMember(dest => dest.Certificate, opt => opt.MapFrom(src => src.Certificate))
.ForMember(dest => dest.Query, opt => opt.Ignore())
.ForMember(dest => dest.Header, opt => opt.Ignore())
.AfterMap((src, dest) =>
dest.Query = src.Query == null
? (Hashtable)null
: DictionaryToHashTable(src.Query))
.AfterMap((src, dest) =>
dest.Header = src.Header == null
? (Hashtable)null
: DictionaryToHashTable(src.Header));
cfg
.CreateMap<AuthorizationHeaderCredentialsContract, PsApiManagementAuthorizationHeaderCredential>()
.ForMember(dest => dest.Scheme, opt => opt.MapFrom(src => src.Scheme))
.ForMember(dest => dest.Parameter, opt => opt.MapFrom(src => src.Parameter));
cfg
.CreateMap<BackendGetContract, PsApiManagementBackend>()
.ForMember(dest => dest.BackendId, opt => opt.MapFrom(src => src.Id))
.ForMember(dest => dest.Url, opt => opt.MapFrom(src => src.Url))
.ForMember(dest => dest.Protocol, opt => opt.MapFrom(src => src.Protocol))
.ForMember(dest => dest.ResourceId, opt => opt.MapFrom(src => src.ResourceId))
.ForMember(dest => dest.Title, opt => opt.MapFrom(src => src.Title))
.ForMember(dest => dest.Description, opt => opt.MapFrom(src => src.Description))
.ForMember(dest => dest.Properties, opt => opt.MapFrom(src => src.Properties))
.ForMember(dest => dest.Proxy, opt => opt.MapFrom(src => src.Proxy));
cfg.CreateMap<Hashtable, Hashtable>();
});
_mapper = config.CreateMapper();
}
public ApiManagementClient(IAzureContext context)
{
if (context == null)
{
throw new ArgumentNullException("AzureProfile");
}
_context = context;
_client = CreateClient();
}
private IApiManagementClient Client
{
get { return _client ?? (_client = CreateClient()); }
}
private Management.ApiManagement.ApiManagementClient CreateClient()
{
return AzureSession.Instance.ClientFactory.CreateClient<Management.ApiManagement.ApiManagementClient>(
_context,
AzureEnvironment.Endpoint.ResourceManager);
}
internal TenantConfigurationLongRunningOperation GetLongRunningOperationStatus(TenantConfigurationLongRunningOperation longRunningOperation)
{
var response =
Client.TenantConfiguration
.GetTenantConfigurationLongRunningOperationStatusAsync(longRunningOperation.OperationLink)
.ConfigureAwait(false)
.GetAwaiter()
.GetResult();
return TenantConfigurationLongRunningOperation.CreateLongRunningOperation(longRunningOperation.OperationName, response);
}
private static IList<T> ListPaged<T>(
Func<IPagedListResponse<T>> listFirstPage,
Func<string, IPagedListResponse<T>> listNextPage)
{
var resultsList = new List<T>();
var pagedResponse = listFirstPage();
resultsList.AddRange(pagedResponse.Result.Values);
while (!string.IsNullOrEmpty(pagedResponse.Result.NextLink))
{
pagedResponse = listNextPage(pagedResponse.Result.NextLink);
resultsList.AddRange(pagedResponse.Result.Values);
}
return resultsList;
}
private static IList<TOut> ListPagedAndMap<TOut, TIn>(
Func<IPagedListResponse<TIn>> listFirstPage,
Func<string, IPagedListResponse<TIn>> listNextPage)
{
IList<TIn> unmappedList = ListPaged(listFirstPage, listNextPage);
var mappedList = Mapper.Map<IList<TOut>>(unmappedList);
return mappedList;
}
#region APIs
public IList<PsApiManagementApi> ApiList(PsApiManagementContext context)
{
var results = ListPagedAndMap<PsApiManagementApi, ApiContract>(
() => Client.Apis.List(context.ResourceGroupName, context.ServiceName, null),
nextLink => Client.Apis.ListNext(nextLink));
return results;
}
public IList<PsApiManagementApi> ApiByName(PsApiManagementContext context, string name)
{
var results = ListPagedAndMap<PsApiManagementApi, ApiContract>(
() => Client.Apis.List(
context.ResourceGroupName,
context.ServiceName,
new QueryParameters
{
Filter = string.Format("name eq '{0}'", name)
}),
nextLink => Client.ProductApis.ListNext(nextLink));
return results;
}
public IList<PsApiManagementApi> ApiByProductId(PsApiManagementContext context, string productId)
{
var results = ListPagedAndMap<PsApiManagementApi, ApiContract>(
() => Client.ProductApis.List(context.ResourceGroupName, context.ServiceName, productId, null),
nextLink => Client.ProductApis.ListNext(nextLink));
return results;
}
public PsApiManagementApi ApiById(PsApiManagementContext context, string id)
{
var response = Client.Apis.Get(context.ResourceGroupName, context.ServiceName, id);
return Mapper.Map<PsApiManagementApi>(response.Value);
}
public PsApiManagementApi ApiCreate(
PsApiManagementContext context,
string id,
string name,
string description,
string serviceUrl,
string urlSuffix,
PsApiManagementSchema[] urlSchema,
string authorizationServerId,
string authorizationScope,
string subscriptionKeyHeaderName,
string subscriptionKeyQueryParamName)
{
var api = new ApiContract
{
Name = name,
Description = description,
ServiceUrl = serviceUrl,
Path = urlSuffix,
Protocols = Mapper.Map<IList<ApiProtocolContract>>(urlSchema),
};
if (!string.IsNullOrWhiteSpace(authorizationServerId))
{
api.AuthenticationSettings = new AuthenticationSettingsContract
{
OAuth2 = new OAuth2AuthenticationSettingsContract
{
AuthorizationServerId = authorizationServerId,
Scope = authorizationScope
}
};
}
if (!string.IsNullOrWhiteSpace(subscriptionKeyHeaderName) || !string.IsNullOrWhiteSpace(subscriptionKeyQueryParamName))
{
api.SubscriptionKeyParameterNames = new SubscriptionKeyParameterNamesContract
{
Header = subscriptionKeyHeaderName,
Query = subscriptionKeyQueryParamName
};
}
Client.Apis.CreateOrUpdate(context.ResourceGroupName, context.ServiceName, id, new ApiCreateOrUpdateParameters(api), null);
var getResponse = Client.Apis.Get(context.ResourceGroupName, context.ServiceName, id);
return Mapper.Map<PsApiManagementApi>(getResponse.Value);
}
public void ApiRemove(PsApiManagementContext context, string id)
{
Client.Apis.Delete(context.ResourceGroupName, context.ServiceName, id, "*");
}
public void ApiSet(
PsApiManagementContext context,
string id,
string name,
string description,
string serviceUrl,
string urlSuffix,
PsApiManagementSchema[] urlSchema,
string authorizationServerId,
string authorizationScope,
string subscriptionKeyHeaderName,
string subscriptionKeyQueryParamName)
{
var api = new ApiContract
{
Name = name,
Description = description,
ServiceUrl = serviceUrl,
Path = urlSuffix,
Protocols = Mapper.Map<IList<ApiProtocolContract>>(urlSchema)
};
if (!string.IsNullOrWhiteSpace(authorizationServerId))
{
api.AuthenticationSettings = new AuthenticationSettingsContract
{
OAuth2 = new OAuth2AuthenticationSettingsContract
{
AuthorizationServerId = authorizationServerId,
Scope = authorizationScope
}
};
}
if (!string.IsNullOrWhiteSpace(subscriptionKeyHeaderName) || !string.IsNullOrWhiteSpace(subscriptionKeyQueryParamName))
{
api.SubscriptionKeyParameterNames = new SubscriptionKeyParameterNamesContract
{
Header = subscriptionKeyHeaderName,
Query = subscriptionKeyQueryParamName
};
}
// fix for issue https://github.com/Azure/azure-powershell/issues/2606
var apiPatchContract = JsonConvert.SerializeObject(api, _jsonSerializerSetting);
Client.Apis.Patch(
context.ResourceGroupName,
context.ServiceName,
id,
new PatchParameters
{
RawJson = apiPatchContract
},
"*");
}
public void ApiImportFromFile(
PsApiManagementContext context,
string apiId,
PsApiManagementApiFormat specificationFormat,
string specificationPath,
string apiPath,
string wsdlServiceName,
string wsdlEndpointName,
PsApiManagementApiType? apiType)
{
string contentType = GetHeaderForApiExportImport(true, specificationFormat, wsdlServiceName, wsdlEndpointName, true);
string apiTypeValue = GetApiTypeForImport(specificationFormat, apiType);
using (var fileStream = File.OpenRead(specificationPath))
{
Client.Apis.Import(context.ResourceGroupName, context.ServiceName, apiId, contentType, fileStream, apiPath, wsdlServiceName, wsdlEndpointName, apiTypeValue);
}
}
public void ApiImportFromUrl(
PsApiManagementContext context,
string apiId,
PsApiManagementApiFormat specificationFormat,
string specificationUrl,
string urlSuffix,
string wsdlServiceName,
string wsdlEndpointName,
PsApiManagementApiType? apiType)
{
string contentType = GetHeaderForApiExportImport(false, specificationFormat, wsdlServiceName, wsdlEndpointName, true);
string apiTypeValue = GetApiTypeForImport(specificationFormat, apiType);
var jobj = JObject.FromObject(
new
{
link = specificationUrl
});
using (var memoryStream = new MemoryStream(Encoding.UTF8.GetBytes(jobj.ToString(Formatting.None))))
{
Client.Apis.Import(context.ResourceGroupName, context.ServiceName, apiId, contentType, memoryStream, urlSuffix, wsdlServiceName, wsdlEndpointName, apiTypeValue);
}
}
public byte[] ApiExportToFile(
PsApiManagementContext context,
string apiId,
PsApiManagementApiFormat specificationFormat,
string saveAs)
{
string acceptType = GetHeaderForApiExportImport(true, specificationFormat, string.Empty, string.Empty, false);
var response = Client.Apis.Export(context.ResourceGroupName, context.ServiceName, apiId, acceptType);
return response.Content;
}
private string GetHeaderForApiExportImport(
bool fromFile,
PsApiManagementApiFormat specificationApiFormat,
string wsdlServiceName,
string wsdlEndpointName,
bool validateWsdlParams)
{
string headerValue;
switch (specificationApiFormat)
{
case PsApiManagementApiFormat.Wadl:
headerValue = fromFile ? "application/vnd.sun.wadl+xml" : "application/vnd.sun.wadl.link+json";
break;
case PsApiManagementApiFormat.Swagger:
headerValue = fromFile ? "application/vnd.swagger.doc+json" : "application/vnd.swagger.link+json";
break;
case PsApiManagementApiFormat.Wsdl:
headerValue = fromFile ? "application/wsdl+xml" : "application/vnd.ms.wsdl.link+xml";
if (validateWsdlParams && string.IsNullOrEmpty(wsdlServiceName))
{
throw new ArgumentException(string.Format(CultureInfo.InvariantCulture, "WsdlServiceName cannot be Empty for Format : {0}", specificationApiFormat));
}
if (validateWsdlParams && string.IsNullOrEmpty(wsdlEndpointName))
{
throw new ArgumentException(string.Format(CultureInfo.InvariantCulture, "WsdlEndpointName cannot be Empty for Format : {0}", specificationApiFormat));
}
break;
default:
throw new ArgumentException(string.Format(CultureInfo.InvariantCulture, "Format '{0}' is not supported.", specificationApiFormat));
}
return headerValue;
}
private string GetApiTypeForImport(
PsApiManagementApiFormat specificationFormat,
PsApiManagementApiType? apiType)
{
if (specificationFormat != PsApiManagementApiFormat.Wsdl)
{
return null;
}
return apiType.HasValue ? apiType.Value.ToString("g") : PsApiManagementApiType.Http.ToString("g");
}
public void ApiAddToProduct(PsApiManagementContext context, string productId, string apiId)
{
Client.ProductApis.Add(context.ResourceGroupName, context.ServiceName, productId, apiId);
}
public void ApiRemoveFromProduct(PsApiManagementContext context, string productId, string apiId)
{
Client.ProductApis.Remove(context.ResourceGroupName, context.ServiceName, productId, apiId);
}
#endregion
#region Operations
public IList<PsApiManagementOperation> OperationList(PsApiManagementContext context, string apiId)
{
var results = ListPagedAndMap<PsApiManagementOperation, OperationContract>(
() => Client.ApiOperations.List(context.ResourceGroupName, context.ServiceName, apiId, null),
nextLink => Client.ApiOperations.ListNext(nextLink));
return results;
}
public PsApiManagementOperation OperationById(PsApiManagementContext context, string apiId, string operationId)
{
var response = Client.ApiOperations.Get(context.ResourceGroupName, context.ServiceName, apiId, operationId);
return Mapper.Map<PsApiManagementOperation>(response.Value);
}
public PsApiManagementOperation OperationCreate(
PsApiManagementContext context,
string apiId,
string operationId,
string name,
string method,
string urlTemplate,
string description,
PsApiManagementParameter[] templateParameters,
PsApiManagementRequest request,
PsApiManagementResponse[] responses)
{
var operationContract = new OperationContract
{
Name = name,
Description = description,
Method = method,
UrlTemplate = urlTemplate,
};
if (templateParameters != null)
{
operationContract.TemplateParameters = Mapper.Map<IList<ParameterContract>>(templateParameters);
}
if (request != null)
{
operationContract.Request = Mapper.Map<RequestContract>(request);
}
if (responses != null)
{
operationContract.Responses = Mapper.Map<IList<ResponseContract>>(responses);
}
Client.ApiOperations.Create(
context.ResourceGroupName,
context.ServiceName,
apiId,
operationId,
new OperationCreateOrUpdateParameters(operationContract));
var getResponse = Client.ApiOperations.Get(context.ResourceGroupName, context.ServiceName, apiId, operationId);
return Mapper.Map<PsApiManagementOperation>(getResponse.Value);
}
public void OperationSet(
PsApiManagementContext context,
string apiId,
string operationId,
string name,
string method,
string urlTemplate,
string description,
PsApiManagementParameter[] templateParameters,
PsApiManagementRequest request,
PsApiManagementResponse[] responses)
{
var operationContract = new OperationContract
{
Name = name,
Description = description,
Method = method,
UrlTemplate = urlTemplate,
};
if (templateParameters != null)
{
operationContract.TemplateParameters = Mapper.Map<IList<ParameterContract>>(templateParameters);
}
if (request != null)
{
operationContract.Request = Mapper.Map<RequestContract>(request);
}
if (responses != null)
{
operationContract.Responses = Mapper.Map<IList<ResponseContract>>(responses);
}
var operationPatchContract = JsonConvert.SerializeObject(operationContract, _jsonSerializerSetting);
Client.ApiOperations.Patch(
context.ResourceGroupName,
context.ServiceName,
apiId,
operationId,
new PatchParameters
{
RawJson = operationPatchContract
},
"*");
}
public void OperationRemove(PsApiManagementContext context, string apiId, string operationId)
{
Client.ApiOperations.Delete(context.ResourceGroupName, context.ServiceName, apiId, operationId, "*");
}
#endregion
#region Products
public IList<PsApiManagementProduct> ProductList(PsApiManagementContext context, string title)
{
var query = new QueryParameters();
if (!string.IsNullOrWhiteSpace(title))
{
query.Filter = string.Format("name eq '{0}'", title);
}
var results = ListPagedAndMap<PsApiManagementProduct, ProductContract>(
() => Client.Products.List(context.ResourceGroupName, context.ServiceName, query),
nextLink => Client.Products.ListNext(nextLink));
return results;
}
public PsApiManagementProduct ProductById(PsApiManagementContext context, string productId)
{
var response = Client.Products.Get(context.ResourceGroupName, context.ServiceName, productId);
var product = Mapper.Map<PsApiManagementProduct>(response.Value);
return product;
}
public void ProductRemove(PsApiManagementContext context, string productId, bool deleteSubscriptions)
{
Client.Products.Delete(context.ResourceGroupName, context.ServiceName, productId, "*", deleteSubscriptions);
}
public PsApiManagementProduct ProductCreate(
PsApiManagementContext context,
string productId,
string title,
string description,
string legalTerms,
bool? subscriptionRequired,
bool? approvalRequired,
int? subscriptionsLimit,
PsApiManagementProductState? state)
{
var productContract = new ProductContract(title)
{
ApprovalRequired = approvalRequired,
Description = description,
SubscriptionRequired = subscriptionRequired,
SubscriptionsLimit = subscriptionsLimit,
Terms = legalTerms
};
if (state.HasValue)
{
switch (state)
{
case PsApiManagementProductState.NotPublished:
productContract.State = ProductStateContract.NotPublished;
break;
case PsApiManagementProductState.Published:
productContract.State = ProductStateContract.Published;
break;
default:
throw new ArgumentOutOfRangeException(string.Format("State '{0}' is not supported.", state));
}
}
Client.Products.Create(context.ResourceGroupName, context.ServiceName, productId, new ProductCreateParameters(productContract));
var response = Client.Products.Get(context.ResourceGroupName, context.ServiceName, productId);
return Mapper.Map<PsApiManagementProduct>(response.Value);
}
public void ProductSet(
PsApiManagementContext context,
string productId,
string title,
string description,
string legalTerms,
bool? subscriptionRequired,
bool? approvalRequired,
int? subscriptionsLimit,
PsApiManagementProductState? state)
{
var productUpdateParameters = new ProductUpdateParameters
{
Name = title,
ApprovalRequired = approvalRequired,
Description = description,
SubscriptionRequired = subscriptionRequired,
SubscriptionsLimit = subscriptionsLimit,
Terms = legalTerms
};
if (state.HasValue)
{
switch (state)
{
case PsApiManagementProductState.NotPublished:
productUpdateParameters.State = ProductStateContract.NotPublished;
break;
case PsApiManagementProductState.Published:
productUpdateParameters.State = ProductStateContract.Published;
break;
default:
throw new ArgumentOutOfRangeException(string.Format("State '{0}' is not supported.", state));
}
}
Client.Products.Update(context.ResourceGroupName, context.ServiceName, productId, productUpdateParameters, "*");
}
public void ProductAddToGroup(PsApiManagementContext context, string groupId, string productId)
{
Client.ProductGroups.Add(context.ResourceGroupName, context.ServiceName, productId, groupId);
}
public void ProductRemoveFromGroup(PsApiManagementContext context, string groupId, string productId)
{
Client.ProductGroups.Remove(context.ResourceGroupName, context.ServiceName, productId, groupId);
}
#endregion
#region Subscriptions
public IList<PsApiManagementSubscription> SubscriptionList(PsApiManagementContext context)
{
var results = ListPagedAndMap<PsApiManagementSubscription, SubscriptionContract>(
() => Client.Subscriptions.List(context.ResourceGroupName, context.ServiceName, null),
nextLink => Client.Subscriptions.ListNext(nextLink));
return results;
}
public IList<PsApiManagementSubscription> SubscriptionByUser(PsApiManagementContext context, string userId)
{
var results = ListPagedAndMap<PsApiManagementSubscription, SubscriptionContract>(
() => Client.UserSubscriptions.List(context.ResourceGroupName, context.ServiceName, userId, null),
nextLink => Client.UserSubscriptions.ListNext(nextLink));
return results;
}
public IList<PsApiManagementSubscription> SubscriptionByProduct(PsApiManagementContext context, string productId)
{
var results = ListPagedAndMap<PsApiManagementSubscription, SubscriptionContract>(
() => Client.ProductSubscriptions.List(context.ResourceGroupName, context.ServiceName, productId, null),
nextLink => Client.ProductSubscriptions.ListNext(nextLink));
return results;
}
public PsApiManagementSubscription SubscriptionById(PsApiManagementContext context, string subscriptionId)
{
var response = Client.Subscriptions.Get(context.ResourceGroupName, context.ServiceName, subscriptionId);
var subscription = Mapper.Map<PsApiManagementSubscription>(response.Value);
return subscription;
}
public PsApiManagementSubscription SubscriptionCreate(
PsApiManagementContext context,
string subscriptionId,
string productId,
string userId,
string name,
string primaryKey,
string secondaryKey,
PsApiManagementSubscriptionState? state)
{
var createParameters = new SubscriptionCreateParameters(
string.Format(UserIdPathTemplate, userId),
string.Format(ProductIdPathTemplate, productId),
name)
{
Name = name,
PrimaryKey = primaryKey,
SecondaryKey = secondaryKey
};
if (state.HasValue)
{
createParameters.State = Mapper.Map<SubscriptionStateContract>(state.Value);
}
Client.Subscriptions.Create(context.ResourceGroupName, context.ServiceName, subscriptionId, createParameters);
var response = Client.Subscriptions.Get(context.ResourceGroupName, context.ServiceName, subscriptionId);
return Mapper.Map<PsApiManagementSubscription>(response.Value);
}
public void SubscriptionSet(
PsApiManagementContext context,
string subscriptionId,
string name,
string primaryKey,
string secondaryKey,
PsApiManagementSubscriptionState? state,
DateTime? expiresOn,
string stateComment)
{
var updateParameters = new SubscriptionUpdateParameters
{
Name = name,
PrimaryKey = primaryKey,
SecondaryKey = secondaryKey,
ExpiresOn = expiresOn,
StateComment = stateComment
};
if (state.HasValue)
{
updateParameters.State = Mapper.Map<SubscriptionStateContract>(state.Value);
}
Client.Subscriptions.Update(context.ResourceGroupName, context.ServiceName, subscriptionId, updateParameters, "*");
}
public void SubscriptionRemove(PsApiManagementContext context, string subscriptionId)
{
Client.Subscriptions.Delete(context.ResourceGroupName, context.ServiceName, subscriptionId, "*");
}
#endregion
#region Users
public PsApiManagementUser UserCreate(
PsApiManagementContext context,
string userId,
string firstName,
string lastName,
string password,
string email,
PsApiManagementUserState? state,
string note)
{
var userCreateParameters = new UserCreateParameters
{
Email = email,
FirstName = firstName,
LastName = lastName,
Note = note,
Password = password
};
if (state.HasValue)
{
userCreateParameters.State = Mapper.Map<UserStateContract>(state.Value);
}
Client.Users.Create(context.ResourceGroupName, context.ServiceName, userId, userCreateParameters);
var response = Client.Users.Get(context.ResourceGroupName, context.ServiceName, userId);
var user = Mapper.Map<PsApiManagementUser>(response.Value);
return user;
}
public void UserSet(
PsApiManagementContext context,
string userId,
string firstName,
string lastName,
string password,
string email,
PsApiManagementUserState? state,
string note)
{
var userUpdateParameters = new UserUpdateParameters
{
Email = email,
FirstName = firstName,
LastName = lastName,
Note = note,
Password = password,
};
if (state.HasValue)
{
userUpdateParameters.State = Mapper.Map<UserStateContract>(state.Value);
}
else
{
// if state not specified, fetch state.
// fix for issue https://github.com/Azure/azure-powershell/issues/2622
var currentUser = Client.Users.Get(context.ResourceGroupName, context.ServiceName, userId);
userUpdateParameters.State = currentUser.Value.State;
}
Client.Users.Update(context.ResourceGroupName, context.ServiceName, userId, userUpdateParameters, "*");
}
public IList<PsApiManagementUser> UsersList(
PsApiManagementContext context,
string firstName,
string lastName,
string email,
PsApiManagementUserState? state,
string groupId)
{
var query = CreateQueryUserParameters(firstName, lastName, email, state);
var results = !string.IsNullOrEmpty(groupId)
? ListPagedAndMap<PsApiManagementUser, UserContract>(
() => Client.GroupUsers.List(context.ResourceGroupName, context.ServiceName, groupId, query),
nextLink => Client.GroupUsers.ListNext(nextLink))
: ListPagedAndMap<PsApiManagementUser, UserContract>(
() => Client.Users.List(context.ResourceGroupName, context.ServiceName, query),
nextLink => Client.Users.ListNext(nextLink));
return results;
}
public PsApiManagementUser UserById(PsApiManagementContext context, string userId)
{
var response = Client.Users.Get(context.ResourceGroupName, context.ServiceName, userId);
var user = Mapper.Map<PsApiManagementUser>(response.Value);
return user;
}
public void UserRemove(PsApiManagementContext context, string userId, bool deleteSubscriptions)
{
Client.Users.Delete(context.ResourceGroupName, context.ServiceName, userId, "*", deleteSubscriptions);
}
public string UserGetSsoUrl(PsApiManagementContext context, string userId)
{
var response = Client.Users.GenerateSsoUrl(context.ResourceGroupName, context.ServiceName, userId);
return response.Value;
}
public void UserAddToGroup(PsApiManagementContext context, string groupId, string userId)
{
Client.UserGroups.AddToGroup(context.ResourceGroupName, context.ServiceName, userId, groupId);
}
public void UserRemoveFromGroup(PsApiManagementContext context, string groupId, string userId)
{
Client.UserGroups.RemoveFromGroup(context.ResourceGroupName, context.ServiceName, userId, groupId);
}
private static QueryParameters CreateQueryUserParameters(string firstName, string lastName, string email, PsApiManagementUserState? state)
{
var isFirstCondition = true;
var query = new QueryParameters();
if (!string.IsNullOrEmpty(firstName))
{
query.Filter = string.Format("firstName eq '{0}'", firstName);
isFirstCondition = false;
}
if (!string.IsNullOrEmpty(lastName))
{
if (!isFirstCondition)
{
query.Filter += "&";
}
query.Filter = string.Format("lastName eq '{0}'", lastName);
isFirstCondition = false;
}
if (!string.IsNullOrEmpty(email))
{
if (!isFirstCondition)
{
query.Filter += "&";
}
query.Filter = string.Format("email eq '{0}'", email);
isFirstCondition = false;
}
if (state.HasValue)
{
if (!isFirstCondition)
{
query.Filter += "&";
}
query.Filter = string.Format("state eq '{0}'", state.Value.ToString().ToLowerInvariant());
}
return query;
}
#endregion
#region Groups
public PsApiManagementGroup GroupCreate(
PsApiManagementContext context,
string groupId,
string name,
string description,
PsApiManagementGroupType? type,
string externalId)
{
var groupCreateParameters = new GroupCreateParameters(name)
{
Description = description
};
if (type.HasValue)
{
groupCreateParameters.Type = Mapper.Map<GroupTypeContract>(type.Value);
}
else
{
groupCreateParameters.Type = Mapper.Map<GroupTypeContract>(PsApiManagementGroupType.Custom);
}
if (!string.IsNullOrEmpty(externalId))
{
groupCreateParameters.ExternalId = externalId;
}
Client.Groups.Create(context.ResourceGroupName, context.ServiceName, groupId, groupCreateParameters);
var response = Client.Groups.Get(context.ResourceGroupName, context.ServiceName, groupId);
var group = Mapper.Map<PsApiManagementGroup>(response.Value);
return group;
}
public IList<PsApiManagementGroup> GroupsList(PsApiManagementContext context, string name, string userId, string productId)
{
var query = new QueryParameters();
if (!string.IsNullOrEmpty(name))
{
query.Filter = string.Format("name eq '{0}'", name);
}
IList<PsApiManagementGroup> results;
if (!string.IsNullOrWhiteSpace(userId))
{
results = ListPagedAndMap<PsApiManagementGroup, GroupContract>(
() => Client.UserGroups.List(context.ResourceGroupName, context.ServiceName, userId, query),
nextLink => Client.UserGroups.ListNext(nextLink));
}
else if (!string.IsNullOrEmpty(productId))
{
results = ListPagedAndMap<PsApiManagementGroup, GroupContract>(
() => Client.ProductGroups.List(context.ResourceGroupName, context.ServiceName, productId, query),
nextLink => Client.ProductGroups.ListNext(nextLink));
}
else
{
results = ListPagedAndMap<PsApiManagementGroup, GroupContract>(
() => Client.Groups.List(context.ResourceGroupName, context.ServiceName, query),
nextLink => Client.Groups.ListNext(nextLink));
}
return results;
}
public PsApiManagementGroup GroupById(PsApiManagementContext context, string groupId)
{
var response = Client.Groups.Get(context.ResourceGroupName, context.ServiceName, groupId);
var group = Mapper.Map<PsApiManagementGroup>(response.Value);
return group;
}
public void GroupRemove(PsApiManagementContext context, string groupId)
{
Client.Groups.Delete(context.ResourceGroupName, context.ServiceName, groupId, "*");
}
public void GroupSet(
PsApiManagementContext context,
string groupId,
string name,
string description)
{
var groupUpdate = new GroupUpdateParameters
{
Name = name,
Description = description
};
Client.Groups.Update(
context.ResourceGroupName,
context.ServiceName,
groupId,
groupUpdate,
"*");
}
#endregion
#region Policy
private static byte[] PolicyGetWrap(Func<PolicyGetResponse> getPolicyFunc)
{
try
{
var response = getPolicyFunc();
return response.PolicyBytes;
}
catch (Hyak.Common.CloudException ex)
{
if (ex.Response.StatusCode == HttpStatusCode.NotFound)
{
return null;
}
throw;
}
}
public byte[] PolicyGetTenantLevel(PsApiManagementContext context, string format)
{
return PolicyGetWrap(() => Client.TenantPolicy.Get(context.ResourceGroupName, context.ServiceName, format));
}
public byte[] PolicyGetProductLevel(PsApiManagementContext context, string format, string productId)
{
return PolicyGetWrap(() => Client.ProductPolicy.Get(context.ResourceGroupName, context.ServiceName, productId, format));
}
public byte[] PolicyGetApiLevel(PsApiManagementContext context, string format, string apiId)
{
return PolicyGetWrap(() => Client.ApiPolicy.Get(context.ResourceGroupName, context.ServiceName, apiId, format));
}
public byte[] PolicyGetOperationLevel(PsApiManagementContext context, string format, string apiId, string operationId)
{
return PolicyGetWrap(() => Client.ApiOperationPolicy.Get(context.ResourceGroupName, context.ServiceName, apiId, operationId, format));
}
public void PolicySetTenantLevel(PsApiManagementContext context, string format, Stream stream)
{
Client.TenantPolicy.Set(context.ResourceGroupName, context.ServiceName, format, stream, "*");
}
public void PolicySetProductLevel(PsApiManagementContext context, string format, Stream stream, string productId)
{
Client.ProductPolicy.Set(context.ResourceGroupName, context.ServiceName, productId, format, stream, "*");
}
public void PolicySetApiLevel(PsApiManagementContext context, string format, Stream stream, string apiId)
{
Client.ApiPolicy.Set(context.ResourceGroupName, context.ServiceName, apiId, format, stream, "*");
}
public void PolicySetOperationLevel(PsApiManagementContext context, string format, Stream stream, string apiId, string operationId)
{
Client.ApiOperationPolicy.Set(context.ResourceGroupName, context.ServiceName, apiId, operationId, format, stream, "*");
}
public void PolicyRemoveTenantLevel(PsApiManagementContext context)
{
Client.TenantPolicy.Delete(context.ResourceGroupName, context.ServiceName, "*");
}
public void PolicyRemoveProductLevel(PsApiManagementContext context, string productId)
{
Client.ProductPolicy.Delete(context.ResourceGroupName, context.ServiceName, productId, "*");
}
public void PolicyRemoveApiLevel(PsApiManagementContext context, string apiId)
{
Client.ApiPolicy.Delete(context.ResourceGroupName, context.ServiceName, apiId, "*");
}
public void PolicyRemoveOperationLevel(PsApiManagementContext context, string apiId, string operationId)
{
Client.ApiOperationPolicy.Delete(context.ResourceGroupName, context.ServiceName, apiId, operationId, "*");
}
#endregion
#region Certificates
public IList<PsApiManagementCertificate> CertificateList(PsApiManagementContext context)
{
var results = ListPagedAndMap<PsApiManagementCertificate, CertificateContract>(
() => Client.Certificates.List(context.ResourceGroupName, context.ServiceName, null),
nextLink => Client.Certificates.ListNext(nextLink));
return results;
}
public PsApiManagementCertificate CertificateById(PsApiManagementContext context, string certificateId)
{
var response = Client.Certificates.Get(context.ResourceGroupName, context.ServiceName, certificateId);
var certificate = Mapper.Map<PsApiManagementCertificate>(response.Value);
return certificate;
}
public PsApiManagementCertificate CertificateCreate(
PsApiManagementContext context,
string certificateId,
byte[] certificateBytes,
string pfxPassword)
{
var createParameters = new CertificateCreateOrUpdateParameters
{
Data = Convert.ToBase64String(certificateBytes),
Password = pfxPassword
};
Client.Certificates.CreateOrUpdate(context.ResourceGroupName, context.ServiceName, certificateId, createParameters, null);
var response = Client.Certificates.Get(context.ResourceGroupName, context.ServiceName, certificateId);
var certificate = Mapper.Map<PsApiManagementCertificate>(response.Value);
return certificate;
}
public PsApiManagementCertificate CertificateSet(
PsApiManagementContext context,
string certificateId,
byte[] certificateBytes,
string pfxPassword)
{
var createParameters = new CertificateCreateOrUpdateParameters
{
Data = Convert.ToBase64String(certificateBytes),
Password = pfxPassword
};
Client.Certificates.CreateOrUpdate(context.ResourceGroupName, context.ServiceName, certificateId, createParameters, "*");
var response = Client.Certificates.Get(context.ResourceGroupName, context.ServiceName, certificateId);
var certificate = Mapper.Map<PsApiManagementCertificate>(response.Value);
return certificate;
}
public void CertificateRemove(PsApiManagementContext context, string certificateId)
{
Client.Certificates.Delete(context.ResourceGroupName, context.ServiceName, certificateId, "*");
}
#endregion
#region Authorization Servers
public IList<PsApiManagementOAuth2AuthrozationServer> AuthorizationServerList(PsApiManagementContext context)
{
var results = ListPagedAndMap<PsApiManagementOAuth2AuthrozationServer, OAuth2AuthorizationServerContract>(
() => Client.AuthorizationServers.List(context.ResourceGroupName, context.ServiceName, null),
nextLink => Client.AuthorizationServers.ListNext(nextLink));
return results;
}
public PsApiManagementOAuth2AuthrozationServer AuthorizationServerById(PsApiManagementContext context, string serverId)
{
var response = Client.AuthorizationServers.Get(context.ResourceGroupName, context.ServiceName, serverId);
var server = Mapper.Map<PsApiManagementOAuth2AuthrozationServer>(response.Value);
return server;
}
public PsApiManagementOAuth2AuthrozationServer AuthorizationServerCreate(
PsApiManagementContext context,
string serverId,
string name,
string description,
string clientRegistrationPageUrl,
string authorizationEndpointUrl,
string tokenEndpointUrl,
string clientId,
string clientSecret,
PsApiManagementAuthorizationRequestMethod[] authorizationRequestMethods,
PsApiManagementGrantType[] grantTypes,
PsApiManagementClientAuthenticationMethod[] clientAuthenticationMethods,
Hashtable tokenBodyParameters,
bool? supportState,
string defaultScope,
PsApiManagementAccessTokenSendingMethod[] accessTokenSendingMethods,
string resourceOwnerUsername,
string resourceOwnerPassword)
{
var serverContract = new OAuth2AuthorizationServerContract
{
Name = name,
Description = description,
ClientRegistrationEndpoint = clientRegistrationPageUrl,
AuthorizationEndpoint = authorizationEndpointUrl,
TokenEndpoint = tokenEndpointUrl,
ClientId = clientId,
ClientSecret = clientSecret,
AuthorizationMethods = Mapper.Map<IList<MethodContract>>(authorizationRequestMethods),
GrantTypes = Mapper.Map<IList<GrantTypesContract>>(grantTypes),
ClientAuthenticationMethod = Mapper.Map<IList<ClientAuthenticationMethodContract>>(clientAuthenticationMethods),
SupportState = supportState ?? false,
DefaultScope = defaultScope,
BearerTokenSendingMethods = Mapper.Map<IList<BearerTokenSendingMethodsContract>>(accessTokenSendingMethods),
ResourceOwnerUsername = resourceOwnerUsername,
ResourceOwnerPassword = resourceOwnerPassword
};
if (tokenBodyParameters != null && tokenBodyParameters.Count > 0)
{
serverContract.TokenBodyParameters = new List<TokenBodyParameterContract>(tokenBodyParameters.Count);
foreach (var key in tokenBodyParameters.Keys)
{
serverContract.TokenBodyParameters.Add(
new TokenBodyParameterContract
{
Name = key.ToString(),
Value = tokenBodyParameters[key].ToString()
});
}
}
Client.AuthorizationServers.Create(
context.ResourceGroupName,
context.ServiceName,
serverId,
new AuthorizationServerCreateOrUpdateParameters(serverContract));
var response = Client.AuthorizationServers.Get(context.ResourceGroupName, context.ServiceName, serverId);
var server = Mapper.Map<PsApiManagementOAuth2AuthrozationServer>(response.Value);
return server;
}
public void AuthorizationServerSet(
PsApiManagementContext context,
string serverId,
string name,
string description,
string clientRegistrationPageUrl,
string authorizationEndpointUrl,
string tokenEndpointUrl,
string clientId,
string clientSecret,
PsApiManagementAuthorizationRequestMethod[] authorizationRequestMethods,
PsApiManagementGrantType[] grantTypes,
PsApiManagementClientAuthenticationMethod[] clientAuthenticationMethods,
Hashtable tokenBodyParameters,
bool? supportState,
string defaultScope,
PsApiManagementAccessTokenSendingMethod[] accessTokenSendingMethods,
string resourceOwnerUsername,
string resourceOwnerPassword)
{
var serverContract = new OAuth2AuthorizationServerContract
{
Name = name,
Description = description,
ClientRegistrationEndpoint = clientRegistrationPageUrl,
AuthorizationEndpoint = authorizationEndpointUrl,
TokenEndpoint = tokenEndpointUrl,
ClientId = clientId,
ClientSecret = clientSecret,
AuthorizationMethods = Mapper.Map<IList<MethodContract>>(authorizationRequestMethods),
GrantTypes = Mapper.Map<IList<GrantTypesContract>>(grantTypes),
ClientAuthenticationMethod = Mapper.Map<IList<ClientAuthenticationMethodContract>>(clientAuthenticationMethods),
SupportState = supportState ?? false,
DefaultScope = defaultScope,
BearerTokenSendingMethods = Mapper.Map<IList<BearerTokenSendingMethodsContract>>(accessTokenSendingMethods),
ResourceOwnerUsername = resourceOwnerUsername,
ResourceOwnerPassword = resourceOwnerPassword
};
if (tokenBodyParameters != null && tokenBodyParameters.Count > 0)
{
serverContract.TokenBodyParameters = new List<TokenBodyParameterContract>(tokenBodyParameters.Count);
foreach (var key in tokenBodyParameters.Keys)
{
serverContract.TokenBodyParameters.Add(
new TokenBodyParameterContract
{
Name = key.ToString(),
Value = tokenBodyParameters[key].ToString()
});
}
}
Client.AuthorizationServers.Update(
context.ResourceGroupName,
context.ServiceName,
serverId,
new AuthorizationServerCreateOrUpdateParameters(serverContract),
"*");
}
public void AuthorizationServerRemove(PsApiManagementContext context, string serverId)
{
Client.AuthorizationServers.Delete(context.ResourceGroupName, context.ServiceName, serverId, "*");
}
#endregion
#region Loggers
public PsApiManagementLogger LoggerCreate(
PsApiManagementContext context,
LoggerTypeContract type,
string loggerId,
string description,
IDictionary<string, string> credentials,
bool isBuffered)
{
var loggerCreateParameters = new LoggerCreateParameters(type, credentials)
{
Description = description,
IsBuffered = isBuffered
};
Client.Loggers.Create(context.ResourceGroupName, context.ServiceName, loggerId, loggerCreateParameters);
var response = Client.Loggers.Get(context.ResourceGroupName, context.ServiceName, loggerId);
var logger = Mapper.Map<PsApiManagementLogger>(response.Value);
return logger;
}
public IList<PsApiManagementLogger> LoggersList(PsApiManagementContext context)
{
var results = ListPagedAndMap<PsApiManagementLogger, LoggerGetContract>(
() => Client.Loggers.List(context.ResourceGroupName, context.ServiceName, null),
nextLink => Client.Loggers.ListNext(nextLink));
return results;
}
public PsApiManagementLogger LoggerById(PsApiManagementContext context, string loggerId)
{
var response = Client.Loggers.Get(context.ResourceGroupName, context.ServiceName, loggerId);
var logger = Mapper.Map<PsApiManagementLogger>(response.Value);
return logger;
}
public void LoggerRemove(PsApiManagementContext context, string loggerId)
{
Client.Loggers.Delete(context.ResourceGroupName, context.ServiceName, loggerId, "*");
}
public void LoggerSet(
PsApiManagementContext context,
LoggerTypeContract type,
string loggerId,
string description,
IDictionary<string, string> credentials,
bool? isBuffered)
{
var loggerUpdateParameters = new LoggerUpdateParameters(type);
if (!string.IsNullOrWhiteSpace(description))
{
loggerUpdateParameters.Description = description;
}
if (isBuffered.HasValue)
{
loggerUpdateParameters.IsBuffered = isBuffered.Value;
}
if (credentials != null && credentials.Count != 0)
{
loggerUpdateParameters.Credentials = credentials;
}
Client.Loggers.Update(
context.ResourceGroupName,
context.ServiceName,
loggerId,
loggerUpdateParameters,
"*");
}
#endregion
#region Properties
public PsApiManagementProperty PropertyCreate(
PsApiManagementContext context,
string propertyId,
string propertyName,
string propertyValue,
bool secret,
IList<string> tags = null)
{
var propertyCreateParameters = new PropertyCreateParameters(propertyName, propertyValue)
{
Secret = secret,
Tags = tags
};
Client.Property.Create(context.ResourceGroupName, context.ServiceName, propertyId, propertyCreateParameters);
var response = Client.Property.Get(context.ResourceGroupName, context.ServiceName, propertyId);
var property = Mapper.Map<PsApiManagementProperty>(response.Value);
return property;
}
public IList<PsApiManagementProperty> PropertiesList(PsApiManagementContext context)
{
var results = ListPagedAndMap<PsApiManagementProperty, PropertyContract>(
() => Client.Property.List(context.ResourceGroupName, context.ServiceName, null),
nextLink => Client.Property.ListNext(nextLink));
return results;
}
public IList<PsApiManagementProperty> PropertyByName(PsApiManagementContext context, string propertyName)
{
var results = ListPagedAndMap<PsApiManagementProperty, PropertyContract>(
() => Client.Property.List(
context.ResourceGroupName,
context.ServiceName,
new QueryParameters
{
Filter = string.Format("substringof('{0}',name)", propertyName)
}),
nextLink => Client.Property.ListNext(nextLink));
return results;
}
public IList<PsApiManagementProperty> PropertyByTag(PsApiManagementContext context, string propertyTag)
{
var results = ListPagedAndMap<PsApiManagementProperty, PropertyContract>(
() => Client.Property.List(
context.ResourceGroupName,
context.ServiceName,
new QueryParameters
{
Filter = string.Format("tags/any(t: t eq '{0}')", propertyTag)
}),
nextLink => Client.Property.ListNext(nextLink));
return results;
}
public PsApiManagementProperty PropertyById(PsApiManagementContext context, string propertyId)
{
var response = Client.Property.Get(context.ResourceGroupName, context.ServiceName, propertyId);
var property = Mapper.Map<PsApiManagementProperty>(response.Value);
return property;
}
public void PropertyRemove(PsApiManagementContext context, string propertyId)
{
Client.Property.Delete(context.ResourceGroupName, context.ServiceName, propertyId, "*");
}
public void PropertySet(
PsApiManagementContext context,
string propertyId,
string propertyName,
string propertyValue,
bool? isSecret,
IList<string> tags = null)
{
var propertyUpdateParameters = new PropertyUpdateParameters();
if (!string.IsNullOrWhiteSpace(propertyName))
{
propertyUpdateParameters.Name = propertyName;
}
if (!string.IsNullOrWhiteSpace(propertyValue))
{
propertyUpdateParameters.Value = propertyValue;
}
if (isSecret.HasValue)
{
propertyUpdateParameters.Secret = isSecret.Value;
}
if (tags != null)
{
propertyUpdateParameters.Tags = tags;
}
Client.Property.Update(
context.ResourceGroupName,
context.ServiceName,
propertyId,
propertyUpdateParameters,
"*");
}
#endregion
#region OpenIdConnectProvider
public PsApiManagementOpenIdConnectProvider OpenIdProviderCreate(
PsApiManagementContext context,
string openIdProviderId,
string name,
string metadataEndpointUri,
string clientId,
string clientSecret,
string description)
{
var openIdProviderCreateParameters = new OpenidConnectProviderCreateContract(name, metadataEndpointUri, clientId);
if (!string.IsNullOrWhiteSpace(clientSecret))
{
openIdProviderCreateParameters.ClientSecret = clientSecret;
}
if (!string.IsNullOrWhiteSpace(description))
{
openIdProviderCreateParameters.Description = description;
}
Client.OpenIdConnectProviders.Create(
context.ResourceGroupName,
context.ServiceName,
openIdProviderId,
openIdProviderCreateParameters);
var response = Client.OpenIdConnectProviders.Get(context.ResourceGroupName, context.ServiceName, openIdProviderId);
var openIdConnectProvider = Mapper.Map<PsApiManagementOpenIdConnectProvider>(response.Value);
return openIdConnectProvider;
}
public IList<PsApiManagementOpenIdConnectProvider> OpenIdConnectProvidersList(PsApiManagementContext context)
{
var results = ListPagedAndMap<PsApiManagementOpenIdConnectProvider, OpenidConnectProviderContract>(
() => Client.OpenIdConnectProviders.List(context.ResourceGroupName, context.ServiceName, null),
nextLink => Client.OpenIdConnectProviders.ListNext(nextLink));
return results;
}
public IList<PsApiManagementOpenIdConnectProvider> OpenIdConnectProviderByName(PsApiManagementContext context, string openIdConnectProviderName)
{
var results = ListPagedAndMap<PsApiManagementOpenIdConnectProvider, OpenidConnectProviderContract>(
() => Client.OpenIdConnectProviders.List(
context.ResourceGroupName,
context.ServiceName,
new QueryParameters
{
Filter = string.Format("substringof('{0}',name)", openIdConnectProviderName)
}),
nextLink => Client.OpenIdConnectProviders.ListNext(nextLink));
return results;
}
public PsApiManagementOpenIdConnectProvider OpenIdConnectProviderById(PsApiManagementContext context, string openIdConnectProviderId)
{
var response = Client.OpenIdConnectProviders.Get(
context.ResourceGroupName,
context.ServiceName,
openIdConnectProviderId);
var openIdConnectProvider = Mapper.Map<PsApiManagementOpenIdConnectProvider>(response.Value);
return openIdConnectProvider;
}
public void OpenIdConnectProviderRemove(PsApiManagementContext context, string openIdConnectProviderId)
{
Client.OpenIdConnectProviders.Delete(context.ResourceGroupName, context.ServiceName, openIdConnectProviderId, "*");
}
public void OpenIdConnectProviderSet(
PsApiManagementContext context,
string openIdConnectProviderId,
string name,
string description,
string clientId,
string clientSecret,
string metadataEndpoint)
{
var openIdConnectProviderUpdateParameters = new OpenidConnectProviderUpdateContract();
if (!string.IsNullOrWhiteSpace(name))
{
openIdConnectProviderUpdateParameters.Name = name;
}
if (!string.IsNullOrWhiteSpace(description))
{
openIdConnectProviderUpdateParameters.Description = description;
}
if (!string.IsNullOrWhiteSpace(clientId))
{
openIdConnectProviderUpdateParameters.ClientId = clientId;
}
if (!string.IsNullOrWhiteSpace(clientSecret))
{
openIdConnectProviderUpdateParameters.ClientSecret = clientSecret;
}
if (!string.IsNullOrWhiteSpace(metadataEndpoint))
{
openIdConnectProviderUpdateParameters.MetadataEndpoint = metadataEndpoint;
}
Client.OpenIdConnectProviders.Update(
context.ResourceGroupName,
context.ServiceName,
openIdConnectProviderId,
openIdConnectProviderUpdateParameters,
"*");
}
#endregion
#region TenantAccessInformation
public PsApiManagementAccessInformation GetTenantGitAccessInformation(PsApiManagementContext context)
{
var response = Client.TenantAccessGit.Get(
context.ResourceGroupName,
context.ServiceName);
return Mapper.Map<PsApiManagementAccessInformation>(response.Value);
}
#endregion
#region TenantConfiguration
public TenantConfigurationLongRunningOperation BeginSaveTenantGitConfiguration(
PsApiManagementContext context,
string branchName,
bool force)
{
var saveConfigurationParams = new SaveConfigurationParameter(branchName)
{
Force = force
};
var longrunningResponse = Client.TenantConfiguration.BeginSave(
context.ResourceGroupName,
context.ServiceName,
saveConfigurationParams);
return TenantConfigurationLongRunningOperation.CreateLongRunningOperation("Save-AzureRmApiManagementTenantGitConfiguration", longrunningResponse);
}
public TenantConfigurationLongRunningOperation BeginPublishTenantGitConfiguration(
PsApiManagementContext context,
string branchName,
bool force)
{
var deployConfigurationParams = new DeployConfigurationParameters(branchName)
{
Force = force
};
var longrunningResponse = Client.TenantConfiguration.BeginDeploy(
context.ResourceGroupName,
context.ServiceName,
deployConfigurationParams);
return TenantConfigurationLongRunningOperation.CreateLongRunningOperation("Publish-AzureRmApiManagementTenantGitConfiguration", longrunningResponse);
}
public TenantConfigurationLongRunningOperation BeginValidateTenantGitConfiguration(
PsApiManagementContext context,
string branchName,
bool force)
{
var deployConfigurationParams = new DeployConfigurationParameters(branchName)
{
Force = force
};
var longrunningResponse = Client.TenantConfiguration.BeginValidate(
context.ResourceGroupName,
context.ServiceName,
deployConfigurationParams);
return TenantConfigurationLongRunningOperation.CreateLongRunningOperation("Publish-AzureRmApiManagementTenantGitConfiguration -ValidateOnly", longrunningResponse);
}
public PsApiManagementTenantConfigurationSyncState GetTenantConfigurationSyncState(
PsApiManagementContext context)
{
var response = Client.TenantConfigurationSyncState.Get(
context.ResourceGroupName,
context.ServiceName);
return Mapper.Map<PsApiManagementTenantConfigurationSyncState>(response.Value);
}
#endregion
#region TenantAccessInformation
public PsApiManagementAccessInformation GetTenantAccessInformation(PsApiManagementContext context)
{
var response = Client.TenantAccess.Get(
context.ResourceGroupName,
context.ServiceName);
return Mapper.Map<PsApiManagementAccessInformation>(response.Value);
}
public void TenantAccessSet(
PsApiManagementContext context,
bool enabledTenantAccess)
{
var accessInformationParams = new AccessInformationUpdateParameters
{
Enabled = enabledTenantAccess
};
Client.TenantAccess.Update(context.ResourceGroupName, context.ServiceName, accessInformationParams, "*");
}
#endregion
#region IdentityProvider
public PsApiManagementIdentityProvider IdentityProviderCreate(
PsApiManagementContext context,
string identityProviderName,
string clientId,
string clientSecret,
string[] allowedTenants)
{
var identityProviderCreateParameters = new IdentityProviderCreateParameters(clientId, clientSecret);
if (allowedTenants != null)
{
identityProviderCreateParameters.AllowedTenants = allowedTenants;
}
Client.IdentityProvider.Create(context.ResourceGroupName, context.ServiceName, identityProviderName,
identityProviderCreateParameters);
var response = Client.IdentityProvider.Get(context.ResourceGroupName, context.ServiceName, identityProviderName);
var identityProvider = Mapper.Map<PsApiManagementIdentityProvider>(response.Value);
return identityProvider;
}
public IList<PsApiManagementIdentityProvider> IdentityProviderList(PsApiManagementContext context)
{
var identityProviderListResponse = Client.IdentityProvider.List(context.ResourceGroupName, context.ServiceName,
new QueryParameters());
var results = Mapper.Map<IList<PsApiManagementIdentityProvider>>(identityProviderListResponse.Result);
return results;
}
public PsApiManagementIdentityProvider IdentityProviderByName(PsApiManagementContext context, string identityProviderName)
{
var response = Client.IdentityProvider.Get(context.ResourceGroupName, context.ServiceName,
identityProviderName);
var identityProvider = Mapper.Map<PsApiManagementIdentityProvider>(response.Value);
return identityProvider;
}
public void IdentityProviderRemove(PsApiManagementContext context, string identityProviderName)
{
Client.IdentityProvider.Delete(context.ResourceGroupName, context.ServiceName, identityProviderName, "*");
}
public void IdentityProviderSet(PsApiManagementContext context, string identityProviderName, string clientId, string clientSecret, string[] allowedTenant)
{
var parameters = new IdentityProviderUpdateParameters();
if (!string.IsNullOrEmpty(clientId))
{
parameters.ClientId = clientId;
}
if (!string.IsNullOrEmpty(clientSecret))
{
parameters.ClientSecret = clientSecret;
}
if (allowedTenant != null)
{
parameters.AllowedTenants = allowedTenant;
}
Client.IdentityProvider.Update(
context.ResourceGroupName,
context.ServiceName,
identityProviderName,
parameters,
"*");
}
#endregion
#region Backends
public PsApiManagementBackend BackendCreate(
PsApiManagementContext context,
string backendId,
string url,
string protocol,
string title,
string description,
string resourceId,
bool? skipCertificateChainValidation,
bool? skipCertificateNameValidation,
PsApiManagementBackendCredential credential,
PsApiManagementBackendProxy proxy)
{
var backendCreateParams = new BackendCreateParameters(url, protocol);
if (!string.IsNullOrEmpty(resourceId))
{
backendCreateParams.ResourceId = resourceId;
}
if (!string.IsNullOrEmpty(title))
{
backendCreateParams.Title = title;
}
if (!string.IsNullOrEmpty(description))
{
backendCreateParams.Description = description;
}
if (skipCertificateChainValidation.HasValue || skipCertificateNameValidation.HasValue)
{
backendCreateParams.Properties = new Dictionary<string, object>();
if (skipCertificateNameValidation.HasValue)
{
backendCreateParams.Properties.Add("skipCertificateNameValidation", skipCertificateNameValidation.Value);
}
if (skipCertificateChainValidation.HasValue)
{
backendCreateParams.Properties.Add("skipCertificateChainValidation", skipCertificateChainValidation.Value);
}
}
if (credential != null)
{
backendCreateParams.Credentials = new BackendCredentialsContract();
if (credential.Query != null)
{
backendCreateParams.Credentials.Query = HashTableToDictionary(credential.Query);
}
if (credential.Header != null)
{
backendCreateParams.Credentials.Header = HashTableToDictionary(credential.Header);
}
if (credential.Certificate != null && credential.Certificate.Any())
{
backendCreateParams.Credentials.Certificate = credential.Certificate.ToList();
}
if (credential.Authorization != null)
{
backendCreateParams.Credentials.Authorization =
Mapper.Map<AuthorizationHeaderCredentialsContract>(credential.Authorization);
}
}
if (proxy != null)
{
backendCreateParams.Proxy = Mapper.Map<PsApiManagementBackendProxy, BackendProxyContract>(proxy);
}
Client.Backends.Create(context.ResourceGroupName, context.ServiceName, backendId, backendCreateParams);
var response = Client.Backends.Get(context.ResourceGroupName, context.ServiceName, backendId);
var backend = Mapper.Map<BackendGetContract, PsApiManagementBackend>(response.Value);
return backend;
}
static Dictionary<string, List<string>> HashTableToDictionary(Hashtable table)
{
if (table == null)
{
return null;
}
var result = new Dictionary<string, List<string>>();
foreach (var entry in table.Cast<DictionaryEntry>())
{
var entryValue = entry.Value as object[];
if (entryValue == null)
{
throw new ArgumentException(
string.Format(CultureInfo.InvariantCulture,
"Invalid input type specified for Key '{0}', expected string[]",
entry.Key));
}
result.Add(entry.Key.ToString(), entryValue.Select(i => i.ToString()).ToList());
}
return result;
}
static Hashtable DictionaryToHashTable(IDictionary<string, List<string>> dictionary)
{
if (dictionary == null)
{
return null;
}
var result = new Hashtable();
foreach (var keyEntry in dictionary.Keys)
{
var keyValue = dictionary[keyEntry];
result.Add(keyEntry, keyValue.Cast<object>().ToArray());
}
return result;
}
public IList<PsApiManagementBackend> BackendsList(PsApiManagementContext context)
{
var results = ListPagedAndMap<PsApiManagementBackend, BackendGetContract>(
() => Client.Backends.List(context.ResourceGroupName, context.ServiceName, null),
nextLink => Client.Backends.ListNext(nextLink));
return results;
}
public PsApiManagementBackend BackendById(PsApiManagementContext context, string backendId)
{
var response = Client.Backends.Get(context.ResourceGroupName, context.ServiceName, backendId);
var backend = Mapper.Map<PsApiManagementBackend>(response.Value);
return backend;
}
public void BackendRemove(PsApiManagementContext context, string backendId)
{
Client.Backends.Delete(context.ResourceGroupName, context.ServiceName, backendId, "*");
}
public void BackendSet(
PsApiManagementContext context,
string backendId,
string url,
string protocol,
string title,
string description,
string resourceId,
bool? skipCertificateChainValidation,
bool? skipCertificateNameValidation,
PsApiManagementBackendCredential credential,
PsApiManagementBackendProxy proxy)
{
var backendUpdateParams = new BackendUpdateParameters();
if (!string.IsNullOrEmpty(url))
{
backendUpdateParams.Url = url;
}
if (!string.IsNullOrEmpty(protocol))
{
backendUpdateParams.Protocol = protocol;
}
if (!string.IsNullOrEmpty(resourceId))
{
backendUpdateParams.ResourceId = resourceId;
}
if (!string.IsNullOrEmpty(title))
{
backendUpdateParams.Title = title;
}
if (!string.IsNullOrEmpty(description))
{
backendUpdateParams.Description = description;
}
if (skipCertificateChainValidation.HasValue || skipCertificateNameValidation.HasValue)
{
backendUpdateParams.Properties = new Dictionary<string, object>();
if (skipCertificateNameValidation.HasValue)
{
backendUpdateParams.Properties.Add("skipCertificateNameValidation", skipCertificateNameValidation.Value);
}
if (skipCertificateChainValidation.HasValue)
{
backendUpdateParams.Properties.Add("skipCertificateChainValidation", skipCertificateChainValidation.Value);
}
}
if (credential != null)
{
backendUpdateParams.Credentials = new BackendCredentialsContract();
if (credential.Query != null)
{
backendUpdateParams.Credentials.Query = HashTableToDictionary(credential.Query);
}
if (credential.Header != null)
{
backendUpdateParams.Credentials.Header = HashTableToDictionary(credential.Header);
}
if (credential.Certificate != null && credential.Certificate.Any())
{
backendUpdateParams.Credentials.Certificate = credential.Certificate.ToList();
}
if (credential.Authorization != null)
{
backendUpdateParams.Credentials.Authorization =
Mapper.Map<AuthorizationHeaderCredentialsContract>(credential.Authorization);
}
}
if (proxy != null)
{
backendUpdateParams.Proxy = Mapper.Map<BackendProxyContract>(proxy);
}
Client.Backends.Update(
context.ResourceGroupName,
context.ServiceName,
backendId,
backendUpdateParams,
"*");
}
#endregion
}
} | 41.963801 | 183 | 0.582122 | [
"MIT"
] | AzureDataBox/azure-powershell | src/ResourceManager/ApiManagement/Commands.ApiManagement.ServiceManagement/ApiManagementClient.cs | 90,533 | C# |
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="CustomUIEventArgs.cs" company="NBug Project">
// Copyright (c) 2011 - 2013 Teoman Soygul. Licensed under MIT license.
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
namespace NBug.Events
{
using System;
using NBug.Core.Reporting.Info;
using NBug.Core.UI;
using NBug.Core.Util.Serialization;
using NBug.Enums;
public class CustomUIEventArgs : EventArgs
{
internal CustomUIEventArgs(UIMode uiMode, SerializableException exception, Report report)
{
this.UIMode = uiMode;
this.Report = report;
this.Exception = exception;
this.Result = new UIDialogResult(ExecutionFlow.BreakExecution, SendReport.DoNotSend);
}
public SerializableException Exception { get; private set; }
public Report Report { get; private set; }
public UIDialogResult Result { get; set; }
public UIMode UIMode { get; private set; }
}
} | 31.5 | 119 | 0.572362 | [
"MIT"
] | JavierCanon/ExceptionReporter.NET | src/Others/NBug/NBug/Events/CustomUIEventArgs.cs | 1,071 | C# |
using UnityEngine;
namespace Ez.Threading
{
public static class TimeExtension
{
public static ITask<float> StartingIn(this ITask<float> self, float durationInSeconds)
{
return self.StartingAt(Time.time + durationInSeconds);
}
public static ITask<float> StartingAt(this ITask<float> self, float startInSeconds)
{
return self.SkipWhile(now => now < startInSeconds);
}
public static ITask<float> EndingIn(this ITask<float> self, float durationInSeconds)
{
return self.EndingAt(Time.time + durationInSeconds);
}
public static ITask<float> EndingAt(this ITask<float> self, float endInSeconds)
{
return self.TakeWhile(now => now < endInSeconds);
}
public static ITask<float> RelativeToStart(this ITask<float> self)
{
return self.RelativeToStart(Time.time);
}
public static ITask<float> RelativeToStart(this ITask<float> self, float startInSeconds)
{
return self.Select(now => now - startInSeconds);
}
public static ITask<float> RelativeToLast(this ITask<float> self)
{
return self.RelativeToLast(Time.time);
}
public static ITask<float> RelativeToLast(this ITask<float> self, float startInSeconds)
{
return self.Select(now =>
{
var delta = now - startInSeconds;
startInSeconds = now;
return delta;
});
}
public static ITask<float> AtFequency(this ITask<float> self, float countPerDuration, float durationInSeconds = 1)
{
return self.AtInterval(durationInSeconds / countPerDuration);
}
public static ITask<float> AtInterval(this ITask<float> self, float intervalInSecond)
{
return self.AtInterval(Time.time, intervalInSecond);
}
public static ITask<float> AtInterval(this ITask<float> self, float start, float intervalInSecond)
{
var next = start + intervalInSecond;
return self
.Where(now =>
{
if (next <= now)
{
next = next + intervalInSecond;
return true;
}
else
return false;
});
}
}
} | 33.540541 | 122 | 0.556809 | [
"MIT"
] | foxtrot-roger/unity-EzThreading | Assets/_Libraries/Ez/Scripts/Threading/Unity/TimeExtension.cs | 2,484 | C# |
namespace SFA.Apprenticeships.Application.UnitTests.Candidates.Strategies.ActivationReminder
{
using Apprenticeships.Application.Candidates.Configuration;
using Apprenticeships.Application.Candidates.Strategies;
using Apprenticeships.Application.Candidates.Strategies.ActivationReminder;
using Configuration;
using SFA.Infrastructure.Interfaces;
using Interfaces.Communications;
using Moq;
using SFA.Apprenticeships.Application.Interfaces;
public class SendAccountRemindersStrategyBuilder
{
private Mock<IConfigurationService> _configurationService;
private Mock<ICommunicationService> _communicationService;
private IHousekeepingStrategy _successor;
public SendAccountRemindersStrategyBuilder()
{
_configurationService = new Mock<IConfigurationService>();
_configurationService.Setup(s => s.Get<HousekeepingConfiguration>()).Returns(new HousekeepingConfigurationBuilder().Build());
_communicationService = new Mock<ICommunicationService>();
_successor = new TerminatingHousekeepingStrategy(_configurationService.Object);
}
public SendAccountRemindersStrategy Build()
{
var strategy = new SendAccountRemindersStrategy(_configurationService.Object, _communicationService.Object);
strategy.SetSuccessor(_successor);
return strategy;
}
public SendAccountRemindersStrategyBuilder With(Mock<IConfigurationService> configurationService)
{
_configurationService = configurationService;
return this;
}
public SendAccountRemindersStrategyBuilder With(HousekeepingConfiguration configuration)
{
_configurationService.Setup(s => s.Get<HousekeepingConfiguration>()).Returns(configuration);
return this;
}
public SendAccountRemindersStrategyBuilder With(IHousekeepingStrategy successor)
{
_successor = successor;
return this;
}
public SendAccountRemindersStrategyBuilder With(Mock<ICommunicationService> communicationService)
{
_communicationService = communicationService;
return this;
}
}
} | 38.677966 | 137 | 0.712971 | [
"MIT"
] | BugsUK/FindApprenticeship | src/SFA.Apprenticeships.Application.UnitTests/Candidates/Strategies/ActivationReminder/SendAccountRemindersStrategyBuilder.cs | 2,284 | C# |
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Agent.Sdk;
using Microsoft.TeamFoundation.DistributedTask.WebApi;
using Microsoft.VisualStudio.Services.PipelineCache.WebApi;
namespace Agent.Plugins.PipelineCache
{
public class SavePipelineCacheV0 : PipelineCacheTaskPluginBase
{
public override string Stage => "post";
/* To mitigate the issue - https://github.com/microsoft/azure-pipelines-tasks/issues/10907, we need to check the restore condition logic, before creating the fingerprint.
Hence we are overriding the RunAsync function to include that logic. */
public override async Task RunAsync(AgentTaskPluginExecutionContext context, CancellationToken token)
{
bool successSoFar = false;
if (context.Variables.TryGetValue("agent.jobstatus", out VariableValue jobStatusVar))
{
if (Enum.TryParse<TaskResult>(jobStatusVar?.Value ?? string.Empty, true, out TaskResult jobStatus))
{
if (jobStatus == TaskResult.Succeeded)
{
successSoFar = true;
}
}
}
if (!successSoFar)
{
context.Info($"Skipping because the job status was not 'Succeeded'.");
return;
}
bool restoreStepRan = false;
if (context.TaskVariables.TryGetValue(RestoreStepRanVariableName, out VariableValue ran))
{
if (ran != null && ran.Value != null && ran.Value.Equals(RestoreStepRanVariableValue, StringComparison.Ordinal))
{
restoreStepRan = true;
}
}
if (!restoreStepRan)
{
context.Info($"Skipping because restore step did not run.");
return;
}
await base.RunAsync(context, token);
}
protected override async Task ProcessCommandInternalAsync(
AgentTaskPluginExecutionContext context,
Fingerprint fingerprint,
Func<Fingerprint[]> restoreKeysGenerator,
string path,
CancellationToken token)
{
string contentFormatValue = context.Variables.GetValueOrDefault(ContentFormatVariableName)?.Value ?? string.Empty;
string calculatedFingerPrint = context.TaskVariables.GetValueOrDefault(ResolvedFingerPrintVariableName)?.Value ?? string.Empty;
if(!string.IsNullOrWhiteSpace(calculatedFingerPrint) && !fingerprint.ToString().Equals(calculatedFingerPrint, StringComparison.Ordinal))
{
context.Warning($"The given cache key has changed in its resolved value between restore and save steps;\n"+
$"original key: {calculatedFingerPrint}\n"+
$"modified key: {fingerprint}\n");
}
ContentFormat contentFormat;
if (string.IsNullOrWhiteSpace(contentFormatValue))
{
contentFormat = ContentFormat.SingleTar;
}
else
{
contentFormat = Enum.Parse<ContentFormat>(contentFormatValue, ignoreCase: true);
}
PipelineCacheServer server = new PipelineCacheServer(context);
await server.UploadAsync(
context,
fingerprint,
path,
token,
contentFormat);
}
}
}
| 38.821053 | 178 | 0.593275 | [
"MIT"
] | 50Wliu/azure-pipelines-agent | src/Agent.Plugins/PipelineCache/SavePipelineCacheV0.cs | 3,688 | C# |
using System;
using System.Windows.Forms;
namespace QO_100_ADIF_Tool
{
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new QO100AdifTool());
}
}
}
| 22 | 65 | 0.581818 | [
"MIT"
] | sanjint/QO-100_ADIF | QO-100 ADIF Tool/Program.cs | 442 | C# |
namespace VkNet.Enums.SafetyEnums
{
/// <summary>
/// Тип служебного альбома с фотографиями
/// </summary>
public sealed class PhotoAlbumType : SafetyEnum<PhotoAlbumType>
{
/// <summary>
/// Фотографии со стены
/// </summary>
public static readonly PhotoAlbumType Wall = RegisterPossibleValue("wall");
/// <summary>
/// Аватары
/// </summary>
public static readonly PhotoAlbumType Profile = RegisterPossibleValue("profile");
/// <summary>
/// Сохраненные фотографии
/// </summary>
public static readonly PhotoAlbumType Saved = RegisterPossibleValue("saved");
/// <summary>
/// Идентификатор альбома
/// </summary>
/// <param name="number">Номер списка.</param>
/// <returns>Номер списка.</returns>
public static PhotoAlbumType Id(long number)
{
return RegisterPossibleValue(number + "");
}
}
} | 25.636364 | 83 | 0.682033 | [
"MIT"
] | uid17/VK | VkNet/Enums/SafetyEnums/PhotoAlbumType.cs | 968 | C# |
using FreeSql.Internal;
using FreeSql.Internal.Model;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
namespace FreeSql.Sqlite
{
class SqliteExpression : CommonExpression
{
public SqliteExpression(CommonUtils common) : base(common) { }
public override string ExpressionLambdaToSqlOther(Expression exp, ExpTSC tsc)
{
Func<Expression, string> getExp = exparg => ExpressionLambdaToSql(exparg, tsc);
switch (exp.NodeType)
{
case ExpressionType.Convert:
var operandExp = (exp as UnaryExpression)?.Operand;
var gentype = exp.Type.NullableTypeOrThis();
if (gentype != operandExp.Type.NullableTypeOrThis())
{
switch (exp.Type.NullableTypeOrThis().ToString())
{
case "System.Boolean": return $"({getExp(operandExp)} not in ('0','false'))";
case "System.Byte": return $"cast({getExp(operandExp)} as int2)";
case "System.Char": return $"substr(cast({getExp(operandExp)} as character), 1, 1)";
case "System.DateTime": return $"datetime({getExp(operandExp)})";
case "System.Decimal": return $"cast({getExp(operandExp)} as decimal(36,18))";
case "System.Double": return $"cast({getExp(operandExp)} as double)";
case "System.Int16":
case "System.Int32":
case "System.Int64":
case "System.SByte": return $"cast({getExp(operandExp)} as smallint)";
case "System.Single": return $"cast({getExp(operandExp)} as float)";
case "System.String": return $"cast({getExp(operandExp)} as character)";
case "System.UInt16": return $"cast({getExp(operandExp)} as unsigned)";
case "System.UInt32": return $"cast({getExp(operandExp)} as decimal(10,0))";
case "System.UInt64": return $"cast({getExp(operandExp)} as decimal(21,0))";
case "System.Guid": return $"substr(cast({getExp(operandExp)} as character), 1, 36)";
}
}
break;
case ExpressionType.Call:
var callExp = exp as MethodCallExpression;
switch (callExp.Method.Name)
{
case "Parse":
case "TryParse":
switch (callExp.Method.DeclaringType.NullableTypeOrThis().ToString())
{
case "System.Boolean": return $"({getExp(callExp.Arguments[0])} not in ('0','false'))";
case "System.Byte": return $"cast({getExp(callExp.Arguments[0])} as int2)";
case "System.Char": return $"substr(cast({getExp(callExp.Arguments[0])} as character), 1, 1)";
case "System.DateTime": return $"datetime({getExp(callExp.Arguments[0])})";
case "System.Decimal": return $"cast({getExp(callExp.Arguments[0])} as decimal(36,18))";
case "System.Double": return $"cast({getExp(callExp.Arguments[0])} as double)";
case "System.Int16":
case "System.Int32":
case "System.Int64":
case "System.SByte": return $"cast({getExp(callExp.Arguments[0])} as smallint)";
case "System.Single": return $"cast({getExp(callExp.Arguments[0])} as float)";
case "System.UInt16": return $"cast({getExp(callExp.Arguments[0])} as unsigned)";
case "System.UInt32": return $"cast({getExp(callExp.Arguments[0])} as decimal(10,0))";
case "System.UInt64": return $"cast({getExp(callExp.Arguments[0])} as decimal(21,0))";
case "System.Guid": return $"substr(cast({getExp(callExp.Arguments[0])} as character), 1, 36)";
}
break;
case "NewGuid":
break;
case "Next":
if (callExp.Object?.Type == typeof(Random)) return "cast(random()*1000000000 as int)";
break;
case "NextDouble":
if (callExp.Object?.Type == typeof(Random)) return "random()";
break;
case "Random":
if (callExp.Method.DeclaringType.IsNumberType()) return "random()";
break;
case "ToString":
if (callExp.Object != null) return callExp.Arguments.Count == 0 ? $"cast({getExp(callExp.Object)} as character)" : null;
break;
}
var objExp = callExp.Object;
var objType = objExp?.Type;
if (objType?.FullName == "System.Byte[]") return null;
var argIndex = 0;
if (objType == null && callExp.Method.DeclaringType == typeof(Enumerable))
{
objExp = callExp.Arguments.FirstOrDefault();
objType = objExp?.Type;
argIndex++;
}
if (objType == null) objType = callExp.Method.DeclaringType;
if (objType != null || objType.IsArray || typeof(IList).IsAssignableFrom(callExp.Method.DeclaringType))
{
var left = objExp == null ? null : getExp(objExp);
switch (callExp.Method.Name)
{
case "Contains":
//判断 in
return $"({getExp(callExp.Arguments[argIndex])}) in {left}";
}
}
break;
case ExpressionType.NewArrayInit:
var arrExp = exp as NewArrayExpression;
var arrSb = new StringBuilder();
arrSb.Append("(");
for (var a = 0; a < arrExp.Expressions.Count; a++)
{
if (a > 0) arrSb.Append(",");
arrSb.Append(getExp(arrExp.Expressions[a]));
}
if (arrSb.Length == 1) arrSb.Append("NULL");
return arrSb.Append(")").ToString();
case ExpressionType.ListInit:
var listExp = exp as ListInitExpression;
var listSb = new StringBuilder();
listSb.Append("(");
for (var a = 0; a < listExp.Initializers.Count; a++)
{
if (listExp.Initializers[a].Arguments.Any() == false) continue;
if (a > 0) listSb.Append(",");
listSb.Append(getExp(listExp.Initializers[a].Arguments.FirstOrDefault()));
}
if (listSb.Length == 1) listSb.Append("NULL");
return listSb.Append(")").ToString();
case ExpressionType.New:
var newExp = exp as NewExpression;
if (typeof(IList).IsAssignableFrom(newExp.Type))
{
if (newExp.Arguments.Count == 0) return "(NULL)";
if (typeof(IEnumerable).IsAssignableFrom(newExp.Arguments[0].Type) == false) return "(NULL)";
return getExp(newExp.Arguments[0]);
}
return null;
}
return null;
}
public override string ExpressionLambdaToSqlMemberAccessString(MemberExpression exp, ExpTSC tsc)
{
if (exp.Expression == null)
{
switch (exp.Member.Name)
{
case "Empty": return "''";
}
return null;
}
var left = ExpressionLambdaToSql(exp.Expression, tsc);
switch (exp.Member.Name)
{
case "Length": return $"length({left})";
}
return null;
}
public override string ExpressionLambdaToSqlMemberAccessDateTime(MemberExpression exp, ExpTSC tsc)
{
if (exp.Expression == null)
{
switch (exp.Member.Name)
{
case "Now": return "datetime(current_timestamp,'localtime')";
case "UtcNow": return "current_timestamp";
case "Today": return "date(current_timestamp,'localtime')";
case "MinValue": return "datetime('0001-01-01 00:00:00.000')";
case "MaxValue": return "datetime('9999-12-31 23:59:59.999')";
}
return null;
}
var left = ExpressionLambdaToSql(exp.Expression, tsc);
switch (exp.Member.Name)
{
case "Date": return $"date({left})";
case "TimeOfDay": return $"strftime('%s',{left})";
case "DayOfWeek": return $"strftime('%w',{left})";
case "Day": return $"strftime('%d',{left})";
case "DayOfYear": return $"strftime('%j',{left})";
case "Month": return $"strftime('%m',{left})";
case "Year": return $"strftime('%Y',{left})";
case "Hour": return $"strftime('%H',{left})";
case "Minute": return $"strftime('%M',{left})";
case "Second": return $"strftime('%S',{left})";
case "Millisecond": return $"(strftime('%f',{left})-strftime('%S',{left}))";
case "Ticks": return $"(strftime('%s',{left})*10000000+621355968000000000)";
}
return null;
}
public override string ExpressionLambdaToSqlMemberAccessTimeSpan(MemberExpression exp, ExpTSC tsc)
{
if (exp.Expression == null)
{
switch (exp.Member.Name)
{
case "Zero": return "0";
case "MinValue": return "-922337203685.477580"; //秒 Ticks / 1000,000,0
case "MaxValue": return "922337203685.477580";
}
return null;
}
var left = ExpressionLambdaToSql(exp.Expression, tsc);
switch (exp.Member.Name)
{
case "Days": return $"floor(({left})/{60 * 60 * 24})";
case "Hours": return $"floor(({left})/{60 * 60}%24)";
case "Milliseconds": return $"(cast({left} as bigint)*1000)";
case "Minutes": return $"floor(({left})/60%60)";
case "Seconds": return $"(({left})%60)";
case "Ticks": return $"(cast({left} as bigint)*10000000)";
case "TotalDays": return $"(({left})/{60 * 60 * 24})";
case "TotalHours": return $"(({left})/{60 * 60})";
case "TotalMilliseconds": return $"(cast({left} as bigint)*1000)";
case "TotalMinutes": return $"(({left})/60)";
case "TotalSeconds": return $"({left})";
}
return null;
}
public override string ExpressionLambdaToSqlCallString(MethodCallExpression exp, ExpTSC tsc)
{
Func<Expression, string> getExp = exparg => ExpressionLambdaToSql(exparg, tsc);
if (exp.Object == null)
{
switch (exp.Method.Name)
{
case "IsNullOrEmpty":
var arg1 = getExp(exp.Arguments[0]);
return $"({arg1} is null or {arg1} = '')";
case "IsNullOrWhiteSpace":
var arg2 = getExp(exp.Arguments[0]);
return $"({arg2} is null or {arg2} = '' or ltrim({arg2}) = '')";
case "Concat":
return _common.StringConcat(exp.Arguments.Select(a => getExp(a)).ToArray(), null);
}
}
else
{
var left = getExp(exp.Object);
switch (exp.Method.Name)
{
case "StartsWith":
case "EndsWith":
case "Contains":
var args0Value = getExp(exp.Arguments[0]);
if (args0Value == "NULL") return $"({left}) IS NULL";
if (exp.Method.Name == "StartsWith") return $"({left}) LIKE {(args0Value.EndsWith("'") ? args0Value.Insert(args0Value.Length - 1, "%") : $"({args0Value})||'%'")}";
if (exp.Method.Name == "EndsWith") return $"({left}) LIKE {(args0Value.StartsWith("'") ? args0Value.Insert(1, "%") : $"'%'||({args0Value})")}";
if (args0Value.StartsWith("'") && args0Value.EndsWith("'")) return $"({left}) LIKE {args0Value.Insert(1, "%").Insert(args0Value.Length, "%")}";
return $"({left}) LIKE '%'||({args0Value})||'%'";
case "ToLower": return $"lower({left})";
case "ToUpper": return $"upper({left})";
case "Substring":
var substrArgs1 = getExp(exp.Arguments[0]);
if (long.TryParse(substrArgs1, out var testtrylng1)) substrArgs1 = (testtrylng1 + 1).ToString();
else substrArgs1 += "+1";
if (exp.Arguments.Count == 1) return $"substr({left}, {substrArgs1})";
return $"substr({left}, {substrArgs1}, {getExp(exp.Arguments[1])})";
case "IndexOf":
var indexOfFindStr = getExp(exp.Arguments[0]);
//if (exp.Arguments.Count > 1 && exp.Arguments[1].Type.FullName == "System.Int32") {
// var locateArgs1 = getExp(exp.Arguments[1]);
// if (long.TryParse(locateArgs1, out var testtrylng2)) locateArgs1 = (testtrylng2 + 1).ToString();
// else locateArgs1 += "+1";
// return $"(instr({left}, {indexOfFindStr}, {locateArgs1})-1)";
//}
return $"(instr({left}, {indexOfFindStr})-1)";
case "PadLeft":
if (exp.Arguments.Count == 1) return $"lpad({left}, {getExp(exp.Arguments[0])})";
return $"lpad({left}, {getExp(exp.Arguments[0])}, {getExp(exp.Arguments[1])})";
case "PadRight":
if (exp.Arguments.Count == 1) return $"rpad({left}, {getExp(exp.Arguments[0])})";
return $"rpad({left}, {getExp(exp.Arguments[0])}, {getExp(exp.Arguments[1])})";
case "Trim":
case "TrimStart":
case "TrimEnd":
if (exp.Arguments.Count == 0)
{
if (exp.Method.Name == "Trim") return $"trim({left})";
if (exp.Method.Name == "TrimStart") return $"ltrim({left})";
if (exp.Method.Name == "TrimEnd") return $"rtrim({left})";
}
var trimArg1 = "";
var trimArg2 = "";
foreach (var argsTrim02 in exp.Arguments)
{
var argsTrim01s = new[] { argsTrim02 };
if (argsTrim02.NodeType == ExpressionType.NewArrayInit)
{
var arritem = argsTrim02 as NewArrayExpression;
argsTrim01s = arritem.Expressions.ToArray();
}
foreach (var argsTrim01 in argsTrim01s)
{
var trimChr = getExp(argsTrim01).Trim('\'');
if (trimChr.Length == 1) trimArg1 += trimChr;
else trimArg2 += $" || ({trimChr})";
}
}
if (exp.Method.Name == "Trim") left = $"trim({left}, {_common.FormatSql("{0}", trimArg1)}{trimArg2})";
if (exp.Method.Name == "TrimStart") left = $"ltrim({left}, {_common.FormatSql("{0}", trimArg1)}{trimArg2})";
if (exp.Method.Name == "TrimEnd") left = $"rtrim({left}, {_common.FormatSql("{0}", trimArg1)}{trimArg2})";
return left;
case "Replace": return $"replace({left}, {getExp(exp.Arguments[0])}, {getExp(exp.Arguments[1])})";
case "CompareTo": return $"case when {left} = {getExp(exp.Arguments[0])} then 0 when {left} > {getExp(exp.Arguments[0])} then 1 else -1 end";
case "Equals": return $"({left} = {getExp(exp.Arguments[0])})";
}
}
return null;
}
public override string ExpressionLambdaToSqlCallMath(MethodCallExpression exp, ExpTSC tsc)
{
Func<Expression, string> getExp = exparg => ExpressionLambdaToSql(exparg, tsc);
switch (exp.Method.Name)
{
case "Abs": return $"abs({getExp(exp.Arguments[0])})";
case "Sign": return $"sign({getExp(exp.Arguments[0])})";
case "Floor": return $"floor({getExp(exp.Arguments[0])})";
case "Ceiling": return $"ceiling({getExp(exp.Arguments[0])})";
case "Round":
if (exp.Arguments.Count > 1 && exp.Arguments[1].Type.FullName == "System.Int32") return $"round({getExp(exp.Arguments[0])}, {getExp(exp.Arguments[1])})";
return $"round({getExp(exp.Arguments[0])})";
case "Exp": return $"exp({getExp(exp.Arguments[0])})";
case "Log": return $"log({getExp(exp.Arguments[0])})";
case "Log10": return $"log10({getExp(exp.Arguments[0])})";
case "Pow": return $"power({getExp(exp.Arguments[0])}, {getExp(exp.Arguments[1])})";
case "Sqrt": return $"sqrt({getExp(exp.Arguments[0])})";
case "Cos": return $"cos({getExp(exp.Arguments[0])})";
case "Sin": return $"sin({getExp(exp.Arguments[0])})";
case "Tan": return $"tan({getExp(exp.Arguments[0])})";
case "Acos": return $"acos({getExp(exp.Arguments[0])})";
case "Asin": return $"asin({getExp(exp.Arguments[0])})";
case "Atan": return $"atan({getExp(exp.Arguments[0])})";
case "Atan2": return $"atan2({getExp(exp.Arguments[0])}, {getExp(exp.Arguments[1])})";
//case "Truncate": return $"truncate({getExp(exp.Arguments[0])}, 0)";
}
return null;
}
public override string ExpressionLambdaToSqlCallDateTime(MethodCallExpression exp, ExpTSC tsc)
{
Func<Expression, string> getExp = exparg => ExpressionLambdaToSql(exparg, tsc);
if (exp.Object == null)
{
switch (exp.Method.Name)
{
case "Compare": return $"(strftime('%s',{getExp(exp.Arguments[0])}) -strftime('%s',{getExp(exp.Arguments[1])}))";
case "DaysInMonth": return $"strftime('%d',date({getExp(exp.Arguments[0])}||'-01-01',{getExp(exp.Arguments[1])}||' months','-1 days'))";
case "Equals": return $"({getExp(exp.Arguments[0])} = {getExp(exp.Arguments[1])})";
case "IsLeapYear":
var isLeapYearArgs1 = getExp(exp.Arguments[0]);
return $"(({isLeapYearArgs1})%4=0 AND ({isLeapYearArgs1})%100<>0 OR ({isLeapYearArgs1})%400=0)";
case "Parse": return $"datetime({getExp(exp.Arguments[0])})";
case "ParseExact":
case "TryParse":
case "TryParseExact": return $"datetime({getExp(exp.Arguments[0])})";
}
}
else
{
var left = getExp(exp.Object);
var args1 = exp.Arguments.Count == 0 ? null : getExp(exp.Arguments[0]);
switch (exp.Method.Name)
{
case "Add": return $"datetime({left},({args1})||' seconds')";
case "AddDays": return $"datetime({left},({args1})||' days')";
case "AddHours": return $"datetime({left},({args1})||' hours')";
case "AddMilliseconds": return $"datetime({left},(({args1})/1000)||' seconds')";
case "AddMinutes": return $"datetime({left},({args1})||' seconds')";
case "AddMonths": return $"datetime({left},({args1})||' months')";
case "AddSeconds": return $"datetime({left},({args1})||' seconds')";
case "AddTicks": return $"datetime({left},(({args1})/10000000)||' seconds')";
case "AddYears": return $"datetime({left},({args1})||' years')";
case "Subtract":
switch ((exp.Arguments[0].Type.IsNullableType() ? exp.Arguments[0].Type.GenericTypeArguments.FirstOrDefault() : exp.Arguments[0].Type).FullName)
{
case "System.DateTime": return $"(strftime('%s',{left})-strftime('%s',{args1}))";
case "System.TimeSpan": return $"datetime({left},(({args1})*-1)||' seconds')";
}
break;
case "Equals": return $"({left} = {args1})";
case "CompareTo": return $"(strftime('%s',{left})-strftime('%s',{args1}))";
case "ToString": return exp.Arguments.Count == 0 ? $"strftime('%Y-%m-%d %H:%M.%f',{left})" : null;
}
}
return null;
}
public override string ExpressionLambdaToSqlCallTimeSpan(MethodCallExpression exp, ExpTSC tsc)
{
Func<Expression, string> getExp = exparg => ExpressionLambdaToSql(exparg, tsc);
if (exp.Object == null)
{
switch (exp.Method.Name)
{
case "Compare": return $"({getExp(exp.Arguments[0])}-({getExp(exp.Arguments[1])}))";
case "Equals": return $"({getExp(exp.Arguments[0])} = {getExp(exp.Arguments[1])})";
case "FromDays": return $"(({getExp(exp.Arguments[0])})*{60 * 60 * 24})";
case "FromHours": return $"(({getExp(exp.Arguments[0])})*{60 * 60})";
case "FromMilliseconds": return $"(({getExp(exp.Arguments[0])})/1000)";
case "FromMinutes": return $"(({getExp(exp.Arguments[0])})*60)";
case "FromSeconds": return $"(({getExp(exp.Arguments[0])}))";
case "FromTicks": return $"(({getExp(exp.Arguments[0])})/10000000)";
case "Parse": return $"cast({getExp(exp.Arguments[0])} as bigint)";
case "ParseExact":
case "TryParse":
case "TryParseExact": return $"cast({getExp(exp.Arguments[0])} as bigint)";
}
}
else
{
var left = getExp(exp.Object);
var args1 = exp.Arguments.Count == 0 ? null : getExp(exp.Arguments[0]);
switch (exp.Method.Name)
{
case "Add": return $"({left}+{args1})";
case "Subtract": return $"({left}-({args1}))";
case "Equals": return $"({left} = {args1})";
case "CompareTo": return $"({left}-({args1}))";
case "ToString": return $"cast({left} as character)";
}
}
return null;
}
public override string ExpressionLambdaToSqlCallConvert(MethodCallExpression exp, ExpTSC tsc)
{
Func<Expression, string> getExp = exparg => ExpressionLambdaToSql(exparg, tsc);
if (exp.Object == null)
{
switch (exp.Method.Name)
{
case "ToBoolean": return $"({getExp(exp.Arguments[0])} not in ('0','false'))";
case "ToByte": return $"cast({getExp(exp.Arguments[0])} as int2)";
case "ToChar": return $"substr(cast({getExp(exp.Arguments[0])} as character), 1, 1)";
case "ToDateTime": return $"datetime({getExp(exp.Arguments[0])})";
case "ToDecimal": return $"cast({getExp(exp.Arguments[0])} as decimal(36,18))";
case "ToDouble": return $"cast({getExp(exp.Arguments[0])} as double)";
case "ToInt16":
case "ToInt32":
case "ToInt64":
case "ToSByte": return $"cast({getExp(exp.Arguments[0])} as smallint)";
case "ToSingle": return $"cast({getExp(exp.Arguments[0])} as float)";
case "ToString": return $"cast({getExp(exp.Arguments[0])} as character)";
case "ToUInt16": return $"cast({getExp(exp.Arguments[0])} as unsigned)";
case "ToUInt32": return $"cast({getExp(exp.Arguments[0])} as decimal(10,0))";
case "ToUInt64": return $"cast({getExp(exp.Arguments[0])} as decimal(21,0))";
}
}
return null;
}
}
}
| 57.201735 | 187 | 0.466705 | [
"MIT"
] | Coldairarrow/FreeSql | Providers/FreeSql.Provider.Sqlite/SqliteExpression.cs | 26,378 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Microsoft.ML.Probabilistic.Distributions;
using Microsoft.ML.Probabilistic.Math;
using Microsoft.ML.Probabilistic.Utilities;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
namespace CrowdsourcingWithWords
{
/// <summary>
/// Results class containing posteriors and predictions.
/// </summary>
public class Results
{
/// <summary>
/// The posterior of the true label for each task.
/// </summary>
public Dictionary<string, Discrete> TrueLabel
{
get;
protected set;
}
/// <summary>
/// The predicted label for each task when doing simulations from the current
/// model state. It avoids overwriting the true label posterior.
/// </summary>
public Dictionary<string, Discrete> LookAheadTrueLabel
{
get;
protected set;
}
/// <summary>
/// The posterior for the constraint that allows online learning for the true label variable.
/// </summary>
public Dictionary<string, Discrete> TrueLabelConstraint
{
get;
protected set;
}
/// <summary>
/// The predicted label for each task
/// </summary>
public Dictionary<string, int?> PredictedLabel
{
get;
protected set;
}
/// <summary>
/// The probabilities that generate the true label of all the tasks.
/// </summary>
public Dirichlet BackgroundLabelProb
{
get;
protected set;
}
/// <summary>
/// The posterior of the confusion matrix of each worker.
/// </summary>
public Dictionary<string, Dirichlet[]> WorkerConfusionMatrix
{
get;
protected set;
}
/// <summary>
/// The look-ahead posterior of the confusion matrix of each worker obtained after simulating
/// a new label in look-ahead run mode.
/// </summary>
public Dictionary<string, Dirichlet[]> LookAheadWorkerConfusionMatrix
{
get;
protected set;
}
/// <summary>
/// The predictive probabilities of the labels produced by each worker.
/// </summary>
public Dictionary<string, Dictionary<string, Discrete>> WorkerPrediction
{
get;
protected set;
}
/// <summary>
/// The community membership probabilities of each worker.
/// </summary>
public Dictionary<string, Discrete> WorkerCommunity
{
get;
protected set;
}
/// <summary>
/// The confusion matrix of each community.
/// </summary>
public Dirichlet[][] CommunityConfusionMatrix
{
get;
protected set;
}
/// <summary>
/// The score matrix of each community.
/// </summary>
public VectorGaussian[][] CommunityScoreMatrix
{
get;
protected set;
}
/// <summary>
/// The posterior for the constraint that allows online learning for worker confusion matrices
/// int the community model.
/// </summary>
public Dictionary<string, VectorGaussian[]> WorkerScoreMatrixConstraint
{
get;
protected set;
}
/// <summary>
/// The probabilities that generate the community memberships of all the workers.
/// </summary>
public Dirichlet CommunityProb
{
get;
protected set;
}
/// <summary>
/// The posterior for the constraint that allows online learning for community membership.
/// int the community model.
/// </summary>
public Dictionary<string, Discrete> CommunityConstraint
{
get;
protected set;
}
/// <summary>
/// Model evidence.
/// </summary>
public Bernoulli ModelEvidence
{
get;
protected set;
}
/// <summary>
/// The data mapping.
/// </summary>
public DataMapping Mapping
{
get;
set;
}
/// <summary>
/// The full data mapping.
/// </summary>
public DataMapping FullMapping
{
get;
set;
}
/// <summary>
/// The gold labels of each task. The gold label type is nullable to
/// support the (usual) situation without labels.
/// </summary>
public Dictionary<string, int?> GoldLabels
{
get;
protected set;
}
/// <summary>
/// The accuracy of the current true label predictions.
/// </summary>
public double Accuracy
{
get;
private set;
}
/// <summary>
/// The accuracy of the worker labels.
/// </summary>
public double WorkerLabelAccuracy
{
get;
protected set;
}
/// <summary>
/// The negative log probability density (NLPD) scores of the current true label predictions.
/// </summary>
public double NegativeLogProb
{
get;
private set;
}
/// <summary>
/// The average recall of the current true label predictions.
/// </summary>
public double AvgRecall
{
get;
private set;
}
/// <summary>
/// The confusion matrix of the predicted true labels against the gold labels
/// The rows are the gold labels and the columns are the predicted labels.
/// </summary>
public double[,] ModelConfusionMatrix
{
get;
private set;
}
/// <summary>
/// The number of communities.
/// </summary>
public int CommunityCount
{
get;
private set;
}
public ReceiverOperatingCharacteristic.ConfusionMatrix BinaryConfusionMatrix
{
get;
private set;
}
public ReceiverOperatingCharacteristic RocCurve
{
get;
private set;
}
public List<double> trueBinaryLabel;
public List<double> probTrueBinaryLabel;
public enum RunMode
{
ClearResults,
BatchTraining,
IncrementalExperiment,
OnlineExperiment,
LookAheadExperiment,
LoadAndUseCommunityPriors,
Prediction,
};
protected virtual void ClearResults()
{
BackgroundLabelProb = Dirichlet.Uniform(Mapping.LabelCount);
WorkerConfusionMatrix = new Dictionary<string, Dirichlet[]>();
WorkerPrediction = new Dictionary<string, Dictionary<String, Discrete>>();
WorkerCommunity = new Dictionary<string, Discrete>();
TrueLabel = new Dictionary<string, Discrete>();
TrueLabelConstraint = new Dictionary<string, Discrete>();
CommunityConfusionMatrix = null;
WorkerScoreMatrixConstraint = new Dictionary<string, VectorGaussian[]>();
CommunityProb = null;
CommunityScoreMatrix = null;
CommunityConstraint = new Dictionary<string, Discrete>();
LookAheadTrueLabel = new Dictionary<string, Discrete>();
LookAheadWorkerConfusionMatrix = new Dictionary<string, Dirichlet[]>();
ModelEvidence = new Bernoulli(0.5);
PredictedLabel = new Dictionary<string, int?>();
}
protected virtual void UpdateResults(BCCPosteriors posteriors, RunMode mode)
{
if (mode == RunMode.LookAheadExperiment)
{
if (posteriors.TrueLabel != null)
{
for (int t = 0; t < posteriors.TrueLabel.Length; t++)
{
LookAheadTrueLabel[Mapping.TaskIndexToId[t]] = posteriors.TrueLabel[t];
}
}
if (posteriors.WorkerConfusionMatrix != null)
{
for (int w = 0; w < posteriors.WorkerConfusionMatrix.Length; w++)
{
LookAheadWorkerConfusionMatrix[Mapping.WorkerIndexToId[w]] = posteriors.WorkerConfusionMatrix[w];
}
}
}
else if (mode == RunMode.Prediction)
{
if (posteriors.WorkerConfusionMatrix != null)
{
for (int w = 0; w < posteriors.WorkerConfusionMatrix.Length; w++)
{
WorkerPrediction[Mapping.WorkerIndexToId[w]] = new Dictionary<string, Discrete>();
for (int tw = 0; tw < posteriors.WorkerPrediction[w].Length; tw++)
{
WorkerPrediction[Mapping.WorkerIndexToId[w]][Mapping.TaskIndexToId[tw]] = posteriors.WorkerPrediction[w][tw];
}
}
}
}
else
{
// Update results for BCC
BackgroundLabelProb = posteriors.BackgroundLabelProb;
if (posteriors.WorkerConfusionMatrix != null)
{
for (int w = 0; w < posteriors.WorkerConfusionMatrix.Length; w++)
{
WorkerConfusionMatrix[Mapping.WorkerIndexToId[w]] = posteriors.WorkerConfusionMatrix[w];
}
}
if (posteriors.TrueLabel != null)
{
for (int t = 0; t < posteriors.TrueLabel.Length; t++)
{
TrueLabel[Mapping.TaskIndexToId[t]] = posteriors.TrueLabel[t];
}
}
if (posteriors.TrueLabelConstraint != null)
{
for (int t = 0; t < posteriors.TrueLabelConstraint.Length; t++)
{
TrueLabelConstraint[Mapping.TaskIndexToId[t]] = posteriors.TrueLabelConstraint[t];
}
}
this.ModelEvidence = posteriors.Evidence;
}
}
/// <summary>
/// Updates the accuracy using the current results.
/// </summary>
protected virtual void UpdateAccuracy()
{
double nlpdThreshold = -Math.Log(0.001);
int labelCount = TrueLabel.First(kvp => kvp.Value != null).Value.Dimension;
var confusionMatrix = Util.ArrayInit(labelCount, labelCount, (i, j) => 0.0);
int correct = 0;
double logProb = 0.0;
int goldX = 0;
// Only for binary labels
if (Mapping.LabelCount == 2)
{
trueBinaryLabel = new List<double>();
probTrueBinaryLabel = new List<double>();
}
foreach (var kvp in GoldLabels)
{
if (kvp.Value == null)
continue;
// We have a gold label
goldX++;
Discrete trueLabel = null;
if (TrueLabel.ContainsKey(kvp.Key))
trueLabel = TrueLabel[kvp.Key];
if (trueLabel == null)
{
trueLabel = Discrete.Uniform(Mapping.LabelCount);
//continue; // No inferred label
}
var probs = trueLabel.GetProbs();
double max = probs.Max();
var predictedLabels = probs.Select((p, i) => new
{
prob = p,
idx = i
}).Where(a => a.prob == max).Select(a => a.idx).ToArray();
int predictedLabel = predictedLabels.Length == 1 ? predictedLabels[0] : predictedLabels[Rand.Int(predictedLabels.Length)];
this.PredictedLabel[kvp.Key] = predictedLabel;
int goldLabel = kvp.Value.Value;
confusionMatrix[goldLabel, predictedLabel] = confusionMatrix[goldLabel, predictedLabel] + 1.0;
var nlp = -trueLabel.GetLogProb(goldLabel);
if (nlp > nlpdThreshold)
nlp = nlpdThreshold;
logProb += nlp;
if (trueBinaryLabel != null)
{
trueBinaryLabel.Add(goldLabel);
probTrueBinaryLabel.Add(probs[goldLabel]);
}
}
Accuracy = correct / (double)goldX;
NegativeLogProb = logProb / goldX;
ModelConfusionMatrix = confusionMatrix;
// Average recall
double sumRec = 0;
for (int i = 0; i < labelCount; i++)
{
double classSum = 0;
for (int j = 0; j < labelCount; j++)
{
classSum += confusionMatrix[i, j];
}
sumRec += confusionMatrix[i, i] / classSum;
}
AvgRecall = sumRec / labelCount;
// WorkerLabelAccuracy: Perc. agreement between worker label and gold label
int sumAcc = 0;
var LabelSet = Mapping.DataWithGold;
int numLabels = LabelSet.Count();
foreach (var datum in LabelSet)
{
sumAcc += datum.WorkerLabel == datum.GoldLabel ? 1 : 0;
}
WorkerLabelAccuracy = sumAcc / (double)numLabels;
if (trueBinaryLabel != null && trueBinaryLabel.Count > 0)
{
RocCurve = new ReceiverOperatingCharacteristic(trueBinaryLabel.ToArray(), probTrueBinaryLabel.ToArray());
RocCurve.Compute(0.001);
BinaryConfusionMatrix = new ReceiverOperatingCharacteristic.ConfusionMatrix((int)confusionMatrix[1, 1], (int)confusionMatrix[0, 0], (int)confusionMatrix[0, 1], (int)confusionMatrix[1, 0]);
}
}
public static void WriteConfusionMatrix(StreamWriter writer, string worker, Dirichlet[] confusionMatrix)
{
int labelCount = confusionMatrix.Length;
var meanConfusionMatrix = confusionMatrix.Select(cm => cm.GetMean()).ToArray();
var printableConfusionMatrix = Util.ArrayInit(labelCount, labelCount, (i, j) => meanConfusionMatrix[i][j]);
WriteWorkerConfusionMatrix(writer, worker, printableConfusionMatrix);
}
public static void WriteWorkerConfusionMatrix(StreamWriter writer, string worker, double[,] confusionMatrix)
{
int labelCount = confusionMatrix.GetLength(0);
writer.WriteLine(worker);
for (int j = 0; j < labelCount; j++)
writer.Write(",{0}", j);
writer.WriteLine();
for (int i = 0; i < labelCount; i++)
{
writer.Write(i);
for (int j = 0; j < labelCount; j++)
writer.Write(",{0:0.0000}", confusionMatrix[i, j]);
writer.WriteLine();
}
}
public virtual void WriteResults(StreamWriter writer, bool writeCommunityParameters, bool writeWorkerParameters, bool writeWorkerCommunities, IList<Datum> data = null)
{
if (writeCommunityParameters && this.CommunityConfusionMatrix != null)
{
for (int communityIndex = 0; communityIndex < this.CommunityConfusionMatrix.Length; communityIndex++)
{
WriteConfusionMatrix(writer, "Community" + communityIndex, this.CommunityConfusionMatrix[communityIndex]);
}
}
if (writeWorkerParameters && this.WorkerConfusionMatrix != null)
{
foreach (var kvp in this.WorkerConfusionMatrix.Distinct().Take(5))
{
WriteConfusionMatrix(writer, kvp.Key, kvp.Value);
}
}
if (this.TrueLabel != null)
{
foreach (var kvp in this.TrueLabel.OrderBy(kvp => kvp.Value.GetProbs()[0]))
{
if (data != null)
{
var taskLabels = data.Where(d => d.TaskId == kvp.Key).Select(l => l.WorkerLabel);
var pos = taskLabels.Where(l => l == 1);
var neg = taskLabels.Where(l => l == 0);
int numPos = pos.Count();
int numNeg = neg.Count();
writer.WriteLine($"{kvp.Key}:\t{kvp.Value}\tnum_neg: {numNeg}\t num_pos: {numPos}");
}
else
{
writer.WriteLine($"{kvp.Key}:\t{kvp.Value}");
}
}
}
}
}
}
| 33.555769 | 204 | 0.512751 | [
"MIT"
] | Bruugs/infer | src/Examples/CrowdsourcingWithWords/Results.cs | 17,451 | C# |
using System.Collections.Generic;
using System.Linq;
using FluentNHibernate.Mapping;
using FluentNHibernate.Conventions;
using NUnit.Framework;
namespace FluentNHibernate.Testing.ConventionFinderTests
{
[TestFixture]
public class FindTests
{
private DefaultConventionFinder finder;
[SetUp]
public void CreateConventionFinder()
{
finder = new DefaultConventionFinder();
}
[Test]
public void ShouldFindNothingWhenNoAssembliesGiven()
{
finder.Find<IEntireMappingsConvention>()
.ShouldBeEmpty();
}
[Test]
public void ShouldFindTypesFromAssembly()
{
finder.AddAssembly(GetType().Assembly);
finder.Find<IEntireMappingsConvention>()
.ShouldContain(c => c is DummyAssemblyConvention);
}
[Test]
public void ShouldFindTypesThatHaveConstructorNeedingFinder()
{
finder.AddAssembly(GetType().Assembly);
finder.Find<IEntireMappingsConvention>()
.ShouldContain(c => c is DummyFinderAssemblyConvention);
}
[Test]
public void ShouldntFindGenericTypes()
{
finder.AddAssembly(GetType().Assembly);
finder.Find<IEntireMappingsConvention>()
.ShouldNotContain(c => c.GetType() == typeof(OpenGenericAssemblyConvention<>));
}
[Test]
public void ShouldOnlyFindExplicitAdded()
{
finder.Add<DummyAssemblyConvention>();
finder.Find<IEntireMappingsConvention>()
.ShouldHaveCount(1)
.ShouldContain(c => c is DummyAssemblyConvention);
}
[Test]
public void ShouldOnlyAddInstanceOnceIfHasMultipleInterfaces()
{
finder.Add<MultiPartConvention>();
var ids = finder.Find<IIdConvention>();
var properties = finder.Find<IPropertyConvention>();
ids.ShouldHaveCount(1);
properties.ShouldHaveCount(1);
ids.First().ShouldEqual(properties.First());
}
[Test]
public void ShouldOnlyAddInstanceOnce()
{
finder.Add<DummyAssemblyConvention>();
finder.Add<DummyAssemblyConvention>();
var conventions = finder.Find<IEntireMappingsConvention>();
conventions.ShouldHaveCount(1);
}
[Test]
public void ShouldAllowAddingInstanceMultipleTimesIfHasMultipleAttribute()
{
finder.Add<DummyAssemblyWithMultipleAttributeConvention>();
finder.Add<DummyAssemblyWithMultipleAttributeConvention>();
var conventions = finder.Find<IEntireMappingsConvention>();
conventions.ShouldHaveCount(2);
}
[Test]
public void ShouldOnlyAddInstanceOnceIfHasMultipleInterfacesWhenAddedByAssembly()
{
finder.AddAssembly(typeof(MultiPartConvention).Assembly);
var ids = finder.Find<IIdConvention>().Where(c => c.GetType() == typeof(MultiPartConvention));
var properties = finder.Find<IPropertyConvention>().Where(c => c.GetType() == typeof(MultiPartConvention));
ids.ShouldHaveCount(1);
properties.ShouldHaveCount(1);
ids.First().ShouldEqual(properties.First());
}
}
public class OpenGenericAssemblyConvention<T> : IEntireMappingsConvention
{
public bool Accept(IEnumerable<IClassMap> target)
{
return false;
}
public void Apply(IEnumerable<IClassMap> target)
{
}
}
public class DummyAssemblyConvention : IEntireMappingsConvention
{
public bool Accept(IEnumerable<IClassMap> target)
{
return false;
}
public void Apply(IEnumerable<IClassMap> target)
{
}
}
[Multiple]
public class DummyAssemblyWithMultipleAttributeConvention : IEntireMappingsConvention
{
public bool Accept(IEnumerable<IClassMap> target)
{
return false;
}
public void Apply(IEnumerable<IClassMap> target)
{
}
}
public class DummyFinderAssemblyConvention : IEntireMappingsConvention
{
public DummyFinderAssemblyConvention(IConventionFinder finder)
{
}
public bool Accept(IEnumerable<IClassMap> target)
{
return false;
}
public void Apply(IEnumerable<IClassMap> target)
{
}
}
public class MultiPartConvention : IIdConvention, IPropertyConvention
{
public bool Accept(IIdentityPart target)
{
return false;
}
public void Apply(IIdentityPart target)
{
}
public bool Accept(IProperty target)
{
return false;
}
public void Apply(IProperty target)
{
}
}
}
| 28.516484 | 120 | 0.582466 | [
"BSD-3-Clause"
] | HudsonAkridge/fluent-nhibernate | src/FluentNHibernate.Testing/ConventionFinderTests/FindTests.cs | 5,190 | C# |
using SKBKontur.Cassandra.CassandraClient.Clusters;
namespace SKBKontur.Cassandra.CassandraClient.Connections
{
public interface ICassandraConnectionParameters
{
int Attempts { get; }
int Timeout { get; }
}
public class CassandraConnectionParameters : ICassandraConnectionParameters
{
public CassandraConnectionParameters(ICassandraClusterSettings cassandraClusterSettings)
{
this.cassandraClusterSettings = cassandraClusterSettings;
}
public int Attempts => cassandraClusterSettings.Attempts;
public int Timeout => cassandraClusterSettings.Timeout;
private readonly ICassandraClusterSettings cassandraClusterSettings;
}
} | 31.608696 | 96 | 0.738652 | [
"MIT"
] | Umqra/cassandra-thrift-client | Cassandra.ThriftClient/Connections/CassandraConnectionParameters.cs | 729 | C# |
//The MIT License (MIT)
//
//Copyright 2015 Microsoft Corporation
//
//Permission is hereby granted, free of charge, to any person obtaining a copy
//of this software and associated documentation files (the "Software"), to deal
//in the Software without restriction, including without limitation the rights
//to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
//copies of the Software, and to permit persons to whom the Software is
//furnished to do so, subject to the following conditions:
//
//The above copyright notice and this permission notice shall be included in
//all copies or substantial portions of the Software.
//
//THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
//IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
//FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
//AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
//LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
//OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
//THE SOFTWARE.
//
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Serialization;
namespace EnhancedMonitoring.Configuration
{
[XmlRoot("SupportedVMDetector")]
public class SupportedVMDetectorConfiguration
{
[XmlElement("GuestDataItemKey")]
public String GuestDataItemKey { get; set; }
[XmlArray("VirtualMachineProperties")]
[XmlArrayItem("VirtualMachineProperties")]
public VirtualMachineProperties VirtualMachineProperties { get; set; }
}
public class VirtualMachineProperties : List<VirtualMachineProperty>
{
}
[XmlRoot("VirtualMachineProperty")]
public class VirtualMachineProperty
{
[XmlElement("Select")]
public String Select { get; set; }
[XmlElement("As")]
public String As { get; set; }
}
}
| 34.793103 | 79 | 0.737859 | [
"MIT"
] | Bhaskers-Blu-Org2/enhanced-monitoring-service | src/EnhancedMonitoring/Configuration/SupportedVMDetectorConfiguration.cs | 2,020 | C# |
using System.Collections.Generic;
using System.Threading.Tasks;
namespace Nettolicious.Common.Mock {
public class TestAsyncEnumerator<T> : IAsyncEnumerator<T> {
private readonly IEnumerator<T> _inner;
public TestAsyncEnumerator(IEnumerator<T> inner) {
_inner = inner;
}
public ValueTask DisposeAsync() {
_inner.Dispose();
return new ValueTask();
}
public T Current {
get {
return _inner.Current;
}
}
public ValueTask<bool> MoveNextAsync() {
return new ValueTask<bool>(_inner.MoveNext());
}
}
}
| 20.857143 | 61 | 0.652397 | [
"MIT"
] | nettolicious/ef-reference | Common/Mock/TestAsyncEnumerator.cs | 586 | C# |
namespace Amazon.Elb.Tests
{
public class DeleteTargetGroupRequestTests
{
[Fact]
public void Serialize()
{
var request = new DeleteTargetGroupRequest("arn");
Assert.Equal("Action=DeleteTargetGroup&TargetGroupArn=arn", Serializer.Serialize(request));
}
}
} | 26.153846 | 104 | 0.597059 | [
"MIT"
] | TheJVaughan/Amazon | src/Amazon.Elb.Tests/Requests/DeleteTargetGroupRequestTests.cs | 342 | C# |
namespace SeeSharper.Northwind.Columns
{
using Serenity.ComponentModel;
using System;
[ColumnsScript("Northwind.SalesByCategory")]
[BasedOnRow(typeof(Entities.SalesByCategoryRow))]
public class SalesByCategoryColumns
{
[Width(150), SortOrder(1)]
public String CategoryName { get; set; }
[Width(250)]
public String ProductName { get; set; }
[Width(150), AlignRight, SortOrder(2, descending: true), DisplayFormat("#,##0.00")]
public Decimal ProductSales { get; set; }
}
} | 30.444444 | 91 | 0.655109 | [
"MIT"
] | kingajay007/SeeSharper-Master | SeeSharper.Web/Modules/Northwind/SalesByCategory/SalesByCategoryColumns.cs | 550 | C# |
using System;
using System.Text;
namespace SecureCodingWorkshop.DES
{
static class Program
{
static void Main(string[] args)
{
var des = new DesEncryption();
var key = des.GenerateRandomNumber(8);
var iv = des.GenerateRandomNumber(8);
const string original = "Text to encrypt";
var encrypted = des.Encrypt(Encoding.UTF8.GetBytes(original), key, iv);
var decrypted = des.Decrypt(encrypted, key, iv);
var decryptedMessage = Encoding.UTF8.GetString(decrypted);
Console.WriteLine("DES Encryption Demonstration in .NET");
Console.WriteLine("------------------------------------");
Console.WriteLine();
Console.WriteLine("Original Text = " + original);
Console.WriteLine("Encrypted Text = " + Convert.ToBase64String(encrypted));
Console.WriteLine("Decrypted Text = " + decryptedMessage);
Console.ReadLine();
}
}
}
| 33.806452 | 88 | 0.560115 | [
"MIT"
] | theDiverDK/SecureCodingWorkshop | Complete/SecureCodingWorkshop/DES/Program.cs | 1,050 | C# |
// <copyright file="ItemOfItemSet.Generated.cs" company="MUnique">
// Licensed under the MIT License. See LICENSE file in the project root for full license information.
// </copyright>
//------------------------------------------------------------------------------
// <auto-generated>
// This source code was auto-generated by a roslyn code generator.
// </auto-generated>
//------------------------------------------------------------------------------
// ReSharper disable All
namespace MUnique.OpenMU.Persistence.BasicModel
{
using System;
using System.Collections.Generic;
using MUnique.OpenMU.Persistence.Json;
/// <summary>
/// A plain implementation of <see cref="ItemOfItemSet"/>.
/// </summary>
public partial class ItemOfItemSet : MUnique.OpenMU.DataModel.Configuration.Items.ItemOfItemSet, IIdentifiable, IConvertibleTo<ItemOfItemSet>
{
/// <summary>
/// Gets or sets the identifier of this instance.
/// </summary>
public Guid Id { get; set; }
/// <summary>
/// Gets the raw object of <see cref="ItemDefinition" />.
/// </summary>
[Newtonsoft.Json.JsonProperty("itemDefinition")]
[System.Text.Json.Serialization.JsonPropertyName("itemDefinition")]
public ItemDefinition RawItemDefinition
{
get => base.ItemDefinition as ItemDefinition;
set => base.ItemDefinition = value;
}
/// <inheritdoc/>
[Newtonsoft.Json.JsonIgnore]
[System.Text.Json.Serialization.JsonIgnore]
public override MUnique.OpenMU.DataModel.Configuration.Items.ItemDefinition ItemDefinition
{
get => base.ItemDefinition;
set => base.ItemDefinition = value;
}
/// <summary>
/// Gets the raw object of <see cref="BonusOption" />.
/// </summary>
[Newtonsoft.Json.JsonProperty("bonusOption")]
[System.Text.Json.Serialization.JsonPropertyName("bonusOption")]
public IncreasableItemOption RawBonusOption
{
get => base.BonusOption as IncreasableItemOption;
set => base.BonusOption = value;
}
/// <inheritdoc/>
[Newtonsoft.Json.JsonIgnore]
[System.Text.Json.Serialization.JsonIgnore]
public override MUnique.OpenMU.DataModel.Configuration.Items.IncreasableItemOption BonusOption
{
get => base.BonusOption;
set => base.BonusOption = value;
}
/// <inheritdoc/>
public override bool Equals(object obj)
{
var baseObject = obj as IIdentifiable;
if (baseObject != null)
{
return baseObject.Id == this.Id;
}
return base.Equals(obj);
}
/// <inheritdoc/>
public override int GetHashCode()
{
return this.Id.GetHashCode();
}
/// <inheritdoc/>
public ItemOfItemSet Convert() => this;
}
} | 33.032609 | 145 | 0.569595 | [
"MIT"
] | MUnique/OpenMU | src/Persistence/BasicModel/ItemOfItemSet.Generated.cs | 3,039 | C# |
[assembly: WebActivatorEx.PreApplicationStartMethod(typeof(WebApi.Region.App_Start.NinjectWebCommon), "Start")]
[assembly: WebActivatorEx.ApplicationShutdownMethodAttribute(typeof(WebApi.Region.App_Start.NinjectWebCommon), "Stop")]
namespace WebApi.Region.App_Start
{
using System;
using System.Web;
using System.Web.Http;
using BlobStorageService.Repository;
using Microsoft.Web.Infrastructure.DynamicModuleHelper;
using Ninject;
using Ninject.Web.Common;
using WebApi.Domain.Services;
using WebApi.ProcedureRegion.Repositories;
using WebAPI.DataAccess.Repositories;
using WebAPI.Domain.Interfaces.Repositories;
using WebAPI.Domain.Interfaces.Services;
using WebAPI.Domain.Services;
public static class NinjectWebCommon
{
private static readonly Bootstrapper bootstrapper = new Bootstrapper();
/// <summary>
/// Starts the application
/// </summary>
public static void Start()
{
DynamicModuleUtility.RegisterModule(typeof(OnePerRequestHttpModule));
DynamicModuleUtility.RegisterModule(typeof(NinjectHttpModule));
bootstrapper.Initialize(CreateKernel);
}
/// <summary>
/// Stops the application.
/// </summary>
public static void Stop()
{
bootstrapper.ShutDown();
}
/// <summary>
/// Creates the kernel that will manage your application.
/// </summary>
/// <returns>The created kernel.</returns>
private static IKernel CreateKernel()
{
var kernel = new StandardKernel();
try
{
kernel.Bind<Func<IKernel>>().ToMethod(ctx => () => new Bootstrapper().Kernel);
kernel.Bind<IHttpModule>().To<HttpApplicationInitializationHttpModule>();
RegisterServices(kernel);
// Install our Ninject-based IDependencyResolver into the Web API config
GlobalConfiguration.Configuration.DependencyResolver = new NinjectDependencyResolver(kernel);
return kernel;
}
catch
{
kernel.Dispose();
throw;
}
}
/// <summary>
/// Load your modules or register your services here!
/// </summary>
/// <param name="kernel">The kernel.</param>
private static void RegisterServices(IKernel kernel)
{
//####################### DataBaseSqlRepository #######################
kernel.Bind(typeof(IBaseRepository<>)).To(typeof(BaseRepository<>));
//kernel.Bind<ICountryRepository>().To<CountryRepository>();
//kernel.Bind<IStateRepository>().To<StateRepository>();
kernel.Bind<IAddressRepository>().To<AddressRepository>();
//########################## DataBaseSqlService #######################
kernel.Bind(typeof(IBaseService<>)).To(typeof(BaseService<>));
//kernel.Bind<ICountryService>().To<CountryService>();
//kernel.Bind<IStateService>().To<StateService>();
kernel.Bind<IAddressService>().To<AddressService>();
//########################## CloudStorageRepository #######################
kernel.Bind<IBlobStorageRepository>().To<BlobStorageRepository>();
//########################## CloudStorageService #######################
kernel.Bind<IBlobStorageService>().To<BlobStorageService>();
//########################## StorageProcedureRepository ##########################
kernel.Bind<ICountryRepository>().To<CountryProcedureRepository>();
kernel.Bind<IStateRepository>().To<StateProcedureRepository>();
//########################## StorageProcedureService ##########################
kernel.Bind<ICountryService>().To<CountryProcedureService>();
kernel.Bind<IStateService>().To<StateProcedureService>();
}
}
}
| 40.058252 | 119 | 0.568589 | [
"MIT"
] | AlexanderVieira/WebApiSocialNetwork-Ioc-Identity | WebApi.Region/App_Start/NinjectWebCommon.cs | 4,126 | C# |
using System;
using UnityEngine;
namespace Game
{
internal class BulletView : MonoBehaviour
{
public struct Ctx
{
public Action onHit;
public float damage;
public Vector3 velocity;
}
[SerializeField] private Collider detector;
[SerializeField] private Rigidbody rigidbody;
public float Damage
=> _ctx.damage;
private Ctx _ctx;
public void SetCtx(Ctx ctx)
{
_ctx = ctx;
rigidbody.velocity = _ctx.velocity;
}
private void OnTriggerEnter(Collider other)
{
_ctx.onHit?.Invoke();
}
}
} | 18.323529 | 50 | 0.600321 | [
"MIT"
] | crossthefrog/testtask1 | arch/Assets/Scripts/Game/Bullets/BulletView.cs | 623 | C# |
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
using System;
using Newtonsoft.Json.Tests.TestObjects;
#if !NETFX_CORE
using NUnit.Framework;
#else
using Microsoft.VisualStudio.TestTools.UnitTesting;
using TestFixture = Microsoft.VisualStudio.TestTools.UnitTesting.TestClassAttribute;
using Test = Microsoft.VisualStudio.TestTools.UnitTesting.TestMethodAttribute;
#endif
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Utilities;
using System.Globalization;
namespace Newtonsoft.Json.Tests.Converters
{
[TestFixture]
public class IsoDateTimeConverterTests : TestFixtureBase
{
[Test]
public void PropertiesShouldBeSet()
{
IsoDateTimeConverter converter = new IsoDateTimeConverter();
Assert.AreEqual(CultureInfo.CurrentCulture, converter.Culture);
Assert.AreEqual(string.Empty, converter.DateTimeFormat);
Assert.AreEqual(DateTimeStyles.RoundtripKind, converter.DateTimeStyles);
converter = new IsoDateTimeConverter()
{
DateTimeFormat = "F",
Culture = CultureInfo.InvariantCulture,
DateTimeStyles = DateTimeStyles.None
};
Assert.AreEqual(CultureInfo.InvariantCulture, converter.Culture);
Assert.AreEqual("F", converter.DateTimeFormat);
Assert.AreEqual(DateTimeStyles.None, converter.DateTimeStyles);
}
[Test]
public void SerializeDateTime()
{
IsoDateTimeConverter converter = new IsoDateTimeConverter();
DateTime d = new DateTime(2000, 12, 15, 22, 11, 3, 55, DateTimeKind.Utc);
string result;
result = JsonConvert.SerializeObject(d, converter);
Assert.AreEqual(@"""2000-12-15T22:11:03.055Z""", result);
Assert.AreEqual(d, JsonConvert.DeserializeObject<DateTime>(result, converter));
d = new DateTime(2000, 12, 15, 22, 11, 3, 55, DateTimeKind.Local);
result = JsonConvert.SerializeObject(d, converter);
Assert.AreEqual(@"""2000-12-15T22:11:03.055" + d.GetUtcOffsetText() + @"""", result);
}
[Test]
public void SerializeFormattedDateTimeInvariantCulture()
{
IsoDateTimeConverter converter = new IsoDateTimeConverter() { DateTimeFormat = "F", Culture = CultureInfo.InvariantCulture };
DateTime d = new DateTime(2000, 12, 15, 22, 11, 3, 0, DateTimeKind.Utc);
string result;
result = JsonConvert.SerializeObject(d, converter);
Assert.AreEqual(@"""Friday, 15 December 2000 22:11:03""", result);
Assert.AreEqual(d, JsonConvert.DeserializeObject<DateTime>(result, converter));
d = new DateTime(2000, 12, 15, 22, 11, 3, 0, DateTimeKind.Local);
result = JsonConvert.SerializeObject(d, converter);
Assert.AreEqual(@"""Friday, 15 December 2000 22:11:03""", result);
}
[Test]
public void SerializeCustomFormattedDateTime()
{
IsoDateTimeConverter converter = new IsoDateTimeConverter
{
DateTimeFormat = "dd/MM/yyyy",
Culture = CultureInfo.InvariantCulture
};
string json = @"""09/12/2006""";
DateTime d = JsonConvert.DeserializeObject<DateTime>(json, converter);
Assert.AreEqual(9, d.Day);
Assert.AreEqual(12, d.Month);
Assert.AreEqual(2006, d.Year);
}
#if !SILVERLIGHT && !NETFX_CORE
[Test]
public void SerializeFormattedDateTimeNewZealandCulture()
{
IsoDateTimeConverter converter = new IsoDateTimeConverter() { DateTimeFormat = "F", Culture = CultureInfo.GetCultureInfo("en-NZ") };
DateTime d = new DateTime(2000, 12, 15, 22, 11, 3, 0, DateTimeKind.Utc);
string result;
result = JsonConvert.SerializeObject(d, converter);
Assert.AreEqual(@"""Friday, 15 December 2000 10:11:03 p.m.""", result);
Assert.AreEqual(d, JsonConvert.DeserializeObject<DateTime>(result, converter));
d = new DateTime(2000, 12, 15, 22, 11, 3, 0, DateTimeKind.Local);
result = JsonConvert.SerializeObject(d, converter);
Assert.AreEqual(@"""Friday, 15 December 2000 10:11:03 p.m.""", result);
}
[Test]
public void SerializeDateTimeCulture()
{
IsoDateTimeConverter converter = new IsoDateTimeConverter() { Culture = CultureInfo.GetCultureInfo("en-NZ") };
string json = @"""09/12/2006""";
DateTime d = JsonConvert.DeserializeObject<DateTime>(json, converter);
Assert.AreEqual(9, d.Day);
Assert.AreEqual(12, d.Month);
Assert.AreEqual(2006, d.Year);
}
#endif
#if !PocketPC && !NET20
[Test]
public void SerializeDateTimeOffset()
{
IsoDateTimeConverter converter = new IsoDateTimeConverter();
DateTimeOffset d = new DateTimeOffset(2000, 12, 15, 22, 11, 3, 55, TimeSpan.Zero);
string result;
result = JsonConvert.SerializeObject(d, converter);
Assert.AreEqual(@"""2000-12-15T22:11:03.055+00:00""", result);
Assert.AreEqual(d, JsonConvert.DeserializeObject<DateTimeOffset>(result, converter));
}
[Test]
public void SerializeUTC()
{
DateTimeTestClass c = new DateTimeTestClass();
c.DateTimeField = new DateTime(2008, 12, 12, 12, 12, 12, 0, DateTimeKind.Utc).ToLocalTime();
c.DateTimeOffsetField = new DateTime(2008, 12, 12, 12, 12, 12, 0, DateTimeKind.Utc).ToLocalTime();
c.PreField = "Pre";
c.PostField = "Post";
string json = JsonConvert.SerializeObject(c, new IsoDateTimeConverter() { DateTimeStyles = DateTimeStyles.AssumeUniversal });
Assert.AreEqual(@"{""PreField"":""Pre"",""DateTimeField"":""2008-12-12T12:12:12Z"",""DateTimeOffsetField"":""2008-12-12T12:12:12+00:00"",""PostField"":""Post""}", json);
//test the other edge case too
c.DateTimeField = new DateTime(2008, 1, 1, 1, 1, 1, 0, DateTimeKind.Utc).ToLocalTime();
c.DateTimeOffsetField = new DateTime(2008, 1, 1, 1, 1, 1, 0, DateTimeKind.Utc).ToLocalTime();
c.PreField = "Pre";
c.PostField = "Post";
json = JsonConvert.SerializeObject(c, new IsoDateTimeConverter() { DateTimeStyles = DateTimeStyles.AssumeUniversal });
Assert.AreEqual(@"{""PreField"":""Pre"",""DateTimeField"":""2008-01-01T01:01:01Z"",""DateTimeOffsetField"":""2008-01-01T01:01:01+00:00"",""PostField"":""Post""}", json);
}
[Test]
public void NullableSerializeUTC()
{
NullableDateTimeTestClass c = new NullableDateTimeTestClass();
c.DateTimeField = new DateTime(2008, 12, 12, 12, 12, 12, 0, DateTimeKind.Utc).ToLocalTime();
c.DateTimeOffsetField = new DateTime(2008, 12, 12, 12, 12, 12, 0, DateTimeKind.Utc).ToLocalTime();
c.PreField = "Pre";
c.PostField = "Post";
string json = JsonConvert.SerializeObject(c, new IsoDateTimeConverter() { DateTimeStyles = DateTimeStyles.AssumeUniversal });
Assert.AreEqual(@"{""PreField"":""Pre"",""DateTimeField"":""2008-12-12T12:12:12Z"",""DateTimeOffsetField"":""2008-12-12T12:12:12+00:00"",""PostField"":""Post""}", json);
//test the other edge case too
c.DateTimeField = null;
c.DateTimeOffsetField = null;
c.PreField = "Pre";
c.PostField = "Post";
json = JsonConvert.SerializeObject(c, new IsoDateTimeConverter() { DateTimeStyles = DateTimeStyles.AssumeUniversal });
Assert.AreEqual(@"{""PreField"":""Pre"",""DateTimeField"":null,""DateTimeOffsetField"":null,""PostField"":""Post""}", json);
}
[Test]
public void NullableDeserializeEmptyString()
{
string json = @"{""DateTimeField"":""""}";
NullableDateTimeTestClass c = JsonConvert.DeserializeObject<NullableDateTimeTestClass>(json,
new JsonSerializerSettings { Converters = new [] {new IsoDateTimeConverter()}});
Assert.AreEqual(null, c.DateTimeField);
}
[Test]
public void DeserializeNullToNonNullable()
{
ExceptionAssert.Throws<JsonSerializationException>("Cannot convert null value to System.DateTime. Path 'DateTimeField', line 1, position 38.",
() =>
{
DateTimeTestClass c2 =
JsonConvert.DeserializeObject<DateTimeTestClass>(@"{""PreField"":""Pre"",""DateTimeField"":null,""DateTimeOffsetField"":null,""PostField"":""Post""}", new IsoDateTimeConverter() { DateTimeStyles = DateTimeStyles.AssumeUniversal });
});
}
[Test]
public void SerializeShouldChangeNonUTCDates()
{
DateTime localDateTime = new DateTime(2008, 1, 1, 1, 1, 1, 0, DateTimeKind.Local);
DateTimeTestClass c = new DateTimeTestClass();
c.DateTimeField = localDateTime;
c.PreField = "Pre";
c.PostField = "Post";
string json = JsonConvert.SerializeObject(c, new IsoDateTimeConverter() { DateTimeStyles = DateTimeStyles.AssumeUniversal }); //note that this fails without the Utc converter...
c.DateTimeField = new DateTime(2008, 1, 1, 1, 1, 1, 0, DateTimeKind.Utc);
string json2 = JsonConvert.SerializeObject(c, new IsoDateTimeConverter() { DateTimeStyles = DateTimeStyles.AssumeUniversal });
TimeSpan offset = localDateTime.GetUtcOffset();
// if the current timezone is utc then local already equals utc
if (offset == TimeSpan.Zero)
Assert.AreEqual(json, json2);
else
Assert.AreNotEqual(json, json2);
}
#endif
[Test]
public void BlogCodeSample()
{
Person p = new Person
{
Name = "Keith",
BirthDate = new DateTime(1980, 3, 8),
LastModified = new DateTime(2009, 4, 12, 20, 44, 55),
};
string jsonText = JsonConvert.SerializeObject(p, new IsoDateTimeConverter());
// {
// "Name": "Keith",
// "BirthDate": "1980-03-08T00:00:00",
// "LastModified": "2009-04-12T20:44:55"
// }
Console.WriteLine(jsonText);
}
}
} | 41.136029 | 241 | 0.651622 | [
"MIT"
] | borewik/SteamBot | lib/JSON Library/Newtonsoft.Json.Tests/Converters/IsoDateTimeConverterTests.cs | 11,191 | C# |
//-----------------------------------------------------------------------
// <copyright file="Definitions.cs" company="None">
// Copyright (c) IIHOSHI Yoshinori.
// Licensed under the BSD-2-Clause license. See LICENSE.txt file in the project root for full license information.
// </copyright>
//-----------------------------------------------------------------------
#pragma warning disable SA1600 // Elements should be documented
namespace ThScoreFileConverter.Models.Th09
{
internal static class Definitions
{
public static string FormatPrefix { get; } = "%T09";
}
}
| 34.823529 | 114 | 0.540541 | [
"BSD-2-Clause"
] | armadillo-winX/ThScoreFileConverter | ThScoreFileConverter/Models/Th09/Definitions.cs | 594 | C# |
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using System;
namespace Tardigrade.Framework.EntityFrameworkCore.Configurations
{
/// <summary>
/// ConfigurationSource for a provider that reads application settings from a database.
/// <a href="https://docs.microsoft.com/en-us/aspnet/core/fundamentals/configuration/?view=aspnetcore-5.0#custom-configuration-provider">Custom configuration provider</a>
/// </summary>
public class AppSettingsConfigurationSource : IConfigurationSource
{
private readonly Action<DbContextOptionsBuilder> optionsAction;
/// <summary>
/// Create an instance of this class.
/// </summary>
/// <param name="optionsAction">Options associated with the database context.</param>
public AppSettingsConfigurationSource(Action<DbContextOptionsBuilder> optionsAction)
{
this.optionsAction = optionsAction;
}
/// <inheritdoc/>
public IConfigurationProvider Build(IConfigurationBuilder builder)
{
return new AppSettingsConfigurationProvider(optionsAction);
}
}
} | 38.8 | 174 | 0.706186 | [
"Apache-2.0"
] | CaptainMesomorph/tardigrade-framework | Code/Tardigrade.Framework/Tardigrade.Framework.EntityFrameworkCore/Configurations/AppSettingsConfigurationSource.cs | 1,166 | C# |
// <auto-generated />
using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using NetTopologySuite.Geometries;
using Persistence.Contexts;
namespace Persistence.Migrations
{
[DbContext(typeof(NSysWebDbContexto))]
[Migration("20220106234059_AjusteEnMunicipiosCRUD")]
partial class AjusteEnMunicipiosCRUD
{
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("Relational:MaxIdentifierLength", 128)
.HasAnnotation("ProductVersion", "5.0.11")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
modelBuilder.Entity("Domain.Entities.Asentamiento", b =>
{
b.Property<int>("IdAsentamiento")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.HasComment("Consecutivo de Asentamiento")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<int>("CodigoPostal")
.HasColumnType("int")
.HasComment("Codigo Postal");
b.Property<bool>("EsHabilitado")
.HasColumnType("bit")
.HasComment("Si el registro esta habilitado ");
b.Property<string>("Estatus")
.IsRequired()
.HasMaxLength(1)
.IsUnicode(false)
.HasColumnType("char(1)")
.IsFixedLength(true)
.HasComment("Estatus del registro");
b.Property<DateTime>("FechaCreacion")
.HasColumnType("datetime")
.HasComment("Fecha de Creacion del Registro");
b.Property<DateTime>("FechaModificacion")
.HasColumnType("datetime")
.HasComment("Fecha de la Ultima Modificacion");
b.Property<int>("IdAsentamientoTipo")
.HasColumnType("int")
.HasComment("El id de la tabla TipoAsentamiento");
b.Property<int>("IdMunicipio")
.HasColumnType("int")
.HasComment("id del municipio al que pertenece");
b.Property<string>("Nombre")
.IsRequired()
.HasMaxLength(100)
.IsUnicode(false)
.HasColumnType("varchar(100)")
.HasComment("Nombre del asentamiento");
b.Property<string>("UsuarioCreacion")
.IsRequired()
.HasMaxLength(50)
.IsUnicode(false)
.HasColumnType("varchar(50)")
.HasComment("Usuario de Creacion del registro");
b.Property<string>("UsuarioModificacion")
.IsRequired()
.HasMaxLength(50)
.IsUnicode(false)
.HasColumnType("varchar(50)")
.HasComment("Ultimo usuario que modifico el registro");
b.HasKey("IdAsentamiento");
b.HasIndex(new[] { "IdAsentamientoTipo" }, "IXFK_Asentamiento_AsentamientoTipo");
b.HasIndex(new[] { "IdMunicipio", "Nombre" }, "IX_NoDuplicadoIdMunicipioNombre")
.IsUnique();
b.ToTable("Asentamiento");
b
.HasComment("Nombre del asentamiento");
});
modelBuilder.Entity("Domain.Entities.AsentamientoTipo", b =>
{
b.Property<int>("IdAsentamientoTipo")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.HasComment("Identificador unico ")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<string>("Abreviatura")
.IsRequired()
.HasMaxLength(8)
.IsUnicode(false)
.HasColumnType("varchar(8)")
.HasComment("Abreviatura de la descripcion de tipo de asentamiento");
b.Property<bool>("EsHabilitado")
.HasColumnType("bit")
.HasComment("Si esta disponible el registro ");
b.Property<string>("Estatus")
.IsRequired()
.HasMaxLength(1)
.IsUnicode(false)
.HasColumnType("char(1)")
.IsFixedLength(true);
b.Property<DateTime>("FechaCreacion")
.HasColumnType("datetime")
.HasComment("Fecha de Creacion del registro");
b.Property<DateTime>("FechaModificacion")
.HasColumnType("datetime")
.HasComment("Ultima Fecha de Modificacion");
b.Property<string>("Nombre")
.IsRequired()
.HasMaxLength(50)
.IsUnicode(false)
.HasColumnType("varchar(50)")
.HasComment("Nombre del tipo de Asentamiento ");
b.Property<string>("UsuarioCreacion")
.IsRequired()
.HasMaxLength(50)
.IsUnicode(false)
.HasColumnType("varchar(50)")
.HasComment("Usuario que creo el registro");
b.Property<string>("UsuarioModificacion")
.IsRequired()
.HasMaxLength(50)
.IsUnicode(false)
.HasColumnType("varchar(50)")
.HasComment("Ultimo usuario que modifico el registro");
b.HasKey("IdAsentamientoTipo");
b.HasIndex(new[] { "Abreviatura" }, "IX_NoDuplicadoAbre")
.IsUnique();
b.HasIndex(new[] { "Nombre" }, "IX_NoDuplicadoAsen")
.IsUnique();
b.ToTable("AsentamientoTipo");
b
.HasComment("Los tipos de Asentamientos como Ejido, Colonia , Poblado");
});
modelBuilder.Entity("Domain.Entities.CorreoElectronico", b =>
{
b.Property<int>("IdCorreoElectronico")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.HasComment("Identificador unico")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<string>("Correo")
.IsRequired()
.HasMaxLength(50)
.IsUnicode(false)
.HasColumnType("varchar(50)")
.HasComment("El Email o Correo electroinico");
b.Property<bool>("EsHabilitado")
.HasColumnType("bit")
.HasComment("Si el registro esta habilitado para trabajar con el, borrado logico");
b.Property<string>("Estatus")
.IsRequired()
.HasMaxLength(1)
.IsUnicode(false)
.HasColumnType("char(1)")
.IsFixedLength(true);
b.Property<DateTime>("FechaCreacion")
.HasColumnType("datetime")
.HasComment("Fecha de Creacion del registro");
b.Property<DateTime>("FechaModificacion")
.HasColumnType("datetime")
.HasComment("Fecha modificacion");
b.Property<string>("TipoCorreo")
.IsRequired()
.HasMaxLength(50)
.IsUnicode(false)
.HasColumnType("varchar(50)")
.HasComment("Tipo de email personal trabajo ");
b.Property<string>("UsuarioCreacion")
.IsRequired()
.HasMaxLength(50)
.IsUnicode(false)
.HasColumnType("varchar(50)")
.HasComment("Usuario Creacion del registro");
b.Property<string>("UsuarioModificacion")
.IsRequired()
.HasMaxLength(50)
.IsUnicode(false)
.HasColumnType("varchar(50)")
.HasComment("Ultimo usuario que modifico el registro");
b.HasKey("IdCorreoElectronico");
b.HasIndex(new[] { "Correo" }, "IX_NoDuplicado")
.IsUnique();
b.ToTable("CorreoElectronico");
b
.HasComment("Todos lo Correos Electronicos de personas y Empresas");
});
modelBuilder.Entity("Domain.Entities.Direccion", b =>
{
b.Property<int>("IdDireccion")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.HasComment("Id Numerico Consecutivo de direcciones")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<string>("Calle")
.IsRequired()
.HasMaxLength(150)
.IsUnicode(false)
.HasColumnType("varchar(150)");
b.Property<Point>("CoordenadasGeo")
.HasColumnType("geography")
.HasComment("Coordenadas geograficas , Acepta nulos");
b.Property<string>("EntreLaCalle")
.IsRequired()
.HasMaxLength(100)
.IsUnicode(false)
.HasColumnType("varchar(100)");
b.Property<bool>("EsFiscal")
.HasColumnType("bit")
.HasComment("Si la direccion es fiscal para la emision de facturas");
b.Property<bool>("EsHabilitado")
.HasColumnType("bit")
.HasComment("Si esta disponible el registro");
b.Property<string>("Estatus")
.IsRequired()
.HasMaxLength(1)
.IsUnicode(false)
.HasColumnType("char(1)")
.IsFixedLength(true)
.HasComment("Estatus de la direccion");
b.Property<DateTime>("FechaCreacion")
.HasColumnType("datetime")
.HasComment("Fecha de creacion del registro");
b.Property<DateTime>("FechaModificacion")
.HasColumnType("datetime")
.HasComment("Fecha de la Ultima Modificacion");
b.Property<string>("Foto")
.IsRequired()
.HasMaxLength(250)
.IsUnicode(false)
.HasColumnType("varchar(250)")
.HasComment("Foto de la ubicacion");
b.Property<int>("IdAsentamiento")
.HasColumnType("int")
.HasComment("El id de la tabla Asentamiento");
b.Property<string>("NumeroExterior")
.IsRequired()
.HasMaxLength(10)
.IsUnicode(false)
.HasColumnType("varchar(10)");
b.Property<string>("NumeroInterior")
.IsRequired()
.HasMaxLength(10)
.IsUnicode(false)
.HasColumnType("varchar(10)");
b.Property<string>("Referencia")
.IsRequired()
.HasMaxLength(250)
.IsUnicode(false)
.HasColumnType("varchar(250)")
.HasComment("Referencias para identificar la direccion");
b.Property<string>("UsuarioCreacion")
.IsRequired()
.HasMaxLength(50)
.IsUnicode(false)
.HasColumnType("varchar(50)")
.HasComment("Usuario que creo el registro");
b.Property<string>("UsuarioModificacion")
.IsRequired()
.HasMaxLength(50)
.IsUnicode(false)
.HasColumnType("varchar(50)")
.HasComment("Usuario que hizo la ultima modificacion");
b.Property<string>("YlaCalle")
.IsRequired()
.HasMaxLength(100)
.IsUnicode(false)
.HasColumnType("varchar(100)")
.HasColumnName("YLaCalle");
b.HasKey("IdDireccion");
b.HasIndex(new[] { "IdAsentamiento" }, "IXFK_Direccion_Asentamiento");
b.ToTable("Direccion");
b
.HasComment("Registra todas las direcciones");
});
modelBuilder.Entity("Domain.Entities.Documento", b =>
{
b.Property<int>("IdDocumento")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.HasComment("El id de la tabla Documento")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<string>("CodigoUnico")
.IsRequired()
.HasMaxLength(50)
.IsUnicode(false)
.HasColumnType("varchar(50)")
.HasComment("La cadena unica del documento");
b.Property<bool>("EsHabilitado")
.HasColumnType("bit")
.HasComment("Si el registro esta disponible para usarlo");
b.Property<string>("Estatus")
.IsRequired()
.HasMaxLength(1)
.IsUnicode(false)
.HasColumnType("char(1)")
.IsFixedLength(true)
.HasComment("algun estatus para el registro");
b.Property<DateTime>("FechaCreacion")
.HasColumnType("datetime")
.HasComment("Fecha de Creacion de registro");
b.Property<DateTime>("FechaModificacion")
.HasColumnType("datetime")
.HasComment("Ultima Fecha de modificacion");
b.Property<string>("Foto")
.IsRequired()
.HasMaxLength(250)
.IsUnicode(false)
.HasColumnType("varchar(250)")
.HasComment("Foto del documento");
b.Property<int>("IdDocumentoTipo")
.HasColumnType("int")
.HasComment("El Identificador unico de la tabla DocumentoTipo");
b.Property<string>("UsuarioCreacion")
.IsRequired()
.HasMaxLength(50)
.IsUnicode(false)
.HasColumnType("varchar(50)");
b.Property<string>("UsuarioModificacion")
.IsRequired()
.HasMaxLength(50)
.IsUnicode(false)
.HasColumnType("varchar(50)")
.HasComment("Ultimo usuario que modifico el registro");
b.HasKey("IdDocumento");
b.HasIndex(new[] { "IdDocumentoTipo" }, "IXFK_Documento_DocumentoTipo");
b.HasIndex(new[] { "CodigoUnico" }, "IX_NoDuplicado")
.IsUnique()
.HasDatabaseName("IX_NoDuplicado1");
b.ToTable("Documento");
b
.HasComment("Se incluyen todos los documentos que las personas fisicas y morales pueden tener");
});
modelBuilder.Entity("Domain.Entities.DocumentoTipo", b =>
{
b.Property<int>("IdDocumentoTipo")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.HasComment("El identificador unico de registro")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<string>("Abreviatura")
.IsRequired()
.HasMaxLength(10)
.IsUnicode(false)
.HasColumnType("varchar(10)")
.HasComment("Abreviatura del documento");
b.Property<bool>("EsHabilitado")
.HasColumnType("bit")
.HasComment("Si el registro esta disponible para trabajar con el");
b.Property<string>("Estatus")
.IsRequired()
.HasMaxLength(1)
.IsUnicode(false)
.HasColumnType("char(1)")
.IsFixedLength(true)
.HasComment("Estatus del registro");
b.Property<DateTime>("FechaCreacion")
.HasColumnType("datetime")
.HasComment("Fecha en que se creo el registro");
b.Property<DateTime>("FechaModificacion")
.HasColumnType("datetime")
.HasComment("Fecha de la ultima modificacion del registro");
b.Property<int>("Longitud")
.HasColumnType("int")
.HasComment("La longitud de caracteres permitido para la Cadena Unica");
b.Property<string>("Nombre")
.IsRequired()
.HasMaxLength(50)
.IsUnicode(false)
.HasColumnType("varchar(50)")
.HasComment("Nombre completo del documento ");
b.Property<string>("UsuarioCreacion")
.IsRequired()
.HasMaxLength(50)
.IsUnicode(false)
.HasColumnType("varchar(50)")
.HasComment("Usuario que creo el registro");
b.Property<string>("UsuarioModificacion")
.IsRequired()
.HasMaxLength(50)
.IsUnicode(false)
.HasColumnType("varchar(50)")
.HasComment("El usuario de la ultima modificacion");
b.HasKey("IdDocumentoTipo");
b.HasIndex(new[] { "Abreviatura" }, "IX_NoDuplicadoAbre")
.IsUnique()
.HasDatabaseName("IX_NoDuplicadoAbre1");
b.HasIndex(new[] { "Nombre" }, "IX_NoDuplicadoNom")
.IsUnique();
b.ToTable("DocumentoTipo");
b
.HasComment("Se capturan los tipos de documentos para que esten disponibles");
});
modelBuilder.Entity("Domain.Entities.Estado", b =>
{
b.Property<int>("IdEstado")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.HasComment("id del estado")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<int>("Clave")
.HasColumnType("int")
.HasComment("Clave del Estado");
b.Property<bool>("EsHabilitado")
.HasColumnType("bit")
.HasComment("si esta disponible el registro");
b.Property<string>("Estatus")
.IsRequired()
.HasMaxLength(1)
.IsUnicode(false)
.HasColumnType("char(1)")
.IsFixedLength(true);
b.Property<DateTime>("FechaCreacion")
.HasColumnType("datetime")
.HasComment("Fecha de creacion del registro");
b.Property<DateTime>("FechaModificacion")
.HasColumnType("datetime")
.HasComment("Fecha de la ultima modificacion");
b.Property<int>("IdPais")
.HasColumnType("int")
.HasComment("Id al pais que pertenece");
b.Property<string>("Nombre")
.IsRequired()
.HasMaxLength(20)
.IsUnicode(false)
.HasColumnType("varchar(20)")
.HasComment("Nombre del estado del pais");
b.Property<string>("RenapoAbrev")
.IsRequired()
.HasMaxLength(2)
.IsUnicode(false)
.HasColumnType("varchar(2)")
.HasComment("Abreviatura de nombre segun Registro de Poblacion (RENAPO)");
b.Property<string>("TresDigitosAbrev")
.IsRequired()
.HasMaxLength(3)
.IsUnicode(false)
.HasColumnType("varchar(3)")
.HasComment("Abreviatura de nombre a Tres Digitos");
b.Property<string>("UsuarioCreacion")
.IsRequired()
.HasMaxLength(50)
.IsUnicode(false)
.HasColumnType("varchar(50)")
.HasComment("Usuario que creo el registro");
b.Property<string>("UsuarioModificacion")
.IsRequired()
.HasMaxLength(50)
.IsUnicode(false)
.HasColumnType("varchar(50)")
.HasComment("Usuario de la ultima modificacion");
b.Property<string>("VariableAbrev")
.IsRequired()
.HasMaxLength(10)
.IsUnicode(false)
.HasColumnType("varchar(10)")
.HasComment("Abreviatura de nombre de tipo Variable");
b.HasKey("IdEstado");
b.HasIndex("IdPais");
b.HasIndex(new[] { "Clave" }, "IX_NoDuplicadoClave")
.IsUnique();
b.HasIndex(new[] { "Nombre" }, "IX_NoDuplicadoNombre")
.IsUnique();
b.HasIndex(new[] { "RenapoAbrev" }, "IX_NoDuplicadoRenapoAbrev")
.IsUnique();
b.HasIndex(new[] { "TresDigitosAbrev" }, "IX_NoDuplicadoTresDigitosAbrev")
.IsUnique();
b.HasIndex(new[] { "VariableAbrev" }, "IX_NoDuplicadoVariableAbrev")
.IsUnique();
b.ToTable("Estado");
b
.HasComment("Estado de paises");
});
modelBuilder.Entity("Domain.Entities.EstadoCivil", b =>
{
b.Property<int>("IdEstadoCivil")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.HasComment("Id consecutivo ")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<string>("Descripcion")
.IsRequired()
.HasMaxLength(50)
.IsUnicode(false)
.HasColumnType("varchar(50)")
.HasComment("Descripcion del estado civil");
b.Property<bool>("EsHabilitado")
.HasColumnType("bit")
.HasComment("Si el registro esta habilitado");
b.Property<string>("Estatus")
.IsRequired()
.HasMaxLength(1)
.IsUnicode(false)
.HasColumnType("char(1)")
.IsFixedLength(true)
.HasComment("Estatus del estado civil");
b.Property<DateTime>("FechaCreacion")
.HasColumnType("datetime")
.HasComment("Fecha de creacion del registro");
b.Property<DateTime>("FechaModificacion")
.HasColumnType("datetime")
.HasComment("Fecha de la ultima modificacion");
b.Property<string>("UsuarioCreacion")
.IsRequired()
.HasMaxLength(50)
.IsUnicode(false)
.HasColumnType("varchar(50)")
.HasComment("El usuario que creo el registro");
b.Property<string>("UsuarioModificacion")
.IsRequired()
.HasMaxLength(50)
.IsUnicode(false)
.HasColumnType("varchar(50)")
.HasComment("Ultimo usuario que modifico el registro");
b.HasKey("IdEstadoCivil");
b.HasIndex(new[] { "Descripcion" }, "IX_NoDuplicado")
.IsUnique()
.HasDatabaseName("IX_NoDuplicado2");
b.ToTable("EstadoCivil");
b
.HasComment("Los Estados Civiles de las Personas");
});
modelBuilder.Entity("Domain.Entities.Municipio", b =>
{
b.Property<int>("IdMunicipio")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.HasComment("id consecutivo de municipio")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<string>("Abreviatura")
.IsRequired()
.HasMaxLength(10)
.IsUnicode(false)
.HasColumnType("varchar(10)");
b.Property<string>("Ciudad")
.IsRequired()
.HasMaxLength(60)
.IsUnicode(false)
.HasColumnType("varchar(60)")
.HasComment("Nombre de la Ciudad, No todos tienen ciudad");
b.Property<int>("Clave")
.HasColumnType("int")
.HasComment("Clave unica de municipio por estado");
b.Property<bool>("EsHabilitado")
.HasColumnType("bit")
.HasComment("Si el registro esta disponible");
b.Property<string>("Estatus")
.IsRequired()
.HasMaxLength(1)
.IsUnicode(false)
.HasColumnType("char(1)")
.IsFixedLength(true);
b.Property<DateTime>("FechaCreacion")
.HasColumnType("datetime")
.HasComment("Fecha de Creacion del registro");
b.Property<DateTime>("FechaModificacion")
.HasColumnType("datetime")
.HasComment("Fecha de la utlima modificacion");
b.Property<int>("IdEstado")
.HasColumnType("int")
.HasComment("Id que pertenece al estado");
b.Property<string>("Nombre")
.IsRequired()
.HasMaxLength(50)
.IsUnicode(false)
.HasColumnType("varchar(50)")
.HasComment("Nombre del Municipio");
b.Property<string>("UsuarioCreacion")
.IsRequired()
.HasMaxLength(50)
.IsUnicode(false)
.HasColumnType("varchar(50)")
.HasComment("Usuario que creo el Registro");
b.Property<string>("UsuarioModificacion")
.IsRequired()
.HasMaxLength(50)
.IsUnicode(false)
.HasColumnType("varchar(50)")
.HasComment("Ultimo usuario que modifico el registro");
b.HasKey("IdMunicipio");
b.HasIndex(new[] { "IdEstado" }, "IXFK_Municipio_Estado");
b.HasIndex(new[] { "Abreviatura" }, "IX_NoDuplicadoAbrevMuni")
.IsUnique();
b.HasIndex(new[] { "IdEstado", "Clave" }, "IX_NoDuplicadoIdEstadoClave")
.IsUnique();
b.HasIndex(new[] { "Nombre", "IdEstado" }, "IX_NoDuplicadoNombreEstado")
.IsUnique();
b.ToTable("Municipio");
b
.HasComment("Municipios de Mexico");
});
modelBuilder.Entity("Domain.Entities.Nacionalidad", b =>
{
b.Property<int>("IdNacionalidad")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.HasComment("Id unico para el registro")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<string>("Descripcion")
.IsRequired()
.HasMaxLength(50)
.IsUnicode(false)
.HasColumnType("varchar(50)")
.HasComment("concepto de nacionalidad de la persona");
b.Property<bool>("EsHabilitado")
.HasColumnType("bit")
.HasComment("si esta disponible el registro ");
b.Property<string>("Estatus")
.IsRequired()
.HasMaxLength(1)
.IsUnicode(false)
.HasColumnType("char(1)")
.IsFixedLength(true)
.HasComment("El Estatus del Registro");
b.Property<DateTime>("FechaCreacion")
.HasColumnType("datetime")
.HasComment("Fecha en que se creo el registro");
b.Property<DateTime>("FechaModificacion")
.HasColumnType("datetime")
.HasComment("fecha de la ultima modificacion");
b.Property<string>("UsuarioCreacion")
.IsRequired()
.HasMaxLength(50)
.IsUnicode(false)
.HasColumnType("varchar(50)")
.HasComment("Usuario que creo el registro");
b.Property<string>("UsuarioModificacion")
.IsRequired()
.HasMaxLength(50)
.IsUnicode(false)
.HasColumnType("varchar(50)")
.HasComment("El ultimo Usuario que modifico el registro");
b.HasKey("IdNacionalidad");
b.HasIndex(new[] { "Descripcion" }, "IX_NoDuplicado")
.IsUnique()
.HasDatabaseName("IX_NoDuplicado3");
b.ToTable("Nacionalidad");
b
.HasComment("Catalogo de Nacionalidades con su bandera");
});
modelBuilder.Entity("Domain.Entities.Pais", b =>
{
b.Property<int>("IdPais")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.HasComment("Identificador unico")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<string>("Abreviatura")
.IsRequired()
.HasMaxLength(5)
.IsUnicode(false)
.HasColumnType("char(5)")
.IsFixedLength(true)
.HasComment("Abreviatura del nombre del Pais");
b.Property<bool>("EsHabilitado")
.HasColumnType("bit")
.HasComment("Si el registro esta disponible para trabajar con el");
b.Property<string>("Estatus")
.IsRequired()
.HasMaxLength(1)
.IsUnicode(false)
.HasColumnType("char(1)")
.IsFixedLength(true)
.HasComment("Estatus del registro");
b.Property<DateTime>("FechaCreacion")
.HasColumnType("datetime")
.HasComment("Fecha en que se creo el registro");
b.Property<DateTime>("FechaModificacion")
.HasColumnType("datetime")
.HasComment("Fecha de la ultima modificacion del registro");
b.Property<string>("Nombre")
.IsRequired()
.HasMaxLength(50)
.IsUnicode(false)
.HasColumnType("char(50)")
.IsFixedLength(true)
.HasComment("Nombre del Pais");
b.Property<string>("UsuarioCreacion")
.IsRequired()
.HasMaxLength(50)
.IsUnicode(false)
.HasColumnType("varchar(50)")
.HasComment("Usuario que creo el registro");
b.Property<string>("UsuarioModificacion")
.IsRequired()
.HasMaxLength(50)
.IsUnicode(false)
.HasColumnType("varchar(50)")
.HasComment("El usuario de la ultima modificacion");
b.HasKey("IdPais");
b.HasIndex(new[] { "Abreviatura" }, "IX_NoDuplicadoAbrevPais")
.IsUnique();
b.HasIndex(new[] { "Nombre" }, "IX_NoDuplicadoNombrePais")
.IsUnique();
b.ToTable("Pais");
b
.HasComment("Catalogo de Paises");
});
modelBuilder.Entity("Domain.Entities.Persona", b =>
{
b.Property<int>("IdPersona")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.HasComment("id consecutivo de la tabla personas")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<string>("ApellidoMaterno")
.IsRequired()
.HasMaxLength(50)
.IsUnicode(false)
.HasColumnType("varchar(50)")
.HasComment("Apellido materno de la persona");
b.Property<string>("ApellidoPaterno")
.IsRequired()
.HasMaxLength(50)
.IsUnicode(false)
.HasColumnType("varchar(50)")
.HasComment("Apellido paterno de la persona");
b.Property<bool>("EsHabilitado")
.HasColumnType("bit")
.HasComment("Si el registro esta habilitado ");
b.Property<string>("Estatus")
.IsRequired()
.HasMaxLength(1)
.IsUnicode(false)
.HasColumnType("char(1)")
.IsFixedLength(true)
.HasComment("Estatus de la Persona ");
b.Property<DateTime>("FechaCreacion")
.HasColumnType("datetime")
.HasComment("Fecha de la Creacion del registro");
b.Property<DateTime>("FechaModificacion")
.HasColumnType("datetime")
.HasComment("Fecha de la ultima modificacion ");
b.Property<DateTime>("FechaNacimiento")
.HasColumnType("date")
.HasComment("Fecha de nacimiento de la persona");
b.Property<string>("Foto")
.IsRequired()
.HasMaxLength(250)
.IsUnicode(false)
.HasColumnType("varchar(250)")
.HasComment("El path de la foto de la persona");
b.Property<int>("IdEstadoCivil")
.HasColumnType("int")
.HasComment("El estado civil de la persona Casado, Divorciado, Soltero, union libre");
b.Property<int>("IdNacionalidad")
.HasColumnType("int")
.HasComment("id Nacionalidad de la persona");
b.Property<string>("Nombres")
.IsRequired()
.HasMaxLength(50)
.IsUnicode(false)
.HasColumnType("varchar(50)")
.HasComment("Nombre o Nombres de la persona");
b.Property<string>("Notas")
.IsRequired()
.IsUnicode(false)
.HasColumnType("varchar(max)")
.HasComment("Notas importantes de la persona");
b.Property<string>("Sexo")
.IsRequired()
.HasMaxLength(1)
.IsUnicode(false)
.HasColumnType("char(1)")
.IsFixedLength(true)
.HasComment("M = Masculino , F = Femenino");
b.Property<string>("UsuarioCreacion")
.IsRequired()
.HasMaxLength(50)
.IsUnicode(false)
.HasColumnType("varchar(50)")
.HasComment("Usuario que creo el registro");
b.Property<string>("UsuarioModificacion")
.IsRequired()
.HasMaxLength(50)
.IsUnicode(false)
.HasColumnType("varchar(50)")
.HasComment("Ultimo usuario que modifico");
b.HasKey("IdPersona");
b.HasIndex(new[] { "IdEstadoCivil" }, "IXFK_Persona_EstadoCivil");
b.HasIndex(new[] { "IdNacionalidad" }, "IXFK_Persona_Nacionalidad");
b.HasIndex(new[] { "ApellidoPaterno", "ApellidoMaterno", "Nombres" }, "IX_NoDuplicado")
.IsUnique()
.HasDatabaseName("IX_NoDuplicado4");
b.ToTable("Persona");
b
.HasComment("Almacena la informacion de todas las personas");
});
modelBuilder.Entity("Domain.Entities.PersonaCorreoElectronico", b =>
{
b.Property<int>("IdPersonaCorreoElectronico")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<int>("IdCorreoElectronico")
.HasColumnType("int")
.HasComment("Identificador unico de la tabla de Correo Electronico");
b.Property<int>("IdPersona")
.HasColumnType("int")
.HasComment("Identificador unico del registro de persona ");
b.HasKey("IdPersonaCorreoElectronico");
b.HasIndex(new[] { "IdCorreoElectronico" }, "IXFK_PersonaCorreoElectronico_CorreoElectronico");
b.HasIndex(new[] { "IdPersona" }, "IXFK_PersonaCorreoElectronico_Persona");
b.HasIndex(new[] { "IdPersona", "IdCorreoElectronico" }, "IX_NoDuplicado")
.IsUnique()
.HasDatabaseName("IX_NoDuplicado5");
b.ToTable("PersonaCorreoElectronico");
b
.HasComment("Los Correos electronicos que tiene una persona");
});
modelBuilder.Entity("Domain.Entities.PersonaDireccion", b =>
{
b.Property<int>("IdPersonaDireccion")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<int>("IdDireccion")
.HasColumnType("int")
.HasComment("El id de la Tabla Direccion");
b.Property<int>("IdPersona")
.HasColumnType("int")
.HasComment("El id de la tabla de Personas");
b.HasKey("IdPersonaDireccion");
b.HasIndex(new[] { "IdDireccion" }, "IXFK_PersonaDireccion_Direccion");
b.HasIndex(new[] { "IdPersona" }, "IXFK_PersonaDireccion_Persona");
b.HasIndex(new[] { "IdPersona", "IdDireccion" }, "IX_NoDuplicado")
.IsUnique()
.HasDatabaseName("IX_NoDuplicado6");
b.ToTable("PersonaDireccion");
b
.HasComment("Las direcciones que tiene una persona");
});
modelBuilder.Entity("Domain.Entities.PersonaDocumento", b =>
{
b.Property<int>("IdPersonaDocumento")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<int>("IdDocumento")
.HasColumnType("int")
.HasComment("IdDocumento de la Tabla Documento");
b.Property<int>("IdPersona")
.HasColumnType("int")
.HasComment("El IdPersona de la tabla Personas");
b.HasKey("IdPersonaDocumento");
b.HasIndex(new[] { "IdDocumento" }, "IXFK_PersonaDocumento_Documento");
b.HasIndex(new[] { "IdPersona" }, "IXFK_PersonaDocumento_Persona");
b.HasIndex(new[] { "IdPersona", "IdDocumento" }, "IX_NoDuplicado")
.IsUnique()
.HasDatabaseName("IX_NoDuplicado7");
b.ToTable("PersonaDocumento");
b
.HasComment("La relacion de los documentos que puede tener una persona");
});
modelBuilder.Entity("Domain.Entities.PersonaTelefono", b =>
{
b.Property<int>("IdPersonaTelefono")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<int>("IdPersona")
.HasColumnType("int")
.HasComment("El identificador de la tabla persona");
b.Property<int>("IdTelefono")
.HasColumnType("int")
.HasComment("El identificador de la tabla telefono");
b.HasKey("IdPersonaTelefono");
b.HasIndex(new[] { "IdPersona" }, "IXFK_PersonaTelefono_Persona");
b.HasIndex(new[] { "IdTelefono" }, "IXFK_PersonaTelefono_Telefono");
b.HasIndex(new[] { "IdPersona", "IdTelefono" }, "IX_NoDuplicado")
.IsUnique()
.HasDatabaseName("IX_NoDuplicado8");
b.ToTable("PersonaTelefono");
b
.HasComment("Los numeros de telefono de las personas");
});
modelBuilder.Entity("Domain.Entities.SysDominioCorreo", b =>
{
b.Property<int>("IdSysDominioCorreo")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.HasComment("Identificador unico ")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<string>("Dominio")
.IsRequired()
.HasMaxLength(80)
.IsUnicode(false)
.HasColumnType("varchar(80)")
.HasComment("Dominio Hotmail.com, Gmail.com, etc..");
b.Property<bool>("EsHabilitado")
.HasColumnType("bit")
.HasComment("Si el registro estra disponible, borrado Logico");
b.Property<string>("Estatus")
.IsRequired()
.HasMaxLength(1)
.IsUnicode(false)
.HasColumnType("char(1)")
.IsFixedLength(true)
.HasComment("estatus del registro");
b.Property<DateTime>("FechaCreacion")
.HasColumnType("datetime")
.HasComment("Fecha de creacion del registro");
b.Property<DateTime>("FechaModificacion")
.HasColumnType("datetime")
.HasComment("Fecha de la ultima modificacion");
b.Property<string>("UsuarioCreacion")
.IsRequired()
.HasMaxLength(50)
.IsUnicode(false)
.HasColumnType("varchar(50)")
.HasComment("Usuario que creo el registro");
b.Property<string>("UsuarioModificacion")
.IsRequired()
.HasMaxLength(50)
.IsUnicode(false)
.HasColumnType("varchar(50)")
.HasComment("Usuario que hizo la ultima modificacion");
b.HasKey("IdSysDominioCorreo");
b.HasIndex(new[] { "Dominio" }, "IX_NoDuplicado")
.IsUnique()
.HasDatabaseName("IX_NoDuplicado9");
b.ToTable("SysDominioCorreo");
b
.HasComment("Dominios precapturados para los correos");
});
modelBuilder.Entity("Domain.Entities.Telefono", b =>
{
b.Property<int>("IdTelefono")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.HasComment("Identificador unico de la tabla telefono")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<string>("CodigoPais")
.IsRequired()
.HasMaxLength(4)
.IsUnicode(false)
.HasColumnType("varchar(4)")
.HasComment("Codigo Telefonico del Pais");
b.Property<bool>("EsHabilitado")
.HasColumnType("bit")
.HasComment("Si el registro esta habilitado para trabajar");
b.Property<string>("Estatus")
.IsRequired()
.HasMaxLength(1)
.IsUnicode(false)
.HasColumnType("char(1)")
.IsFixedLength(true)
.HasComment("Estatus del registro");
b.Property<DateTime>("FechaCreacion")
.HasColumnType("datetime")
.HasComment("Fecha de creacion del registro");
b.Property<DateTime>("FechaModificacion")
.HasColumnType("datetime")
.HasComment("Ultima fecha de Modificacion del registro");
b.Property<string>("Numero")
.IsRequired()
.HasMaxLength(15)
.IsUnicode(false)
.HasColumnType("varchar(15)")
.HasComment("Numero telefonico");
b.Property<string>("TipoTelefono")
.IsRequired()
.HasMaxLength(50)
.IsUnicode(false)
.HasColumnType("varchar(50)")
.HasComment("Celular o Fijo");
b.Property<string>("UsuarioCreacion")
.IsRequired()
.HasMaxLength(50)
.IsUnicode(false)
.HasColumnType("varchar(50)")
.HasComment("Usuario que creo el registro");
b.Property<string>("UsuarioModificacion")
.IsRequired()
.HasMaxLength(50)
.IsUnicode(false)
.HasColumnType("varchar(50)")
.HasComment("Ultimo usuario que modifico el registro");
b.HasKey("IdTelefono");
b.HasIndex(new[] { "CodigoPais", "Numero" }, "IX_NoDuplicadoCodigoPaisNumero")
.IsUnique();
b.ToTable("Telefono");
b
.HasComment("Todos los Telefonos de personas y empresas");
});
modelBuilder.Entity("Domain.Entities.Asentamiento", b =>
{
b.HasOne("Domain.Entities.AsentamientoTipo", "AsentamientoTipo")
.WithMany("Asentamientos")
.HasForeignKey("IdAsentamientoTipo")
.HasConstraintName("FK_Asentamiento_AsentamientoTipo")
.IsRequired();
b.HasOne("Domain.Entities.Municipio", "Municipio")
.WithMany("Asentamientos")
.HasForeignKey("IdMunicipio")
.HasConstraintName("FK_Asentamiento_Municipio")
.IsRequired();
b.Navigation("AsentamientoTipo");
b.Navigation("Municipio");
});
modelBuilder.Entity("Domain.Entities.Direccion", b =>
{
b.HasOne("Domain.Entities.Asentamiento", "Asentamiento")
.WithMany("Direcciones")
.HasForeignKey("IdAsentamiento")
.HasConstraintName("FK_Direccion_Asentamiento")
.IsRequired();
b.Navigation("Asentamiento");
});
modelBuilder.Entity("Domain.Entities.Documento", b =>
{
b.HasOne("Domain.Entities.DocumentoTipo", "DocumentoTipo")
.WithMany("Documentos")
.HasForeignKey("IdDocumentoTipo")
.HasConstraintName("FK_Documento_DocumentoTipo")
.IsRequired();
b.Navigation("DocumentoTipo");
});
modelBuilder.Entity("Domain.Entities.Estado", b =>
{
b.HasOne("Domain.Entities.Pais", "Pais")
.WithMany("Estados")
.HasForeignKey("IdPais")
.HasConstraintName("FK_Estado_Pais")
.OnDelete(DeleteBehavior.Restrict)
.IsRequired();
b.Navigation("Pais");
});
modelBuilder.Entity("Domain.Entities.Municipio", b =>
{
b.HasOne("Domain.Entities.Estado", "Estado")
.WithMany("Municipios")
.HasForeignKey("IdEstado")
.HasConstraintName("FK_Municipio_Estado")
.IsRequired();
b.Navigation("Estado");
});
modelBuilder.Entity("Domain.Entities.Persona", b =>
{
b.HasOne("Domain.Entities.EstadoCivil", "EstadoCivil")
.WithMany("Personas")
.HasForeignKey("IdEstadoCivil")
.HasConstraintName("FK_Persona_EstadoCivil")
.IsRequired();
b.HasOne("Domain.Entities.Nacionalidad", "Nacionalidad")
.WithMany("Personas")
.HasForeignKey("IdNacionalidad")
.HasConstraintName("FK_Persona_Nacionalidad")
.IsRequired();
b.Navigation("EstadoCivil");
b.Navigation("Nacionalidad");
});
modelBuilder.Entity("Domain.Entities.PersonaCorreoElectronico", b =>
{
b.HasOne("Domain.Entities.CorreoElectronico", "CorreoElectronico")
.WithMany("PersonasCorreosElectronicos")
.HasForeignKey("IdCorreoElectronico")
.HasConstraintName("FK_PersonaCorreoElectronico_CorreoElectronico")
.IsRequired();
b.HasOne("Domain.Entities.Persona", "Persona")
.WithMany("PersonaCorreosElectronicos")
.HasForeignKey("IdPersona")
.HasConstraintName("FK_PersonaCorreoElectronico_Persona")
.IsRequired();
b.Navigation("CorreoElectronico");
b.Navigation("Persona");
});
modelBuilder.Entity("Domain.Entities.PersonaDireccion", b =>
{
b.HasOne("Domain.Entities.Direccion", "Direccion")
.WithMany("PersonaDirecciones")
.HasForeignKey("IdDireccion")
.HasConstraintName("FK_PersonaDireccion_Direccion")
.IsRequired();
b.HasOne("Domain.Entities.Persona", "Persona")
.WithMany("PersonaDirecciones")
.HasForeignKey("IdPersona")
.HasConstraintName("FK_PersonaDireccion_Persona")
.IsRequired();
b.Navigation("Direccion");
b.Navigation("Persona");
});
modelBuilder.Entity("Domain.Entities.PersonaDocumento", b =>
{
b.HasOne("Domain.Entities.Documento", "Documento")
.WithMany("PersonaDocumentos")
.HasForeignKey("IdDocumento")
.HasConstraintName("FK_PersonaDocumento_Documento")
.IsRequired();
b.HasOne("Domain.Entities.Persona", "Persona")
.WithMany("PersonaDocumentos")
.HasForeignKey("IdPersona")
.HasConstraintName("FK_PersonaDocumento_Persona")
.IsRequired();
b.Navigation("Documento");
b.Navigation("Persona");
});
modelBuilder.Entity("Domain.Entities.PersonaTelefono", b =>
{
b.HasOne("Domain.Entities.Persona", "Persona")
.WithMany("PersonaTelefonos")
.HasForeignKey("IdPersona")
.HasConstraintName("FK_PersonaTelefono_Persona")
.IsRequired();
b.HasOne("Domain.Entities.Telefono", "Telefono")
.WithMany("PersonaTelefonos")
.HasForeignKey("IdTelefono")
.HasConstraintName("FK_PersonaTelefono_Telefono")
.IsRequired();
b.Navigation("Persona");
b.Navigation("Telefono");
});
modelBuilder.Entity("Domain.Entities.Asentamiento", b =>
{
b.Navigation("Direcciones");
});
modelBuilder.Entity("Domain.Entities.AsentamientoTipo", b =>
{
b.Navigation("Asentamientos");
});
modelBuilder.Entity("Domain.Entities.CorreoElectronico", b =>
{
b.Navigation("PersonasCorreosElectronicos");
});
modelBuilder.Entity("Domain.Entities.Direccion", b =>
{
b.Navigation("PersonaDirecciones");
});
modelBuilder.Entity("Domain.Entities.Documento", b =>
{
b.Navigation("PersonaDocumentos");
});
modelBuilder.Entity("Domain.Entities.DocumentoTipo", b =>
{
b.Navigation("Documentos");
});
modelBuilder.Entity("Domain.Entities.Estado", b =>
{
b.Navigation("Municipios");
});
modelBuilder.Entity("Domain.Entities.EstadoCivil", b =>
{
b.Navigation("Personas");
});
modelBuilder.Entity("Domain.Entities.Municipio", b =>
{
b.Navigation("Asentamientos");
});
modelBuilder.Entity("Domain.Entities.Nacionalidad", b =>
{
b.Navigation("Personas");
});
modelBuilder.Entity("Domain.Entities.Pais", b =>
{
b.Navigation("Estados");
});
modelBuilder.Entity("Domain.Entities.Persona", b =>
{
b.Navigation("PersonaCorreosElectronicos");
b.Navigation("PersonaDirecciones");
b.Navigation("PersonaDocumentos");
b.Navigation("PersonaTelefonos");
});
modelBuilder.Entity("Domain.Entities.Telefono", b =>
{
b.Navigation("PersonaTelefonos");
});
#pragma warning restore 612, 618
}
}
}
| 41.860041 | 125 | 0.450421 | [
"MIT"
] | NSysX/NSysWeb | NSysWeb/src/Infraestructure/Persistence/Migrations/20220106234059_AjusteEnMunicipiosCRUD.Designer.cs | 61,913 | C# |
using System;
using My2C2P.Org.BouncyCastle.Asn1;
using My2C2P.Org.BouncyCastle.Math;
namespace My2C2P.Org.BouncyCastle.Crypto.Parameters
{
public class DHPublicKeyParameters
: DHKeyParameters
{
private readonly BigInteger y;
public DHPublicKeyParameters(
BigInteger y,
DHParameters parameters)
: base(false, parameters)
{
if (y == null)
throw new ArgumentNullException("y");
this.y = y;
}
public DHPublicKeyParameters(
BigInteger y,
DHParameters parameters,
DerObjectIdentifier algorithmOid)
: base(false, parameters, algorithmOid)
{
if (y == null)
throw new ArgumentNullException("y");
this.y = y;
}
public BigInteger Y
{
get { return y; }
}
public override bool Equals(
object obj)
{
if (obj == this)
return true;
DHPublicKeyParameters other = obj as DHPublicKeyParameters;
if (other == null)
return false;
return Equals(other);
}
protected bool Equals(
DHPublicKeyParameters other)
{
return y.Equals(other.y) && base.Equals(other);
}
public override int GetHashCode()
{
return y.GetHashCode() ^ base.GetHashCode();
}
}
}
| 19.402985 | 62 | 0.605385 | [
"MIT"
] | 2C2P/My2C2PPKCS7 | My2C2PPKCS7/crypto/parameters/DHPublicKeyParameters.cs | 1,300 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class RegisterButton : MonoBehaviour
{
public GameObject registration;
private void OnMouseDown()
{
registration.SetActive(true);
}
}
| 17.75 | 43 | 0.697183 | [
"MIT"
] | Andrii-Samoilov/EndJoy | EndJoy/Assets/Scripts/RegisterButton.cs | 286 | C# |
using System;
using System.Collections.Generic;
using System.Windows.Forms;
namespace MySqlBackupTestApp
{
static class Program
{
public static string Version = "V2.3.6";
public static string DateVersion = "October 17, 2021";
private static string _connectionString = "";
public static string ConnectionString
{
get
{
if (String.IsNullOrEmpty(_connectionString))
throw new Exception("Connection string is empty.");
else
return _connectionString;
}
set
{
_connectionString = value;
}
}
public static string DefaultFolder = "";
public static string TargetFile = "";
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new FormMain());
}
public static bool TargetDirectoryIsValid()
{
try
{
string dir = System.IO.Path.GetDirectoryName(Program.TargetFile);
if (!System.IO.Directory.Exists(dir))
{
System.IO.Directory.CreateDirectory(dir);
}
return true;
}
catch (Exception ex)
{
MessageBox.Show("Specify path is not valid. Press [Export As] to specify a valid file path." + Environment.NewLine + Environment.NewLine + ex.Message, "Invalid Directory", MessageBoxButtons.OK, MessageBoxIcon.Information);
return false;
}
}
public static bool SourceFileExists()
{
if (!System.IO.File.Exists(Program.TargetFile))
{
MessageBox.Show("File is not exists. Press [Select File] to choose a SQL Dump file." + Environment.NewLine + Environment.NewLine + Program.TargetFile, "Import", MessageBoxButtons.OK, MessageBoxIcon.Information);
return false;
}
return true;
}
}
}
| 31.680556 | 238 | 0.544936 | [
"Unlicense"
] | MySqlBackupNET/MySqlBackup.Net | source code/Test_WinForm/Program.cs | 2,283 | C# |
namespace ET
{
public class MessageHandlerAttribute: BaseAttribute
{
public SceneType SceneType { get; }
public MessageHandlerAttribute(SceneType sceneType)
{
this.SceneType = sceneType;
}
}
} | 20.833333 | 59 | 0.616 | [
"MIT"
] | xushi-mike/ET | Unity/Codes/Model/Module/Message/MessageHandlerAttribute.cs | 252 | C# |
using Microsoft.EntityFrameworkCore;
using System;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace library.entities
{
public class Members
{
[Key]
[Column(Order=1)]
public int MemberId { get; set; }
[Column(Order=2)]
public Guid MemberMsk { get; set; }
[Column(Order=3)]
public string Name { get; set; }
}
} | 21.1 | 52 | 0.665877 | [
"MIT"
] | LuisAlvar/reminderapi | library/entities/Members.cs | 422 | C# |
#if NET20
// ReSharper disable once CheckNamespace
namespace System.Runtime.CompilerServices
{
[AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = false)]
internal class ExtensionAttribute : Attribute
{
}
}
#endif | 25.4 | 87 | 0.755906 | [
"MIT"
] | UblSharp/UblSharp | src/UblSharp/Internal/ExtensionAttribute.cs | 256 | C# |
namespace AngleSharp.Dom.Css
{
/// <summary>
/// Available device update frequencies.
/// </summary>
public enum UpdateFrequency : byte
{
/// <summary>
/// Once it has been rendered, the layout can no longer
/// be updated. Example: documents printed on paper.
/// </summary>
None,
/// <summary>
/// The layout may change dynamically according to the
/// usual rules of CSS, but the output device is not
/// able to render or display changes quickly enough for
/// them to be percieved as a smooth animation.
/// Example: E-ink screens or severely under-powered
/// devices.
/// </summary>
Slow,
/// <summary>
/// The layout may change dynamically according to the
/// usual rules of CSS, and the output device is not
/// unusually constrained in speed, so regularly-updating
/// things like CSS Animations can be used.
/// Example: computer screens.
/// </summary>
Normal
}
}
| 33.6875 | 65 | 0.57885 | [
"MIT"
] | ArmyMedalMei/AngleSharp | src/AngleSharp/Dom/Css/Constants/UpdateFrequency.cs | 1,080 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace MeisterGeister.ViewModel.Generator.Container
{
class Person : PersonNurName
{
// toString überschreiben
// Formatierbares ergänzen
}
}
| 17.625 | 55 | 0.663121 | [
"Apache-2.0"
] | Constructor0987/MeisterGeister | ViewModel/Generator/Container/Person.cs | 286 | C# |
using UnityEngine;
namespace AbstractFactory
{
public partial class UiSystemPlatformsFactoryUsage
{
//Concrete Product A1
public class XboxInput : IInput
{
public KeyCode Jump => KeyCode.JoystickButton0;
public KeyCode Attack => KeyCode.JoystickButton1;
public KeyCode Block => KeyCode.JoystickButton2;
public KeyCode PowerUp => KeyCode.JoystickButton3;
}
//Concrete Product A2
public class Ps4Input : IInput
{
public KeyCode Jump => KeyCode.JoystickButton3;
public KeyCode Attack => KeyCode.JoystickButton2;
public KeyCode Block => KeyCode.JoystickButton1;
public KeyCode PowerUp => KeyCode.JoystickButton0;
}
//------------------------------------------------------------------------------------------------------------------
//Concrete Product B1
public class XboxWindow : IWindow
{
public string Name => "XboxWindow";
}
//Concrete Product B2
public class Ps4Window : IWindow
{
public string Name => "Ps4Window";
}
//------------------------------------------------------------------------------------------------------------------
//Concrete Product C1
public class XboxButton : IButton
{
public string Name => "XboxButton";
}
//Concrete Product C2
public class Ps4Button : IButton
{
public string Name => "Ps4Button";
}
}
} | 30.188679 | 124 | 0.485 | [
"MIT"
] | ycarowr/Unity-Design-Patterns | Assets/Creational/AbstractFactory/UiSystemPlatformsFactory/Scripts/UiSystemPlatformsFactoryUsage.ConcreteProducts.cs | 1,600 | 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.Extensions.Options;
namespace Microsoft.AspNetCore.Mvc.Razor;
internal class RazorViewEngineOptionsSetup : IConfigureOptions<RazorViewEngineOptions>
{
public void Configure(RazorViewEngineOptions options)
{
if (options == null)
{
throw new ArgumentNullException(nameof(options));
}
options.ViewLocationFormats.Add("/Views/{1}/{0}" + RazorViewEngine.ViewExtension);
options.ViewLocationFormats.Add("/Views/Shared/{0}" + RazorViewEngine.ViewExtension);
options.AreaViewLocationFormats.Add("/Areas/{2}/Views/{1}/{0}" + RazorViewEngine.ViewExtension);
options.AreaViewLocationFormats.Add("/Areas/{2}/Views/Shared/{0}" + RazorViewEngine.ViewExtension);
options.AreaViewLocationFormats.Add("/Views/Shared/{0}" + RazorViewEngine.ViewExtension);
}
}
| 39.52 | 107 | 0.72166 | [
"MIT"
] | 3ejki/aspnetcore | src/Mvc/Mvc.Razor/src/RazorViewEngineOptionsSetup.cs | 988 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using WebApi.Entities;
using WebApi.Helpers;
namespace WebApi.Services
{
public interface IUserService
{
User Authenticate(string username, string password);
IEnumerable<User> GetAll();
User GetById(int id);
User Create(User user, string password);
void Update(User user, string password = null);
void Delete(int id);
void DeleteAccess(int id);
void DeleteDatabase(int id);
}
public class UserService : IUserService
{
private DataContext _context;
public UserService(DataContext context)
{
_context = context;
}
public User Authenticate(string username, string password)
{
if (string.IsNullOrEmpty(username) || string.IsNullOrEmpty(password))
return null;
var user = _context.Users.SingleOrDefault(x => x.Username == username);
// check if username exists
if (user == null)
return null;
// check if password is correct
if (!VerifyPasswordHash(password, user.PasswordHash, user.PasswordSalt))
return null;
// authentication successful
return user;
}
public IEnumerable<User> GetAll()
{
return _context.Users;
}
public User GetById(int id)
{
return _context.Users.Find(id);
}
public User Create(User user,string password)
{
// validation
if (string.IsNullOrWhiteSpace(password))
throw new AppException("Password is required");
if (_context.Users.Any(x => x.Username == user.Username))
throw new AppException("Username \"" + user.Username + "\" is already taken");
byte[] passwordHash, passwordSalt;
CreatePasswordHash(password, out passwordHash, out passwordSalt);
user.PasswordHash = passwordHash;
user.PasswordSalt = passwordSalt;
_context.Users.Add(user);
_context.SaveChanges();
return user;
}
public void Update(User userParam, string password = null)
{
var user = _context.Users.Find(userParam.Id);
if (user == null)
throw new AppException("User not found");
if (userParam.Username != user.Username)
{
// username has changed so check if the new username is already taken
if (_context.Users.Any(x => x.Username == userParam.Username))
throw new AppException("Username " + userParam.Username + " is already taken");
}
// update user properties
user.FirstName = userParam.FirstName;
user.LastName = userParam.LastName;
user.Username = userParam.Username;
user.Lattitude = userParam.Lattitude;
user.Longitude = userParam.Longitude;
// update password if it was entered
if (!string.IsNullOrWhiteSpace(password))
{
byte[] passwordHash, passwordSalt;
CreatePasswordHash(password, out passwordHash, out passwordSalt);
user.PasswordHash = passwordHash;
user.PasswordSalt = passwordSalt;
}
_context.Users.Update(user);
_context.SaveChanges();
}
public void Delete(int id)
{
var user = _context.Users.Find(id);
if (user != null)
{
_context.Users.Remove(user);
_context.SaveChanges();
}
}
public void DeleteAccess(int id)
{
var access = _context.UserAccounts.Find(id);
if (access != null)
{
_context.UserAccounts.Remove(access);
_context.SaveChanges();
}
}
public void DeleteDatabase(int id)
{
var database = _context.Accounts.Find(id);
if (database != null)
{
_context.Accounts.Remove(database);
_context.SaveChanges();
}
}
// private helper methods
private static void CreatePasswordHash(string password, out byte[] passwordHash, out byte[] passwordSalt)
{
if (password == null) throw new ArgumentNullException("password");
if (string.IsNullOrWhiteSpace(password)) throw new ArgumentException("Value cannot be empty or whitespace only string.", "password");
using (var hmac = new System.Security.Cryptography.HMACSHA512())
{
passwordSalt = hmac.Key;
passwordHash = hmac.ComputeHash(System.Text.Encoding.UTF8.GetBytes(password));
}
}
private static bool VerifyPasswordHash(string password, byte[] storedHash, byte[] storedSalt)
{
if (password == null) throw new ArgumentNullException("password");
if (string.IsNullOrWhiteSpace(password)) throw new ArgumentException("Value cannot be empty or whitespace only string.", "password");
if (storedHash.Length != 64) throw new ArgumentException("Invalid length of password hash (64 bytes expected).", "passwordHash");
if (storedSalt.Length != 128) throw new ArgumentException("Invalid length of password salt (128 bytes expected).", "passwordHash");
using (var hmac = new System.Security.Cryptography.HMACSHA512(storedSalt))
{
var computedHash = hmac.ComputeHash(System.Text.Encoding.UTF8.GetBytes(password));
for (int i = 0; i < computedHash.Length; i++)
{
if (computedHash[i] != storedHash[i]) return false;
}
}
return true;
}
}
} | 33.395604 | 145 | 0.561204 | [
"MIT"
] | grabraine/grabraine | Services/UserService.cs | 6,078 | C# |
using Faker.Tests.Base;
using NUnit.Framework;
namespace Faker.Tests.en
{
[TestFixture]
[SetUICulture("en")]
[SetCulture("en")]
[Category("Culture 'en'")]
public class LoremEnglishTests : LoremTestsBase
{
}
} | 17.714286 | 51 | 0.625 | [
"MIT"
] | AdmiringWorm/Faker.NET.Portable | tests/Faker.Tests/en_LoremEnglishTests.cs | 250 | C# |
/*
*
* (c) Copyright Ascensio System Limited 2010-2020
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.IO.Compression;
using System.Net;
using System.Security.Cryptography;
using System.Text;
using System.Threading;
using System.Web.Optimization;
using ASC.Common.Logging;
using ASC.Common.Web;
using ASC.Data.Storage.Configuration;
using Google;
using Google.Apis.Auth.OAuth2;
using Google.Cloud.Storage.V1;
namespace ASC.Web.Core.Client.Bundling
{
public class GoogleCloudStorageTransform : IBundleTransform
{
private static readonly ILog log = LogManager.GetLogger("ASC.Web.Bundle.GoogleCloudStorageTransform");
private static readonly Dictionary<string, string> appenders = new Dictionary<string, string>();
private static readonly ConcurrentQueue<CdnItem> queue = new ConcurrentQueue<CdnItem>();
private static int work = 0;
private static bool successInitialized = false;
private static string _bucket = "";
private static string _json = "";
private static string _region = "";
static GoogleCloudStorageTransform()
{
try
{
var section = (StorageConfigurationSection)ConfigurationManagerExtension.GetSection("storage");
if (section == null)
{
throw new Exception("Storage section not found.");
}
if (section.Appenders.Count == 0)
{
throw new Exception("Appenders not found.");
}
foreach (AppenderConfigurationElement a in section.Appenders)
{
var url = string.IsNullOrEmpty(a.AppendSecure) ? a.Append : a.AppendSecure;
if (url.StartsWith("~"))
{
throw new Exception("Only absolute cdn path supported. Can not use " + url);
}
appenders[a.Extensions + "|"] = url.TrimEnd('/') + "/";
}
foreach (HandlerConfigurationElement h in section.Handlers)
{
if (h.Name == "cdn")
{
_json = h.HandlerProperties["json"].Value;
_bucket = h.HandlerProperties["bucket"].Value;
_region = h.HandlerProperties["region"].Value;
break;
}
}
successInitialized = true;
}
catch (Exception fatal)
{
log.Fatal(fatal);
}
}
private StorageClient GetStorage()
{
var credential = GoogleCredential.FromJson(_json);
return StorageClient.Create(credential);
}
public void Process(BundleContext context, BundleResponse response)
{
if (successInitialized && BundleTable.Bundles.UseCdn)
{
try
{
var bundle = context.BundleCollection.GetBundleFor(context.BundleVirtualPath);
if (bundle != null)
{
queue.Enqueue(new CdnItem { Bundle = bundle, Response = response });
Action upload = UploadToCdn;
upload.BeginInvoke(null, null);
}
}
catch (Exception fatal)
{
log.Fatal(fatal);
throw;
}
}
}
private void UploadToCdn()
{
try
{
// one thread only
if (Interlocked.CompareExchange(ref work, 1, 0) == 0)
{
var @continue = false;
try
{
CdnItem item;
if (queue.TryDequeue(out item))
{
@continue = true;
var cdnpath = GetCdnPath(item.Bundle.Path);
var key = new Uri(cdnpath).PathAndQuery.TrimStart('/');
var content = Encoding.UTF8.GetBytes(item.Response.Content);
var inputStream = new MemoryStream();
var storage = GetStorage();
if (ClientSettings.GZipEnabled)
{
using (var zip = new GZipStream(inputStream, CompressionMode.Compress, true))
{
zip.Write(content, 0, content.Length);
zip.Flush();
}
}
else
{
inputStream.Write(content, 0, content.Length);
}
var upload = false;
Google.Apis.Storage.v1.Data.Object objInfo = null;
try
{
objInfo = storage.GetObject(_bucket, key);
}
catch (GoogleApiException ex)
{
if (ex.HttpStatusCode == HttpStatusCode.NotFound)
{
upload = true;
}
else
{
throw;
}
}
if (objInfo != null)
{
String contentMd5Hash = String.Empty;
using (var sha1 = SHA1.Create())
{
byte[] bytes = Encoding.UTF8.GetBytes(item.Response.Content);
byte[] hashBytes = sha1.ComputeHash(bytes);
StringBuilder sb = new StringBuilder();
foreach (byte b in hashBytes)
sb.Append(b.ToString("X2"));
contentMd5Hash = sb.ToString().ToLower();
}
if (String.Compare(objInfo.Md5Hash, contentMd5Hash, StringComparison.InvariantCultureIgnoreCase) != 0)
upload = true;
}
if (upload)
{
UploadObjectOptions uploadObjectOptions = new UploadObjectOptions
{
PredefinedAcl = PredefinedObjectAcl.PublicRead
};
inputStream.Position = 0;
var uploaded = storage.UploadObject(_bucket, key, MimeMapping.GetMimeMapping(Path.GetFileName(key)), inputStream, uploadObjectOptions, null);
inputStream.Close();
if (uploaded.Metadata == null)
uploaded.Metadata = new Dictionary<String, String>();
if (ClientSettings.GZipEnabled)
{
uploaded.ContentEncoding = "gzip";
}
var cache = TimeSpan.FromDays(365);
uploaded.CacheControl = String.Format("public, maxage={0}", (int)cache.TotalSeconds);
uploaded.Metadata["Expires"] = DateTime.UtcNow.Add(TimeSpan.FromDays(365)).ToString("R");
storage.UpdateObject(uploaded);
}
else
{
inputStream.Close();
}
item.Bundle.CdnPath = cdnpath;
}
}
catch (Exception err)
{
log.Error(err);
}
finally
{
work = 0;
if (@continue)
{
Action upload = () => UploadToCdn();
upload.BeginInvoke(null, null);
}
}
}
}
catch (Exception fatal)
{
log.Fatal(fatal);
}
}
private static string GetCdnPath(string path)
{
var ext = Path.GetExtension(path).ToLowerInvariant();
var abspath = string.Empty;
foreach (var a in appenders)
{
abspath = a.Value;
if (a.Key.ToLowerInvariant().Contains(ext + "|"))
{
break;
}
}
return abspath + path.TrimStart('~', '/');
}
}
}
| 35.921708 | 173 | 0.428472 | [
"Apache-2.0"
] | Ektai-Solution-Pty-Ltd/CommunityServer | web/core/ASC.Web.Core/Client/Bundling/GoogleCloudStorageTransform.cs | 10,094 | C# |
namespace $safeprojectname$
{
using $safeprojectname$.Views;
using More;
using More.Composition;
using More.Composition.Hosting;
using System;
using System.Linq;
/// <summary>
/// Represents the current program.
/// </summary>
public static class Program
{
/// <summary>
/// The main entry point to the application.
/// </summary>
[STAThread]
public static void Main()
{
using ( var host = new WindowsHost<MainWindow>() )
{$if$ ($showTips$ == true)
// TODO: register and/or configure tasks to execute during start up
// the ShowShellViewTask is automatically registered. if you do not
// have additional start up logic, then there is nothing to do here.$endif$
host.Run( new App() );
}
}
}
} | 29.8 | 91 | 0.559284 | [
"MIT"
] | JTOne123/More | src/Sdk/Templates/Desktop/Projects/WpfApplication/Program.cs | 896 | C# |
// Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information.
namespace Microsoft.Intune.PowerShellGraphSDK.PowerShellCmdlets
{
using System.Management.Automation;
/// <summary>
/// <para type="synopsis">Retrieves "microsoft.graph.managedEBookAssignment" objects.</para>
/// <para type="description">Retrieves "microsoft.graph.managedEBookAssignment" objects in the "assignments" collection.</para>
/// <para type="description">The list of assignments for this eBook.</para>
/// <para type="description">Graph call: GET ~/deviceAppManagement/managedEBooks/{managedEBookId}/assignments</para>
/// </summary>
/// <para type="link" uri="https://github.com/Microsoft/Intune-PowerShell-SDK">GitHub Repository</para>
[Cmdlet("Get", "DeviceAppManagement_ManagedEBooks_Assignments", DefaultParameterSetName = @"Search")]
[ODataType("microsoft.graph.managedEBookAssignment", "microsoft.graph.iosVppEBookAssignment")]
[ResourceTypePropertyName("assignmentODataType")]
[ResourceReference]
[Alias("Get-IntuneManagedEBookAssignment")]
public class Get_DeviceAppManagement_ManagedEBooks_Assignments : GetOrSearchCmdlet
{
/// <summary>
/// <para type="description">A required ID for referencing a "microsoft.graph.managedEBook" object in the "managedEBooks" collection.</para>
/// </summary>
[Selectable]
[Expandable]
[IdParameter]
[ValidateNotNullOrEmpty]
[Parameter(Mandatory = true, ValueFromPipelineByPropertyName = true, HelpMessage = @"A required ID for referencing a "microsoft.graph.managedEBook" object in the "managedEBooks" collection.")]
public System.String managedEBookId { get; set; }
/// <summary>
/// <para type="description">The ID for a "microsoft.graph.managedEBookAssignment" object in the "assignments" collection.</para>
/// </summary>
[Selectable]
[Expandable]
[IdParameter]
[ResourceIdParameter]
[ValidateNotNullOrEmpty]
[Parameter(ParameterSetName = @"Get", Mandatory = true, ValueFromPipelineByPropertyName = true, HelpMessage = @"The ID for a "microsoft.graph.managedEBookAssignment" object in the "assignments" collection.")]
public System.String managedEBookAssignmentId { get; set; }
/// <summary>
/// <para type="description">The "target" property, of type "microsoft.graph.deviceAndAppManagementAssignmentTarget".</para>
/// <para type="description">This property is on the "microsoft.graph.managedEBookAssignment" type.</para>
/// <para type="description">The assignment target for eBook.</para>
/// </summary>
[ODataType("microsoft.graph.deviceAndAppManagementAssignmentTarget", "microsoft.graph.allDevicesAssignmentTarget", "microsoft.graph.groupAssignmentTarget", "microsoft.graph.exclusionGroupAssignmentTarget", "microsoft.graph.allLicensedUsersAssignmentTarget")]
[Selectable]
[Sortable]
public System.Object target { get; set; }
/// <summary>
/// <para type="description">The "installIntent" property, of type "microsoft.graph.installIntent".</para>
/// <para type="description">This property is on the "microsoft.graph.managedEBookAssignment" type.</para>
/// <para type="description">The install intent for eBook.</para>
/// </summary>
[ODataType("microsoft.graph.installIntent")]
[Selectable]
[Sortable]
public System.String installIntent { get; set; }
internal override System.String GetResourcePath()
{
return $"deviceAppManagement/managedEBooks/{managedEBookId}/assignments/{managedEBookAssignmentId ?? string.Empty}";
}
}
/// <summary>
/// <para type="synopsis">Creates a "microsoft.graph.managedEBookAssignment" object.</para>
/// <para type="description">Adds a "microsoft.graph.managedEBookAssignment" object to the "assignments" collection.</para>
/// <para type="description">The list of assignments for this eBook.</para>
/// <para type="description">Graph call: POST ~/deviceAppManagement/managedEBooks/{managedEBookId}/assignments</para>
/// </summary>
/// <para type="link" uri="https://github.com/Microsoft/Intune-PowerShell-SDK">GitHub Repository</para>
[Cmdlet("New", "DeviceAppManagement_ManagedEBooks_Assignments", ConfirmImpact = ConfirmImpact.Low)]
[ODataType("microsoft.graph.managedEBookAssignment", "microsoft.graph.iosVppEBookAssignment")]
[ResourceTypePropertyName("assignmentODataType")]
[ResourceReference]
[Alias("New-IntuneManagedEBookAssignment")]
public class New_DeviceAppManagement_ManagedEBooks_Assignments : PostCmdlet
{
/// <summary>
/// <para type="description">The ID for a "microsoft.graph.managedEBookAssignment" object in the "assignments" collection.</para>
/// </summary>
[Selectable]
[Expandable]
[IdParameter]
[ResourceIdParameter]
public System.String managedEBookAssignmentId { get; set; }
/// <summary>
/// <para type="description">A required ID for referencing a "microsoft.graph.managedEBook" object in the "managedEBooks" collection.</para>
/// </summary>
[Selectable]
[Expandable]
[IdParameter]
[ValidateNotNullOrEmpty]
[Parameter(Mandatory = true, ValueFromPipelineByPropertyName = true, HelpMessage = @"A required ID for referencing a "microsoft.graph.managedEBook" object in the "managedEBooks" collection.")]
public System.String managedEBookId { get; set; }
/// <summary>
/// <para type="description">A switch parameter for selecting the parameter set which corresponds to the "microsoft.graph.managedEBookAssignment" type.</para>
/// </summary>
[Selectable]
[Expandable]
[ParameterSetSelector(@"microsoft.graph.managedEBookAssignment")]
[Parameter(ParameterSetName = @"microsoft.graph.managedEBookAssignment", Mandatory = true, HelpMessage = @"A switch parameter for selecting the parameter set which corresponds to the "microsoft.graph.managedEBookAssignment" type.")]
public System.Management.Automation.SwitchParameter managedEBookAssignment { get; set; }
/// <summary>
/// <para type="description">The "target" property, of type "microsoft.graph.deviceAndAppManagementAssignmentTarget".</para>
/// <para type="description">This property is on the "microsoft.graph.managedEBookAssignment" type.</para>
/// <para type="description">The assignment target for eBook.</para>
/// </summary>
[ODataType("microsoft.graph.deviceAndAppManagementAssignmentTarget", "microsoft.graph.allDevicesAssignmentTarget", "microsoft.graph.groupAssignmentTarget", "microsoft.graph.exclusionGroupAssignmentTarget", "microsoft.graph.allLicensedUsersAssignmentTarget")]
[Selectable]
[Parameter(ParameterSetName = @"microsoft.graph.managedEBookAssignment", ValueFromPipelineByPropertyName = true, HelpMessage = @"The "target" property, of type "microsoft.graph.deviceAndAppManagementAssignmentTarget".")]
[Parameter(ParameterSetName = @"microsoft.graph.iosVppEBookAssignment", ValueFromPipelineByPropertyName = true, HelpMessage = @"The "target" property, of type "microsoft.graph.deviceAndAppManagementAssignmentTarget".")]
[Parameter(ParameterSetName = @"ManualTypeSelection", ValueFromPipelineByPropertyName = true, HelpMessage = @"The "target" property, of type "microsoft.graph.deviceAndAppManagementAssignmentTarget".")]
public System.Object target { get; set; }
/// <summary>
/// <para type="description">The "installIntent" property, of type "microsoft.graph.installIntent".</para>
/// <para type="description">This property is on the "microsoft.graph.managedEBookAssignment" type.</para>
/// <para type="description">The install intent for eBook.</para>
/// <para type="description">
/// Valid values: 'available', 'required', 'uninstall', 'availableWithoutEnrollment'
/// </para>
/// </summary>
[ODataType("microsoft.graph.installIntent")]
[Selectable]
[ValidateSet(@"available", @"required", @"uninstall", @"availableWithoutEnrollment")]
[Parameter(ParameterSetName = @"microsoft.graph.managedEBookAssignment", ValueFromPipelineByPropertyName = true, HelpMessage = @"The "installIntent" property, of type "microsoft.graph.installIntent".")]
[Parameter(ParameterSetName = @"microsoft.graph.iosVppEBookAssignment", ValueFromPipelineByPropertyName = true, HelpMessage = @"The "installIntent" property, of type "microsoft.graph.installIntent".")]
[Parameter(ParameterSetName = @"ManualTypeSelection", ValueFromPipelineByPropertyName = true, HelpMessage = @"The "installIntent" property, of type "microsoft.graph.installIntent".")]
public System.String installIntent { get; set; }
/// <summary>
/// <para type="description">A switch parameter for selecting the parameter set which corresponds to the "microsoft.graph.iosVppEBookAssignment" type.</para>
/// </summary>
[Selectable]
[Expandable]
[ParameterSetSelector(@"microsoft.graph.iosVppEBookAssignment")]
[Parameter(ParameterSetName = @"microsoft.graph.iosVppEBookAssignment", Mandatory = true, HelpMessage = @"A switch parameter for selecting the parameter set which corresponds to the "microsoft.graph.iosVppEBookAssignment" type.")]
public System.Management.Automation.SwitchParameter iosVppEBookAssignment { get; set; }
internal override System.String GetResourcePath()
{
return $"deviceAppManagement/managedEBooks/{managedEBookId}/assignments/{managedEBookAssignmentId}";
}
}
/// <summary>
/// <para type="synopsis">Updates a "microsoft.graph.managedEBookAssignment".</para>
/// <para type="description">Updates a "microsoft.graph.managedEBookAssignment" object in the "assignments" collection.</para>
/// <para type="description">The list of assignments for this eBook.</para>
/// <para type="description">Graph Call: PATCH ~/deviceAppManagement/managedEBooks/{managedEBookId}/assignments</para>
/// </summary>
/// <para type="link" uri="https://github.com/Microsoft/Intune-PowerShell-SDK">GitHub Repository</para>
[Cmdlet("Update", "DeviceAppManagement_ManagedEBooks_Assignments", ConfirmImpact = ConfirmImpact.Medium)]
[ODataType("microsoft.graph.managedEBookAssignment", "microsoft.graph.iosVppEBookAssignment")]
[ResourceTypePropertyName("assignmentODataType")]
[Alias("Update-IntuneManagedEBookAssignment")]
public class Update_DeviceAppManagement_ManagedEBooks_Assignments : PatchCmdlet
{
/// <summary>
/// <para type="description">The ID for a "microsoft.graph.managedEBookAssignment" object in the "assignments" collection.</para>
/// </summary>
[Selectable]
[Expandable]
[IdParameter]
[ResourceIdParameter]
[ValidateNotNullOrEmpty]
[Parameter(Mandatory = true, ValueFromPipelineByPropertyName = true, HelpMessage = @"The ID for a "microsoft.graph.managedEBookAssignment" object in the "assignments" collection.")]
public System.String managedEBookAssignmentId { get; set; }
/// <summary>
/// <para type="description">A required ID for referencing a "microsoft.graph.managedEBook" object in the "managedEBooks" collection.</para>
/// </summary>
[Selectable]
[Expandable]
[IdParameter]
[ValidateNotNullOrEmpty]
[Parameter(Mandatory = true, ValueFromPipelineByPropertyName = true, HelpMessage = @"A required ID for referencing a "microsoft.graph.managedEBook" object in the "managedEBooks" collection.")]
public System.String managedEBookId { get; set; }
/// <summary>
/// <para type="description">A switch parameter for selecting the parameter set which corresponds to the "microsoft.graph.managedEBookAssignment" type.</para>
/// </summary>
[Selectable]
[Expandable]
[ParameterSetSelector(@"microsoft.graph.managedEBookAssignment")]
[Parameter(ParameterSetName = @"microsoft.graph.managedEBookAssignment", Mandatory = true, HelpMessage = @"A switch parameter for selecting the parameter set which corresponds to the "microsoft.graph.managedEBookAssignment" type.")]
public System.Management.Automation.SwitchParameter managedEBookAssignment { get; set; }
/// <summary>
/// <para type="description">The "target" property, of type "microsoft.graph.deviceAndAppManagementAssignmentTarget".</para>
/// <para type="description">This property is on the "microsoft.graph.managedEBookAssignment" type.</para>
/// <para type="description">The assignment target for eBook.</para>
/// </summary>
[ODataType("microsoft.graph.deviceAndAppManagementAssignmentTarget", "microsoft.graph.allDevicesAssignmentTarget", "microsoft.graph.groupAssignmentTarget", "microsoft.graph.exclusionGroupAssignmentTarget", "microsoft.graph.allLicensedUsersAssignmentTarget")]
[Selectable]
[Parameter(ParameterSetName = @"microsoft.graph.managedEBookAssignment", HelpMessage = @"The "target" property, of type "microsoft.graph.deviceAndAppManagementAssignmentTarget".")]
[Parameter(ParameterSetName = @"microsoft.graph.iosVppEBookAssignment", HelpMessage = @"The "target" property, of type "microsoft.graph.deviceAndAppManagementAssignmentTarget".")]
[Parameter(ParameterSetName = @"ManualTypeSelection", HelpMessage = @"The "target" property, of type "microsoft.graph.deviceAndAppManagementAssignmentTarget".")]
public System.Object target { get; set; }
/// <summary>
/// <para type="description">The "installIntent" property, of type "microsoft.graph.installIntent".</para>
/// <para type="description">This property is on the "microsoft.graph.managedEBookAssignment" type.</para>
/// <para type="description">The install intent for eBook.</para>
/// <para type="description">
/// Valid values: 'available', 'required', 'uninstall', 'availableWithoutEnrollment'
/// </para>
/// </summary>
[ODataType("microsoft.graph.installIntent")]
[Selectable]
[ValidateSet(@"available", @"required", @"uninstall", @"availableWithoutEnrollment")]
[Parameter(ParameterSetName = @"microsoft.graph.managedEBookAssignment", HelpMessage = @"The "installIntent" property, of type "microsoft.graph.installIntent".")]
[Parameter(ParameterSetName = @"microsoft.graph.iosVppEBookAssignment", HelpMessage = @"The "installIntent" property, of type "microsoft.graph.installIntent".")]
[Parameter(ParameterSetName = @"ManualTypeSelection", HelpMessage = @"The "installIntent" property, of type "microsoft.graph.installIntent".")]
public System.String installIntent { get; set; }
/// <summary>
/// <para type="description">A switch parameter for selecting the parameter set which corresponds to the "microsoft.graph.iosVppEBookAssignment" type.</para>
/// </summary>
[Selectable]
[Expandable]
[ParameterSetSelector(@"microsoft.graph.iosVppEBookAssignment")]
[Parameter(ParameterSetName = @"microsoft.graph.iosVppEBookAssignment", Mandatory = true, HelpMessage = @"A switch parameter for selecting the parameter set which corresponds to the "microsoft.graph.iosVppEBookAssignment" type.")]
public System.Management.Automation.SwitchParameter iosVppEBookAssignment { get; set; }
internal override System.String GetResourcePath()
{
return $"deviceAppManagement/managedEBooks/{managedEBookId}/assignments/{managedEBookAssignmentId}";
}
}
/// <summary>
/// <para type="synopsis">Removes a "microsoft.graph.managedEBookAssignment" object.</para>
/// <para type="description">Removes a "microsoft.graph.managedEBookAssignment" object from the "assignments" collection.</para>
/// <para type="description">The list of assignments for this eBook.</para>
/// <para type="description">Graph Call: DELETE ~/deviceAppManagement/managedEBooks/{managedEBookId}/assignments/managedEBookAssignmentId</para>
/// </summary>
/// <para type="link" uri="https://github.com/Microsoft/Intune-PowerShell-SDK">GitHub Repository</para>
[Cmdlet("Remove", "DeviceAppManagement_ManagedEBooks_Assignments", ConfirmImpact = ConfirmImpact.High)]
[ODataType("microsoft.graph.managedEBookAssignment", "microsoft.graph.iosVppEBookAssignment")]
[ResourceTypePropertyName("assignmentODataType")]
[Alias("Remove-IntuneManagedEBookAssignment")]
public class Remove_DeviceAppManagement_ManagedEBooks_Assignments : DeleteCmdlet
{
/// <summary>
/// <para type="description">The ID for a "microsoft.graph.managedEBookAssignment" object in the "assignments" collection.</para>
/// </summary>
[Selectable]
[Expandable]
[IdParameter]
[ResourceIdParameter]
[ValidateNotNullOrEmpty]
[Parameter(Mandatory = true, ValueFromPipelineByPropertyName = true, HelpMessage = @"The ID for a "microsoft.graph.managedEBookAssignment" object in the "assignments" collection.")]
public System.String managedEBookAssignmentId { get; set; }
/// <summary>
/// <para type="description">A required ID for referencing a "microsoft.graph.managedEBook" object in the "managedEBooks" collection.</para>
/// </summary>
[Selectable]
[Expandable]
[IdParameter]
[ValidateNotNullOrEmpty]
[Parameter(Mandatory = true, ValueFromPipelineByPropertyName = true, HelpMessage = @"A required ID for referencing a "microsoft.graph.managedEBook" object in the "managedEBooks" collection.")]
public System.String managedEBookId { get; set; }
internal override System.String GetResourcePath()
{
return $"deviceAppManagement/managedEBooks/{managedEBookId}/assignments/{managedEBookAssignmentId}";
}
}
} | 70.539568 | 266 | 0.704742 | [
"MIT"
] | 365Academic/Intune-PowerShell-SDK | PowerShellCmdlets/Generated/SDK/DeviceAppManagement/ManagedEBooks/Assignments.cs | 19,610 | 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.AzureNative.ServiceFabric.V20191101Preview.Inputs
{
/// <summary>
/// Represents the health policy used to evaluate the health of services belonging to a service type.
/// </summary>
public sealed class ArmServiceTypeHealthPolicyArgs : Pulumi.ResourceArgs
{
/// <summary>
/// The maximum percentage of partitions per service allowed to be unhealthy before your application is considered in error.
/// </summary>
[Input("maxPercentUnhealthyPartitionsPerService")]
public Input<int>? MaxPercentUnhealthyPartitionsPerService { get; set; }
/// <summary>
/// The maximum percentage of replicas per partition allowed to be unhealthy before your application is considered in error.
/// </summary>
[Input("maxPercentUnhealthyReplicasPerPartition")]
public Input<int>? MaxPercentUnhealthyReplicasPerPartition { get; set; }
/// <summary>
/// The maximum percentage of services allowed to be unhealthy before your application is considered in error.
/// </summary>
[Input("maxPercentUnhealthyServices")]
public Input<int>? MaxPercentUnhealthyServices { get; set; }
public ArmServiceTypeHealthPolicyArgs()
{
MaxPercentUnhealthyPartitionsPerService = 0;
MaxPercentUnhealthyReplicasPerPartition = 0;
MaxPercentUnhealthyServices = 0;
}
}
}
| 39.75 | 132 | 0.692396 | [
"Apache-2.0"
] | polivbr/pulumi-azure-native | sdk/dotnet/ServiceFabric/V20191101Preview/Inputs/ArmServiceTypeHealthPolicyArgs.cs | 1,749 | C# |
using System;
namespace Askmethat.Aspnet.JsonLocalizer.Sample.I18nTest.Data
{
public class WeatherForecast
{
public DateTime Date { get; set; }
public int TemperatureC { get; set; }
public int TemperatureF => 32 + (int) (TemperatureC / 0.5556);
public string Summary { get; set; }
}
} | 22.133333 | 70 | 0.635542 | [
"MIT"
] | ErikApption/Askmethat-Aspnet-JsonLocalizer | test/Askmethat.Aspnet.JsonLocalizer.I18nTestSample/Data/WeatherForecast.cs | 332 | C# |
// ***********************************************************************
// Copyright (c) 2014 Charlie Poole, Rob Prouse
//
// 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.Collections.Generic;
using System.IO;
using System.Xml;
using NUnit.Framework;
using NUnit.Framework.Internal;
using NUnit.Engine.Extensibility;
using System;
namespace NUnit.Engine.Drivers.Tests
{
// Functional tests of the NUnitFrameworkDriver calling into the framework.
public abstract class NotRunnableFrameworkDriverTests
{
private const string DRIVER_ID = "99";
private const string EXPECTED_ID = "99-1";
protected string _expectedRunState;
protected string _expectedReason;
protected string _expectedResult;
protected string _expectedLabel;
[TestCase("junk.dll", "Assembly")]
[TestCase("junk.exe", "Assembly")]
[TestCase("junk.cfg", "Unknown")]
public void Load(string filePath, string expectedType)
{
IFrameworkDriver driver = GetDriver(filePath);
var result = XmlHelper.CreateXmlNode(driver.Load(filePath, new Dictionary<string, object>()));
Assert.That(result.Name, Is.EqualTo("test-suite"));
Assert.That(result.GetAttribute("type"), Is.EqualTo(expectedType));
Assert.That(result.GetAttribute("id"), Is.EqualTo(EXPECTED_ID));
Assert.That(result.GetAttribute("name"), Is.EqualTo(filePath));
Assert.That(result.GetAttribute("fullname"), Is.EqualTo(Path.GetFullPath(filePath)));
Assert.That(result.GetAttribute("runstate"), Is.EqualTo(_expectedRunState));
Assert.That(result.GetAttribute("testcasecount"), Is.EqualTo("0"));
Assert.That(GetSkipReason(result), Is.EqualTo(_expectedReason));
Assert.That(result.SelectNodes("test-suite").Count, Is.EqualTo(0), "Load result should not have child tests");
}
[TestCase("junk.dll", "Assembly")]
[TestCase("junk.exe", "Assembly")]
[TestCase("junk.cfg", "Unknown")]
public void Explore(string filePath, string expectedType)
{
IFrameworkDriver driver = GetDriver(filePath);
var result = XmlHelper.CreateXmlNode(driver.Explore(TestFilter.Empty.Text));
Assert.That(result.Name, Is.EqualTo("test-suite"));
Assert.That(result.GetAttribute("id"), Is.EqualTo(EXPECTED_ID));
Assert.That(result.GetAttribute("name"), Is.EqualTo(filePath));
Assert.That(result.GetAttribute("fullname"), Is.EqualTo(Path.GetFullPath(filePath)));
Assert.That(result.GetAttribute("type"), Is.EqualTo(expectedType));
Assert.That(result.GetAttribute("runstate"), Is.EqualTo(_expectedRunState));
Assert.That(result.GetAttribute("testcasecount"), Is.EqualTo("0"));
Assert.That(GetSkipReason(result), Is.EqualTo(_expectedReason));
Assert.That(result.SelectNodes("test-suite").Count, Is.EqualTo(0), "Result should not have child tests");
}
[TestCase("junk.dll")]
[TestCase("junk.exe")]
[TestCase("junk.cfg")]
public void CountTestCases(string filePath)
{
IFrameworkDriver driver = CreateDriver(filePath);
Assert.That(driver.CountTestCases(TestFilter.Empty.Text), Is.EqualTo(0));
}
[TestCase("junk.dll", "Assembly")]
[TestCase("junk.exe", "Assembly")]
[TestCase("junk.cfg", "Unknown")]
public void Run(string filePath, string expectedType)
{
IFrameworkDriver driver = GetDriver(filePath);
var result = XmlHelper.CreateXmlNode(driver.Run(new NullListener(), TestFilter.Empty.Text));
Assert.That(result.Name, Is.EqualTo("test-suite"));
Assert.That(result.GetAttribute("id"), Is.EqualTo(EXPECTED_ID));
Assert.That(result.GetAttribute("name"), Is.EqualTo(filePath));
Assert.That(result.GetAttribute("fullname"), Is.EqualTo(Path.GetFullPath(filePath)));
Assert.That(result.GetAttribute("type"), Is.EqualTo(expectedType));
Assert.That(result.GetAttribute("runstate"), Is.EqualTo(_expectedRunState));
Assert.That(result.GetAttribute("testcasecount"), Is.EqualTo("0"));
Assert.That(GetSkipReason(result), Is.EqualTo(_expectedReason));
Assert.That(result.SelectNodes("test-suite").Count, Is.EqualTo(0), "Load result should not have child tests");
Assert.That(result.GetAttribute("result"), Is.EqualTo(_expectedResult));
Assert.That(result.GetAttribute("label"), Is.EqualTo(_expectedLabel));
Assert.That(result.SelectSingleNode("reason/message").InnerText, Is.EqualTo(_expectedReason));
}
#region Abstract Properties and Methods
protected abstract IFrameworkDriver CreateDriver(string filePath);
#endregion
#region Helper Methods
private IFrameworkDriver GetDriver(string filePath)
{
IFrameworkDriver driver = CreateDriver(filePath);
driver.ID = DRIVER_ID;
return driver;
}
private static string GetSkipReason(XmlNode result)
{
var propNode = result.SelectSingleNode(string.Format("properties/property[@name='{0}']", PropertyNames.SkipReason));
return propNode == null ? null : propNode.GetAttribute("value");
}
#endregion
#region Nested NullListener Class
private class NullListener : ITestEventListener
{
public void OnTestEvent(string testEvent)
{
// No action
}
}
#endregion
}
public class InvalidAssemblyFrameworkDriverTests : NotRunnableFrameworkDriverTests
{
public InvalidAssemblyFrameworkDriverTests()
{
_expectedRunState = "NotRunnable";
_expectedReason = "Assembly could not be found";
_expectedResult = "Failed";
_expectedLabel = "Invalid";
}
protected override IFrameworkDriver CreateDriver(string filePath)
{
return new InvalidAssemblyFrameworkDriver(filePath, _expectedReason);
}
}
public class SkippedAssemblyFrameworkDriverTests : NotRunnableFrameworkDriverTests
{
public SkippedAssemblyFrameworkDriverTests()
{
_expectedRunState = "Runnable";
_expectedReason = "Skipping non-test assembly";
_expectedResult = "Skipped";
_expectedLabel = "NoTests";
}
protected override IFrameworkDriver CreateDriver(string filePath)
{
return new SkippedAssemblyFrameworkDriver(filePath);
}
}
}
| 44.134078 | 128 | 0.649241 | [
"MIT"
] | IlyaFinkelshteyn/nunit-console | src/NUnitEngine/nunit.engine.tests/Drivers/NotRunnableFrameworkDriverTests.cs | 7,902 | C# |
using System.Collections.Generic;
using System.Linq;
namespace Xunit.Sdk
{
static class CollectionExtensions
{
public static List<T> CastOrToList<T>(this IEnumerable<T> source)
{
return source as List<T> ?? source.ToList();
}
public static T[] CastOrToArray<T>(this IEnumerable<T> source)
{
return source as T[] ?? source.ToArray();
}
}
}
| 22.368421 | 73 | 0.592941 | [
"Apache-2.0"
] | nerdymishka/gainz | dotnet/src/Testing/Mettle.Xunit/Common/CollectionExtensions.cs | 425 | C# |
using Cysharp.Threading.Tasks;
using Cysharp.Threading.Tasks.Linq;
using FluentAssertions;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reactive.Concurrency;
using System.Reactive.Linq;
using System.Threading.Tasks;
using Xunit;
namespace NetCoreTests.Linq
{
public class Convert
{
[Fact]
public async Task ToAsyncEnumerable()
{
{
var xs = await Enumerable.Range(1, 100).ToUniTaskAsyncEnumerable().ToArrayAsync();
xs.Length.Should().Be(100);
}
{
var xs = await Enumerable.Empty<int>().ToUniTaskAsyncEnumerable().ToArrayAsync();
xs.Length.Should().Be(0);
}
}
[Fact]
public async Task ToObservable()
{
{
var xs = await UniTaskAsyncEnumerable.Range(1, 10).ToObservable().ToArray();
xs.Should().Equal(Enumerable.Range(1, 10));
}
{
var xs = await UniTaskAsyncEnumerable.Range(1, 0).ToObservable().ToArray();
xs.Should().Equal(Enumerable.Range(1, 0));
}
}
[Fact]
public async Task ToAsyncEnumerableTask()
{
var t = Task.FromResult(100);
var xs = await t.ToUniTaskAsyncEnumerable().ToArrayAsync();
xs.Length.Should().Be(1);
xs[0].Should().Be(100);
}
[Fact]
public async Task ToAsyncEnumerableUniTask()
{
var t = UniTask.FromResult(100);
var xs = await t.ToUniTaskAsyncEnumerable().ToArrayAsync();
xs.Length.Should().Be(1);
xs[0].Should().Be(100);
}
[Fact]
public async Task ToAsyncEnumerableObservable()
{
{
var xs = await Observable.Range(1, 100).ToUniTaskAsyncEnumerable().ToArrayAsync();
var ys = await Observable.Range(1, 100).ToArray();
xs.Should().Equal(ys);
}
{
var xs = await Observable.Range(1, 100, ThreadPoolScheduler.Instance).ToUniTaskAsyncEnumerable().ToArrayAsync();
var ys = await Observable.Range(1, 100, ThreadPoolScheduler.Instance).ToArray();
xs.Should().Equal(ys);
}
{
var xs = await Observable.Empty<int>(ThreadPoolScheduler.Instance).ToUniTaskAsyncEnumerable().ToArrayAsync();
var ys = await Observable.Empty<int>(ThreadPoolScheduler.Instance).ToArray();
xs.Should().Equal(ys);
}
}
[Fact]
public async Task ToDictionary()
{
{
var xs = await Enumerable.Range(1, 100).ToUniTaskAsyncEnumerable().ToDictionaryAsync(x => x);
var ys = Enumerable.Range(1, 100).ToDictionary(x => x);
xs.OrderBy(x => x.Key).Should().Equal(ys.OrderBy(x => x.Key));
}
{
var xs = await Enumerable.Range(1, 0).ToUniTaskAsyncEnumerable().ToDictionaryAsync(x => x);
var ys = Enumerable.Range(1, 0).ToDictionary(x => x);
xs.OrderBy(x => x.Key).Should().Equal(ys.OrderBy(x => x.Key));
}
{
var xs = await Enumerable.Range(1, 100).ToUniTaskAsyncEnumerable().ToDictionaryAsync(x => x, x => x * 2);
var ys = Enumerable.Range(1, 100).ToDictionary(x => x, x => x * 2);
xs.OrderBy(x => x.Key).Should().Equal(ys.OrderBy(x => x.Key));
}
{
var xs = await Enumerable.Range(1, 0).ToUniTaskAsyncEnumerable().ToDictionaryAsync(x => x, x => x * 2);
var ys = Enumerable.Range(1, 0).ToDictionary(x => x, x => x * 2);
xs.OrderBy(x => x.Key).Should().Equal(ys.OrderBy(x => x.Key));
}
}
[Fact]
public async Task ToLookup()
{
var arr = new[] { 1, 4, 10, 10, 4, 5, 10, 9 };
{
var xs = await arr.ToUniTaskAsyncEnumerable().ToLookupAsync(x => x);
var ys = arr.ToLookup(x => x);
xs.Count.Should().Be(ys.Count);
xs.Should().BeEquivalentTo(ys);
foreach (var key in xs.Select(x => x.Key))
{
xs[key].Should().Equal(ys[key]);
}
}
{
var xs = await Enumerable.Range(1, 0).ToUniTaskAsyncEnumerable().ToLookupAsync(x => x);
var ys = Enumerable.Range(1, 0).ToLookup(x => x);
xs.Should().BeEquivalentTo(ys);
}
{
var xs = await arr.ToUniTaskAsyncEnumerable().ToLookupAsync(x => x, x => x * 2);
var ys = arr.ToLookup(x => x, x => x * 2);
xs.Count.Should().Be(ys.Count);
xs.Should().BeEquivalentTo(ys);
foreach (var key in xs.Select(x => x.Key))
{
xs[key].Should().Equal(ys[key]);
}
}
{
var xs = await Enumerable.Range(1, 0).ToUniTaskAsyncEnumerable().ToLookupAsync(x => x, x => x * 2);
var ys = Enumerable.Range(1, 0).ToLookup(x => x, x => x * 2);
xs.Should().BeEquivalentTo(ys);
}
}
[Fact]
public async Task ToList()
{
{
var xs = await Enumerable.Range(1, 100).ToUniTaskAsyncEnumerable().ToListAsync();
var ys = Enumerable.Range(1, 100).ToList();
xs.Should().Equal(ys);
}
{
var xs = await Enumerable.Empty<int>().ToUniTaskAsyncEnumerable().ToListAsync();
var ys = Enumerable.Empty<int>().ToList();
xs.Should().Equal(ys);
}
}
[Fact]
public async Task ToHashSet()
{
{
var xs = await new[] { 1, 20, 4, 5, 20, 4, 6 }.ToUniTaskAsyncEnumerable().ToHashSetAsync();
var ys = new[] { 1, 20, 4, 5, 20, 4, 6 }.ToHashSet();
xs.OrderBy(x => x).Should().Equal(ys.OrderBy(x => x));
}
{
var xs = await Enumerable.Empty<int>().ToUniTaskAsyncEnumerable().ToHashSetAsync();
var ys = Enumerable.Empty<int>().ToHashSet();
xs.Should().Equal(ys);
}
}
}
}
| 33.13198 | 128 | 0.493642 | [
"MIT"
] | Cysharp/UniTask | src/UniTask.NetCoreTests/Linq/Convert.cs | 6,527 | C# |
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Security.Cryptography.X509Certificates;
using static OrchardCore.OpenId.Settings.OpenIdServerSettings;
namespace OrchardCore.OpenId.ViewModels
{
public class OpenIdServerSettingsViewModel
{
public TokenFormat AccessTokenFormat { get; set; }
[Url]
public string Authority { get; set; }
public StoreLocation? CertificateStoreLocation { get; set; }
public StoreName? CertificateStoreName { get; set; }
public string CertificateThumbprint { get; set; }
public IList<CertificateInfo> AvailableCertificates { get; } = new List<CertificateInfo>();
public bool EnableTokenEndpoint { get; set; }
public bool EnableAuthorizationEndpoint { get; set; }
public bool EnableLogoutEndpoint { get; set; }
public bool EnableUserInfoEndpoint { get; set; }
public bool AllowPasswordFlow { get; set; }
public bool AllowClientCredentialsFlow { get; set; }
public bool AllowAuthorizationCodeFlow { get; set; }
public bool AllowRefreshTokenFlow { get; set; }
public bool AllowImplicitFlow { get; set; }
public bool UseRollingTokens { get; set; }
public class CertificateInfo
{
public string FriendlyName { get; set; }
public string Issuer { get; set; }
public DateTime NotAfter { get; set; }
public DateTime NotBefore { get; set; }
public StoreLocation StoreLocation { get; set; }
public StoreName StoreName { get; set; }
public string Subject { get; set; }
public string ThumbPrint { get; set; }
public bool HasPrivateKey { get; set; }
public bool Archived { get; set; }
}
}
}
| 42.136364 | 99 | 0.653722 | [
"BSD-3-Clause"
] | 1426463237/OrchardCore | src/OrchardCore.Modules/OrchardCore.OpenId/ViewModels/OpenIdServerSettingsViewModel.cs | 1,854 | C# |
// Code generated by Microsoft (R) AutoRest Code Generator 1.0.1.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Management.Internal.Network.Version2017_03_01.Models
{
using Microsoft.Azure;
using Microsoft.Azure.Management;
using Microsoft.Azure.Management.Internal;
using Microsoft.Azure.Management.Internal.Network;
using Microsoft.Azure.Management.Internal.Network.Version2017_03_01;
/// <summary>
/// Defines values for ProbeProtocol.
/// </summary>
public static class ProbeProtocol
{
public const string Http = "Http";
public const string Tcp = "Tcp";
}
}
| 32.454545 | 79 | 0.69888 | [
"MIT"
] | Azure/azure-powershell-common | src/Network/Version2017_03_01/Models/ProbeProtocol.cs | 714 | C# |
using System;
using HW.SF.Models;
using HW.Core.Repositories;
using HW.SF.Models.SYSModel;
using HW.Core.EfDbContext;
using HW.SF.IRepositories;
using HW.SF.Models;
namespace HW.SF.Repositories
{
public class DbBackupRepository : BaseRepository<Sys_DbBackup, String>, IDbBackupRepository
{
public DbBackupRepository(DefaultDbContext dbContext) : base(dbContext)
{
}
}
} | 23.882353 | 95 | 0.73399 | [
"MIT"
] | dahaideyu/HWPlatform | HW.SF.Repositories/DbBackupRepository.cs | 406 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using System.Collections.Generic;
using System.Globalization;
using System.Threading.Tasks;
using Microsoft.Bot.Schema;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace SkillSample.Tests
{
[TestClass]
[TestCategory("UnitTests")]
public class LocalizationTests : SkillTestBase
{
[TestMethod]
public async Task Test_Localization_Spanish()
{
CultureInfo.CurrentUICulture = new CultureInfo("es-es");
await GetTestFlow()
.Send(new Activity()
{
Type = ActivityTypes.ConversationUpdate,
MembersAdded = new List<ChannelAccount>() { new ChannelAccount("user") }
})
.AssertReply(TemplateEngine.GenerateActivityForLocale("IntroMessage"))
.StartTestAsync();
}
[TestMethod]
public async Task Test_Localization_German()
{
CultureInfo.CurrentUICulture = new CultureInfo("de-de");
await GetTestFlow()
.Send(new Activity()
{
Type = ActivityTypes.ConversationUpdate,
MembersAdded = new List<ChannelAccount>() { new ChannelAccount("user") }
})
.AssertReply(TemplateEngine.GenerateActivityForLocale("IntroMessage"))
.StartTestAsync();
}
[TestMethod]
public async Task Test_Localization_French()
{
CultureInfo.CurrentUICulture = new CultureInfo("fr-fr");
await GetTestFlow()
.Send(new Activity()
{
Type = ActivityTypes.ConversationUpdate,
MembersAdded = new List<ChannelAccount>() { new ChannelAccount("user") }
})
.AssertReply(TemplateEngine.GenerateActivityForLocale("IntroMessage"))
.StartTestAsync();
}
[TestMethod]
public async Task Test_Localization_Italian()
{
CultureInfo.CurrentUICulture = new CultureInfo("it-it");
await GetTestFlow()
.Send(new Activity()
{
Type = ActivityTypes.ConversationUpdate,
MembersAdded = new List<ChannelAccount>() { new ChannelAccount("user") }
})
.AssertReply(TemplateEngine.GenerateActivityForLocale("IntroMessage"))
.StartTestAsync();
}
[TestMethod]
public async Task Test_Localization_Chinese()
{
CultureInfo.CurrentUICulture = new CultureInfo("zh-cn");
await GetTestFlow()
.Send(new Activity()
{
Type = ActivityTypes.ConversationUpdate,
MembersAdded = new List<ChannelAccount>() { new ChannelAccount("user") }
})
.AssertReply(TemplateEngine.GenerateActivityForLocale("IntroMessage"))
.StartTestAsync();
}
[TestMethod]
public async Task Test_Defaulting_Localization()
{
CultureInfo.CurrentUICulture = new CultureInfo("en-uk");
await GetTestFlow()
.Send(new Activity()
{
Type = ActivityTypes.ConversationUpdate,
MembersAdded = new List<ChannelAccount>() { new ChannelAccount("user") }
})
.AssertReply(TemplateEngine.GenerateActivityForLocale("IntroMessage"))
.StartTestAsync();
}
}
} | 35.238095 | 92 | 0.557568 | [
"MIT"
] | 47-studio-org/botframework-solutions | samples/csharp/skill/SkillSample.Tests/LocalizationTests.cs | 3,702 | C# |
using System;
using System.Collections.Generic;
using Xero.Api.Core.Model;
using Xero.Api.Core.Model.Types;
namespace CoreTests.Integration.Receipts
{
public abstract class ReceiptTest : ApiWrapperTest
{
public Receipt Given_a_receipt(Guid userId, string contactName, string description, decimal amount, string account)
{
return Api.Create(new Receipt
{
Date = DateTime.UtcNow.Date,
Contact = new Contact { Name = contactName },
LineAmountTypes = LineAmountType.Inclusive,
LineItems = new List<LineItem>
{
new LineItem
{
Description = description,
UnitAmount = amount,
AccountCode = account
}
},
Total = amount,
User = new User
{
Id = userId
}
});
}
}
}
| 29.714286 | 123 | 0.484615 | [
"MIT",
"Unlicense"
] | prajapatichintan/Xero-Net-With-oAuth2.0-Support | CoreTests/Integration/Receipts/ReceiptTest.cs | 1,042 | 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 System.Collections.Generic;
using Aliyun.Acs.Core;
namespace Aliyun.Acs.Vpc.Model.V20160428
{
public class ModifySslVpnServerResponse : AcsResponse
{
private string requestId;
private string regionId;
private string sslVpnServerId;
private string vpnGatewayId;
private string name;
private string localSubnet;
private string clientIpPool;
private long? createTime;
private string cipher;
private string proto;
private int? port;
private bool? compress;
private int? connections;
private int? maxConnections;
private string internetIp;
public string RequestId
{
get
{
return requestId;
}
set
{
requestId = value;
}
}
public string RegionId
{
get
{
return regionId;
}
set
{
regionId = value;
}
}
public string SslVpnServerId
{
get
{
return sslVpnServerId;
}
set
{
sslVpnServerId = value;
}
}
public string VpnGatewayId
{
get
{
return vpnGatewayId;
}
set
{
vpnGatewayId = value;
}
}
public string Name
{
get
{
return name;
}
set
{
name = value;
}
}
public string LocalSubnet
{
get
{
return localSubnet;
}
set
{
localSubnet = value;
}
}
public string ClientIpPool
{
get
{
return clientIpPool;
}
set
{
clientIpPool = value;
}
}
public long? CreateTime
{
get
{
return createTime;
}
set
{
createTime = value;
}
}
public string Cipher
{
get
{
return cipher;
}
set
{
cipher = value;
}
}
public string Proto
{
get
{
return proto;
}
set
{
proto = value;
}
}
public int? Port
{
get
{
return port;
}
set
{
port = value;
}
}
public bool? Compress
{
get
{
return compress;
}
set
{
compress = value;
}
}
public int? Connections
{
get
{
return connections;
}
set
{
connections = value;
}
}
public int? MaxConnections
{
get
{
return maxConnections;
}
set
{
maxConnections = value;
}
}
public string InternetIp
{
get
{
return internetIp;
}
set
{
internetIp = value;
}
}
}
}
| 13.987448 | 63 | 0.566258 | [
"Apache-2.0"
] | bitType/aliyun-openapi-net-sdk | aliyun-net-sdk-vpc/Vpc/Model/V20160428/ModifySslVpnServerResponse.cs | 3,343 | C# |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using Kira.LaconicInvoicing.Identity;
using Kira.LaconicInvoicing.Identity.Entities;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Identity;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.IdentityModel.Tokens;
using OSharp.Core.Options;
using OSharp.Data;
using OSharp.Exceptions;
using OSharp.Extensions;
using OSharp.Identity;
using OSharp.Identity.JwtBearer;
namespace Kira.LaconicInvoicing.Service.Identity
{
/// <summary>
/// 身份认证模块,此模块必须在MVC模块之前启动
/// </summary>
[Description("身份认证模块")]
public class IdentityPack : IdentityPackBase<UserStore, RoleStore, User, Role, int, int>
{
/// <summary>
/// 获取 模块启动顺序,模块启动的顺序先按级别启动,级别内部再按此顺序启动,
/// 级别默认为0,表示无依赖,需要在同级别有依赖顺序的时候,再重写为>0的顺序值
/// </summary>
public override int Order => 0;
/// <summary>
/// 将模块服务添加到依赖注入服务容器中
/// </summary>
/// <param name="services">依赖注入服务容器</param>
/// <returns></returns>
public override IServiceCollection AddServices(IServiceCollection services)
{
services.AddScoped<IIdentityContract, IdentityService>();
return base.AddServices(services);
}
/// <summary>
/// 重写以实现<see cref="IdentityOptions"/>的配置
/// </summary>
/// <returns></returns>
protected override Action<IdentityOptions> IdentityOptionsAction()
{
return options =>
{
//登录
options.SignIn.RequireConfirmedEmail = true;
//密码
options.Password.RequireNonAlphanumeric = false;
options.Password.RequireUppercase = false;
//用户
options.User.RequireUniqueEmail = true;
//锁定
options.Lockout.DefaultLockoutTimeSpan = TimeSpan.FromMinutes(15);
};
}
/// <summary>
/// 重写以实现<see cref="CookieAuthenticationOptions"/>的配置
/// </summary>
/// <returns></returns>
protected override Action<CookieAuthenticationOptions> CookieOptionsAction()
{
return options =>
{
options.Cookie.HttpOnly = true;
options.Cookie.Name = "osharp.identity";
options.ExpireTimeSpan = TimeSpan.FromMinutes(20);
options.SlidingExpiration = true;
options.LoginPath = "/#/identity/login";
};
}
/// <summary>
/// 添加Authentication服务
/// </summary>
/// <param name="services">服务集合</param>
protected override void AddAuthentication(IServiceCollection services)
{
IConfiguration configuration = services.GetConfiguration();
AuthenticationBuilder authenticationBuilder = services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
}).AddJwtBearer(jwt =>
{
string secret = configuration["OSharp:Jwt:Secret"];
if (secret.IsNullOrEmpty())
{
throw new OsharpException("配置文件中Jwt节点的Secret不能为空");
}
jwt.TokenValidationParameters = new TokenValidationParameters()
{
ValidIssuer = configuration["OSharp:Jwt:Issuer"],
ValidAudience = configuration["OSharp:Jwt:Audience"],
IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(secret)),
LifetimeValidator = (before, expires, token, param) => expires > DateTime.Now,
ValidateLifetime = true
};
jwt.SecurityTokenValidators.Clear();
jwt.SecurityTokenValidators.Add(new OnlineUserJwtSecurityTokenHandler());
jwt.Events = new JwtBearerEvents()
{
// 生成SignalR的用户信息
OnMessageReceived = context =>
{
string token = context.Request.Query["access_token"];
string path = context.HttpContext.Request.Path;
if (!string.IsNullOrEmpty(token) && path.Contains("hub"))
{
context.Token = token;
}
return Task.CompletedTask;
}
};
//}).AddQQ(qq =>
//{
// qq.AppId = configuration["Authentication:QQ:AppId"];
// qq.AppKey = configuration["Authentication:QQ:AppKey"];
// qq.CallbackPath = new PathString("/api/identity/OAuth2Callback");
});
// OAuth2
IConfigurationSection section = configuration.GetSection("OSharp:OAuth2");
IDictionary<string, OAuth2Options> dict = section.Get<Dictionary<string, OAuth2Options>>();
if (dict == null)
{
return;
}
foreach (KeyValuePair<string, OAuth2Options> pair in dict)
{
OAuth2Options value = pair.Value;
if (!value.Enabled)
{
continue;
}
if (string.IsNullOrEmpty(value.ClientId))
{
throw new OsharpException($"配置文件中OSharp:OAuth2配置的{pair.Key}节点的ClientId不能为空");
}
if (string.IsNullOrEmpty(value.ClientSecret))
{
throw new OsharpException($"配置文件中OSharp:OAuth2配置的{pair.Key}节点的ClientSecret不能为空");
}
switch (pair.Key)
{
case "QQ":
authenticationBuilder.AddQQ(opts =>
{
opts.AppId = value.ClientId;
opts.AppKey = value.ClientSecret;
});
break;
case "Microsoft":
authenticationBuilder.AddMicrosoftAccount(opts =>
{
opts.ClientId = value.ClientId;
opts.ClientSecret = value.ClientSecret;
});
break;
case "GitHub":
authenticationBuilder.AddGitHub(opts =>
{
opts.ClientId = value.ClientId;
opts.ClientSecret = value.ClientSecret;
});
break;
}
}
}
/// <summary>
/// 重写以实现 AddIdentity 之后的构建逻辑
/// </summary>
/// <param name="builder"></param>
/// <returns></returns>
protected override IdentityBuilder OnIdentityBuild(IdentityBuilder builder)
{
//如需要昵称唯一,启用下面这个验证码
//builder.AddUserValidator<UserNickNameValidator<User, int>>();
return builder.AddDefaultTokenProviders();
}
/// <summary>
/// 应用模块服务
/// </summary>
/// <param name="app">应用程序构建器</param>
public override void UsePack(IApplicationBuilder app)
{
app.UseAuthentication();
IsEnabled = true;
}
}
} | 38.341232 | 104 | 0.517305 | [
"MIT"
] | JolyneStone/Kira.LaconicInvoicing | App/Kira.LaconicInvoicing.Service/Identity/IdentityPack.cs | 8,578 | C# |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// Общие сведения об этой сборке предоставляются следующим набором
// набора атрибутов. Измените значения этих атрибутов для изменения сведений,
// связанные со сборкой.
[assembly: AssemblyTitle("WpfMvvm.AttachedProperties")]
[assembly: AssemblyDescription("Присоединяемые свойства")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("EldHasp")]
[assembly: AssemblyProduct("WpfMvvm.AttachedProperties")]
[assembly: AssemblyCopyright("Copyright © 2020")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Установка значения False для параметра ComVisible делает типы в этой сборке невидимыми
// для компонентов COM. Если необходимо обратиться к типу в этой сборке через
// COM, задайте атрибуту ComVisible значение TRUE для этого типа.
[assembly: ComVisible(false)]
// Следующий GUID служит для идентификации библиотеки типов, если этот проект будет видимым для COM
[assembly: Guid("44addba0-5ec5-48ac-8728-2144eaf68e79")]
// Сведения о версии сборки состоят из указанных ниже четырех значений:
//
// Основной номер версии
// Дополнительный номер версии
// Номер сборки
// Редакция
//
// Можно задать все значения или принять номера сборки и редакции по умолчанию
// используя "*", как показано ниже:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("0.0.0.0")]
[assembly: AssemblyFileVersion("0.0.0.0")]
| 40.162162 | 99 | 0.769852 | [
"MIT"
] | WpfMvvm/WpfMvvm.AttachedProperties | WpfMvvm.AttachedProperties/Properties/AssemblyInfo.cs | 2,087 | C# |
using System;
using System.Data;
using System.Windows.Forms;
namespace SQL_Contact_Wallet_V2
{
//This class manages every interactions with the contact's card form
public partial class ContactCard : Form
{
private DataRow contact_data_row;
public ContactCard()
{
InitializeComponent();
}
//This is the only constructor used here
//Gets the whole row of the contact thanks to its ID and fills all textboxes with
public ContactCard(int id)
{
InitializeComponent();
DisableBoxes();
contact_data_row = ContactsData.GetContactsRowByID(id);
boxID.Text = contact_data_row[0].ToString();
boxSocietyID.Text = contact_data_row[1].ToString();
ManageSocietyName((int)contact_data_row[1]);
boxTitle.Text = contact_data_row[2].ToString();
boxSurname.Text = contact_data_row[3].ToString();
boxName.Text = contact_data_row[4].ToString();
boxFunction.Text = contact_data_row[5].ToString();
}
//Displays the name of a society thanks to its ID given by the user
//If the ID is not in the society table it writes an error message
private void ManageSocietyName(int id_society)
{
if (SocietiesData.GetSocietyNameByID(id_society) != null)
boxSociety.Text = SocietiesData.GetSocietyNameByID(id_society);
else
boxSociety.Text = "Not in the database";
}
//Sends modifications to the database
private void SaveContactEdition()
{
contact_data_row[1] = boxSocietyID.Text;
contact_data_row[2] = boxTitle.Text;
contact_data_row[3] = boxSurname.Text;
contact_data_row[4] = boxName.Text;
contact_data_row[5] = boxFunction.Text;
ContactsData.UpdateContact(contact_data_row);
}
private void EnableBoxes()
{
boxSocietyID.Enabled = true;
boxTitle.Enabled = true;
boxSurname.Enabled = true;
boxName.Enabled = true;
boxFunction.Enabled = true;
}
private void DisableBoxes()
{
boxID.Enabled = false;
boxSocietyID.Enabled = false;
boxSociety.Enabled = false;
boxTitle.Enabled = false;
boxSurname.Enabled = false;
boxName.Enabled = false;
boxFunction.Enabled = false;
}
//Checks if the non-nullables values aren't null and numbers values are numbers
//Also checks if the ID of society is valable
private void EnableSave()
{
int society_id = -1;
Int32.TryParse(boxSocietyID.Text, out society_id);
if (boxSocietyID.Text != "" && SocietiesData.FindSocietyByID(society_id) != -1
&& StringLib.StrIsNum(boxSocietyID.Text) && boxTitle.Text != ""
&& boxSurname.Text != "" && boxName.Text != "")
buttonEdit.Enabled = true;
else
buttonEdit.Enabled = false;
}
private void buttonClose_Click(object sender, EventArgs e)
{
this.Close();
}
//Manage the edit and save process
private void buttonEdit_Click(object sender, EventArgs e)
{
if (buttonEdit.Text == "Edit")
{
buttonEdit.Text = "Save";
buttonEdit.Enabled = false;
EnableBoxes();
EnableSave();
} else if (buttonEdit.Text == "Save") {
SaveContactEdition();
buttonEdit.Text = "Edit";
DisableBoxes();
}
}
//Sends the ID given by the user to the ManageSocietyName function
private void boxSocietyID_TextChanged(object sender, EventArgs e)
{
int id_society = -1;
Int32.TryParse(boxSocietyID.Text, out id_society);
ManageSocietyName(id_society);
EnableSave();
}
private void boxTitle_TextChanged(object sender, EventArgs e)
{
EnableSave();
}
private void boxSurname_TextChanged(object sender, EventArgs e)
{
EnableSave();
}
private void boxName_TextChanged(object sender, EventArgs e)
{
EnableSave();
}
}
}
| 34.080882 | 91 | 0.551456 | [
"MIT"
] | BillowBone/SQL_Contact_Wallet_V2 | Source/Forms/Edit/ContactCard.cs | 4,637 | C# |
namespace Easy.Common.Tests.Unit.DiagnosticReport
{
using System;
using Easy.Common.Extensions;
using NUnit.Framework;
using Shouldly;
using DiagnosticReport = Easy.Common.DiagnosticReport;
[TestFixture]
internal sealed class DiagnosticReportTests
{
[Test]
public void When_generating_full_report()
{
var report = DiagnosticReport.Generate();
report.ShouldNotBeNull();
report.Timestamp.ShouldBeLessThanOrEqualTo(DateTimeOffset.Now);
report.TimeTaken.ShouldBeGreaterThan(0.Milliseconds());
report.Type.ShouldBe(DiagnosticReportType.Full);
report.SystemDetails.ShouldNotBeNull();
report.ProcessDetails.ShouldNotBeNull();
report.DriveDetails.ShouldNotBeNull();
report.DriveDetails.ShouldNotBeEmpty();
report.Assemblies.ShouldNotBeNull();
report.Assemblies.ShouldNotBeEmpty();
report.EnvironmentVariables.ShouldNotBeNull();
report.EnvironmentVariables.ShouldNotBeEmpty();
report.NetworkingDetails.ShouldNotBeNull();
var formattedReport = report.ToString();
formattedReport.ShouldNotBeNull();
formattedReport.Length.ShouldBeGreaterThan(1000);
formattedReport.ShouldStartWith("/\r\n|Diagnostic Report generated at:");
formattedReport.ShouldContain("\r\n|\r\n|System|...");
formattedReport.ShouldContain("\r\n|\r\n|Process|...");
formattedReport.ShouldContain("\r\n|\r\n|Drives|...");
formattedReport.ShouldContain("\r\n|\r\n|Assemblies|...");
formattedReport.ShouldContain("\r\n|\r\n|Environment-Variables|...");
formattedReport.ShouldContain("\r\n|\r\n|Networks|...");
formattedReport.ShouldContain("|\r\n|\t. Windows IP Configuration\r\n|");
formattedReport.ShouldEndWith("\\");
}
[Test]
public void When_generating_full_report_with_flag()
{
// ReSharper disable once RedundantArgumentDefaultValue
var report = DiagnosticReport.Generate(DiagnosticReportType.Full);
report.ShouldNotBeNull();
report.Timestamp.ShouldBeLessThanOrEqualTo(DateTimeOffset.Now);
report.TimeTaken.ShouldBeGreaterThan(0.Milliseconds());
report.Type.ShouldBe(DiagnosticReportType.Full);
report.SystemDetails.ShouldNotBeNull();
report.ProcessDetails.ShouldNotBeNull();
report.DriveDetails.ShouldNotBeNull();
report.DriveDetails.ShouldNotBeEmpty();
report.Assemblies.ShouldNotBeNull();
report.Assemblies.ShouldNotBeEmpty();
report.EnvironmentVariables.ShouldNotBeNull();
report.EnvironmentVariables.ShouldNotBeEmpty();
report.NetworkingDetails.ShouldNotBeNull();
var formattedReport = report.ToString();
formattedReport.ShouldNotBeNull();
formattedReport.Length.ShouldBeGreaterThan(1000);
formattedReport.ShouldStartWith("/\r\n|Diagnostic Report generated at:");
formattedReport.ShouldContain("\r\n|\r\n|System|...");
formattedReport.ShouldContain("\r\n|\r\n|Process|...");
formattedReport.ShouldContain("\r\n|\r\n|Drives|...");
formattedReport.ShouldContain("\r\n|\r\n|Assemblies|...");
formattedReport.ShouldContain("\r\n|\r\n|Environment-Variables|...");
formattedReport.ShouldContain("\r\n|\r\n|Networks|...");
formattedReport.ShouldContain("|\r\n|\t. Windows IP Configuration\r\n|");
formattedReport.ShouldEndWith("\\");
}
[Test]
public void When_generating_system_report_with_flag()
{
var report = DiagnosticReport.Generate(DiagnosticReportType.System);
report.ShouldNotBeNull();
report.Timestamp.ShouldBeLessThanOrEqualTo(DateTimeOffset.Now);
report.TimeTaken.ShouldBeGreaterThan(0.Milliseconds());
report.Type.ShouldBe(DiagnosticReportType.System);
report.SystemDetails.ShouldNotBeNull();
report.ProcessDetails.ShouldBeNull();
report.DriveDetails.ShouldBeNull();
report.DriveDetails.ShouldBeNull();
report.Assemblies.ShouldBeNull();
report.EnvironmentVariables.ShouldBeNull();
report.NetworkingDetails.ShouldBeNull();
var formattedReport = report.ToString();
formattedReport.ShouldNotBeNull();
formattedReport.Length.ShouldBeGreaterThan(100);
formattedReport.ShouldStartWith("/\r\n|Diagnostic Report generated at:");
formattedReport.ShouldContain("\r\n|\r\n|System|...");
formattedReport.ShouldNotContain("\r\n|\r\n|Process|...");
formattedReport.ShouldNotContain("\r\n|\r\n|Drives|...");
formattedReport.ShouldNotContain("\r\n|\r\n|Assemblies|...");
formattedReport.ShouldNotContain("\r\n|\r\n|Environment-Variables|...");
formattedReport.ShouldNotContain("\r\n|\r\n|Networks|...");
formattedReport.ShouldNotContain("|\r\n|\t. Windows IP Configuration\r\n|");
formattedReport.ShouldEndWith("\\");
}
[Test]
public void When_generating_process_report_with_flag()
{
var report = DiagnosticReport.Generate(DiagnosticReportType.Process);
report.ShouldNotBeNull();
report.Timestamp.ShouldBeLessThanOrEqualTo(DateTimeOffset.Now);
report.TimeTaken.ShouldBeGreaterThan(0.Milliseconds());
report.Type.ShouldBe(DiagnosticReportType.Process);
report.SystemDetails.ShouldBeNull();
report.ProcessDetails.ShouldNotBeNull();
report.DriveDetails.ShouldBeNull();
report.Assemblies.ShouldBeNull();
report.EnvironmentVariables.ShouldBeNull();
report.NetworkingDetails.ShouldBeNull();
var formattedReport = report.ToString();
formattedReport.ShouldNotBeNull();
formattedReport.Length.ShouldBeGreaterThan(100);
formattedReport.ShouldStartWith("/\r\n|Diagnostic Report generated at:");
formattedReport.ShouldNotContain("\r\n|\r\n|System|...");
formattedReport.ShouldContain("\r\n|\r\n|Process|...");
formattedReport.ShouldNotContain("\r\n|\r\n|Drives|...");
formattedReport.ShouldNotContain("\r\n|\r\n|Assemblies|...");
formattedReport.ShouldNotContain("\r\n|\r\n|Environment-Variables|...");
formattedReport.ShouldNotContain("\r\n|\r\n|Networks|...");
formattedReport.ShouldNotContain("|\r\n|\t. Windows IP Configuration\r\n|");
formattedReport.ShouldEndWith("\\");
}
[Test]
public void When_generating_drives_report_with_flag()
{
var report = DiagnosticReport.Generate(DiagnosticReportType.Drives);
report.ShouldNotBeNull();
report.Timestamp.ShouldBeLessThanOrEqualTo(DateTimeOffset.Now);
report.TimeTaken.ShouldBeGreaterThan(0.Milliseconds());
report.Type.ShouldBe(DiagnosticReportType.Drives);
report.SystemDetails.ShouldBeNull();
report.ProcessDetails.ShouldBeNull();
report.DriveDetails.ShouldNotBeNull();
report.DriveDetails.ShouldNotBeEmpty();
report.Assemblies.ShouldBeNull();
report.EnvironmentVariables.ShouldBeNull();
report.NetworkingDetails.ShouldBeNull();
var formattedReport = report.ToString();
formattedReport.ShouldNotBeNull();
formattedReport.Length.ShouldBeGreaterThan(100);
formattedReport.ShouldStartWith("/\r\n|Diagnostic Report generated at:");
formattedReport.ShouldNotContain("\r\n|\r\n|System|...");
formattedReport.ShouldNotContain("\r\n|\r\n|Process|...");
formattedReport.ShouldContain("\r\n|\r\n|Drives|...");
formattedReport.ShouldNotContain("\r\n|\r\n|Assemblies|...");
formattedReport.ShouldNotContain("\r\n|\r\n|Environment-Variables|...");
formattedReport.ShouldNotContain("\r\n|\r\n|Networks|...");
formattedReport.ShouldNotContain("|\r\n|\t. Windows IP Configuration\r\n|");
formattedReport.ShouldEndWith("\\");
}
[Test]
public void When_generating_assemblies_report_with_flag()
{
var report = DiagnosticReport.Generate(DiagnosticReportType.Assemblies);
report.ShouldNotBeNull();
report.Timestamp.ShouldBeLessThanOrEqualTo(DateTimeOffset.Now);
report.TimeTaken.ShouldBeGreaterThan(0.Milliseconds());
report.Type.ShouldBe(DiagnosticReportType.Assemblies);
report.SystemDetails.ShouldBeNull();
report.ProcessDetails.ShouldBeNull();
report.DriveDetails.ShouldBeNull();
report.Assemblies.ShouldNotBeNull();
report.Assemblies.ShouldNotBeEmpty();
report.EnvironmentVariables.ShouldBeNull();
report.NetworkingDetails.ShouldBeNull();
var formattedReport = report.ToString();
formattedReport.ShouldNotBeNull();
formattedReport.Length.ShouldBeGreaterThan(100);
formattedReport.ShouldStartWith("/\r\n|Diagnostic Report generated at:");
formattedReport.ShouldNotContain("\r\n|\r\n|System|...");
formattedReport.ShouldNotContain("\r\n|\r\n|Process|...");
formattedReport.ShouldNotContain("\r\n|\r\n|Drives|...");
formattedReport.ShouldContain("\r\n|\r\n|Assemblies|...");
formattedReport.ShouldNotContain("\r\n|\r\n|Environment-Variables|...");
formattedReport.ShouldNotContain("\r\n|\r\n|Networks|...");
formattedReport.ShouldNotContain("|\r\n|\t. Windows IP Configuration\r\n|");
formattedReport.ShouldEndWith("\\");
}
[Test]
public void When_generating_environment_variables_report_with_flag()
{
var report = DiagnosticReport.Generate(DiagnosticReportType.EnvironmentVariables);
report.ShouldNotBeNull();
report.Timestamp.ShouldBeLessThanOrEqualTo(DateTimeOffset.Now);
report.TimeTaken.ShouldBeGreaterThan(0.Milliseconds());
report.Type.ShouldBe(DiagnosticReportType.EnvironmentVariables);
report.SystemDetails.ShouldBeNull();
report.ProcessDetails.ShouldBeNull();
report.DriveDetails.ShouldBeNull();
report.Assemblies.ShouldBeNull();
report.EnvironmentVariables.ShouldNotBeNull();
report.EnvironmentVariables.ShouldNotBeEmpty();
report.NetworkingDetails.ShouldBeNull();
var formattedReport = report.ToString();
formattedReport.ShouldNotBeNull();
formattedReport.Length.ShouldBeGreaterThan(100);
formattedReport.ShouldStartWith("/\r\n|Diagnostic Report generated at:");
formattedReport.ShouldNotContain("\r\n|\r\n|System|...");
formattedReport.ShouldNotContain("\r\n|\r\n|Process|...");
formattedReport.ShouldNotContain("\r\n|\r\n|Drives|...");
formattedReport.ShouldNotContain("\r\n|\r\n|Assemblies|...");
formattedReport.ShouldContain("\r\n|\r\n|Environment-Variables|...");
formattedReport.ShouldNotContain("\r\n|\r\n|Networks|...");
formattedReport.ShouldNotContain("|\r\n|\t. Windows IP Configuration\r\n|");
formattedReport.ShouldEndWith("\\");
}
[Test]
public void When_generating_networking_report_with_flag()
{
var report = DiagnosticReport.Generate(DiagnosticReportType.Networks);
report.ShouldNotBeNull();
report.Timestamp.ShouldBeLessThanOrEqualTo(DateTimeOffset.Now);
report.TimeTaken.ShouldBeGreaterThan(0.Milliseconds());
report.Type.ShouldBe(DiagnosticReportType.Networks);
report.SystemDetails.ShouldBeNull();
report.ProcessDetails.ShouldBeNull();
report.DriveDetails.ShouldBeNull();
report.Assemblies.ShouldBeNull();
report.EnvironmentVariables.ShouldBeNull();
report.NetworkingDetails.ShouldNotBeNull();
var formattedReport = report.ToString();
formattedReport.ShouldNotBeNull();
formattedReport.Length.ShouldBeGreaterThan(100);
formattedReport.ShouldStartWith("/\r\n|Diagnostic Report generated at:");
formattedReport.ShouldNotContain("\r\n|\r\n|System|...");
formattedReport.ShouldNotContain("\r\n|\r\n|Process|...");
formattedReport.ShouldNotContain("\r\n|\r\n|Drives|...");
formattedReport.ShouldNotContain("\r\n|\r\n|Assemblies|...");
formattedReport.ShouldNotContain("\r\n|\r\n|Environment-Variables|...");
formattedReport.ShouldContain("\r\n|\r\n|Networks|...");
formattedReport.ShouldContain("|\r\n|\t. Windows IP Configuration\r\n|");
formattedReport.ShouldEndWith("\\");
}
[Test]
public void When_generating_system_and_process_report()
{
const DiagnosticReportType Flags = DiagnosticReportType.System
| DiagnosticReportType.Process;
var report = DiagnosticReport.Generate(Flags);
report.ShouldNotBeNull();
report.Timestamp.ShouldBeLessThanOrEqualTo(DateTimeOffset.Now);
report.TimeTaken.ShouldBeGreaterThan(0.Milliseconds());
report.Type.ShouldBe(Flags);
report.SystemDetails.ShouldNotBeNull();
report.ProcessDetails.ShouldNotBeNull();
report.DriveDetails.ShouldBeNull();
report.Assemblies.ShouldBeNull();
report.EnvironmentVariables.ShouldBeNull();
report.NetworkingDetails.ShouldBeNull();
var formattedReport = report.ToString();
formattedReport.ShouldNotBeNull();
formattedReport.Length.ShouldBeGreaterThan(100);
formattedReport.ShouldStartWith("/\r\n|Diagnostic Report generated at:");
formattedReport.ShouldContain("\r\n|\r\n|System|...");
formattedReport.ShouldContain("\r\n|\r\n|Process|...");
formattedReport.ShouldNotContain("\r\n|\r\n|Drives|...");
formattedReport.ShouldNotContain("\r\n|\r\n|Assemblies|...");
formattedReport.ShouldNotContain("\r\n|\r\n|Environment-Variables|...");
formattedReport.ShouldNotContain("\r\n|\r\n|Networks|...");
formattedReport.ShouldNotContain("|\r\n|\t. Windows IP Configuration\r\n|");
formattedReport.ShouldEndWith("\\");
}
[Test]
public void When_generating_system_and_drives_report()
{
const DiagnosticReportType Flags = DiagnosticReportType.System
| DiagnosticReportType.Drives;
var report = DiagnosticReport.Generate(Flags);
report.ShouldNotBeNull();
report.Timestamp.ShouldBeLessThanOrEqualTo(DateTimeOffset.Now);
report.TimeTaken.ShouldBeGreaterThan(0.Milliseconds());
report.Type.ShouldBe(Flags);
report.SystemDetails.ShouldNotBeNull();
report.ProcessDetails.ShouldBeNull();
report.DriveDetails.ShouldNotBeNull();
report.DriveDetails.ShouldNotBeEmpty();
report.Assemblies.ShouldBeNull();
report.EnvironmentVariables.ShouldBeNull();
report.NetworkingDetails.ShouldBeNull();
var formattedReport = report.ToString();
formattedReport.ShouldNotBeNull();
formattedReport.Length.ShouldBeGreaterThan(100);
formattedReport.ShouldStartWith("/\r\n|Diagnostic Report generated at:");
formattedReport.ShouldContain("\r\n|\r\n|System|...");
formattedReport.ShouldNotContain("\r\n|\r\n|Process|...");
formattedReport.ShouldContain("\r\n|\r\n|Drives|...");
formattedReport.ShouldNotContain("\r\n|\r\n|Assemblies|...");
formattedReport.ShouldNotContain("\r\n|\r\n|Environment-Variables|...");
formattedReport.ShouldNotContain("\r\n|\r\n|Networks|...");
formattedReport.ShouldNotContain("|\r\n|\t. Windows IP Configuration\r\n|");
formattedReport.ShouldEndWith("\\");
}
[Test]
public void When_generating_system_and_assemblies_report()
{
const DiagnosticReportType Flags = DiagnosticReportType.System
| DiagnosticReportType.Assemblies;
var report = DiagnosticReport.Generate(Flags);
report.ShouldNotBeNull();
report.Timestamp.ShouldBeLessThanOrEqualTo(DateTimeOffset.Now);
report.TimeTaken.ShouldBeGreaterThan(0.Milliseconds());
report.Type.ShouldBe(Flags);
report.SystemDetails.ShouldNotBeNull();
report.ProcessDetails.ShouldBeNull();
report.DriveDetails.ShouldBeNull();
report.Assemblies.ShouldNotBeNull();
report.Assemblies.ShouldNotBeEmpty();
report.EnvironmentVariables.ShouldBeNull();
report.NetworkingDetails.ShouldBeNull();
var formattedReport = report.ToString();
formattedReport.ShouldNotBeNull();
formattedReport.Length.ShouldBeGreaterThan(100);
formattedReport.ShouldStartWith("/\r\n|Diagnostic Report generated at:");
formattedReport.ShouldContain("\r\n|\r\n|System|...");
formattedReport.ShouldNotContain("\r\n|\r\n|Process|...");
formattedReport.ShouldNotContain("\r\n|\r\n|Drives|...");
formattedReport.ShouldContain("\r\n|\r\n|Assemblies|...");
formattedReport.ShouldNotContain("\r\n|\r\n|Environment-Variables|...");
formattedReport.ShouldNotContain("\r\n|\r\n|Networks|...");
formattedReport.ShouldNotContain("|\r\n|\t. Windows IP Configuration\r\n|");
formattedReport.ShouldEndWith("\\");
}
[Test]
public void When_generating_system_and_environment_variables_report()
{
const DiagnosticReportType Flags = DiagnosticReportType.System
| DiagnosticReportType.EnvironmentVariables;
var report = DiagnosticReport.Generate(Flags);
report.ShouldNotBeNull();
report.Timestamp.ShouldBeLessThanOrEqualTo(DateTimeOffset.Now);
report.TimeTaken.ShouldBeGreaterThan(0.Milliseconds());
report.Type.ShouldBe(Flags);
report.SystemDetails.ShouldNotBeNull();
report.ProcessDetails.ShouldBeNull();
report.DriveDetails.ShouldBeNull();
report.Assemblies.ShouldBeNull();
report.EnvironmentVariables.ShouldNotBeNull();
report.EnvironmentVariables.ShouldNotBeEmpty();
report.NetworkingDetails.ShouldBeNull();
var formattedReport = report.ToString();
formattedReport.ShouldNotBeNull();
formattedReport.Length.ShouldBeGreaterThan(100);
formattedReport.ShouldStartWith("/\r\n|Diagnostic Report generated at:");
formattedReport.ShouldContain("\r\n|\r\n|System|...");
formattedReport.ShouldNotContain("\r\n|\r\n|Process|...");
formattedReport.ShouldNotContain("\r\n|\r\n|Drives|...");
formattedReport.ShouldNotContain("\r\n|\r\n|Assemblies|...");
formattedReport.ShouldContain("\r\n|\r\n|Environment-Variables|...");
formattedReport.ShouldNotContain("\r\n|\r\n|Networks|...");
formattedReport.ShouldNotContain("|\r\n|\t. Windows IP Configuration\r\n|");
formattedReport.ShouldEndWith("\\");
}
[Test]
public void When_generating_system_and_networking_report()
{
const DiagnosticReportType Flags = DiagnosticReportType.System
| DiagnosticReportType.Networks;
var report = DiagnosticReport.Generate(Flags);
report.ShouldNotBeNull();
report.Timestamp.ShouldBeLessThanOrEqualTo(DateTimeOffset.Now);
report.TimeTaken.ShouldBeGreaterThan(0.Milliseconds());
report.Type.ShouldBe(Flags);
report.SystemDetails.ShouldNotBeNull();
report.ProcessDetails.ShouldBeNull();
report.DriveDetails.ShouldBeNull();
report.Assemblies.ShouldBeNull();
report.EnvironmentVariables.ShouldBeNull();
report.NetworkingDetails.ShouldNotBeNull();
var formattedReport = report.ToString();
formattedReport.ShouldNotBeNull();
formattedReport.Length.ShouldBeGreaterThan(100);
formattedReport.ShouldStartWith("/\r\n|Diagnostic Report generated at:");
formattedReport.ShouldContain("\r\n|\r\n|System|...");
formattedReport.ShouldNotContain("\r\n|\r\n|Process|...");
formattedReport.ShouldNotContain("\r\n|\r\n|Drives|...");
formattedReport.ShouldNotContain("\r\n|\r\n|Assemblies|...");
formattedReport.ShouldNotContain("\r\n|\r\n|Environment-Variables|...");
formattedReport.ShouldContain("\r\n|\r\n|Networks|...");
formattedReport.ShouldContain("|\r\n|\t. Windows IP Configuration\r\n|");
formattedReport.ShouldEndWith("\\");
}
[Test]
public void When_generating_system_and_process_and_drives_and_assemblies_and_environment_variables_and_networking_report()
{
const DiagnosticReportType Flags = DiagnosticReportType.System
| DiagnosticReportType.Process
| DiagnosticReportType.Drives
| DiagnosticReportType.Assemblies
| DiagnosticReportType.EnvironmentVariables
| DiagnosticReportType.Networks;
var report = DiagnosticReport.Generate();
report.ShouldNotBeNull();
report.Timestamp.ShouldBeLessThanOrEqualTo(DateTimeOffset.Now);
report.TimeTaken.ShouldBeGreaterThan(0.Milliseconds());
report.Type.ShouldBe(Flags);
report.SystemDetails.ShouldNotBeNull();
report.ProcessDetails.ShouldNotBeNull();
report.DriveDetails.ShouldNotBeNull();
report.DriveDetails.ShouldNotBeEmpty();
report.Assemblies.ShouldNotBeNull();
report.Assemblies.ShouldNotBeEmpty();
report.EnvironmentVariables.ShouldNotBeNull();
report.EnvironmentVariables.ShouldNotBeEmpty();
report.NetworkingDetails.ShouldNotBeNull();
var formattedReport = report.ToString();
formattedReport.ShouldNotBeNull();
formattedReport.Length.ShouldBeGreaterThan(1000);
formattedReport.ShouldStartWith("/\r\n|Diagnostic Report generated at:");
formattedReport.ShouldContain("\r\n|\r\n|System|...");
formattedReport.ShouldContain("\r\n|\r\n|Process|...");
formattedReport.ShouldContain("\r\n|\r\n|Drives|...");
formattedReport.ShouldContain("\r\n|\r\n|Assemblies|...");
formattedReport.ShouldContain("\r\n|\r\n|Environment-Variables|...");
formattedReport.ShouldContain("\r\n|\r\n|Networks|...");
formattedReport.ShouldContain("|\r\n|\t. Windows IP Configuration\r\n|");
formattedReport.ShouldEndWith("\\");
}
[Test]
public void When_generating_process_and_assemblies_and_networking_report()
{
const DiagnosticReportType Flags = DiagnosticReportType.Process
| DiagnosticReportType.Assemblies
| DiagnosticReportType.Networks;
var report = DiagnosticReport.Generate(Flags);
report.ShouldNotBeNull();
report.Timestamp.ShouldBeLessThanOrEqualTo(DateTimeOffset.Now);
report.TimeTaken.ShouldBeGreaterThan(0.Milliseconds());
report.Type.ShouldBe(Flags);
report.SystemDetails.ShouldBeNull();
report.ProcessDetails.ShouldNotBeNull();
report.DriveDetails.ShouldBeNull();
report.Assemblies.ShouldNotBeNull();
report.Assemblies.ShouldNotBeEmpty();
report.EnvironmentVariables.ShouldBeNull();
report.NetworkingDetails.ShouldNotBeNull();
var formattedReport = report.ToString();
formattedReport.ShouldNotBeNull();
formattedReport.Length.ShouldBeGreaterThan(500);
formattedReport.ShouldStartWith("/\r\n|Diagnostic Report generated at:");
formattedReport.ShouldNotContain("\r\n|\r\n|System|...");
formattedReport.ShouldContain("\r\n|\r\n|Process|...");
formattedReport.ShouldNotContain("\r\n|\r\n|Drives|...");
formattedReport.ShouldContain("\r\n|\r\n|Assemblies|...");
formattedReport.ShouldNotContain("\r\n|\r\n|Environment-Variables|...");
formattedReport.ShouldContain("\r\n|\r\n|Networks|...");
formattedReport.ShouldContain("|\r\n|\t. Windows IP Configuration\r\n|");
formattedReport.ShouldEndWith("\\");
}
[Test]
public void When_generating_process_and_assemblies_and_networking_and_full_report()
{
const DiagnosticReportType Flags = DiagnosticReportType.Process
| DiagnosticReportType.Assemblies
| DiagnosticReportType.Networks
| DiagnosticReportType.Full;
var report = DiagnosticReport.Generate();
report.ShouldNotBeNull();
report.Timestamp.ShouldBeLessThanOrEqualTo(DateTimeOffset.Now);
report.TimeTaken.ShouldBeGreaterThan(0.Milliseconds());
report.Type.ShouldBe(Flags);
report.SystemDetails.ShouldNotBeNull();
report.ProcessDetails.ShouldNotBeNull();
report.DriveDetails.ShouldNotBeNull();
report.DriveDetails.ShouldNotBeEmpty();
report.Assemblies.ShouldNotBeNull();
report.Assemblies.ShouldNotBeEmpty();
report.EnvironmentVariables.ShouldNotBeNull();
report.EnvironmentVariables.ShouldNotBeEmpty();
report.NetworkingDetails.ShouldNotBeNull();
var formattedReport = report.ToString();
formattedReport.ShouldNotBeNull();
formattedReport.Length.ShouldBeGreaterThan(1000);
formattedReport.ShouldStartWith("/\r\n|Diagnostic Report generated at:");
formattedReport.ShouldContain("\r\n|\r\n|System|...");
formattedReport.ShouldContain("\r\n|\r\n|Process|...");
formattedReport.ShouldContain("\r\n|\r\n|Drives|...");
formattedReport.ShouldContain("\r\n|\r\n|Assemblies|...");
formattedReport.ShouldContain("\r\n|\r\n|Environment-Variables|...");
formattedReport.ShouldContain("\r\n|\r\n|Networks|...");
formattedReport.ShouldContain("|\r\n|\t. Windows IP Configuration\r\n|");
formattedReport.ShouldEndWith("\\");
}
}
} | 50.607339 | 130 | 0.635909 | [
"MIT"
] | jimd-personal/Easy.Common | Easy.Common.Tests.Unit/DiagnosticReport/DiagnosticReportTests.cs | 27,583 | C# |
using Phoesion.Glow.SDK;
using Phoesion.Glow.SDK.Firefly;
using System;
using models = Foompany.Services.API.SampleService2.Modules.PostSamples.Models;
namespace Foompany.Services.SampleService2
{
[API(typeof(API.SampleService2.Modules.PostSamples.Actions))]
public class PostSamples : Phoesion.Glow.SDK.Firefly.FireflyModule
{
//----------------------------------------------------------------------------------------------------------------------------------------------
[ActionBody(Methods.POST)]
public string Action1()
{
return "Called Action1 using POST in PostSamples module";
}
//----------------------------------------------------------------------------------------------------------------------------------------------
/// <summary> Sample action that exposes both GET and POST methods </summary>
[ActionBody(Methods.GET | Methods.POST)]
public string Action2()
{
return $"Called Action2 using {RestRequest.Method} in PostSamples module.";
}
//----------------------------------------------------------------------------------------------------------------------------------------------
/* Example of a data model request/response action.
*
* The Phoesion Glow system will automatically handle the deserialization of the request and the serialization of the response
* based on the context of the request.
*
* For example in a REST Request :
* - For the deserialization of the body, the 'Content-Type' will be examined to determine the deserialization method.
* If the Content-Type is 'application/json' the body will deserialized using a json deserializer.
* An other Content-Type can be 'application/xml' and in this case a Xml deserializer will be used.
*
* - For the serialization of the response, the 'Accept' header will be examined the serialization method based on the client expectations.
* If the Accept type is 'application/json' the response will serialized using a json deserializer.
* An other Accept type can be 'application/xml' and in this case a Xml serializer will be used.
* ( 'application/msgpack' is also handled automatically )
*/
[ActionBody(Methods.POST)]
public models.MyDataModel.Response DoTheThing(models.MyDataModel.Request Model)
{
return new models.MyDataModel.Response()
{
IsSuccess = true,
Message = $"Hello {Model.InputName}",
};
}
//----------------------------------------------------------------------------------------------------------------------------------------------
/// <summary> Sample action that reads body as string </summary>
[ActionBody(Methods.POST)]
public string Action3([FromBody] string body)
{
return $"Called Action3 using body : " + Environment.NewLine + body;
}
//----------------------------------------------------------------------------------------------------------------------------------------------
}
}
| 48.731343 | 152 | 0.490046 | [
"MIT"
] | Phoesion/Glow-Samples | 1_REST/Services/Foompany.Services.SampleService2/Modules/PostSamples.cs | 3,267 | C# |
using System;
namespace RegionOrebroLan.Web.Paging
{
public interface IPaginationValidator
{
#region Methods
void ValidateMaximumNumberOfDisplayedPages(int maximumNumberOfDisplayedPages);
void ValidateNumberOfItems(int numberOfItems);
void ValidatePageIndexKey(string pageIndexKey);
void ValidatePageSize(int pageSize);
void ValidateUrl(Uri url);
#endregion
}
} | 22.470588 | 80 | 0.808901 | [
"MIT"
] | RegionOrebroLan/.NET-Web-Extensions | Source/Project/Paging/IPaginationValidator.cs | 384 | C# |
/*
* Copyright (c) 2021 bd_
*
* 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.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
using UdonSharpEditor;
namespace net.fushizen.attachable
{
[CustomEditor(typeof(AttachableConfig))]
[CanEditMultipleObjects]
class AttachableEditor : Editor
{
static bool lang_jp = false;
bool show_general = true;
bool show_selection = true;
bool show_perms = true;
bool show_animator = false;
SerializedProperty m_t_pickup;
SerializedProperty m_t_attachmentDirection;
SerializedProperty m_range;
SerializedProperty m_directionality;
SerializedProperty m_disableFingerTracking;
SerializedProperty m_respawnTime;
SerializedProperty m_perm_removeTracee;
SerializedProperty m_perm_removeOwner;
SerializedProperty m_perm_removeOther;
SerializedProperty m_c_animator;
SerializedProperty m_anim_onTrack, m_anim_onTrackLocal, m_anim_onHeld, m_anim_onHeldLocal;
struct Strings
{
public GUIContent btn_langSwitch;
public GUIContent header_general;
public GUIContent m_t_pickup;
public GUIContent header_selection;
public GUIContent m_range;
public GUIContent m_disableFingerTracking;
public GUIContent m_respawnTime;
public GUIContent m_t_attachmentDirection;
public GUIContent m_directionality;
public GUIContent header_pickup_perms;
public GUIContent header_pickup_perms_2;
public GUIContent header_pickup_perms_3;
public GUIContent m_perm_removeTracee;
public GUIContent m_perm_removeOwner;
public GUIContent m_perm_removeOther;
public GUIContent header_animator;
public GUIContent m_c_animator;
public GUIContent header_animator_flags;
public GUIContent m_anim_onTrack, m_anim_onTrackLocal;
public GUIContent m_anim_onHeld, m_anim_onHeldLocal;
public GUIContent header_internal;
public GUIContent warn_direction, warn_missing;
public GUIContent m_trackOnUpdate;
}
Strings en, jp;
void LoadStrings()
{
jp = new Strings()
{
btn_langSwitch = new GUIContent("Switch to English", "Switch language"),
header_general = new GUIContent("基本設定"),
m_t_pickup = new GUIContent("ピックアップオブジェクト"),
header_selection = new GUIContent("選択設定"),
m_range = new GUIContent("ボーン選択範囲", "この範囲内のボーンが選択対象になります"),
m_directionality = new GUIContent("指向性", "この数値をゼロ以上にすると、【方向マーカー】に指定されたオブジェクトのZ+方向の先にあるボーンを優先的に選択します。"),
m_t_attachmentDirection = new GUIContent("方向マーカー", "このオブジェクトのZ+方向と位置を基準にボーンの選択を行います"),
m_disableFingerTracking = new GUIContent("指ボーンに追従しない"),
m_respawnTime = new GUIContent("リスポーン時間", "設定時間以上放置されていると、初期地点に戻ります。秒数で入力、ゼロで無効化できます。"),
warn_direction = new GUIContent("方向マーカーをプレハブの子に設定してください"),
header_pickup_perms = new GUIContent("取り外しできるプレイヤーの設定"),
header_pickup_perms_2 = new GUIContent("追尾しているピックアップを取り外せるプレイヤーを設定できます。"),
header_pickup_perms_3 = new GUIContent("追尾していない場合はだれでも手にとれます。"),
m_perm_removeTracee = new GUIContent("追尾対象プレイヤー自身"),
m_perm_removeOwner = new GUIContent("最後に触った人"),
m_perm_removeOther = new GUIContent("その他の人"),
header_internal = new GUIContent("内部設定"),
warn_missing = new GUIContent("必須項目です。"),
header_animator = new GUIContent("Animator連動設定"),
m_c_animator = new GUIContent("連動させるAnimator"),
header_animator_flags = new GUIContent("フラグパラメーター名"),
m_anim_onTrack = new GUIContent("トラッキング中フラグ"),
m_anim_onTrackLocal = new GUIContent("ローカルプレイヤーをトラッキング中"),
m_anim_onHeld = new GUIContent("誰かが持っているフラグ"),
m_anim_onHeldLocal = new GUIContent("ローカルで持っているフラグ"),
m_trackOnUpdate = new GUIContent("処理タイミングをずらす", "Dynamic Bone等物理演算がぷるぷるするときはチェック入れましょう(少しラグが発生します)"),
};
en = new Strings()
{
btn_langSwitch = new GUIContent("日本語に切り替え", "Switch language"),
header_general = new GUIContent("General settings"),
m_t_pickup = new GUIContent("Pickup object"),
header_selection = new GUIContent("Selection configuration"),
m_range = new GUIContent("Bone selection radius", "Bones within this radius will be considered as potential targets"),
m_directionality = new GUIContent("Directionality", "If you set this value above zero, "),
m_t_attachmentDirection = new GUIContent("Direction marker", "This object's Z+ direction and position will be used as the basis for bone selection."),
m_disableFingerTracking = new GUIContent("Disable finger bone tracking"),
m_respawnTime = new GUIContent("Respawn time ", "If the prop is left idle for longer than this time, it will return to its initial position. Expressed in seconds, zero to disable."),
warn_direction = new GUIContent("Please ensure that the direction marker is a child of the pickup object."),
header_pickup_perms = new GUIContent("Removal permissions"),
header_pickup_perms_2 = new GUIContent("Select which players can remove a tracking pickup."),
header_pickup_perms_3 = new GUIContent("When not tracking a bone, anyone can pick up the pickup."),
m_perm_removeTracee = new GUIContent("Person being tracked can remove"),
m_perm_removeOwner = new GUIContent("Last person to touch pickup can remove"),
m_perm_removeOther = new GUIContent("Anyone else can remove"),
header_internal = new GUIContent("Internal settings"),
warn_missing = new GUIContent("This field is required"),
header_animator = new GUIContent("Animator control configuration"),
m_c_animator = new GUIContent("Animator to control"),
header_animator_flags = new GUIContent("Flag parameter names"),
m_anim_onTrack = new GUIContent("Tracking bone"),
m_anim_onTrackLocal = new GUIContent("Tracking the local player's bone"),
m_anim_onHeld = new GUIContent("Held in hand"),
m_anim_onHeldLocal = new GUIContent("Held by local player"),
m_trackOnUpdate = new GUIContent("Alternate timing", "Check this if a dynamic bone or other physics object vibrates when moving " +
"(this will result in some additional lag, only check it if you need it!)"),
};
}
private void OnEnable()
{
LoadStrings();
m_t_pickup = serializedObject.FindProperty("t_pickup");
m_t_attachmentDirection = serializedObject.FindProperty("t_attachmentDirection");
m_range = serializedObject.FindProperty("range");
m_directionality = serializedObject.FindProperty("directionality");
m_disableFingerTracking = serializedObject.FindProperty("disableFingerTracking");
m_respawnTime = serializedObject.FindProperty("respawnTime");
m_perm_removeTracee = serializedObject.FindProperty("perm_removeTracee");
m_perm_removeOwner = serializedObject.FindProperty("perm_removeOwner");
m_perm_removeOther = serializedObject.FindProperty("perm_removeOther");
m_c_animator = serializedObject.FindProperty("c_animator");
m_anim_onHeld = serializedObject.FindProperty("anim_onHeld");
m_anim_onHeldLocal = serializedObject.FindProperty("anim_onHeldLocal");
m_anim_onTrack = serializedObject.FindProperty("anim_onTrack");
m_anim_onTrackLocal = serializedObject.FindProperty("anim_onTrackLocal");
}
public override void OnInspectorGUI()
{
bool isMultiple = targets.Length > 1;
var lang = lang_jp ? jp : en;
bool switchLanguage = GUILayout.Button(lang.btn_langSwitch);
if (switchLanguage)
{
lang_jp = !lang_jp;
}
Transform t_pickup = null;
EditorGUILayout.Space();
show_general = EditorGUILayout.Foldout(show_general, lang.header_general);
if (show_general)
{
if (!isMultiple)
{
EditorGUILayout.PropertyField(m_t_pickup, lang.m_t_pickup);
}
}
t_pickup = (Transform)m_t_pickup.objectReferenceValue;
if (t_pickup == null)
{
if (!show_general)
{
show_general = true;
EditorUtility.SetDirty(target);
}
EditorGUILayout.HelpBox(lang.warn_missing.text, MessageType.Error);
}
if (show_general)
{
// trackOnUpdate seems unnecessary with OnPostLateUpdate update loops.
// Leaving it in (available in the debug inspector) just in case for now.
//EditorGUILayout.PropertyField(m_trackOnUpdate, lang.m_trackOnUpdate);
EditorGUILayout.PropertyField(m_respawnTime, lang.m_respawnTime);
EditorGUILayout.Space();
}
show_selection = EditorGUILayout.Foldout(show_selection, lang.header_selection);
if (show_selection)
{
EditorGUILayout.PropertyField(m_range, lang.m_range);
if (!isMultiple) EditorGUILayout.PropertyField(m_t_attachmentDirection, lang.m_t_attachmentDirection);
}
if (!isMultiple)
{
var t_direction = (Transform)m_t_attachmentDirection.objectReferenceValue;
if (t_direction == null)
{
if (!show_selection)
{
show_selection = true;
EditorUtility.SetDirty(target);
}
EditorGUILayout.HelpBox(lang.warn_missing.text, MessageType.Error);
} else
{
var trace = t_direction.parent;
while (trace != null && trace != t_pickup)
{
trace = trace.parent;
}
if (trace == null)
{
if (!show_selection)
{
show_selection = true;
EditorUtility.SetDirty(target);
}
EditorGUILayout.HelpBox(lang.warn_direction.text, MessageType.Warning);
}
}
}
if (show_selection)
{
EditorGUILayout.PropertyField(m_directionality, lang.m_directionality);
EditorGUILayout.PropertyField(m_disableFingerTracking, lang.m_disableFingerTracking);
}
EditorGUILayout.Space();
show_perms = EditorGUILayout.Foldout(show_perms, lang.header_pickup_perms);
if (show_perms)
{
EditorGUILayout.LabelField(lang.header_pickup_perms_2);
EditorGUILayout.LabelField(lang.header_pickup_perms_3);
EditorGUILayout.Space();
EditorGUILayout.PropertyField(m_perm_removeTracee, lang.m_perm_removeTracee);
EditorGUILayout.PropertyField(m_perm_removeOwner, lang.m_perm_removeOwner);
EditorGUILayout.PropertyField(m_perm_removeOther, lang.m_perm_removeOther);
}
show_animator = EditorGUILayout.Foldout(show_animator, lang.header_animator);
if (show_animator)
{
EditorGUILayout.PropertyField(m_c_animator, lang.m_c_animator);
EditorGUILayout.Space();
EditorGUILayout.LabelField(lang.header_animator_flags);
EditorGUILayout.PropertyField(m_anim_onHeld, lang.m_anim_onHeld);
EditorGUILayout.PropertyField(m_anim_onHeldLocal, lang.m_anim_onHeldLocal);
EditorGUILayout.PropertyField(m_anim_onTrack, lang.m_anim_onTrack);
EditorGUILayout.PropertyField(m_anim_onTrackLocal, lang.m_anim_onTrackLocal);
}
serializedObject.ApplyModifiedProperties();
}
}
} | 46.342193 | 198 | 0.626066 | [
"MIT"
] | bdunderscore/attach-to-me | Assets/bd_/AttachToMe/Scripts/Editor/AttachableEditor.cs | 14,849 | C# |
using System;
using System.Collections.Generic;
namespace BitcoinUtilities.Node
{
/// <summary>
/// Thread-safe collection of known Bitcoin nodes' addresses.
/// </summary>
public class NodeAddressCollection
{
private const int MaxUntestedAddressesCount = 1000;
private const int MaxRejectedAddressesCount = 1000;
private const int MaxBannedAddressesCount = 1000;
private const int MaxConfirmedAddressesCount = 32;
private const int MaxTemporaryRejectedAddressesCount = 32;
private static readonly TimeSpan untestedTimeout = TimeSpan.FromHours(12);
private static readonly TimeSpan rejectedTimeout = TimeSpan.FromHours(1);
private static readonly TimeSpan bannedTimeout = TimeSpan.FromHours(24);
private static readonly TimeSpan confirmedTimeout = TimeSpan.FromDays(14);
private static readonly TimeSpan temporaryRejectedTimeout = TimeSpan.FromDays(14);
private readonly object lockObject = new object();
private readonly LimitedNodeAddressDictionary untested = new LimitedNodeAddressDictionary(MaxUntestedAddressesCount, untestedTimeout);
private readonly LimitedNodeAddressDictionary rejected = new LimitedNodeAddressDictionary(MaxRejectedAddressesCount, rejectedTimeout);
private readonly LimitedNodeAddressDictionary banned = new LimitedNodeAddressDictionary(MaxBannedAddressesCount, bannedTimeout);
private readonly LimitedNodeAddressDictionary confirmed = new LimitedNodeAddressDictionary(MaxConfirmedAddressesCount, confirmedTimeout);
private readonly LimitedNodeAddressDictionary temporaryRejected = new LimitedNodeAddressDictionary(MaxTemporaryRejectedAddressesCount, temporaryRejectedTimeout);
public List<NodeAddress> GetNewestUntested(int count)
{
lock (lockObject)
{
return untested.GetNewest(count);
}
}
public List<NodeAddress> GetOldestRejected(int count)
{
lock (lockObject)
{
return rejected.GetOldest(count);
}
}
public List<NodeAddress> GetNewestBanned(int count)
{
lock (lockObject)
{
return banned.GetNewest(count);
}
}
public List<NodeAddress> GetNewestConfirmed(int count)
{
lock (lockObject)
{
return confirmed.GetNewest(count);
}
}
public List<NodeAddress> GetOldestTemporaryRejected(int count)
{
lock (lockObject)
{
return temporaryRejected.GetOldest(count);
}
}
public void Add(NodeAddress address)
{
lock (lockObject)
{
if (!rejected.ContainsKey(address) && !banned.ContainsKey(address) && !confirmed.ContainsKey(address) && !temporaryRejected.ContainsKey(address))
{
untested.Add(address);
}
}
}
public void Confirm(NodeAddress address)
{
lock (lockObject)
{
if (banned.ContainsKey(address))
{
return;
}
untested.Remove(address);
rejected.Remove(address);
temporaryRejected.Remove(address);
confirmed.Add(address);
}
}
public void Reject(NodeAddress address)
{
lock (lockObject)
{
if (confirmed.Remove(address) || temporaryRejected.Remove(address))
{
temporaryRejected.Add(address);
}
else if (banned.ContainsKey(address))
{
// do nothing
}
else
{
untested.Remove(address);
rejected.Remove(address);
rejected.Add(address);
}
}
}
public void Ban(NodeAddress address)
{
lock (lockObject)
{
untested.Remove(address);
rejected.Remove(address);
confirmed.Remove(address);
temporaryRejected.Remove(address);
banned.Add(address);
}
}
}
} | 34.631579 | 170 | 0.558619 | [
"MIT"
] | yu-kopylov/bitcoin-utilities | BitcoinUtilities/Node/NodeAddressCollection.cs | 4,476 | C# |
namespace Rg.ApiTypes
{
/// <summary>
/// A request to add a like.
/// </summary>
public class CommentRequest
{
/// <summary>
/// The message for this comment. May include emoji.
/// </summary>
public string Message { get; set; }
}
}
| 21.714286 | 61 | 0.506579 | [
"MIT"
] | jenyayel/rgroup | src/Rg.ApiTypes/CommentRequest.cs | 306 | C# |
namespace scan_button_responder
{
partial class RegisterNewEventFrm
{
/// <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.label1 = new System.Windows.Forms.Label();
this.tbName = new System.Windows.Forms.TextBox();
this.cbProfiles = new System.Windows.Forms.ComboBox();
this.lbProfile = new System.Windows.Forms.Label();
this.btnOk = new System.Windows.Forms.Button();
this.btnCancel = new System.Windows.Forms.Button();
this.SuspendLayout();
//
// label1
//
this.label1.AutoSize = true;
this.label1.Location = new System.Drawing.Point(12, 9);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(142, 13);
this.label1.TabIndex = 0;
this.label1.Text = "Which button did you press?";
//
// tbName
//
this.tbName.Location = new System.Drawing.Point(15, 25);
this.tbName.Name = "tbName";
this.tbName.Size = new System.Drawing.Size(235, 20);
this.tbName.TabIndex = 1;
//
// cbProfiles
//
this.cbProfiles.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.cbProfiles.FormattingEnabled = true;
this.cbProfiles.Location = new System.Drawing.Point(15, 73);
this.cbProfiles.Name = "cbProfiles";
this.cbProfiles.Size = new System.Drawing.Size(235, 21);
this.cbProfiles.TabIndex = 8;
this.cbProfiles.SelectedIndexChanged += new System.EventHandler(this.cbProfiles_SelectedIndexChanged);
//
// lbProfile
//
this.lbProfile.AutoSize = true;
this.lbProfile.Location = new System.Drawing.Point(12, 57);
this.lbProfile.Name = "lbProfile";
this.lbProfile.Size = new System.Drawing.Size(234, 13);
this.lbProfile.TabIndex = 9;
this.lbProfile.Text = "Which NAPS2 profile would you like to link it to?";
//
// btnOk
//
this.btnOk.Location = new System.Drawing.Point(139, 111);
this.btnOk.Name = "btnOk";
this.btnOk.Size = new System.Drawing.Size(111, 23);
this.btnOk.TabIndex = 10;
this.btnOk.Text = "Ok";
this.btnOk.UseVisualStyleBackColor = true;
this.btnOk.Click += new System.EventHandler(this.btnOk_Click);
//
// btnCancel
//
this.btnCancel.Location = new System.Drawing.Point(14, 111);
this.btnCancel.Name = "btnCancel";
this.btnCancel.Size = new System.Drawing.Size(115, 23);
this.btnCancel.TabIndex = 11;
this.btnCancel.Text = "Cancel";
this.btnCancel.UseVisualStyleBackColor = true;
this.btnCancel.Click += new System.EventHandler(this.btnCancel_Click);
//
// RegisterNewEventFrm
//
this.AcceptButton = this.btnOk;
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.CancelButton = this.btnCancel;
this.ClientSize = new System.Drawing.Size(265, 153);
this.Controls.Add(this.btnCancel);
this.Controls.Add(this.btnOk);
this.Controls.Add(this.lbProfile);
this.Controls.Add(this.cbProfiles);
this.Controls.Add(this.tbName);
this.Controls.Add(this.label1);
this.Name = "RegisterNewEventFrm";
this.Text = "New Button";
this.Load += new System.EventHandler(this.RegisterNewEventFrm_Load);
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.Label label1;
private System.Windows.Forms.TextBox tbName;
private System.Windows.Forms.ComboBox cbProfiles;
private System.Windows.Forms.Label lbProfile;
private System.Windows.Forms.Button btnOk;
private System.Windows.Forms.Button btnCancel;
}
} | 41.169355 | 114 | 0.570617 | [
"MIT"
] | reikjarloekl/scan-button-responder | scan-button-responder/RegisterNewEventFrm.Designer.cs | 5,107 | C# |
using CSRedis;
using System.IO;
using Microsoft.AspNetCore.DataProtection;
using Microsoft.Extensions.Hosting;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using WaterCloud.Code;
using WaterCloud.Code.Model;
using System.Text.Encodings.Web;
using System.Text.Unicode;
using Newtonsoft.Json.Serialization;
using WaterCloud.Service.AutoJob;
using WaterCloud.DataBase;
using System.Reflection;
using System.Linq;
using WaterCloud.Service;
using Autofac;
using Microsoft.AspNetCore.Mvc;
using Quartz;
using Quartz.Impl;
using Quartz.Spi;
using System;
using SqlSugar;
using System.Collections.Generic;
using WaterCloud.Domain.SystemOrganize;
using Microsoft.AspNetCore.ResponseCompression;
using System.IO.Compression;
namespace WaterCloud.Web
{
public class Startup
{
public IConfiguration Configuration { get; }
public IWebHostEnvironment WebHostEnvironment { get; set; }
public Startup(IConfiguration configuration, IWebHostEnvironment env)
{
Configuration = configuration;
WebHostEnvironment = env;
GlobalContext.LogWhenStart(env);
GlobalContext.HostingEnvironment = env;
}
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.Configure<CookiePolicyOptions>(options =>
{
// This lambda determines whether user consent for non-essential cookies is needed for a given request.
options.CheckConsentNeeded = context => true;
options.MinimumSameSitePolicy = SameSiteMode.None;
});
services.AddSession();
//代替HttpContext.Current
services.AddHttpContextAccessor();
//缓存缓存选择
if (Configuration.GetSection("SystemConfig:CacheProvider").Value!= Define.CACHEPROVIDER_REDIS)
{
services.AddMemoryCache();
}
else
{
//redis 注入服务
string redisConnectiong = Configuration.GetSection("SystemConfig:RedisConnectionString").Value;
// 多客户端 1、基础 2、操作日志
var redisDB1 = new CSRedisClient(redisConnectiong + ",defaultDatabase=" + 0);
BaseHelper.Initialization(redisDB1);
var redisDB2 = new CSRedisClient(redisConnectiong + ",defaultDatabase=" + 1);
HandleLogHelper.Initialization(redisDB2);
services.AddSingleton(redisDB1);
services.AddSingleton(redisDB2);
}
//连续guid初始化,示例IDGen.NextId()
services.AddSingleton<IDistributedIDGenerator, SequentialGuidIDGenerator>();
//更新数据库管理员和主系统,获取所有数据库连接
#region 数据库模式
List<ConnectionConfig> list = new List<ConnectionConfig>();
var defaultConfig = DBContexHelper.Contex(Configuration.GetSection("SystemConfig:DBConnectionString").Value, Configuration.GetSection("SystemConfig:DBProvider").Value);
defaultConfig.ConfigId = "0";
list.Add(defaultConfig);
if (Configuration.GetSection("SystemConfig:SqlMode").Value== "TenantSql")
{
try
{
using (var context = new UnitOfWork(new SqlSugarClient(defaultConfig)))
{
var sqls = context.GetDbClient().Queryable<SystemSetEntity>().ToList();
foreach (var item in sqls.Where(a => a.F_EnabledMark == true && a.F_EndTime > DateTime.Now.Date && a.F_DbNumber != "0"))
{
var config = DBContexHelper.Contex(item.F_DbString, item.F_DBProvider);
config.ConfigId = item.F_DbNumber;
list.Add(config);
}
}
}
catch (Exception ex)
{
LogHelper.Write(ex);
}
}
else
{
try
{
var configs=(DBConfig[]) Configuration.GetSection("SystemConfig:SqlConfig").Get(typeof(DBConfig[]));
foreach (var item in configs)
{
var config = DBContexHelper.Contex(item.DBConnectionString, item.DBProvider);
config.ConfigId = item.DBNumber;
list.Add(config);
}
}
catch (Exception ex)
{
LogHelper.Write(ex);
}
}
#endregion
#region 依赖注入
//注入数据库连接
// 注册 SqlSugar 客户端 多租户模式
services.AddScoped<ISqlSugarClient>(u =>
{
return new SqlSugarClient(list);
});
services.AddScoped<IUnitOfWork,UnitOfWork>();
#region 注入 Quartz调度类
services.AddSingleton<JobExecute>();
//注册ISchedulerFactory的实例。
services.AddSingleton<ISchedulerFactory, StdSchedulerFactory>();
services.AddSingleton<IJobFactory, IOCJobFactory>();
//是否开启后台任务
if (Configuration.GetSection("SystemConfig:OpenQuarz").Value == "True")
{
services.AddHostedService<JobCenter>();
}
#endregion
//注入SignalR实时通讯,默认用json传输
services.AddSignalR(options =>
{
//客户端发保持连接请求到服务端最长间隔,默认30秒,改成4分钟,网页需跟着设置connection.keepAliveIntervalInMilliseconds = 12e4;即2分钟
options.ClientTimeoutInterval = TimeSpan.FromMinutes(4);
//服务端发保持连接请求到客户端间隔,默认15秒,改成2分钟,网页需跟着设置connection.serverTimeoutInMilliseconds = 24e4;即4分钟
options.KeepAliveInterval = TimeSpan.FromMinutes(2);
});
////注册html解析
//services.AddSingleton(HtmlEncoder.Create(UnicodeRanges.All));
////注册特性
//services.AddScoped<HandlerLoginAttribute>();
//services.AddScoped<HandlerAuthorizeAttribute>();
////ajax不能使用注入
////services.AddScoped<HandlerAjaxOnlyAttribute>();
//services.AddScoped<HandlerAdminAttribute>();
//////定时任务(已废除)
////services.AddBackgroundServices();
#endregion
services.AddCors(options => options.AddPolicy("CorsPolicy",
builder =>
{
builder.AllowAnyMethod().AllowAnyHeader()
.WithOrigins(Configuration.GetSection("SystemConfig:AllowCorsSite").Value.Split(","))
.AllowCredentials();
}));
services.AddHttpClient();
services.AddControllersWithViews(options =>
{
options.Filters.Add<GlobalExceptionFilter>();
options.Filters.Add<ModelActionFilter>();
options.ModelMetadataDetailsProviders.Add(new ModelBindingMetadataProvider());
options.Filters.Add(new AutoValidateAntiforgeryTokenAttribute());
}).AddNewtonsoftJson(options =>
{
// 返回数据首字母不小写,CamelCasePropertyNamesContractResolver是小写
options.SerializerSettings.ContractResolver = new DefaultContractResolver();
});
services.AddAntiforgery(options => options.HeaderName = "X-CSRF-TOKEN");
services.AddControllersWithViews().AddControllersAsServices();
//调试前端可更新
services.AddControllersWithViews().AddRazorRuntimeCompilation();
//启用 Gzip 和 Brotil 压缩功能
services.AddResponseCompression(options =>
{
options.Providers.Add<BrotliCompressionProvider>();
options.Providers.Add<GzipCompressionProvider>();
options.MimeTypes =
ResponseCompressionDefaults.MimeTypes.Concat(
new[] { "image/svg+xml" });
});
services.Configure<BrotliCompressionProviderOptions>(options =>
{
options.Level = (CompressionLevel)4; // 4 or 5 is OK
});
services.AddOptions();
services.AddDataProtection().PersistKeysToFileSystem(new DirectoryInfo(GlobalContext.HostingEnvironment.ContentRootPath + Path.DirectorySeparatorChar + "DataProtection"));
GlobalContext.SystemConfig = Configuration.GetSection("SystemConfig").Get<SystemConfig>();
GlobalContext.Services = services;
GlobalContext.Configuration = Configuration;
try
{
if (GlobalContext.SystemConfig.ReviseSysem == true)
{
using (var context =new UnitOfWork(new SqlSugarClient(DBContexHelper.Contex())))
{
context.CurrentBeginTrans();
context.GetDbClient().Updateable<SystemSetEntity>(a => new SystemSetEntity
{
F_AdminAccount= GlobalContext.SystemConfig.SysemUserCode,
F_AdminPassword = GlobalContext.SystemConfig.SysemUserPwd
}).Where(a => a.F_Id == GlobalContext.SystemConfig.SysemMasterProject).ExecuteCommand();
context.GetDbClient().Updateable<SystemSetEntity>(a => new SystemSetEntity
{
F_AdminAccount = GlobalContext.SystemConfig.SysemUserCode,
F_AdminPassword = GlobalContext.SystemConfig.SysemUserPwd
}).Where(a => a.F_Id == GlobalContext.SystemConfig.SysemMasterProject).ExecuteCommand();
var user = context.GetDbClient().Queryable<UserEntity>().Where(a => a.F_OrganizeId == GlobalContext.SystemConfig.SysemMasterProject && a.F_IsAdmin == true).First();
var userinfo = context.GetDbClient().Queryable<UserLogOnEntity>().Where(a => a.F_UserId == user.F_Id).First();
userinfo.F_UserSecretkey = Md5.md5(Utils.CreateNo(), 16).ToLower();
userinfo.F_UserPassword = Md5.md5(DESEncrypt.Encrypt(Md5.md5(GlobalContext.SystemConfig.SysemUserPwd, 32).ToLower(), userinfo.F_UserSecretkey).ToLower(), 32).ToLower();
context.GetDbClient().Updateable<UserEntity>(a => new UserEntity
{
F_Account = GlobalContext.SystemConfig.SysemUserCode
}).Where(a => a.F_Id == user.F_Id).ExecuteCommand();
context.GetDbClient().Updateable<UserLogOnEntity>(a => new UserLogOnEntity
{
F_UserPassword = userinfo.F_UserPassword,
F_UserSecretkey = userinfo.F_UserSecretkey
}).Where(a => a.F_Id == userinfo.F_Id).ExecuteCommand();
context.Commit();
}
}
}
catch (Exception ex)
{
LogHelper.Write(ex);
}
//清理缓存
//CacheHelper.FlushAll().GetAwaiter().GetResult();
}
//AutoFac注入
public void ConfigureContainer(ContainerBuilder builder)
{
var assemblys = Assembly.Load("WaterCloud.Service");//Service是继承接口的实现方法类库名称
var baseType = typeof(IDenpendency);//IDenpendency 是一个接口(所有要实现依赖注入的借口都要继承该接口)
builder.RegisterAssemblyTypes(assemblys).Where(m => baseType.IsAssignableFrom(m) && m != baseType)
.InstancePerLifetimeScope()//生命周期,这里没有使用接口方式
.PropertiesAutowired() ;//属性注入
//Controller中使用属性注入
var controllerBaseType = typeof(Controller);
builder.RegisterAssemblyTypes(typeof(Program).Assembly)
.Where(t => controllerBaseType.IsAssignableFrom(t) && t != controllerBaseType)
.PropertiesAutowired();
////注入redis
//if (Configuration.GetSection("SystemConfig:CacheProvider").Value== Define.CACHEPROVIDER_REDIS)
//{
// //redis 注入服务
// string redisConnectiong = Configuration.GetSection("SystemConfig:RedisConnectionString").Value;
// // 多客户端
// var redisDB = new CSRedisClient(redisConnectiong + ",defaultDatabase=" + 0);
// RedisHelper.Initialization(redisDB);
// builder.RegisterInstance(redisDB).SingleInstance();//生命周期只能单例
//}
//注册html解析
builder.RegisterInstance(HtmlEncoder.Create(UnicodeRanges.All)).SingleInstance();
//注册特性
builder.RegisterType(typeof(HandlerLoginAttribute)).InstancePerLifetimeScope();
builder.RegisterType(typeof(HandlerAuthorizeAttribute)).InstancePerLifetimeScope();
builder.RegisterType(typeof(HandlerAdminAttribute)).InstancePerLifetimeScope();
builder.RegisterType(typeof(HandlerLockAttribute)).InstancePerLifetimeScope();
////注册ue编辑器
//Config.ConfigFile = "config.json";
//Config.noCache = true;
//var actions = new UEditorActionCollection();
//builder.RegisterInstance(actions).SingleInstance();
//builder.RegisterInstance(typeof(UEditorService)).SingleInstance();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app)
{
//由于.Net Core默认只会从wwwroot目录加载静态文件,其他文件夹的静态文件无法正常访问。
//而我们希望将图片上传到网站根目录的upload文件夹下,所以需要额外在Startup.cs类的Configure方法中
//string resource = Path.Combine(Directory.GetCurrentDirectory(), "upload");
//if (!FileHelper.IsExistDirectory(resource))
//{
// FileHelper.CreateFolder(resource);
//}
//app.UseStaticFiles(new StaticFileOptions
//{
// FileProvider = new PhysicalFileProvider(resource),
// RequestPath = "/upload",
// OnPrepareResponse = ctx =>
// {
// ctx.Context.Response.Headers.Append("Cache-Control", "public,max-age=36000");
// }
//});
//虚拟目录
//如需使用,所有URL修改,例:"/Home/Index"改成'@Url.Content("~/Home/Index")',部署访问首页必须带虚拟目录;
//if (!string.IsNullOrEmpty(GlobalContext.SystemConfig.VirtualDirectory))
//{
// app.UsePathBase(new PathString(GlobalContext.SystemConfig.VirtualDirectory)); // 让 Pathbase 中间件成为第一个处理请求的中间件, 才能正确的模拟虚拟路径
//}
//实时通讯跨域
app.UseCors("CorsPolicy");
if (WebHostEnvironment.IsDevelopment())
{
GlobalContext.SystemConfig.Debug = true;
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Home/Error?msg=404");
}
//文件地址Resource
//静态资源wwwroot
app.UseStaticFiles(new StaticFileOptions
{
ContentTypeProvider = new CustomerFileExtensionContentTypeProvider(),
OnPrepareResponse = GlobalContext.SetCacheControl
});
//启用 Gzip 和 Brotil 压缩功能
app.UseResponseCompression();
//session
app.UseSession();
//路径
app.UseRouting();
//MVC路由
app.UseEndpoints(endpoints =>
{
endpoints.MapHub<MessageHub>("/chatHub");
endpoints.MapControllerRoute("areas", "{area:exists}/{controller=Home}/{action=Index}/{id?}");
endpoints.MapControllerRoute("default", "{controller=Login}/{action=Index}/{id?}");
});
GlobalContext.ServiceProvider = app.ApplicationServices;
}
}
}
| 48.367647 | 193 | 0.571785 | [
"MIT"
] | MonstorUncle/WaterCloud | WaterCloud.Web/Startup.cs | 17,437 | C# |
/*
* Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the workdocs-2016-05-01.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
namespace Amazon.WorkDocs.Model
{
/// <summary>
/// This is the response object from the DeleteDocument operation.
/// </summary>
public partial class DeleteDocumentResponse : AmazonWebServiceResponse
{
}
} | 29.864865 | 106 | 0.733032 | [
"Apache-2.0"
] | Bio2hazard/aws-sdk-net | sdk/src/Services/WorkDocs/Generated/Model/DeleteDocumentResponse.cs | 1,105 | C# |
using Microsoft.Extensions.Logging;
using ChatCore.Config;
using ChatCore.Interfaces;
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Numerics;
namespace ChatCore.Services
{
public class MainSettingsProvider
{
[ConfigSection("WebApp")]
[HTMLIgnore]
[ConfigMeta(Comment = "Set to true to disable the webapp entirely.")]
public bool DisableWebApp = false;
[ConfigMeta(Comment = "Whether or not to launch the webapp in your default browser when ChatCore is started.")]
public bool LaunchWebAppOnStartup = true;
[ConfigMeta(Comment = "The port the webapp will run on.")]
public int WebAppPort = 8338;
[ConfigSection("Global")]
[ConfigMeta(Comment = "When enabled, emojis will be parsed.")]
public bool ParseEmojis = true;
[ConfigSection("Twitch")]
[ConfigMeta(Comment = "When enabled, BetterTwitchTV emotes will be parsed.")]
public bool ParseBTTVEmotes = true;
[ConfigMeta(Comment = "When enabled, FrankerFaceZ emotes will be parsed.")]
public bool ParseFFZEmotes = true;
[ConfigMeta(Comment = "When enabled, Twitch emotes will be parsed.")]
public bool ParseTwitchEmotes = true;
[ConfigMeta(Comment = "When enabled, Twitch cheermotes will be parsed.")]
public bool ParseCheermotes = true;
[ConfigSection("Mixer")]
[ConfigMeta(Comment = "When enabled, Mixer emotes will be parsed.")]
public bool ParseMixerEmotes = true;
public MainSettingsProvider(ILogger<MainSettingsProvider> logger, IPathProvider pathProvider)
{
_logger = logger;
_pathProvider = pathProvider;
_configSerializer = new ObjectSerializer();
string path = Path.Combine(_pathProvider.GetDataPath(), "settings.ini");
_configSerializer.Load(this, path);
_configSerializer.Save(this, path);
}
private ILogger _logger;
private IPathProvider _pathProvider;
private ObjectSerializer _configSerializer;
public void Save()
{
_configSerializer.Save(this, Path.Combine(_pathProvider.GetDataPath(), "settings.ini"));
}
public Dictionary<string, string> GetSettingsAsHTML()
{
return _configSerializer.GetSettingsAsHTML(this);
}
public void SetFromDictionary(Dictionary<string, string> postData)
{
_configSerializer.SetFromDictionary(this, postData);
}
}
}
| 36.478873 | 119 | 0.658687 | [
"MIT"
] | brian91292/ChatCore | ChatCore/Services/MainSettingsProvider.cs | 2,592 | C# |
// ----------------------------------------------------------------------------------
//
// Copyright Microsoft Corporation
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ----------------------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Text;
using ProjectResources = Microsoft.Azure.Commands.ResourceManager.Cmdlets.Properties.Resources;
namespace Microsoft.Azure.Commands.ResourceManager.Cmdlets.Components
{
public class ResourceIdentifier
{
public string ResourceType { get; set; }
public string ResourceGroupName { get; set; }
public string ResourceName { get; set; }
public string ParentResource { get; set; }
public string Subscription { get; set; }
public ResourceIdentifier() { }
public ResourceIdentifier(string idFromServer)
{
if (!string.IsNullOrEmpty(idFromServer))
{
string[] tokens = idFromServer.Split(new[] {'/'}, StringSplitOptions.RemoveEmptyEntries);
if (tokens.Length < 8)
{
throw new ArgumentException(ProjectResources.InvalidFormatOfResourceId, "idFromServer");
}
Subscription = tokens[1];
ResourceGroupName = tokens[3];
ResourceName = tokens[tokens.Length - 1];
List<string> resourceTypeBuilder = new List<string>();
resourceTypeBuilder.Add(tokens[5]);
List<string> parentResourceBuilder = new List<string>();
for (int i = 6; i <= tokens.Length - 3; i++)
{
parentResourceBuilder.Add(tokens[i]);
// Add every other token to type
if (i%2 == 0)
{
resourceTypeBuilder.Add(tokens[i]);
}
}
resourceTypeBuilder.Add(tokens[tokens.Length - 2]);
if (parentResourceBuilder.Count > 0)
{
ParentResource = string.Join("/", parentResourceBuilder);
}
if (resourceTypeBuilder.Count > 0)
{
ResourceType = string.Join("/", resourceTypeBuilder);
}
}
}
public static ResourceIdentifier FromResourceGroupIdentifier(string resourceGroupId)
{
if (!string.IsNullOrEmpty(resourceGroupId))
{
string[] tokens = resourceGroupId.Split(new[] { '/' }, StringSplitOptions.RemoveEmptyEntries);
if (tokens.Length != 4)
{
throw new ArgumentException(ProjectResources.InvalidFormatOfResourceGroupId, "resourceGroupId");
}
return new ResourceIdentifier
{
Subscription = tokens[1],
ResourceGroupName = tokens[3],
};
}
return new ResourceIdentifier();
}
public static string GetProviderFromResourceType(string resourceType)
{
if (resourceType == null)
{
return null;
}
int indexOfSlash = resourceType.IndexOf('/');
if (indexOfSlash < 0)
{
return string.Empty;
}
else
{
return resourceType.Substring(0, indexOfSlash);
}
}
public static string GetTypeFromResourceType(string resourceType)
{
if (resourceType == null)
{
return null;
}
int lastIndexOfSlash = resourceType.LastIndexOf('/');
if (lastIndexOfSlash < 0)
{
return string.Empty;
}
else
{
return resourceType.Substring(lastIndexOfSlash + 1);
}
}
public override string ToString()
{
string provider = GetProviderFromResourceType(ResourceType);
string type = GetTypeFromResourceType(ResourceType);
string parentAndType = string.IsNullOrEmpty(ParentResource) ? type : ParentResource + "/" + type;
StringBuilder resourceId = new StringBuilder();
AppendIfNotNull(resourceId, "/subscriptions/{0}", Subscription);
AppendIfNotNull(resourceId, "/resourceGroups/{0}", ResourceGroupName);
AppendIfNotNull(resourceId, "/providers/{0}", provider);
AppendIfNotNull(resourceId, "/{0}", parentAndType);
AppendIfNotNull(resourceId, "/{0}", ResourceName);
return resourceId.ToString();
}
private void AppendIfNotNull(StringBuilder resourceId, string format, string value)
{
if (!string.IsNullOrEmpty(value))
{
resourceId.AppendFormat(format, value);
}
}
}
}
| 36.916129 | 117 | 0.523593 | [
"MIT"
] | 3quanfeng/azure-powershell | src/Resources/ResourceManager/Components/ResourceIdentifier.cs | 5,570 | C# |
using System.Diagnostics.Contracts;
namespace GitCandy.Ssh.Services
{
public class UserauthArgs
{
public UserauthArgs(string keyAlgorithm, string fingerprint, byte[] key)
{
Contract.Requires(keyAlgorithm != null);
Contract.Requires(fingerprint != null);
Contract.Requires(key != null);
KeyAlgorithm = keyAlgorithm;
Fingerprint = fingerprint;
Key = key;
}
public string KeyAlgorithm { get; private set; }
public string Fingerprint { get; private set; }
public byte[] Key { get; private set; }
public bool Result { get; set; }
}
}
| 28.041667 | 80 | 0.59584 | [
"MIT"
] | Aimeast/GitCandy | GitCandy/Ssh/Services/UserauthArgs.cs | 675 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using BTDB.Buffer;
using BTDB.KVDBLayer;
using Xunit;
namespace BTDBTest
{
public class InMemoryInMemoryKeyValueDBTest
{
[Fact]
public void CreateEmptyDatabase()
{
using (new InMemoryKeyValueDB())
{
}
}
[Fact]
public void EmptyTransaction()
{
using (IKeyValueDB db = new InMemoryKeyValueDB())
{
using (var tr = db.StartTransaction())
{
tr.Commit();
}
}
}
[Fact]
public void EmptyWritingTransaction()
{
using (IKeyValueDB db = new InMemoryKeyValueDB())
{
using (var tr = db.StartWritingTransaction().Result)
{
tr.Commit();
}
}
}
[Fact]
public void FirstTransaction()
{
using (IKeyValueDB db = new InMemoryKeyValueDB())
{
using (var tr = db.StartTransaction())
{
Assert.True(tr.CreateOrUpdateKeyValue(ByteBuffer.NewAsync(_key1), ByteBuffer.NewAsync(new byte[0])));
tr.Commit();
}
}
}
[Fact]
public void CanGetSizeOfPair()
{
using (IKeyValueDB db = new InMemoryKeyValueDB())
{
using (var tr = db.StartTransaction())
{
tr.CreateOrUpdateKeyValue(ByteBuffer.NewAsync(_key1), ByteBuffer.NewAsync(new byte[1]));
var s = tr.GetStorageSizeOfCurrentKey();
Assert.Equal(_key1.Length, (int)s.Key);
Assert.Equal(1u, s.Value);
}
}
}
[Fact]
public void FirstTransactionIsNumber1()
{
using (IKeyValueDB db = new InMemoryKeyValueDB())
{
using (var tr = db.StartTransaction())
{
Assert.Equal(0, tr.GetTransactionNumber());
Assert.True(tr.CreateOrUpdateKeyValue(ByteBuffer.NewAsync(_key1), ByteBuffer.NewAsync(new byte[0])));
Assert.Equal(1, tr.GetTransactionNumber());
tr.Commit();
}
}
}
[Fact]
public void ReadOnlyTransactionThrowsOnWriteAccess()
{
using (IKeyValueDB db = new InMemoryKeyValueDB())
{
using (var tr = db.StartReadOnlyTransaction())
{
Assert.Throws<BTDBTransactionRetryException>(() => tr.CreateKey(new byte[1]));
}
}
}
[Fact]
public void MoreComplexTransaction()
{
using (IKeyValueDB db = new InMemoryKeyValueDB())
{
using (var tr = db.StartTransaction())
{
Assert.True(tr.CreateOrUpdateKeyValue(ByteBuffer.NewAsync(_key1), ByteBuffer.NewAsync(new byte[0])));
Assert.False(tr.CreateOrUpdateKeyValue(ByteBuffer.NewAsync(_key1), ByteBuffer.NewAsync(new byte[0])));
Assert.Equal(FindResult.Previous, tr.Find(ByteBuffer.NewAsync(_key2)));
Assert.True(tr.CreateOrUpdateKeyValue(ByteBuffer.NewAsync(_key2), ByteBuffer.NewAsync(new byte[0])));
Assert.Equal(FindResult.Exact, tr.Find(ByteBuffer.NewAsync(_key1)));
Assert.Equal(FindResult.Exact, tr.Find(ByteBuffer.NewAsync(_key2)));
Assert.Equal(FindResult.Previous, tr.Find(ByteBuffer.NewAsync(_key3)));
Assert.Equal(FindResult.Next, tr.Find(ByteBuffer.NewEmpty()));
tr.Commit();
}
}
}
[Fact]
public void CommitWorks()
{
using (IKeyValueDB db = new InMemoryKeyValueDB())
{
using (var tr1 = db.StartTransaction())
{
tr1.CreateKey(_key1);
using (var tr2 = db.StartTransaction())
{
Assert.Equal(0, tr2.GetTransactionNumber());
Assert.False(tr2.FindExactKey(_key1));
}
tr1.Commit();
}
using (var tr3 = db.StartTransaction())
{
Assert.Equal(1, tr3.GetTransactionNumber());
Assert.True(tr3.FindExactKey(_key1));
}
}
}
[Fact]
public void CommitWithUlongWorks()
{
using (IKeyValueDB db = new InMemoryKeyValueDB())
{
using (var tr1 = db.StartTransaction())
{
Assert.Equal(0ul, tr1.GetCommitUlong());
tr1.SetCommitUlong(42);
tr1.Commit();
}
using (var tr2 = db.StartTransaction())
{
Assert.Equal(42ul, tr2.GetCommitUlong());
}
}
}
[Fact]
public void RollbackWorks()
{
using (IKeyValueDB db = new InMemoryKeyValueDB())
{
using (var tr1 = db.StartTransaction())
{
tr1.CreateKey(_key1);
// Rollback because of missing commit
}
using (var tr2 = db.StartTransaction())
{
Assert.Equal(0, tr2.GetTransactionNumber());
Assert.False(tr2.FindExactKey(_key1));
}
}
}
[Fact]
public void OnlyOneWrittingTransactionPossible()
{
using (IKeyValueDB db = new InMemoryKeyValueDB())
{
using (var tr1 = db.StartTransaction())
{
tr1.CreateKey(_key1);
using (var tr2 = db.StartTransaction())
{
Assert.False(tr2.FindExactKey(_key1));
Assert.Throws<BTDBTransactionRetryException>(() => tr2.CreateKey(_key2));
}
}
}
}
[Fact]
public void OnlyOneWrittingTransactionPossible2()
{
using (IKeyValueDB db = new InMemoryKeyValueDB())
{
var tr1 = db.StartTransaction();
tr1.CreateKey(_key1);
using (var tr2 = db.StartTransaction())
{
tr1.Commit();
tr1.Dispose();
Assert.False(tr2.FindExactKey(_key1));
Assert.Throws<BTDBTransactionRetryException>(() => tr2.CreateKey(_key2));
}
}
}
[Fact]
public void TwoEmptyWriteTransactionsWithNestedWaiting()
{
using (IKeyValueDB db = new InMemoryKeyValueDB())
{
Task<IKeyValueDBTransaction> trOuter;
using (var tr = db.StartWritingTransaction().Result)
{
trOuter = db.StartWritingTransaction();
tr.Commit();
}
using (var tr = trOuter.Result)
{
tr.Commit();
}
}
}
[Theory]
[InlineData(0)]
[InlineData(1)]
[InlineData(2)]
[InlineData(5000)]
[InlineData(1200000)]
public void BiggerKey(int keyLength)
{
var key = new byte[keyLength];
for (int i = 0; i < keyLength; i++) key[i] = (byte)i;
using (IKeyValueDB db = new InMemoryKeyValueDB())
{
using (var tr1 = db.StartTransaction())
{
tr1.CreateKey(key);
tr1.Commit();
}
using (var tr2 = db.StartTransaction())
{
Assert.True(tr2.FindExactKey(key));
Assert.Equal(key, tr2.GetKeyAsByteArray());
}
}
}
[Fact]
public void TwoTransactions()
{
using (IKeyValueDB db = new InMemoryKeyValueDB())
{
using (var tr1 = db.StartTransaction())
{
tr1.CreateKey(_key1);
tr1.Commit();
}
using (var tr2 = db.StartTransaction())
{
tr2.CreateKey(_key2);
Assert.True(tr2.FindExactKey(_key1));
Assert.True(tr2.FindExactKey(_key2));
Assert.False(tr2.FindExactKey(_key3));
tr2.Commit();
}
using (var tr3 = db.StartTransaction())
{
Assert.True(tr3.FindExactKey(_key1));
Assert.True(tr3.FindExactKey(_key2));
Assert.False(tr3.FindExactKey(_key3));
}
}
}
[Theory]
[InlineData(1000)]
public void MultipleTransactions(int transactionCount)
{
using (IKeyValueDB db = new InMemoryKeyValueDB())
{
var key = new byte[2 + transactionCount * 10];
for (int i = 0; i < transactionCount; i++)
{
key[0] = (byte)(i / 256);
key[1] = (byte)(i % 256);
using (var tr1 = db.StartTransaction())
{
tr1.CreateOrUpdateKeyValue(ByteBuffer.NewSync(key, 0, 2 + i * 10), ByteBuffer.NewEmpty());
if (i % 100 == 0 || i == transactionCount - 1)
{
for (int j = 0; j < i; j++)
{
key[0] = (byte)(j / 256);
key[1] = (byte)(j % 256);
Assert.Equal(FindResult.Exact, tr1.Find(ByteBuffer.NewSync(key, 0, 2 + j * 10)));
}
}
tr1.Commit();
}
}
}
}
[Theory]
[InlineData(1000)]
public void MultipleTransactions2(int transactionCount)
{
using (IKeyValueDB db = new InMemoryKeyValueDB())
{
var key = new byte[2 + transactionCount * 10];
for (int i = 0; i < transactionCount; i++)
{
key[0] = (byte)((transactionCount - i) / 256);
key[1] = (byte)((transactionCount - i) % 256);
using (var tr1 = db.StartTransaction())
{
tr1.CreateOrUpdateKeyValue(ByteBuffer.NewSync(key, 0, 2 + i * 10), ByteBuffer.NewEmpty());
if (i % 100 == 0 || i == transactionCount - 1)
{
for (int j = 0; j < i; j++)
{
key[0] = (byte)((transactionCount - j) / 256);
key[1] = (byte)((transactionCount - j) % 256);
Assert.Equal(FindResult.Exact, tr1.Find(ByteBuffer.NewSync(key, 0, 2 + j * 10)));
}
}
tr1.Commit();
}
}
}
}
[Fact]
public void SimpleFindPreviousKeyWorks()
{
using (IKeyValueDB db = new InMemoryKeyValueDB())
{
using (var tr1 = db.StartTransaction())
{
tr1.CreateKey(_key1);
tr1.CreateKey(_key2);
tr1.CreateKey(_key3);
tr1.Commit();
}
using (var tr2 = db.StartTransaction())
{
Assert.True(tr2.FindExactKey(_key3));
Assert.True(tr2.FindPreviousKey());
Assert.Equal(_key1, tr2.GetKeyAsByteArray());
Assert.False(tr2.FindPreviousKey());
}
}
}
[Fact]
public void FindKeyWithPreferPreviousKeyWorks()
{
const int keyCount = 10000;
using (IKeyValueDB db = new InMemoryKeyValueDB())
{
using (var tr = db.StartTransaction())
{
var key = new byte[100];
for (int i = 0; i < keyCount; i++)
{
key[0] = (byte)(i / 256);
key[1] = (byte)(i % 256);
tr.CreateKey(key);
}
tr.Commit();
}
using (var tr = db.StartTransaction())
{
var key = new byte[101];
for (int i = 0; i < keyCount; i++)
{
key[0] = (byte)(i / 256);
key[1] = (byte)(i % 256);
var findKeyResult = tr.Find(ByteBuffer.NewSync(key));
Assert.Equal(FindResult.Previous, findKeyResult);
Assert.Equal(i, tr.GetKeyIndex());
}
}
using (var tr = db.StartTransaction())
{
var key = new byte[99];
for (int i = 0; i < keyCount; i++)
{
key[0] = (byte)(i / 256);
key[1] = (byte)(i % 256);
var findKeyResult = tr.Find(ByteBuffer.NewSync(key));
if (i == 0)
{
Assert.Equal(FindResult.Next, findKeyResult);
Assert.Equal(i, tr.GetKeyIndex());
}
else
{
Assert.Equal(FindResult.Previous, findKeyResult);
Assert.Equal(i - 1, tr.GetKeyIndex());
}
}
}
}
}
[Fact]
public void SimpleFindNextKeyWorks()
{
using (IKeyValueDB db = new InMemoryKeyValueDB())
{
using (var tr1 = db.StartTransaction())
{
tr1.CreateKey(_key1);
tr1.CreateKey(_key2);
tr1.CreateKey(_key3);
tr1.Commit();
}
using (var tr2 = db.StartTransaction())
{
Assert.True(tr2.FindExactKey(_key3));
Assert.True(tr2.FindNextKey());
Assert.Equal(_key2, tr2.GetKeyAsByteArray());
Assert.False(tr2.FindNextKey());
}
}
}
[Fact]
public void AdvancedFindPreviousAndNextKeyWorks()
{
using (IKeyValueDB db = new InMemoryKeyValueDB())
{
var key = new byte[2];
const int keysCreated = 10000;
using (var tr = db.StartTransaction())
{
for (int i = 0; i < keysCreated; i++)
{
key[0] = (byte)(i / 256);
key[1] = (byte)(i % 256);
tr.CreateKey(key);
}
tr.Commit();
}
using (var tr = db.StartTransaction())
{
Assert.Equal(-1, tr.GetKeyIndex());
tr.FindExactKey(key);
Assert.Equal(keysCreated - 1, tr.GetKeyIndex());
for (int i = 1; i < keysCreated; i++)
{
Assert.True(tr.FindPreviousKey());
Assert.Equal(keysCreated - 1 - i, tr.GetKeyIndex());
}
Assert.False(tr.FindPreviousKey());
Assert.Equal(-1, tr.GetKeyIndex());
for (int i = 0; i < keysCreated; i++)
{
Assert.True(tr.FindNextKey());
Assert.Equal(i, tr.GetKeyIndex());
}
Assert.False(tr.FindNextKey());
Assert.Equal(-1, tr.GetKeyIndex());
}
}
}
[Fact]
public void SetKeyIndexWorks()
{
using (IKeyValueDB db = new InMemoryKeyValueDB())
{
var key = new byte[2];
const int keysCreated = 10000;
using (var tr = db.StartTransaction())
{
for (int i = 0; i < keysCreated; i++)
{
key[0] = (byte)(i / 256);
key[1] = (byte)(i % 256);
tr.CreateKey(key);
}
tr.Commit();
}
using (var tr = db.StartTransaction())
{
Assert.False(tr.SetKeyIndex(keysCreated));
for (int i = 0; i < keysCreated; i += 5)
{
Assert.True(tr.SetKeyIndex(i));
key = tr.GetKeyAsByteArray();
Assert.Equal((byte)(i / 256), key[0]);
Assert.Equal((byte)(i % 256), key[1]);
Assert.Equal(i, tr.GetKeyIndex());
}
}
}
}
[Theory]
[InlineData(0)]
[InlineData(1)]
[InlineData(2)]
[InlineData(3)]
[InlineData(4)]
[InlineData(5)]
[InlineData(6)]
[InlineData(7)]
[InlineData(8)]
[InlineData(256)]
[InlineData(5000)]
[InlineData(10000000)]
public void CreateOrUpdateKeyValueWorks(int length)
{
var valbuf = new byte[length];
new Random(0).NextBytes(valbuf);
using (IKeyValueDB db = new InMemoryKeyValueDB())
{
using (var tr1 = db.StartTransaction())
{
Assert.True(tr1.CreateOrUpdateKeyValueUnsafe(_key1, valbuf));
Assert.False(tr1.CreateOrUpdateKeyValueUnsafe(_key1, valbuf));
Assert.True(tr1.CreateOrUpdateKeyValueUnsafe(_key2, valbuf));
tr1.Commit();
}
using (var tr2 = db.StartTransaction())
{
Assert.True(tr2.FindExactKey(_key1));
var valbuf2 = tr2.GetValueAsByteArray();
for (int i = 0; i < length; i++)
{
if (valbuf[i] != valbuf2[i])
Assert.Equal(valbuf[i], valbuf2[i]);
}
Assert.True(tr2.FindExactKey(_key2));
valbuf2 = tr2.GetValueAsByteArray();
for (int i = 0; i < length; i++)
{
if (valbuf[i] != valbuf2[i])
Assert.Equal(valbuf[i], valbuf2[i]);
}
}
}
}
[Fact]
public void FindFirstKeyWorks()
{
using (IKeyValueDB db = new InMemoryKeyValueDB())
{
using (var tr = db.StartTransaction())
{
Assert.False(tr.FindFirstKey());
tr.CreateKey(_key1);
tr.CreateKey(_key2);
tr.CreateKey(_key3);
Assert.True(tr.FindFirstKey());
Assert.Equal(_key1, tr.GetKeyAsByteArray());
tr.Commit();
}
}
}
[Fact]
public void FindLastKeyWorks()
{
using (IKeyValueDB db = new InMemoryKeyValueDB())
{
using (var tr = db.StartTransaction())
{
Assert.False(tr.FindLastKey());
tr.CreateKey(_key1);
tr.CreateKey(_key2);
tr.CreateKey(_key3);
Assert.True(tr.FindLastKey());
Assert.Equal(_key2, tr.GetKeyAsByteArray());
tr.Commit();
}
}
}
[Fact]
public void SimplePrefixWorks()
{
using (IKeyValueDB db = new InMemoryKeyValueDB())
{
using (var tr = db.StartTransaction())
{
tr.CreateKey(_key1);
tr.CreateKey(_key2);
tr.CreateKey(_key3);
Assert.Equal(3, tr.GetKeyValueCount());
tr.SetKeyPrefix(ByteBuffer.NewAsync(_key1, 0, 3));
Assert.Equal(2, tr.GetKeyValueCount());
tr.FindFirstKey();
Assert.Equal(new byte[0], tr.GetKeyAsByteArray());
tr.FindLastKey();
Assert.Equal(_key3.Skip(3).ToArray(), tr.GetKeyAsByteArray());
tr.Commit();
}
}
}
[Fact]
public void PrefixWithFindNextKeyWorks()
{
using (IKeyValueDB db = new InMemoryKeyValueDB())
{
using (var tr = db.StartTransaction())
{
tr.CreateKey(_key1);
tr.CreateKey(_key2);
tr.SetKeyPrefix(ByteBuffer.NewAsync(_key2, 0, 1));
Assert.True(tr.FindFirstKey());
Assert.True(tr.FindNextKey());
Assert.False(tr.FindNextKey());
tr.Commit();
}
}
}
[Fact]
public void PrefixWithFindPrevKeyWorks()
{
using (IKeyValueDB db = new InMemoryKeyValueDB())
{
using (var tr = db.StartTransaction())
{
tr.CreateKey(_key1);
tr.CreateKey(_key2);
tr.SetKeyPrefix(ByteBuffer.NewAsync(_key2, 0, 1));
Assert.True(tr.FindFirstKey());
Assert.False(tr.FindPreviousKey());
tr.Commit();
}
}
}
[Fact]
public void SimpleEraseCurrentWorks()
{
using (IKeyValueDB db = new InMemoryKeyValueDB())
{
using (var tr = db.StartTransaction())
{
tr.CreateKey(_key1);
tr.CreateKey(_key2);
tr.CreateKey(_key3);
tr.EraseCurrent();
Assert.True(tr.FindFirstKey());
Assert.Equal(_key1, tr.GetKeyAsByteArray());
Assert.True(tr.FindNextKey());
Assert.Equal(_key2, tr.GetKeyAsByteArray());
Assert.False(tr.FindNextKey());
Assert.Equal(2, tr.GetKeyValueCount());
}
}
}
[Fact]
public void AdvancedEraseRangeWorks()
{
foreach(var range in EraseRangeSource())
AdvancedEraseRangeWorks(range[0], range[1], range[2]);
}
public void AdvancedEraseRangeWorks(int createKeys, int removeStart, int removeCount)
{
using (IKeyValueDB db = new InMemoryKeyValueDB())
{
var key = new byte[2];
using (var tr = db.StartTransaction())
{
for (int i = 0; i < createKeys; i++)
{
key[0] = (byte)(i / 256);
key[1] = (byte)(i % 256);
tr.CreateKey(key);
}
tr.Commit();
}
using (var tr = db.StartTransaction())
{
tr.EraseRange(removeStart, removeStart + removeCount - 1);
Assert.Equal(createKeys - removeCount, tr.GetKeyValueCount());
tr.Commit();
}
using (var tr = db.StartTransaction())
{
Assert.Equal(createKeys - removeCount, tr.GetKeyValueCount());
for (int i = 0; i < createKeys; i++)
{
key[0] = (byte)(i / 256);
key[1] = (byte)(i % 256);
if (i >= removeStart && i < removeStart + removeCount)
{
Assert.False(tr.FindExactKey(key), $"{i} should be removed");
}
else
{
Assert.True(tr.FindExactKey(key), $"{i} should be found");
}
}
}
}
}
// ReSharper disable UnusedMember.Global
public static IEnumerable<int[]> EraseRangeSource()
// ReSharper restore UnusedMember.Global
{
yield return new[] { 1, 0, 1 };
for (int i = 11; i < 1000; i += i)
{
yield return new[] { i, 0, 1 };
yield return new[] { i, i - 1, 1 };
yield return new[] { i, i / 2, 1 };
yield return new[] { i, i / 2, i / 4 };
yield return new[] { i, i / 4, 1 };
yield return new[] { i, i / 4, i / 2 };
yield return new[] { i, i - i / 2, i / 2 };
yield return new[] { i, 0, i / 2 };
yield return new[] { i, 3 * i / 4, 1 };
yield return new[] { i, 0, i };
}
}
[Fact]
public void ALotOf5KBTransactionsWorks()
{
using (IKeyValueDB db = new InMemoryKeyValueDB())
{
for (int i = 0; i < 5000; i++)
{
var key = new byte[5000];
using (var tr = db.StartTransaction())
{
key[0] = (byte)(i / 256);
key[1] = (byte)(i % 256);
Assert.True(tr.CreateKey(key));
tr.Commit();
}
}
}
}
[Fact]
public void SetKeyPrefixInOneTransaction()
{
using (IKeyValueDB db = new InMemoryKeyValueDB())
{
var key = new byte[5];
var value = new byte[100];
var rnd = new Random();
using (var tr = db.StartTransaction())
{
for (byte i = 0; i < 100; i++)
{
key[0] = i;
for (byte j = 0; j < 100; j++)
{
key[4] = j;
rnd.NextBytes(value);
tr.CreateOrUpdateKeyValue(key, value);
}
}
tr.Commit();
}
using (var tr = db.StartTransaction())
{
for (byte i = 0; i < 100; i++)
{
key[0] = i;
tr.SetKeyPrefix(ByteBuffer.NewSync(key, 0, 4));
Assert.Equal(100, tr.GetKeyValueCount());
}
}
}
}
[Fact]
public void CompressibleValueLoad()
{
using (IKeyValueDB db = new InMemoryKeyValueDB())
{
using (var tr = db.StartTransaction())
{
tr.CreateOrUpdateKeyValue(_key1, new byte[1000]);
Assert.Equal(new byte[1000], tr.GetValueAsByteArray());
tr.Commit();
}
}
}
[Fact]
public void StartWritingTransactionWorks()
{
using (IKeyValueDB db = new InMemoryKeyValueDB())
{
var tr1 = db.StartWritingTransaction().Result;
var tr2Task = db.StartWritingTransaction();
var task = Task.Factory.StartNew(() =>
{
var tr2 = tr2Task.Result;
Assert.True(tr2.FindExactKey(_key1));
tr2.CreateKey(_key2);
tr2.Commit();
tr2.Dispose();
});
tr1.CreateKey(_key1);
tr1.Commit();
tr1.Dispose();
task.Wait(1000);
using (var tr = db.StartTransaction())
{
Assert.True(tr.FindExactKey(_key1));
Assert.True(tr.FindExactKey(_key2));
}
}
}
readonly byte[] _key1 = { 1, 2, 3 };
readonly byte[] _key2 = { 1, 3, 2 };
readonly byte[] _key3 = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 };
}
} | 35.673054 | 122 | 0.406318 | [
"MIT"
] | danaph7t/BTDB | BTDBTest/InMemoryKeyValueDBTest.cs | 29,787 | C# |
// Copyright (c) Microsoft Corporation. All Rights Reserved.
// Licensed under the MIT License.
using Datasync.Common.Test.Models;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Datasync;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using System;
using System.Diagnostics.CodeAnalysis;
using System.Threading;
using System.Threading.Tasks;
namespace Datasync.Webservice.Controllers
{
[AllowAnonymous]
[Route("tables/movies_rated")]
[ExcludeFromCodeCoverage(Justification = "Test suite")]
public class RRatedMoviesController : TableController<InMemoryMovie>, IAccessControlProvider<InMemoryMovie>
{
public RRatedMoviesController(IRepository<InMemoryMovie> repository, ILogger<InMemoryMovie> logger) : base(repository)
{
AccessControlProvider = this;
Logger = logger;
}
/// <summary>
/// Provides a function used in a LINQ <see cref="Where{TEntity}"/> clause to limit
/// the data that the client can see. Return null to provide all data.
/// </summary>
/// <returns>A LINQ <see cref="Where{TEntity}"/> function, or null for all data.</returns>
public virtual Func<InMemoryMovie, bool> GetDataView() => movie => movie.Rating == "R";
/// <summary>
/// Determines if the user is authorized to see the data provided for the purposes of the operation.
/// </summary>
/// <param name="operation">The operation being performed</param>
/// <param name="entity">The entity being handled (null if more than one entity)</param>
/// <param name="token">A cancellation token</param>
/// <returns>True if the client is allowed to perform the operation</returns>
public virtual Task<bool> IsAuthorizedAsync(TableOperation operation, InMemoryMovie entity, CancellationToken token = default)
=> Task.FromResult(HttpContext.User?.Identity?.IsAuthenticated == true);
/// <summary>
/// Allows the user to set up any modifications that are necessary to support the chosen access control rules.
/// Called immediately before writing to the data store.
/// </summary>
/// <param name="operation">The operation being performed</param>
/// <param name="entity">The entity being handled</param>
/// <param name="token">A cancellation token</param>
public virtual Task PreCommitHookAsync(TableOperation operation, InMemoryMovie entity, CancellationToken token = default)
{
entity.Title = entity.Title.ToUpper();
return Task.CompletedTask;
}
}
}
| 46.017241 | 134 | 0.682653 | [
"MIT"
] | Azure/azure-mobile-apps | sdk/dotnet/test/Datasync.Webservice/Controllers/RRatedMoviesController.cs | 2,671 | C# |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
namespace InterviewTeaChallenge
{
public class Program
{
public static void Main(string[] args)
{
BuildWebHost(args).Run();
}
public static IWebHost BuildWebHost(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>()
.Build();
}
}
| 23.5 | 61 | 0.667758 | [
"MIT"
] | jamesoneill/InterviewTeaChallenge | InterviewTeaChallenge/InterviewTeaChallenge/Program.cs | 613 | C# |
// <license>
// The MIT License (MIT)
// </license>
// <copyright company="TTRider Technologies, Inc.">
// Copyright (c) 2014-2015 All Rights Reserved
// </copyright>
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Common;
using System.Linq;
using System.Text;
namespace TTRider.FluidSql
{
public static class FluidExtensions
{
static IEnumerable<Name> ToNames(Name name, params Name[] names)
{
if (name != null) yield return name;
foreach (var nm in names)
{
yield return nm;
}
}
static IEnumerable<Name> ToNames(string name, params string[] names)
{
if (name != null) yield return name;
foreach (var nm in names)
{
yield return nm;
}
}
static IEnumerable<Name> ToNames(IEnumerable<string> names)
{
if (names != null)
{
foreach (var nm in names)
{
yield return nm;
}
}
}
static IEnumerable<Order> ToOrders(Order order, params Order[] orders)
{
if (order != null) yield return order;
foreach (var nm in orders)
{
yield return nm;
}
}
static IEnumerable<Order> ToOrders(string order, params string[] orders)
{
if (order != null) yield return Sql.Order(order);
foreach (var nm in orders)
{
yield return Sql.Order(nm);
}
}
public static IDataParameterCollection SetValue(this IDataParameterCollection parameterCollection,
string parameterName, object value)
{
if (parameterCollection == null) throw new ArgumentNullException(nameof(parameterCollection));
if (string.IsNullOrWhiteSpace(parameterName)) throw new ArgumentNullException(nameof(parameterName));
if (parameterCollection.Contains(parameterName))
{
((DbParameter)parameterCollection[parameterName]).Value = value;
}
return parameterCollection;
}
public static Parameter DefaultValue(this Parameter parameter, object defaultValue)
{
parameter.DefaultValue = defaultValue;
return parameter;
}
public static Parameter Value(this Parameter parameter, object Value)
{
parameter.Value = Value;
return parameter;
}
public static Parameter ParameterDirection(this Parameter parameter, ParameterDirection direction)
{
parameter.Direction = direction;
return parameter;
}
public static Parameter UseDefault(this Parameter parameter, bool useDefault = true)
{
parameter.UseDefault = useDefault;
return parameter;
}
public static Parameter ReadOnly(this Parameter parameter, bool readOnly = true)
{
parameter.ReadOnly = readOnly;
return parameter;
}
public static IList<ParameterValue> Add(this IList<ParameterValue> list, string name, object value)
{
list.Add(new ParameterValue { Name = name, Value = value });
return list;
}
public static T As<T>(this T token, string alias)
where T : IAliasToken
{
if (!string.IsNullOrWhiteSpace(alias))
{
token.Alias = alias;
}
return token;
}
public static SelectStatement Distinct(this SelectStatement statement, bool distinct = true)
{
statement.Distinct = distinct;
return statement;
}
public static SelectStatement All(this SelectStatement statement, bool all = true)
{
statement.Distinct = !all;
return statement;
}
public static SelectStatement Output(this SelectStatement statement, params ExpressionToken[] columns)
{
statement.Output.AddRange(columns);
return statement;
}
public static SelectStatement Output(this SelectStatement statement, IEnumerable<ExpressionToken> columns)
{
if (columns != null)
{
statement.Output.AddRange(columns);
}
return statement;
}
public static AssignToken SetTo(this Name target, ExpressionToken expression)
{
return new AssignToken { First = target, Second = expression };
}
public static T Assign<T>(this T statement, Parameter target, ExpressionToken expression)
where T : ISetStatement
{
statement.Set.Add(new AssignToken { First = target, Second = expression });
return statement;
}
public static T Set<T>(this T statement, Parameter target, ExpressionToken expression)
where T : ISetStatement
{
statement.Set.Add(new AssignToken { First = target, Second = expression });
return statement;
}
public static T PlusAssign<T>(this T statement, Parameter target, ExpressionToken expression)
where T : ISetStatement
{
statement.Set.Add(new PlusToken { First = target, Second = expression, Equal = true });
return statement;
}
public static T MinusAssign<T>(this T statement, Parameter target, ExpressionToken expression)
where T : ISetStatement
{
statement.Set.Add(new MinusToken { First = target, Second = expression, Equal = true });
return statement;
}
public static T DivideAssign<T>(this T statement, Parameter target, ExpressionToken expression)
where T : ISetStatement
{
statement.Set.Add(new DivideToken { First = target, Second = expression, Equal = true });
return statement;
}
public static T BitwiseAndAssign<T>(this T statement, Parameter target, ExpressionToken expression)
where T : ISetStatement
{
statement.Set.Add(new BitwiseAndToken { First = target, Second = expression, Equal = true });
return statement;
}
public static T BitwiseOrAssign<T>(this T statement, Parameter target, ExpressionToken expression)
where T : ISetStatement
{
statement.Set.Add(new BitwiseOrToken { First = target, Second = expression, Equal = true });
return statement;
}
public static T BitwiseXorAssign<T>(this T statement, Parameter target, ExpressionToken expression)
where T : ISetStatement
{
statement.Set.Add(new BitwiseXorToken { First = target, Second = expression, Equal = true });
return statement;
}
public static T ModuloAssign<T>(this T statement, Parameter target, ExpressionToken expression)
where T : ISetStatement
{
statement.Set.Add(new ModuloToken { First = target, Second = expression, Equal = true });
return statement;
}
public static T MultiplyAssign<T>(this T statement, Parameter target, ExpressionToken expression)
where T : ISetStatement
{
statement.Set.Add(new MultiplyToken { First = target, Second = expression, Equal = true });
return statement;
}
//public static T BitwiseNotAssign<T>(this T statement, Parameter target, ExpressionToken expression)
// where T : ISetStatement
//{
// statement.Set.Add(new BitwiseNotToken { First = target, Second = expression, Equal = true });
// return statement;
//}
public static T Assign<T>(this T statement, Name target, ExpressionToken expression)
where T : ISetStatement
{
statement.Set.Add(new AssignToken { First = target, Second = expression });
return statement;
}
public static T Set<T>(this T statement, Name target, ExpressionToken expression)
where T : ISetStatement
{
statement.Set.Add(new AssignToken { First = target, Second = expression });
return statement;
}
public static T Set<T>(this T statement, IList<BinaryEqualToken> setList)
where T : ISetStatement
{
if (setList != null)
{
foreach (BinaryEqualToken item in setList)
statement.Set.Add(item);
}
return statement;
}
public static T PlusAssign<T>(this T statement, Name target, ExpressionToken expression)
where T : ISetStatement
{
statement.Set.Add(new PlusToken { First = target, Second = expression, Equal = true });
return statement;
}
public static T MinusAssign<T>(this T statement, Name target, ExpressionToken expression)
where T : ISetStatement
{
statement.Set.Add(new MinusToken { First = target, Second = expression, Equal = true });
return statement;
}
public static T DivideAssign<T>(this T statement, Name target, ExpressionToken expression)
where T : ISetStatement
{
statement.Set.Add(new DivideToken { First = target, Second = expression, Equal = true });
return statement;
}
public static T BitwiseAndAssign<T>(this T statement, Name target, ExpressionToken expression)
where T : ISetStatement
{
statement.Set.Add(new BitwiseAndToken { First = target, Second = expression, Equal = true });
return statement;
}
public static T BitwiseOrAssign<T>(this T statement, Name target, ExpressionToken expression)
where T : ISetStatement
{
statement.Set.Add(new BitwiseOrToken { First = target, Second = expression, Equal = true });
return statement;
}
public static T BitwiseXorAssign<T>(this T statement, Name target, ExpressionToken expression)
where T : ISetStatement
{
statement.Set.Add(new BitwiseXorToken { First = target, Second = expression, Equal = true });
return statement;
}
public static T ModuloAssign<T>(this T statement, Name target, ExpressionToken expression)
where T : ISetStatement
{
statement.Set.Add(new ModuloToken { First = target, Second = expression, Equal = true });
return statement;
}
public static T MultiplyAssign<T>(this T statement, Name target, ExpressionToken expression)
where T : ISetStatement
{
statement.Set.Add(new MultiplyToken { First = target, Second = expression, Equal = true });
return statement;
}
//public static T BitwiseNotAssign<T>(this T statement, Name target, ExpressionToken expression)
// where T : ISetStatement
//{
// statement.Set.Add(new BitwiseNotToken { First = target, Second = expression, Equal = true });
// return statement;
//}
public static T Output<T>(this T statement, params Name[] columns)
where T : RecordsetStatement
{
statement.Output.AddRange(columns);
return statement;
}
public static T Output<T>(this T statement, IEnumerable<Name> columns)
where T : RecordsetStatement
{
if (columns != null)
{
statement.Output.AddRange(columns);
}
return statement;
}
public static T Output<T>(this T statement, IEnumerable<string> columns)
where T : RecordsetStatement
{
if (columns != null)
{
statement.Output.AddRange(columns.Select(s => Sql.Name(s)));
}
return statement;
}
public static T OutputInto<T>(this T statement, Name target, params Name[] columns)
where T : RecordsetStatement
{
statement.Output.AddRange(columns);
statement.OutputInto = target;
return statement;
}
public static T OutputInto<T>(this T statement, Name target, params ExpressionToken[] columns)
where T : RecordsetStatement
{
statement.Output.AddRange(columns);
statement.OutputInto = target;
return statement;
}
public static T OutputInto<T>(this T statement, Name target, IEnumerable<Name> columns)
where T : RecordsetStatement
{
if (columns != null)
{
statement.Output.AddRange(columns);
}
statement.OutputInto = target;
return statement;
}
public static T OutputInto<T>(this T statement, Name target, IEnumerable<ExpressionToken> columns)
where T : RecordsetStatement
{
if (columns != null)
{
statement.Output.AddRange(columns);
}
statement.OutputInto = target;
return statement;
}
public static T OutputInto<T>(this T statement, Name target, IEnumerable<string> columns)
where T : RecordsetStatement
{
if (columns != null)
{
statement.Output.AddRange(columns.Select(s => Sql.Name(s)));
}
statement.OutputInto = target;
return statement;
}
public static T Into<T>(this T statement, Name target)
where T : IIntoStatement
{
statement.Into = target;
return statement;
}
public static SelectStatement GroupBy(this SelectStatement statement, params Name[] columns)
{
statement.GroupBy.AddRange(columns);
return statement;
}
public static SelectStatement GroupBy(this SelectStatement statement, IEnumerable<Name> columns)
{
if (columns != null)
{
statement.GroupBy.AddRange(columns);
}
return statement;
}
public static SelectStatement GroupBy(this SelectStatement statement, params string[] columns)
{
statement.GroupBy.AddRange(columns.Select(name => Sql.Name(name)));
return statement;
}
public static SelectStatement GroupBy(this SelectStatement statement, IEnumerable<string> columns)
{
if (columns != null)
{
statement.GroupBy.AddRange(columns.Select(name => Sql.Name(name)));
}
return statement;
}
public static T OrderBy<T>(this T statement, Name column,
Direction direction = Direction.Asc)
where T : IOrderByStatement
{
statement.OrderBy.Add(Sql.Order(column, direction));
return statement;
}
public static T OrderBy<T>(this T statement, string column,
Direction direction = Direction.Asc)
where T : IOrderByStatement
{
statement.OrderBy.Add(Sql.Order(column, direction));
return statement;
}
public static T OrderBy<T>(this T statement, params Order[] columns)
where T : IOrderByStatement
{
statement.OrderBy.AddRange(columns);
return statement;
}
public static T OrderBy<T>(this T statement, IEnumerable<Order> columns)
where T : IOrderByStatement
{
if (columns != null)
{
statement.OrderBy.AddRange(columns);
}
return statement;
}
public static SelectStatement From(this SelectStatement statement, string name, string alias = null)
{
statement.From.Add(new RecordsetSourceToken { Source = Sql.Name(name), Alias = alias });
return statement;
}
public static SelectStatement From(this SelectStatement statement, RecordsetSourceToken token,
string alias = null)
{
statement.From.Add(token.As(alias));
return statement;
}
public static SelectStatement From(this SelectStatement statement, List<RecordsetSourceToken> token, string alias = null)
{
statement.From.AddRange(token);
return statement;
}
public static DeleteStatement From(this DeleteStatement statement, Token token)
{
statement.RecordsetSource = new RecordsetSourceToken { Source = token };
return statement;
}
public static UpdateStatement From(this UpdateStatement statement, Token token)
{
statement.RecordsetSource = new RecordsetSourceToken { Source = token };
return statement;
}
public static MergeStatement Using(this MergeStatement statement, RecordsetStatement token, string alias = null)
{
statement.Using = token.As(alias);
return statement;
}
public static MergeStatement Using(this MergeStatement statement, Name token, string alias = null)
{
statement.Using = token.As(alias);
return statement;
}
public static MergeStatement On(this MergeStatement statement, Token token)
{
statement.On = token;
return statement;
}
public static MergeStatement WhenMatchedThenDelete(this MergeStatement statement, Token andCondition = null)
{
statement.WhenMatched.Add(new WhenMatchedTokenThenDeleteToken
{
AndCondition = andCondition
});
return statement;
}
public static MergeStatement WhenMatchedThenUpdateSet(this MergeStatement statement,
IEnumerable<AssignToken> set)
{
var wm = new WhenMatchedTokenThenUpdateSetToken();
if (set != null)
{
foreach (var columnValue in set)
{
wm.Set.Add(columnValue);
}
}
statement.WhenMatched.Add(wm);
return statement;
}
public static MergeStatement WhenMatchedThenUpdateSet(this MergeStatement statement, params AssignToken[] set)
{
return WhenMatchedThenUpdateSet(statement, (IEnumerable<AssignToken>)set);
}
public static MergeStatement WhenMatchedThenUpdateSet(this MergeStatement statement, Token andCondition,
IEnumerable<AssignToken> set)
{
var wm = new WhenMatchedTokenThenUpdateSetToken
{
AndCondition = andCondition
};
if (set != null)
{
foreach (var columnValue in set)
{
wm.Set.Add(columnValue);
}
}
statement.WhenMatched.Add(wm);
return statement;
}
public static MergeStatement WhenMatchedThenUpdateSet(this MergeStatement statement, Token andCondition,
params AssignToken[] set)
{
return WhenMatchedThenUpdateSet(statement, andCondition, (IEnumerable<AssignToken>)set);
}
public static MergeStatement WhenNotMatchedBySourceThenDelete(this MergeStatement statement,
Token andCondition = null)
{
statement.WhenNotMatchedBySource.Add(new WhenMatchedTokenThenDeleteToken
{
AndCondition = andCondition
});
return statement;
}
public static MergeStatement WhenNotMatchedBySourceThenUpdate(this MergeStatement statement, Token andCondition,
IEnumerable<AssignToken> set)
{
var wm = new WhenMatchedTokenThenUpdateSetToken
{
AndCondition = andCondition
};
if (set != null)
{
foreach (var columnValue in set)
{
wm.Set.Add(columnValue);
}
}
statement.WhenNotMatchedBySource.Add(wm);
return statement;
}
public static MergeStatement WhenNotMatchedBySourceThenUpdate(this MergeStatement statement, Token andCondition,
params AssignToken[] set)
{
return WhenNotMatchedBySourceThenUpdate(statement, andCondition, (IEnumerable<AssignToken>)set);
}
public static MergeStatement WhenNotMatchedBySourceThenUpdate(this MergeStatement statement,
params AssignToken[] set)
{
return WhenNotMatchedBySourceThenUpdate(statement, null, (IEnumerable<AssignToken>)set);
}
public static MergeStatement WhenNotMatchedBySourceThenUpdate(this MergeStatement statement,
IEnumerable<AssignToken> set)
{
return WhenNotMatchedBySourceThenUpdate(statement, null, set);
}
public static MergeStatement WhenNotMatchedThenInsert(this MergeStatement statement, IEnumerable<Name> columns)
{
var wm = new WhenNotMatchedTokenThenInsertToken();
if (columns != null)
{
foreach (var column in columns)
{
wm.Columns.Add(column);
}
}
statement.WhenNotMatched.Add(wm);
return statement;
}
public static MergeStatement WhenNotMatchedThenInsert(this MergeStatement statement, Token andCondition,
IEnumerable<Name> columns)
{
var wm = new WhenNotMatchedTokenThenInsertToken
{
AndCondition = andCondition
};
if (columns != null)
{
foreach (var column in columns)
{
wm.Columns.Add(column);
}
}
statement.WhenNotMatched.Add(wm);
return statement;
}
public static MergeStatement WhenNotMatchedThenInsert(this MergeStatement statement, IEnumerable<Name> columns,
IEnumerable<Name> values)
{
var wm = new WhenNotMatchedTokenThenInsertToken();
if (columns != null)
{
foreach (var column in columns)
{
wm.Columns.Add(column);
}
}
if (values != null)
{
foreach (var value in values)
{
wm.Values.Add(value);
}
}
statement.WhenNotMatched.Add(wm);
return statement;
}
public static MergeStatement WhenNotMatchedThenInsert(this MergeStatement statement, Token andCondition,
IEnumerable<Name> columns, IEnumerable<Name> values)
{
var wm = new WhenNotMatchedTokenThenInsertToken
{
AndCondition = andCondition
};
if (columns != null)
{
foreach (var column in columns)
{
wm.Columns.Add(column);
}
}
if (values != null)
{
foreach (var value in values)
{
wm.Values.Add(value);
}
}
statement.WhenNotMatched.Add(wm);
return statement;
}
public static MergeStatement WhenNotMatchedThenInsert(this MergeStatement statement, params Name[] columns)
{
var wm = new WhenNotMatchedTokenThenInsertToken();
if (columns != null)
{
foreach (var column in columns)
{
wm.Columns.Add(column);
}
}
statement.WhenNotMatched.Add(wm);
return statement;
}
public static MergeStatement WhenNotMatchedThenInsert(this MergeStatement statement, Token andCondition,
params Name[] columns)
{
var wm = new WhenNotMatchedTokenThenInsertToken
{
AndCondition = andCondition
};
if (columns != null)
{
foreach (var column in columns)
{
wm.Columns.Add(column);
}
}
statement.WhenNotMatched.Add(wm);
return statement;
}
public static InsertStatement From(this InsertStatement statement, RecordsetStatement recordset)
{
statement.From = recordset;
return statement;
}
public static InsertStatement IdentityInsert(this InsertStatement statement, bool value = true)
{
statement.IdentityInsert = value;
return statement;
}
public static UnionStatement Union(this RecordsetStatement statement, RecordsetStatement with)
{
return new UnionStatement(statement, with);
}
public static UnionStatement UnionAll(this RecordsetStatement statement, RecordsetStatement with)
{
return new UnionStatement(statement, with, true);
}
public static UnionStatement UnionDistinct(this RecordsetStatement statement, RecordsetStatement with)
{
return new UnionStatement(statement, with, false);
}
public static ExceptStatement Except(this RecordsetStatement statement, RecordsetStatement with)
{
return new ExceptStatement(statement, with, false);
}
public static ExceptStatement ExceptAll(this RecordsetStatement statement, RecordsetStatement with)
{
return new ExceptStatement(statement, with, true);
}
public static ExceptStatement ExceptDistinct(this RecordsetStatement statement, RecordsetStatement with)
{
return new ExceptStatement(statement, with, false);
}
public static IntersectStatement Intersect(this RecordsetStatement statement, RecordsetStatement with)
{
return new IntersectStatement(statement, with, false);
}
public static IntersectStatement IntersectAll(this RecordsetStatement statement, RecordsetStatement with)
{
return new IntersectStatement(statement, with, true);
}
public static IntersectStatement IntersectDistinct(this RecordsetStatement statement, RecordsetStatement with)
{
return new IntersectStatement(statement, with, false);
}
public static SelectStatement WrapAsSelect(this RecordsetStatement statement, string alias)
{
return new SelectStatement()
.From(statement, alias)
.Output(statement.Output.Select(
column => !string.IsNullOrWhiteSpace(column.Alias)
? column.Alias // we should use alias
: ((column is Name) ? ((Name)column).LastPart : null)) // or the LAST PART of the name
.Where(name => !string.IsNullOrWhiteSpace(name))
.Select(name => Sql.Name(alias, name)));
}
public static SelectStatement Having(this SelectStatement statement, Token condition)
{
statement.Having = condition;
return statement;
}
public static T Where<T>(this T statement, Token condition)
where T : IWhereStatement
{
statement.Where = condition;
return statement;
}
public static ExpressionToken IsEqual(this ExpressionToken first, ExpressionToken second)
{
return new IsEqualsToken { First = first, Second = second };
}
public static ExpressionToken NotEqual(this ExpressionToken first, ExpressionToken second)
{
return new NotEqualToken { First = first, Second = second };
}
public static ExpressionToken Less(this ExpressionToken first, ExpressionToken second)
{
return new LessToken { First = first, Second = second };
}
public static ExpressionToken NotLess(this ExpressionToken first, ExpressionToken second)
{
return new NotLessToken { First = first, Second = second };
}
public static ExpressionToken LessOrEqual(this ExpressionToken first, ExpressionToken second)
{
return new LessOrEqualToken { First = first, Second = second };
}
public static ExpressionToken Greater(this ExpressionToken first, ExpressionToken second)
{
return new GreaterToken { First = first, Second = second };
}
public static ExpressionToken NotGreater(this ExpressionToken first, ExpressionToken second)
{
return new NotGreaterToken { First = first, Second = second };
}
public static ExpressionToken GreaterOrEqual(this ExpressionToken first, ExpressionToken second)
{
return new GreaterOrEqualToken { First = first, Second = second };
}
public static ExpressionToken And(this ExpressionToken first, ExpressionToken second)
{
return new AndToken { First = first, Second = second };
}
public static ExpressionToken Or(this ExpressionToken first, ExpressionToken second)
{
return new OrToken { First = first, Second = second };
}
public static ExpressionToken PlusEqual(this ExpressionToken first, ExpressionToken second)
{
return new PlusToken { First = first, Second = second, Equal = true };
}
public static ExpressionToken MinusEqual(this ExpressionToken first, ExpressionToken second)
{
return new MinusToken { First = first, Second = second, Equal = true };
}
public static ExpressionToken DivideEqual(this ExpressionToken first, ExpressionToken second)
{
return new DivideToken { First = first, Second = second, Equal = true };
}
public static ExpressionToken BitwiseAndEqual(this ExpressionToken first, ExpressionToken second)
{
return new BitwiseAndToken { First = first, Second = second, Equal = true };
}
public static ExpressionToken BitwiseOrEqual(this ExpressionToken first, ExpressionToken second)
{
return new BitwiseOrToken { First = first, Second = second, Equal = true };
}
public static ExpressionToken BitwiseXorEqual(this ExpressionToken first, ExpressionToken second)
{
return new BitwiseXorToken { First = first, Second = second, Equal = true };
}
//public static ExpressionToken BitwiseNotEqual(this ExpressionToken first, ExpressionToken second)
//{
// return new BitwiseNotToken { First = first, Second = second, Equal = true };
//}
public static ExpressionToken ModuloEqual(this ExpressionToken first, ExpressionToken second)
{
return new ModuloToken { First = first, Second = second, Equal = true };
}
public static ExpressionToken MultiplyEqual(this ExpressionToken first, ExpressionToken second)
{
return new MultiplyToken { First = first, Second = second, Equal = true };
}
public static ExpressionToken Plus(this ExpressionToken first, ExpressionToken second)
{
return new PlusToken { First = first, Second = second };
}
public static ExpressionToken Minus(this ExpressionToken first, ExpressionToken second)
{
return new MinusToken { First = first, Second = second };
}
public static ExpressionToken Divide(this ExpressionToken first, ExpressionToken second)
{
return new DivideToken { First = first, Second = second };
}
public static ExpressionToken BitwiseAnd(this ExpressionToken first, ExpressionToken second)
{
return new BitwiseAndToken { First = first, Second = second };
}
public static ExpressionToken BitwiseOr(this ExpressionToken first, ExpressionToken second)
{
return new BitwiseOrToken { First = first, Second = second };
}
public static ExpressionToken BitwiseXor(this ExpressionToken first, ExpressionToken second)
{
return new BitwiseXorToken { First = first, Second = second };
}
public static ExpressionToken BitwiseNot(this ExpressionToken token)
{
return new BitwiseNotToken { Token = token };
}
public static ExpressionToken Modulo(this ExpressionToken first, ExpressionToken second)
{
return new ModuloToken { First = first, Second = second };
}
public static MultiplyToken Multiply(this ExpressionToken first, ExpressionToken second)
{
return new MultiplyToken { First = first, Second = second };
}
public static ExpressionToken IsEqual(this ExpressionToken first, string second)
{
return new IsEqualsToken { First = first, Second = Sql.Name(second) };
}
public static ExpressionToken NotEqual(this ExpressionToken first, string second)
{
return new NotEqualToken { First = first, Second = Sql.Name(second) };
}
public static ExpressionToken Less(this ExpressionToken first, string second)
{
return new LessToken { First = first, Second = Sql.Name(second) };
}
public static ExpressionToken NotLess(this ExpressionToken first, string second)
{
return new NotLessToken { First = first, Second = Sql.Name(second) };
}
public static ExpressionToken LessOrEqual(this ExpressionToken first, string second)
{
return new LessOrEqualToken { First = first, Second = Sql.Name(second) };
}
public static ExpressionToken Greater(this ExpressionToken first, string second)
{
return new GreaterToken { First = first, Second = Sql.Name(second) };
}
public static ExpressionToken NotGreater(this ExpressionToken first, string second)
{
return new NotGreaterToken { First = first, Second = Sql.Name(second) };
}
public static ExpressionToken GreaterOrEqual(this ExpressionToken first, string second)
{
return new GreaterOrEqualToken { First = first, Second = Sql.Name(second) };
}
public static ExpressionToken And(this ExpressionToken first, string second)
{
return new AndToken { First = first, Second = Sql.Name(second) };
}
public static ExpressionToken Or(this ExpressionToken first, string second)
{
return new OrToken { First = first, Second = Sql.Name(second) };
}
public static ExpressionToken PlusEqual(this ExpressionToken first, string second)
{
return new PlusToken { First = first, Second = Sql.Name(second), Equal = true };
}
public static ExpressionToken MinusEqual(this ExpressionToken first, string second)
{
return new MinusToken { First = first, Second = Sql.Name(second), Equal = true };
}
public static ExpressionToken DivideEqual(this ExpressionToken first, string second)
{
return new DivideToken { First = first, Second = Sql.Name(second), Equal = true };
}
public static ExpressionToken BitwiseAndEqual(this ExpressionToken first, string second)
{
return new BitwiseAndToken { First = first, Second = Sql.Name(second), Equal = true };
}
public static ExpressionToken BitwiseOrEqual(this ExpressionToken first, string second)
{
return new BitwiseOrToken { First = first, Second = Sql.Name(second), Equal = true };
}
public static ExpressionToken BitwiseXorEqual(this ExpressionToken first, string second)
{
return new BitwiseXorToken { First = first, Second = Sql.Name(second), Equal = true };
}
//public static ExpressionToken BitwiseNotEqual(this ExpressionToken first, string second)
//{
// return new BitwiseNotToken { First = first, Second = Sql.Name(second), Equal = true };
//}
public static ExpressionToken ModuloEqual(this ExpressionToken first, string second)
{
return new ModuloToken { First = first, Second = Sql.Name(second), Equal = true };
}
public static ExpressionToken MultiplyEqual(this ExpressionToken first, string second)
{
return new MultiplyToken { First = first, Second = Sql.Name(second), Equal = true };
}
public static ExpressionToken Plus(this ExpressionToken first, string second)
{
return new PlusToken { First = first, Second = Sql.Name(second) };
}
public static ExpressionToken Minus(this ExpressionToken first, string second)
{
return new MinusToken { First = first, Second = Sql.Name(second) };
}
public static ExpressionToken Divide(this ExpressionToken first, string second)
{
return new DivideToken { First = first, Second = Sql.Name(second) };
}
public static ExpressionToken BitwiseAnd(this ExpressionToken first, string second)
{
return new BitwiseAndToken { First = first, Second = Sql.Name(second) };
}
public static ExpressionToken BitwiseOr(this ExpressionToken first, string second)
{
return new BitwiseOrToken { First = first, Second = Sql.Name(second) };
}
public static ExpressionToken BitwiseXor(this ExpressionToken first, string second)
{
return new BitwiseXorToken { First = first, Second = Sql.Name(second) };
}
//public static ExpressionToken BitwiseNot(this ExpressionToken first, string second)
//{
// return new BitwiseNotToken { First = first, Second = Sql.Name(second) };
//}
public static ExpressionToken Modulo(this ExpressionToken first, string second)
{
return new ModuloToken { First = first, Second = Sql.Name(second) };
}
public static ExpressionToken Multiply(this ExpressionToken first, string second)
{
return new MultiplyToken { First = first, Second = Sql.Name(second) };
}
public static GroupToken Group(this Token token)
{
return new GroupToken { Token = token };
}
public static UnaryMinusToken Minus(this Token token)
{
return new UnaryMinusToken { Token = token };
}
public static ExpressionToken Not(this ExpressionToken token)
{
return new NotToken { Token = token };
}
public static ExpressionToken IsNull(this ExpressionToken token)
{
return new IsNullToken { Token = token };
}
public static ExpressionToken IsNotNull(this ExpressionToken token)
{
return new IsNotNullToken { Token = token };
}
public static BetweenToken Between(this ExpressionToken token, ExpressionToken first, ExpressionToken second)
{
return new BetweenToken { Token = token, First = first, Second = second };
}
public static ExpressionToken In(this ExpressionToken token, params ExpressionToken[] tokens)
{
var value = new InToken { Token = token };
value.Set.AddRange(tokens);
return value;
}
public static ExpressionToken NotIn(this ExpressionToken token, params ExpressionToken[] tokens)
{
var value = new NotInToken { Token = token };
value.Set.AddRange(tokens);
return value;
}
public static ExpressionToken In(this ExpressionToken token, IEnumerable<ExpressionToken> tokens)
{
var value = new InToken { Token = token };
if (tokens != null)
{
value.Set.AddRange(tokens);
}
return value;
}
public static ExpressionToken NotIn(this ExpressionToken token, IEnumerable<ExpressionToken> tokens)
{
var value = new NotInToken { Token = token };
if (tokens != null)
{
value.Set.AddRange(tokens);
}
return value;
}
public static ExpressionToken Contains(this ExpressionToken first, ExpressionToken second)
{
return new ContainsToken { First = first, Second = second };
}
public static ExpressionToken StartsWith(this ExpressionToken first, ExpressionToken second)
{
return new StartsWithToken { First = first, Second = second };
}
public static ExpressionToken EndsWith(this ExpressionToken first, ExpressionToken second)
{
return new EndsWithToken { First = first, Second = second };
}
public static ExpressionToken Like(this ExpressionToken first, ExpressionToken second)
{
return new LikeToken { First = first, Second = second };
}
public static IfStatement Then(this IfStatement statement, params IStatement[] statements)
{
return Then(statement, (IEnumerable<IStatement>)statements);
}
public static IfStatement Then(this IfStatement statement, IEnumerable<IStatement> statements)
{
statement.Then = new StatementsStatement();
if (statements != null)
{
statement.Then.Statements.AddRange(statements);
}
return statement;
}
public static IfStatement Else(this IfStatement statement, params IStatement[] statements)
{
return Else(statement, (IEnumerable<IStatement>)statements);
}
public static IfStatement Else(this IfStatement statement, IEnumerable<IStatement> statements)
{
statement.Else = new StatementsStatement();
if (statements != null)
statement.Else.Statements.AddRange(statements);
return statement;
}
public static CommentStatement CommentOut(this IStatement statement)
{
return new CommentStatement { Content = statement };
}
public static CommentToken CommentOut(this Token token)
{
return new CommentToken { Content = token };
}
public static StringifyStatement Stringify(this IStatement statement)
{
return new StringifyStatement { Content = statement };
}
public static StringifyToken Stringify(this Token token)
{
return new StringifyToken { Content = token };
}
public static InsertStatement DefaultValues(this InsertStatement statement, bool useDefaultValues = true)
{
statement.DefaultValues = useDefaultValues;
return statement;
}
public static InsertStatement Columns(this InsertStatement statement, IEnumerable<Name> columns)
{
if (columns != null)
{
statement.Columns.AddRange(columns);
}
return statement;
}
public static InsertStatement Columns(this InsertStatement statement, Name column, params Name[] columns)
{
return Columns(statement, ToNames(column, columns));
}
public static InsertStatement Columns(this InsertStatement statement, string column, params string[] columns)
{
return Columns(statement, ToNames(column, columns));
}
public static InsertStatement Columns(this InsertStatement statement, IEnumerable<string> columns)
{
return Columns(statement, ToNames(columns));
}
public static InsertStatement Values(this InsertStatement statement, IEnumerable<Token> values)
{
if (values != null)
{
statement.Values.Add(values.ToArray());
}
return statement;
}
public static InsertStatement Values(this InsertStatement statement, params Token[] values)
{
return Values(statement, (IEnumerable<Token>)values);
}
public static InsertStatement Values(this InsertStatement statement, params object[] values)
{
return Values(statement, (values ?? Enumerable.Empty<object>()).Select(Sql.Scalar));
}
public static InsertStatement Values(this InsertStatement statement, IEnumerable<object> values)
{
return Values(statement, (values ?? Enumerable.Empty<object>()).Select(Sql.Scalar));
}
public static InsertStatement OrReplace(this InsertStatement statement)
{
statement.Conflict = OnConflict.Replace;
return statement;
}
public static InsertStatement OrRollback(this InsertStatement statement)
{
statement.Conflict = OnConflict.Rollback;
return statement;
}
public static InsertStatement OrAbort(this InsertStatement statement)
{
statement.Conflict = OnConflict.Abort;
return statement;
}
public static InsertStatement OrFail(this InsertStatement statement)
{
statement.Conflict = OnConflict.Fail;
return statement;
}
public static InsertStatement OrIgnore(this InsertStatement statement)
{
statement.Conflict = OnConflict.Ignore;
return statement;
}
public static UpdateStatement OrReplace(this UpdateStatement statement)
{
statement.Conflict = OnConflict.Replace;
return statement;
}
public static UpdateStatement OrRollback(this UpdateStatement statement)
{
statement.Conflict = OnConflict.Rollback;
return statement;
}
public static UpdateStatement OrAbort(this UpdateStatement statement)
{
statement.Conflict = OnConflict.Abort;
return statement;
}
public static UpdateStatement OrFail(this UpdateStatement statement)
{
statement.Conflict = OnConflict.Fail;
return statement;
}
public static UpdateStatement OrIgnore(this UpdateStatement statement)
{
statement.Conflict = OnConflict.Ignore;
return statement;
}
public static CreateIndexStatement OnColumn(this CreateIndexStatement statement, IEnumerable<Order> columns)
{
if (columns != null)
{
statement.Columns.AddRange(columns);
}
return statement;
}
public static AlterIndexStatement OnColumn(this AlterIndexStatement statement, IEnumerable<Order> columns)
{
if (columns != null)
{
statement.Columns.AddRange(columns);
}
return statement;
}
public static CreateIndexStatement OnColumn(this CreateIndexStatement statement, Name column,
Direction direction = Direction.Asc)
{
statement.Columns.Add(Sql.Order(column, direction));
return statement;
}
public static AlterIndexStatement OnColumn(this AlterIndexStatement statement, Name column,
Direction direction = Direction.Asc)
{
statement.Columns.Add(Sql.Order(column, direction));
return statement;
}
public static CreateIndexStatement OnColumn(this CreateIndexStatement statement, string column,
Direction direction = Direction.Asc)
{
statement.Columns.Add(Sql.Order(column, direction));
return statement;
}
public static AlterIndexStatement OnColumn(this AlterIndexStatement statement, string column,
Direction direction = Direction.Asc)
{
statement.Columns.Add(Sql.Order(column, direction));
return statement;
}
public static CreateIndexStatement OnColumn(this CreateIndexStatement statement, Order column,
params Order[] columns)
{
return OnColumn(statement, ToOrders(column, columns));
}
public static AlterIndexStatement OnColumn(this AlterIndexStatement statement, Order column,
params Order[] columns)
{
return OnColumn(statement, ToOrders(column, columns));
}
public static CreateIndexStatement OnColumn(this CreateIndexStatement statement, string column,
params string[] columns)
{
return OnColumn(statement, ToOrders(column, columns));
}
public static AlterIndexStatement OnColumn(this AlterIndexStatement statement, string column,
params string[] columns)
{
return OnColumn(statement, ToOrders(column, columns));
}
public static CreateIndexStatement Include(this CreateIndexStatement statement, IEnumerable<Name> columns)
{
if (columns != null)
{
statement.Include.AddRange(columns);
}
return statement;
}
public static CreateIndexStatement Include(this CreateIndexStatement statement, string column,
params string[] columns)
{
return Include(statement, ToNames(column, columns));
}
public static CreateIndexStatement Include(this CreateIndexStatement statement, Name column,
params Name[] columns)
{
return Include(statement, ToNames(column, columns));
}
public static CreateIndexStatement Unique(this CreateIndexStatement statement, bool unique = true)
{
statement.Unique = unique;
return statement;
}
public static CreateIndexStatement Clustered(this CreateIndexStatement statement, bool clustered = true)
{
statement.Clustered = clustered;
return statement;
}
public static CreateIndexStatement Nonclustered(this CreateIndexStatement statement, bool nonclustered = true)
{
statement.Nonclustered = nonclustered;
return statement;
}
public static AlterIndexStatement Rebuild(this AlterIndexStatement statement)
{
statement.Rebuild = true;
return statement;
}
public static AlterIndexStatement Disable(this AlterIndexStatement statement)
{
statement.Disable = true;
return statement;
}
public static AlterIndexStatement Reorganize(this AlterIndexStatement statement)
{
statement.Reorganize = true;
return statement;
}
public static CreateTableStatement Columns(this CreateTableStatement statement, params TableColumn[] columns)
{
statement.Columns.AddRange(columns);
return statement;
}
public static CreateTableStatement Columns(this CreateTableStatement statement, IEnumerable<TableColumn> columns)
{
if (columns != null)
{
statement.Columns.AddRange(columns);
}
return statement;
}
public static TableColumn Null(this TableColumn column, bool notNull = false)
{
column.Null = !notNull;
return column;
}
public static TableColumn Null(this TableColumn column, OnConflict onConflict, bool notNull = false)
{
column.Null = !notNull;
column.NullConflict = onConflict;
return column;
}
public static TableColumn NotNull(this TableColumn column)
{
column.Null = false;
return column;
}
public static TableColumn NotNull(this TableColumn column, OnConflict onConflict)
{
column.Null = false;
column.NullConflict = onConflict;
return column;
}
public static TableColumn Identity(this TableColumn column, int seed = 1, int increment = 1)
{
column.Identity.On = true;
column.Identity.Seed = seed;
column.Identity.Increment = increment;
return column;
}
public static TableColumn AutoIncrement(this TableColumn column)
{
column.Identity.On = true;
column.Identity.Seed = 1;
column.Identity.Increment = 1;
return column;
}
public static TableColumn PrimaryKey(this TableColumn column, Direction direction = Direction.Asc)
{
column.PrimaryKeyDirection = direction;
return column;
}
public static TableColumn PrimaryKey(this TableColumn column, OnConflict onConflict,
Direction direction = Direction.Asc)
{
column.PrimaryKeyDirection = direction;
column.PrimaryKeyConflict = onConflict;
return column;
}
public static TableColumn Default(this TableColumn column, object value)
{
column.DefaultValue = Sql.Scalar(value);
return column;
}
public static TableColumn Default(this TableColumn column, Scalar value)
{
column.DefaultValue = value;
return column;
}
public static TableColumn Default(this TableColumn column, Function value)
{
column.DefaultValue = value;
return column;
}
public static TableColumn Default(this TableColumn column, FunctionExpressionToken value)
{
column.DefaultValue = value;
return column;
}
public static TableColumn Sparse(this TableColumn column)
{
column.Sparse = true;
return column;
}
public static TableColumn RowGuid(this TableColumn column)
{
column.RowGuid = true;
return column;
}
public static TryCatchStatement Catch(this TryCatchStatement statement, IStatement catchStatement)
{
statement.CatchStatement = catchStatement;
return statement;
}
public static WhileStatement Do(this WhileStatement statement, params IStatement[] statements)
{
statement.Do = new StatementsStatement();
statement.Do.Statements.AddRange(statements);
return statement;
}
public static WhileStatement Do(this WhileStatement statement, IEnumerable<IStatement> statements)
{
statement.Do = new StatementsStatement();
if (statements != null)
{
statement.Do.Statements.AddRange(statements);
}
return statement;
}
#region Schema
public static CreateSchemaStatement Authorization(this CreateSchemaStatement statement, string ownerName)
{
statement.Owner = ownerName;
return statement;
}
public static DropSchemaStatement Cascade(this DropSchemaStatement statement)
{
statement.IsCascade = true;
return statement;
}
public static DropSchemaStatement Restrict(this DropSchemaStatement statement)
{
statement.IsCascade = false;
return statement;
}
public static AlterSchemaStatement RenameTo(this AlterSchemaStatement statement, string newName)
{
statement.NewName = Sql.Name(newName);
return statement;
}
public static AlterSchemaStatement RenameTo(this AlterSchemaStatement statement, Name newName)
{
statement.NewName = newName;
return statement;
}
public static AlterSchemaStatement OwnerTo(this AlterSchemaStatement statement, string newOwner)
{
statement.NewOwner = Sql.Name(newOwner);
return statement;
}
public static AlterSchemaStatement OwnerTo(this AlterSchemaStatement statement, Name newOwner)
{
statement.NewOwner = newOwner;
return statement;
}
#endregion Schema
public static string GetCommandSummary(this IDbCommand command)
{
if (command == null) return string.Empty;
var sb = new StringBuilder();
foreach (var p in command.Parameters.Cast<IDbDataParameter>())
{
sb.AppendFormat("-- DECLARE {0} ", p.ParameterName);
switch (p.DbType)
{
case DbType.VarNumeric:
sb.AppendFormat("NUMERIC({1},{2}) = {0}", p.Value, p.Precision, p.Scale);
break;
case DbType.UInt64:
case DbType.Int64:
sb.AppendFormat("BIGINT = {0}", p.Value);
break;
case DbType.Binary:
sb.AppendFormat("BINARY({1}) = '{0}'", p.Value, p.Size);
break;
case DbType.Boolean:
sb.AppendFormat("BIT = {0}", p.Value);
break;
case DbType.AnsiStringFixedLength:
sb.AppendFormat("CHAR({1}) = N'{0}'", p.Value, p.Size);
break;
case DbType.DateTime:
sb.AppendFormat("DATETIME = N'{0}'", p.Value);
break;
case DbType.Decimal:
sb.AppendFormat("DECIMAL({1},{2}) = {0}", p.Value, p.Precision, p.Scale);
break;
case DbType.Single:
sb.AppendFormat("FLOAT = {0}", p.Value);
break;
case DbType.UInt32:
case DbType.Int32:
sb.AppendFormat("INT = {0}", p.Value);
break;
case DbType.Currency:
sb.AppendFormat("MONEY = {0}", p.Value);
break;
case DbType.StringFixedLength:
case DbType.AnsiString:
sb.AppendFormat("NCHAR({1}) = N'{0}'", p.Value, p.Size);
break;
case DbType.String:
sb.AppendFormat("NVARCHAR({1}) = N'{0}'", p.Value, (p.Size == -1) ? "MAX" : p.Size.ToString());
break;
case DbType.Double:
sb.AppendFormat("REAL = {0}", p.Value);
break;
case DbType.Guid:
sb.AppendFormat("UNIQUEIDENTIFIER = N'{0}'", p.Value);
break;
case DbType.UInt16:
case DbType.Int16:
sb.AppendFormat("SMALLINT = {0}", p.Value);
break;
case DbType.Byte:
case DbType.SByte:
sb.AppendFormat("TINYINT = {0}", p.Value);
break;
case DbType.Xml:
sb.AppendFormat("XML = N'{0}'", p.Value);
break;
case DbType.Date:
sb.AppendFormat("DATE = N'{0}'", p.Value);
break;
case DbType.Time:
sb.AppendFormat("TIME = N'{0}'", p.Value);
break;
case DbType.DateTime2:
sb.AppendFormat("DATETIME2({1}) = N'{0}'", p.Value, p.Size);
break;
case DbType.DateTimeOffset:
sb.AppendFormat("DATETIMEOFFSET({1}) = N'{0}'", p.Value, p.Size);
break;
}
sb.AppendLine();
}
sb.AppendLine(command.CommandText);
return sb.ToString();
}
#region INNER JOIN
public static T Join<T>(this T statement, Joins join, RecordsetSourceToken source, ExpressionToken on)
where T : IJoinStatement
{
statement.Joins.Add(new Join
{
Type = join,
Source = source,
On = on
});
return statement;
}
public static T InnerJoin<T>(this T statement, RecordsetSourceToken source, ExpressionToken on)
where T : IJoinStatement
{
return Join(statement, Joins.Inner, source, on);
}
public static T InnerJoin<T>(this T statement, RecordsetSourceToken source, string alias, ExpressionToken on)
where T : IJoinStatement
{
return Join(statement, Joins.Inner, source.As(alias), on);
}
public static T InnerJoin<T>(this T statement, string source, ExpressionToken on)
where T : IJoinStatement
{
return Join(statement, Joins.Inner, Sql.Name(source), on);
}
public static T InnerJoin<T>(this T statement, string source, string alias, ExpressionToken on)
where T : IJoinStatement
{
return Join(statement, Joins.Inner, Sql.NameAs(source, alias), on);
}
public static T LeftOuterJoin<T>(this T statement, RecordsetSourceToken source, ExpressionToken on)
where T : IJoinStatement
{
return Join(statement, Joins.LeftOuter, source, on);
}
public static T LeftOuterJoin<T>(this T statement, RecordsetSourceToken source, string alias, ExpressionToken on)
where T : IJoinStatement
{
return Join(statement, Joins.LeftOuter, source.As(alias), on);
}
public static T LeftOuterJoin<T>(this T statement, string source, ExpressionToken on)
where T : IJoinStatement
{
return Join(statement, Joins.LeftOuter, Sql.Name(source), on);
}
public static T LeftOuterJoin<T>(this T statement, string source, string alias, ExpressionToken on)
where T : IJoinStatement
{
return Join(statement, Joins.LeftOuter, Sql.NameAs(source, alias), on);
}
public static T RightOuterJoin<T>(this T statement, RecordsetSourceToken source, ExpressionToken on)
where T : IJoinStatement
{
return Join(statement, Joins.RightOuter, source, on);
}
public static T RightOuterJoin<T>(this T statement, RecordsetSourceToken source, string alias,
ExpressionToken on)
where T : IJoinStatement
{
return Join(statement, Joins.RightOuter, source.As(alias), on);
}
public static T RightOuterJoin<T>(this T statement, string source, ExpressionToken on)
where T : IJoinStatement
{
return Join(statement, Joins.RightOuter, Sql.Name(source), on);
}
public static T RightOuterJoin<T>(this T statement, string source, string alias, ExpressionToken on)
where T : IJoinStatement
{
return Join(statement, Joins.RightOuter, Sql.NameAs(source, alias), on);
}
public static T FullOuterJoin<T>(this T statement, RecordsetSourceToken source, ExpressionToken on)
where T : IJoinStatement
{
return Join(statement, Joins.FullOuter, source, on);
}
public static T FullOuterJoin<T>(this T statement, RecordsetSourceToken source, string alias, ExpressionToken on)
where T : IJoinStatement
{
return Join(statement, Joins.FullOuter, source.As(alias), on);
}
public static T FullOuterJoin<T>(this T statement, string source, ExpressionToken on)
where T : IJoinStatement
{
return Join(statement, Joins.FullOuter, Sql.Name(source), on);
}
public static T FullOuterJoin<T>(this T statement, string source, string alias, ExpressionToken on)
where T : IJoinStatement
{
return Join(statement, Joins.FullOuter, Sql.NameAs(source, alias), on);
}
public static T CrossJoin<T>(this T statement, RecordsetSourceToken source)
where T : IJoinStatement
{
return Join(statement, Joins.Cross, source, null);
}
public static T CrossJoin<T>(this T statement, RecordsetSourceToken source, string alias)
where T : IJoinStatement
{
return Join(statement, Joins.Cross, source.As(alias), null);
}
public static T CrossJoin<T>(this T statement, string source)
where T : IJoinStatement
{
return Join(statement, Joins.Cross, Sql.Name(source), null);
}
public static T CrossJoin<T>(this T statement, string source, string alias)
where T : IJoinStatement
{
return Join(statement, Joins.Cross, Sql.NameAs(source, alias), null);
}
#endregion INNER JOIN
#region PrimaryKey
public static CreateTableStatement PrimaryKey(this CreateTableStatement statement, Name name,
params Order[] columns)
{
if (statement.PrimaryKey == null)
{
statement.PrimaryKey = new ConstrainDefinition();
}
statement.PrimaryKey.Name = name;
statement.PrimaryKey.Columns.AddRange(columns);
return statement;
}
//for postgresql
public static CreateTableStatement PrimaryKey(this CreateTableStatement statement, Name name,
params Name[] columns)
{
if (statement.PrimaryKey == null)
{
statement.PrimaryKey = new ConstrainDefinition();
}
statement.PrimaryKey.Name = name;
foreach (var columnName in columns)
{
statement.PrimaryKey.Columns.Add(new Order { Column = columnName });
}
return statement;
}
public static CreateTableStatement PrimaryKey(this CreateTableStatement statement, Name name,
IEnumerable<Order> columns)
{
if (statement.PrimaryKey == null)
{
statement.PrimaryKey = new ConstrainDefinition();
}
statement.PrimaryKey.Name = name;
if (columns != null)
{
statement.PrimaryKey.Columns.AddRange(columns);
}
return statement;
}
public static CreateTableStatement PrimaryKey(this CreateTableStatement statement, Name name, bool clustered,
params Order[] columns)
{
if (statement.PrimaryKey == null)
{
statement.PrimaryKey = new ConstrainDefinition();
}
statement.PrimaryKey.Clustered = clustered;
statement.PrimaryKey.Name = name;
statement.PrimaryKey.Columns.AddRange(columns);
return statement;
}
public static CreateTableStatement PrimaryKey(this CreateTableStatement statement, Name name, bool clustered,
IEnumerable<Order> columns)
{
if (statement.PrimaryKey == null)
{
statement.PrimaryKey = new ConstrainDefinition();
}
statement.PrimaryKey.Clustered = clustered;
statement.PrimaryKey.Name = name;
if (columns != null)
{
statement.PrimaryKey.Columns.AddRange(columns);
}
return statement;
}
public static CreateTableStatement PrimaryKey(this CreateTableStatement statement, params Order[] columns)
{
if (statement.PrimaryKey == null)
{
statement.PrimaryKey = new ConstrainDefinition();
}
statement.PrimaryKey.Name = Sql.Name("PK_" + statement.Name.LastPart);
statement.PrimaryKey.Columns.AddRange(columns);
return statement;
}
public static CreateTableStatement PrimaryKey(this CreateTableStatement statement, IEnumerable<Order> columns)
{
if (statement.PrimaryKey == null)
{
statement.PrimaryKey = new ConstrainDefinition();
}
statement.PrimaryKey.Name = Sql.Name("PK_" + statement.Name.LastPart);
if (columns != null)
{
statement.PrimaryKey.Columns.AddRange(columns);
}
return statement;
}
public static CreateTableStatement PrimaryKey(this CreateTableStatement statement, bool clustered,
params Order[] columns)
{
if (statement.PrimaryKey == null)
{
statement.PrimaryKey = new ConstrainDefinition();
}
statement.PrimaryKey.Clustered = clustered;
statement.PrimaryKey.Name = Sql.Name("PK_" + statement.Name.LastPart);
statement.PrimaryKey.Columns.AddRange(columns);
return statement;
}
public static CreateTableStatement PrimaryKey(this CreateTableStatement statement, bool clustered,
IEnumerable<Order> columns)
{
if (statement.PrimaryKey == null)
{
statement.PrimaryKey = new ConstrainDefinition();
}
statement.PrimaryKey.Clustered = clustered;
statement.PrimaryKey.Name = Sql.Name("PK_" + statement.Name.LastPart);
if (columns != null)
{
statement.PrimaryKey.Columns.AddRange(columns);
}
return statement;
}
public static CreateTableStatement PrimaryKey(this CreateTableStatement statement, Name name,
OnConflict onConflict,
params Order[] columns)
{
if (statement.PrimaryKey == null)
{
statement.PrimaryKey = new ConstrainDefinition();
}
statement.PrimaryKey.Name = name;
statement.PrimaryKey.Conflict = onConflict;
statement.PrimaryKey.Columns.AddRange(columns);
return statement;
}
public static CreateTableStatement PrimaryKey(this CreateTableStatement statement, Name name,
OnConflict onConflict,
IEnumerable<Order> columns)
{
if (statement.PrimaryKey == null)
{
statement.PrimaryKey = new ConstrainDefinition();
}
statement.PrimaryKey.Name = name;
statement.PrimaryKey.Conflict = onConflict;
if (columns != null)
{
statement.PrimaryKey.Columns.AddRange(columns);
}
return statement;
}
public static CreateTableStatement PrimaryKey(this CreateTableStatement statement, Name name, bool clustered,
OnConflict onConflict,
params Order[] columns)
{
if (statement.PrimaryKey == null)
{
statement.PrimaryKey = new ConstrainDefinition();
}
statement.PrimaryKey.Clustered = clustered;
statement.PrimaryKey.Conflict = onConflict;
statement.PrimaryKey.Name = name;
statement.PrimaryKey.Columns.AddRange(columns);
return statement;
}
public static CreateTableStatement PrimaryKey(this CreateTableStatement statement, Name name, bool clustered,
OnConflict onConflict, IEnumerable<Order> columns)
{
if (statement.PrimaryKey == null)
{
statement.PrimaryKey = new ConstrainDefinition();
}
statement.PrimaryKey.Clustered = clustered;
statement.PrimaryKey.Conflict = onConflict;
statement.PrimaryKey.Name = name;
if (columns != null)
{
statement.PrimaryKey.Columns.AddRange(columns);
}
return statement;
}
public static CreateTableStatement PrimaryKey(this CreateTableStatement statement, OnConflict onConflict,
params Order[] columns)
{
if (statement.PrimaryKey == null)
{
statement.PrimaryKey = new ConstrainDefinition();
}
statement.PrimaryKey.Name = Sql.Name("PK_" + statement.Name.LastPart);
statement.PrimaryKey.Conflict = onConflict;
statement.PrimaryKey.Columns.AddRange(columns);
return statement;
}
public static CreateTableStatement PrimaryKey(this CreateTableStatement statement, OnConflict onConflict,
IEnumerable<Order> columns)
{
if (statement.PrimaryKey == null)
{
statement.PrimaryKey = new ConstrainDefinition();
}
statement.PrimaryKey.Name = Sql.Name("PK_" + statement.Name.LastPart);
statement.PrimaryKey.Conflict = onConflict;
if (columns != null)
{
statement.PrimaryKey.Columns.AddRange(columns);
}
return statement;
}
public static CreateTableStatement PrimaryKey(this CreateTableStatement statement, bool clustered,
OnConflict onConflict, params Order[] columns)
{
if (statement.PrimaryKey == null)
{
statement.PrimaryKey = new ConstrainDefinition();
}
statement.PrimaryKey.Clustered = clustered;
statement.PrimaryKey.Conflict = onConflict;
statement.PrimaryKey.Name = Sql.Name("PK_" + statement.Name.LastPart);
statement.PrimaryKey.Columns.AddRange(columns);
return statement;
}
public static CreateTableStatement PrimaryKey(this CreateTableStatement statement, bool clustered,
OnConflict onConflict,
IEnumerable<Order> columns)
{
if (statement.PrimaryKey == null)
{
statement.PrimaryKey = new ConstrainDefinition();
}
statement.PrimaryKey.Clustered = clustered;
statement.PrimaryKey.Conflict = onConflict;
statement.PrimaryKey.Name = Sql.Name("PK_" + statement.Name.LastPart);
if (columns != null)
{
statement.PrimaryKey.Columns.AddRange(columns);
}
return statement;
}
public static CreateTableStatement As(this CreateTableStatement statement, ISelectStatement selectStatement)
{
statement.AsSelectStatement = selectStatement;
return statement;
}
#endregion PrimaryKey
#region UniqueConstrainOn
public static CreateTableStatement UniqueConstrainOn(this CreateTableStatement statement, string name,
params Order[] columns)
{
var index = new ConstrainDefinition { Clustered = false, Name = Sql.Name(name) };
index.Columns.AddRange(columns);
statement.UniqueConstrains.Add(index);
return statement;
}
public static CreateTableStatement UniqueConstrainOn(this CreateTableStatement statement, string name,
IEnumerable<Order> columns)
{
var index = new ConstrainDefinition { Clustered = false, Name = Sql.Name(name) };
if (columns != null)
{
index.Columns.AddRange(columns);
}
statement.UniqueConstrains.Add(index);
return statement;
}
public static CreateTableStatement UniqueConstrainOn(this CreateTableStatement statement, Name name,
params Order[] columns)
{
var index = new ConstrainDefinition { Clustered = false, Name = name };
index.Columns.AddRange(columns);
statement.UniqueConstrains.Add(index);
return statement;
}
public static CreateTableStatement UniqueConstrainOn(this CreateTableStatement statement, Name name,
IEnumerable<Order> columns)
{
var index = new ConstrainDefinition { Clustered = false, Name = name };
if (columns != null)
{
index.Columns.AddRange(columns);
}
statement.UniqueConstrains.Add(index);
return statement;
}
public static CreateTableStatement UniqueConstrainOn(this CreateTableStatement statement, string name,
bool clustered, params Order[] columns)
{
var index = new ConstrainDefinition { Clustered = clustered, Name = Sql.Name(name) };
index.Columns.AddRange(columns);
statement.UniqueConstrains.Add(index);
return statement;
}
public static CreateTableStatement UniqueConstrainOn(this CreateTableStatement statement, string name,
bool clustered, IEnumerable<Order> columns)
{
var index = new ConstrainDefinition { Clustered = clustered, Name = Sql.Name(name) };
if (columns != null)
{
index.Columns.AddRange(columns);
}
statement.UniqueConstrains.Add(index);
return statement;
}
public static CreateTableStatement UniqueConstrainOn(this CreateTableStatement statement, Name name,
bool clustered, params Order[] columns)
{
var index = new ConstrainDefinition { Clustered = clustered, Name = name };
index.Columns.AddRange(columns);
statement.UniqueConstrains.Add(index);
return statement;
}
public static CreateTableStatement UniqueConstrainOn(this CreateTableStatement statement, Name name,
bool clustered, IEnumerable<Order> columns)
{
var index = new ConstrainDefinition { Clustered = clustered, Name = name };
if (columns != null)
{
index.Columns.AddRange(columns);
}
statement.UniqueConstrains.Add(index);
return statement;
}
public static CreateTableStatement UniqueConstrainOn(this CreateTableStatement statement, params Order[] columns)
{
var index = new ConstrainDefinition { Clustered = false, Name = Sql.Name("UC_" + statement.Name.LastPart) };
index.Columns.AddRange(columns);
statement.UniqueConstrains.Add(index);
return statement;
}
public static CreateTableStatement UniqueConstrainOn(this CreateTableStatement statement,
IEnumerable<Order> columns)
{
var index = new ConstrainDefinition { Clustered = false, Name = Sql.Name("UC_" + statement.Name.LastPart) };
if (columns != null)
{
index.Columns.AddRange(columns);
}
statement.UniqueConstrains.Add(index);
return statement;
}
public static CreateTableStatement UniqueConstrainOn(this CreateTableStatement statement, bool clustered,
params Order[] columns)
{
var index = new ConstrainDefinition
{
Clustered = clustered,
Name = Sql.Name("UC_" + statement.Name.LastPart)
};
index.Columns.AddRange(columns);
statement.UniqueConstrains.Add(index);
return statement;
}
public static CreateTableStatement UniqueConstrainOn(this CreateTableStatement statement, bool clustered,
IEnumerable<Order> columns)
{
var index = new ConstrainDefinition
{
Clustered = clustered,
Name = Sql.Name("UC_" + statement.Name.LastPart)
};
if (columns != null)
{
index.Columns.AddRange(columns);
}
statement.UniqueConstrains.Add(index);
return statement;
}
#endregion UniqueConstrainOn
#region IndexOn
public static CreateTableStatement IndexOn(this CreateTableStatement statement, string name,
params Order[] columns)
{
var index = new CreateIndexStatement
{
Clustered = false,
Name = Sql.Name(name),
On = statement.Name,
Unique = false
};
index.Columns.AddRange(columns);
statement.Indicies.Add(index);
return statement;
}
public static CreateTableStatement IndexOn(this CreateTableStatement statement, string name,
IEnumerable<Order> columns)
{
var index = new CreateIndexStatement
{
Clustered = false,
Name = Sql.Name(name),
On = statement.Name,
Unique = false
};
if (columns != null)
{
index.Columns.AddRange(columns);
}
statement.Indicies.Add(index);
return statement;
}
public static CreateTableStatement IndexOn(this CreateTableStatement statement, Name name,
params Order[] columns)
{
var index = new CreateIndexStatement { Clustered = false, Name = name, On = statement.Name, Unique = false };
index.Columns.AddRange(columns);
statement.Indicies.Add(index);
return statement;
}
public static CreateTableStatement IndexOn(this CreateTableStatement statement, Name name,
IEnumerable<Order> columns)
{
var index = new CreateIndexStatement { Clustered = false, Name = name, On = statement.Name, Unique = false };
if (columns != null)
{
index.Columns.AddRange(columns);
}
statement.Indicies.Add(index);
return statement;
}
public static CreateTableStatement IndexOn(this CreateTableStatement statement, string name,
IEnumerable<Order> columns, IEnumerable<string> includeColumns)
{
var index = new CreateIndexStatement
{
Clustered = false,
Name = Sql.Name(name),
On = statement.Name,
Unique = false
};
if (columns != null)
{
index.Columns.AddRange(columns);
}
if (includeColumns != null)
{
index.Include.AddRange(includeColumns.Select(ic => Sql.Name(ic)));
}
statement.Indicies.Add(index);
return statement;
}
public static CreateTableStatement IndexOn(this CreateTableStatement statement, Name name,
IEnumerable<Order> columns, IEnumerable<string> includeColumns)
{
var index = new CreateIndexStatement { Clustered = false, Name = name, On = statement.Name, Unique = false };
if (columns != null)
{
index.Columns.AddRange(columns);
}
if (includeColumns != null)
{
index.Include.AddRange(includeColumns.Select(ic => Sql.Name(ic)));
}
statement.Indicies.Add(index);
return statement;
}
public static CreateTableStatement IndexOn(this CreateTableStatement statement, string name,
IEnumerable<Order> columns, IEnumerable<Name> includeColumns)
{
var index = new CreateIndexStatement
{
Clustered = false,
Name = Sql.Name(name),
On = statement.Name,
Unique = false
};
if (columns != null)
{
index.Columns.AddRange(columns);
}
if (includeColumns != null)
{
index.Include.AddRange(includeColumns);
}
statement.Indicies.Add(index);
return statement;
}
public static CreateTableStatement IndexOn(this CreateTableStatement statement, Name name,
IEnumerable<Order> columns, IEnumerable<Name> includeColumns)
{
var index = new CreateIndexStatement { Clustered = false, Name = name, On = statement.Name, Unique = false };
if (columns != null)
{
index.Columns.AddRange(columns);
}
if (includeColumns != null)
{
index.Include.AddRange(includeColumns);
}
statement.Indicies.Add(index);
return statement;
}
#endregion IndexOn
#region Top
public static SelectStatement Top(this SelectStatement statement, int value, bool percent, bool withTies = false)
{
statement.Top = new Top(value, percent, withTies);
return statement;
}
public static SelectStatement Top(this SelectStatement statement, Parameter value, bool percent,
bool withTies = false)
{
statement.Top = new Top(value, percent, withTies);
return statement;
}
public static T Top<T>(this T statement, long value, bool percent = false)
where T : ITopStatement
{
statement.Top = new Top(value, percent, false);
return statement;
}
public static T Top<T>(this T statement, Parameter value, bool percent = false)
where T : ITopStatement
{
statement.Top = new Top(value, percent, false);
return statement;
}
public static T Limit<T>(this T statement, long value)
where T : ITopStatement
{
statement.Top = new Top(value, false, false);
return statement;
}
public static T Limit<T>(this T statement, long value, bool percent)
where T : ITopStatement
{
statement.Top = new Top(value, percent, false);
return statement;
}
public static T Offset<T>(this T statement, long value)
where T : IOffsetStatement
{
statement.Offset = new Scalar { Value = value };
return statement;
}
public static T FetchNext<T>(this T statement, long value)
where T : ITopStatement
{
statement.Top = new Top(value, false, false);
return statement;
}
#endregion Top
#region CTE
public static CTEDefinition As(this CTEDeclaration cte, ISelectStatement definition)
{
return new CTEDefinition
{
Declaration = cte,
Definition = definition
};
}
public static CTEDeclaration Recursive(this CTEDeclaration cte, bool recursive = true)
{
cte.Recursive = recursive;
return cte;
}
public static CTEDeclaration With(this CTEDefinition previousCommonTableExpression, string name,
params string[] columnNames)
{
var cte = new CTEDeclaration
{
Name = name,
PreviousCommonTableExpression = previousCommonTableExpression
};
if (columnNames != null)
{
cte.Columns.AddRange(columnNames.Select(n => Sql.Name(n)));
}
return cte;
}
public static CTEDeclaration With(this CTEDefinition previousCommonTableExpression, string name,
IEnumerable<string> columnNames)
{
var cte = new CTEDeclaration
{
Name = name,
PreviousCommonTableExpression = previousCommonTableExpression
};
if (columnNames != null)
{
cte.Columns.AddRange(columnNames.Select(n => Sql.Name(n)));
}
return cte;
}
static IEnumerable<CTEDefinition> GetCteDefinitions(CTEDefinition definition)
{
if (definition != null)
{
if (definition.Declaration != null && definition.Declaration.PreviousCommonTableExpression != null)
{
foreach (
var prevDefinition in GetCteDefinitions(definition.Declaration.PreviousCommonTableExpression))
{
yield return prevDefinition;
}
}
yield return definition;
}
}
public static SelectStatement Select(this CTEDefinition cte)
{
var statement = new SelectStatement();
statement.CommonTableExpressions.AddRange(GetCteDefinitions(cte));
return statement;
}
public static DeleteStatement Delete(this CTEDefinition cte)
{
var statement = new DeleteStatement();
statement.CommonTableExpressions.AddRange(GetCteDefinitions(cte));
return statement;
}
public static DeleteStatement Only(this DeleteStatement statement)
{
statement.Only = true;
return statement;
}
public static DeleteStatement WhereCurrentOf(this DeleteStatement statement, Name token)
{
statement.CursorName = token;
return statement;
}
public static DeleteStatement Using(this DeleteStatement statement, params Name[] token)
{
statement.UsingList.AddRange(token);
return statement;
}
public static InsertStatement Insert(this CTEDefinition cte)
{
var statement = new InsertStatement();
statement.CommonTableExpressions.AddRange(GetCteDefinitions(cte));
return statement;
}
public static MergeStatement Merge(this CTEDefinition cte)
{
var statement = new MergeStatement();
statement.CommonTableExpressions.AddRange(GetCteDefinitions(cte));
return statement;
}
public static UpdateStatement Update(this CTEDefinition cte, string target)
{
var statement = new UpdateStatement
{
Target = Sql.Name(target)
};
statement.CommonTableExpressions.AddRange(GetCteDefinitions(cte));
return statement;
}
public static UpdateStatement WhereCurrentOf(this UpdateStatement statement, Name token)
{
statement.CursorName = token;
return statement;
}
public static UpdateStatement Update(this CTEDefinition cte, Name target)
{
var statement = new UpdateStatement
{
Target = target
};
statement.CommonTableExpressions.AddRange(GetCteDefinitions(cte));
return statement;
}
public static UpdateStatement Only(this UpdateStatement statement)
{
statement.Only = true;
return statement;
}
public static DropTableStatement Cascade(this DropTableStatement statement)
{
statement.IsCascade = true;
return statement;
}
public static DropTableStatement Restrict(this DropTableStatement statement)
{
statement.IsCascade = false;
return statement;
}
#endregion CTE
#region Snippet
public static Snippet Dialect(this Snippet snippet, string value, string dialectName,
params string[] additionalDialects)
{
return snippet.Dialect(value, Enumerable.Repeat(dialectName, 1).Concat(additionalDialects));
}
public static Snippet Dialect(this Snippet snippet, string value, IEnumerable<string> dialects)
{
if (dialects != null)
{
foreach (var d in dialects
.Where(d => !string.IsNullOrWhiteSpace(d))
.SelectMany(d => d.Split(new[] { ';', ',', ' ' }, StringSplitOptions.RemoveEmptyEntries))
.Distinct(StringComparer.OrdinalIgnoreCase))
{
snippet.Dialects[d] = value;
}
}
return snippet;
}
public static SnippetStatement Dialect(this SnippetStatement snippetStatement, string value, string dialectName,
params string[] additionalDialects)
{
return snippetStatement.Dialect(value, Enumerable.Repeat(dialectName, 1).Concat(additionalDialects));
}
public static SnippetStatement Dialect(this SnippetStatement snippetStatement, string value,
IEnumerable<string> dialects)
{
if (dialects != null)
{
foreach (var d in dialects
.Where(d => !string.IsNullOrWhiteSpace(d))
.SelectMany(d => d.Split(new[] { ';', ',', ' ' }, StringSplitOptions.RemoveEmptyEntries))
.Distinct(StringComparer.OrdinalIgnoreCase))
{
snippetStatement.Dialects[d] = value;
}
}
return snippetStatement;
}
#endregion Snippet
#region Case
public static CaseToken On(this CaseToken caseToken, ExpressionToken caseValue)
{
caseToken.CaseValueToken = caseValue;
return caseToken;
}
public static CaseToken When(this CaseToken caseToken, ExpressionToken when, ExpressionToken then)
{
caseToken.WhenConditions.Add(new CaseWhenToken { WhenToken = when, ThenToken = then });
return caseToken;
}
public static CaseToken Else(this CaseToken caseToken, ExpressionToken elseToken)
{
caseToken.ElseToken = elseToken;
return caseToken;
}
#endregion Case
#region Continue
public static ContinueStatement Label(this ContinueStatement continueStatement, string label)
{
continueStatement.Label = label;
return continueStatement;
}
public static ContinueStatement When(this ContinueStatement continueStatement, ExpressionToken whenToken)
{
continueStatement.When = whenToken;
return continueStatement;
}
#endregion Continue
#region Break
public static BreakStatement Label(this BreakStatement breakStatement, string label)
{
breakStatement.Label = label;
return breakStatement;
}
#endregion Break
#region Exit
public static ExitStatement Label(this ExitStatement exitStatement, string label)
{
exitStatement.Label = label;
return exitStatement;
}
public static ExitStatement When(this ExitStatement exitStatement, ExpressionToken whenToken)
{
exitStatement.When = whenToken;
return exitStatement;
}
#endregion Case
#region Date Add
public static DateFunctionExpressionToken AddYears(this DateFunctionExpressionToken token, Token number)
{
return new DateAddFunctionToken { Token = token, Number = number, DatePart = DatePart.Year };
}
public static DateFunctionExpressionToken AddYears(this DateFunctionExpressionToken token, int number)
{
return new DateAddFunctionToken { Token = token, Number = Sql.Scalar(number), DatePart = DatePart.Year };
}
public static DateFunctionExpressionToken AddMonths(this DateFunctionExpressionToken token, Token number)
{
return new DateAddFunctionToken { Token = token, Number = number, DatePart = DatePart.Month };
}
public static DateFunctionExpressionToken AddMonths(this DateFunctionExpressionToken token, int number)
{
return new DateAddFunctionToken { Token = token, Number = Sql.Scalar(number), DatePart = DatePart.Month };
}
public static DateFunctionExpressionToken AddWeeks(this DateFunctionExpressionToken token, Token number)
{
return new DateAddFunctionToken { Token = token, Number = number, DatePart = DatePart.Week };
}
public static DateFunctionExpressionToken AddWeeks(this DateFunctionExpressionToken token, int number)
{
return new DateAddFunctionToken { Token = token, Number = Sql.Scalar(number), DatePart = DatePart.Week };
}
public static DateFunctionExpressionToken AddDays(this DateFunctionExpressionToken token, Token number)
{
return new DateAddFunctionToken { Token = token, Number = number, DatePart = DatePart.Day };
}
public static DateFunctionExpressionToken AddDays(this DateFunctionExpressionToken token, int number)
{
return new DateAddFunctionToken { Token = token, Number = Sql.Scalar(number), DatePart = DatePart.Day };
}
public static DateFunctionExpressionToken AddHours(this DateFunctionExpressionToken token, Token number)
{
return new DateAddFunctionToken { Token = token, Number = number, DatePart = DatePart.Hour };
}
public static DateFunctionExpressionToken AddHours(this DateFunctionExpressionToken token, int number)
{
return new DateAddFunctionToken { Token = token, Number = Sql.Scalar(number), DatePart = DatePart.Hour };
}
public static DateFunctionExpressionToken AddMinutes(this DateFunctionExpressionToken token, Token number)
{
return new DateAddFunctionToken { Token = token, Number = number, DatePart = DatePart.Minute };
}
public static DateFunctionExpressionToken AddMinutes(this DateFunctionExpressionToken token, int number)
{
return new DateAddFunctionToken { Token = token, Number = Sql.Scalar(number), DatePart = DatePart.Minute };
}
public static DateFunctionExpressionToken AddSeconds(this DateFunctionExpressionToken token, Token number)
{
return new DateAddFunctionToken { Token = token, Number = number, DatePart = DatePart.Second };
}
public static DateFunctionExpressionToken AddSeconds(this DateFunctionExpressionToken token, int number)
{
return new DateAddFunctionToken { Token = token, Number = Sql.Scalar(number), DatePart = DatePart.Second };
}
public static DateFunctionExpressionToken AddMilliseconds(this DateFunctionExpressionToken token, Token number)
{
return new DateAddFunctionToken { Token = token, Number = number, DatePart = DatePart.Millisecond };
}
public static DateFunctionExpressionToken AddMilliseconds(this DateFunctionExpressionToken token, int number)
{
return new DateAddFunctionToken
{
Token = token,
Number = Sql.Scalar(number),
DatePart = DatePart.Millisecond
};
}
public static DateFunctionExpressionToken SubtractYears(this DateFunctionExpressionToken token, Token number)
{
return new DateAddFunctionToken
{
Subtract = true,
Token = token,
Number = number,
DatePart = DatePart.Year
};
}
public static DateFunctionExpressionToken SubtractYears(this DateFunctionExpressionToken token, int number)
{
return new DateAddFunctionToken
{
Subtract = true,
Token = token,
Number = Sql.Scalar(number),
DatePart = DatePart.Year
};
}
public static DateFunctionExpressionToken SubtractMonths(this DateFunctionExpressionToken token, Token number)
{
return new DateAddFunctionToken
{
Subtract = true,
Token = token,
Number = number,
DatePart = DatePart.Month
};
}
public static DateFunctionExpressionToken SubtractMonths(this DateFunctionExpressionToken token, int number)
{
return new DateAddFunctionToken
{
Subtract = true,
Token = token,
Number = Sql.Scalar(number),
DatePart = DatePart.Month
};
}
public static DateFunctionExpressionToken SubtractWeeks(this DateFunctionExpressionToken token, Token number)
{
return new DateAddFunctionToken
{
Subtract = true,
Token = token,
Number = number,
DatePart = DatePart.Week
};
}
public static DateFunctionExpressionToken SubtractWeeks(this DateFunctionExpressionToken token, int number)
{
return new DateAddFunctionToken
{
Subtract = true,
Token = token,
Number = Sql.Scalar(number),
DatePart = DatePart.Week
};
}
public static DateFunctionExpressionToken SubtractDays(this DateFunctionExpressionToken token, Token number)
{
return new DateAddFunctionToken { Subtract = true, Token = token, Number = number, DatePart = DatePart.Day };
}
public static DateFunctionExpressionToken SubtractDays(this DateFunctionExpressionToken token, int number)
{
return new DateAddFunctionToken
{
Subtract = true,
Token = token,
Number = Sql.Scalar(number),
DatePart = DatePart.Day
};
}
public static DateFunctionExpressionToken SubtractHours(this DateFunctionExpressionToken token, Token number)
{
return new DateAddFunctionToken
{
Subtract = true,
Token = token,
Number = number,
DatePart = DatePart.Hour
};
}
public static DateFunctionExpressionToken SubtractHours(this DateFunctionExpressionToken token, int number)
{
return new DateAddFunctionToken
{
Subtract = true,
Token = token,
Number = Sql.Scalar(number),
DatePart = DatePart.Hour
};
}
public static DateFunctionExpressionToken SubtractMinutes(this DateFunctionExpressionToken token, Token number)
{
return new DateAddFunctionToken
{
Subtract = true,
Token = token,
Number = number,
DatePart = DatePart.Minute
};
}
public static DateFunctionExpressionToken SubtractMinutes(this DateFunctionExpressionToken token, int number)
{
return new DateAddFunctionToken
{
Subtract = true,
Token = token,
Number = Sql.Scalar(number),
DatePart = DatePart.Minute
};
}
public static DateFunctionExpressionToken SubtractSeconds(this DateFunctionExpressionToken token, Token number)
{
return new DateAddFunctionToken
{
Subtract = true,
Token = token,
Number = number,
DatePart = DatePart.Second
};
}
public static DateFunctionExpressionToken SubtractSeconds(this DateFunctionExpressionToken token, int number)
{
return new DateAddFunctionToken
{
Subtract = true,
Token = token,
Number = Sql.Scalar(number),
DatePart = DatePart.Second
};
}
public static DateFunctionExpressionToken SubtractMilliseconds(this DateFunctionExpressionToken token,
Token number)
{
return new DateAddFunctionToken
{
Subtract = true,
Token = token,
Number = number,
DatePart = DatePart.Millisecond
};
}
public static DateFunctionExpressionToken SubtractMilliseconds(this DateFunctionExpressionToken token,
int number)
{
return new DateAddFunctionToken
{
Subtract = true,
Token = token,
Number = Sql.Scalar(number),
DatePart = DatePart.Millisecond
};
}
#endregion
#region Stored Procedure
public static T As<T>(this T statement, IStatement body) where T : IProcedureStatement
{
statement.Body = body;
return statement;
}
public static T As<T>(this T statement, IStatement body, params IStatement[] additionalBodyStatements)
where T : IProcedureStatement
{
statement.Body = (additionalBodyStatements.Length > 0)
? Sql.Statements(body, additionalBodyStatements)
: body;
return statement;
}
public static T Parameters<T>(this T statement, Parameter parameter, params Parameter[] parameters)
where T : IProcedureStatement
{
statement.Parameters.Add(parameter);
foreach (var p in parameters)
{
statement.Parameters.Add(p);
}
return statement;
}
public static T Parameters<T>(this T statement, ParameterDirection direction, Parameter parameter,
params Parameter[] parameters) where T : IProcedureStatement
{
parameter.Direction = direction;
statement.Parameters.Add(parameter);
foreach (var p in parameters)
{
p.Direction = direction;
statement.Parameters.Add(p);
}
return statement;
}
public static T Declarations<T>(this T statement, Parameter parameter, params Parameter[] parameters)
where T : IProcedureStatement
{
statement.Declarations.Add(parameter);
foreach (var p in parameters)
{
statement.Declarations.Add(p);
}
return statement;
}
public static T Declarations<T>(this T statement, ParameterDirection direction, Parameter parameter,
params Parameter[] parameters) where T : IProcedureStatement
{
parameter.Direction = direction;
statement.Declarations.Add(parameter);
foreach (var p in parameters)
{
parameter.Direction = direction;
statement.Declarations.Add(p);
}
return statement;
}
public static T InputParameters<T>(this T statement, Parameter parameter, params Parameter[] parameters)
where T : IProcedureStatement
{
return statement.Parameters(System.Data.ParameterDirection.Input, parameter, parameters);
}
public static T InputOutputParameters<T>(this T statement, Parameter parameter, params Parameter[] parameters)
where T : IProcedureStatement
{
return statement.Parameters(System.Data.ParameterDirection.InputOutput, parameter, parameters);
}
public static T OutputParameters<T>(this T statement, Parameter parameter, params Parameter[] parameters)
where T : IProcedureStatement
{
return statement.Parameters(System.Data.ParameterDirection.Output, parameter, parameters);
}
public static T ReturnValue<T>(this T statement, Parameter parameter) where T : IProcedureStatement
{
return statement.Parameters(System.Data.ParameterDirection.ReturnValue, parameter);
}
public static T Parameters<T>(this T statement, IEnumerable<Parameter> parameters) where T : IProcedureStatement
{
if (parameters != null)
{
foreach (var p in parameters)
{
statement.Parameters.Add(p);
}
}
return statement;
}
public static T Parameters<T>(this T statement, ParameterDirection direction, IEnumerable<Parameter> parameters)
where T : IProcedureStatement
{
if (parameters != null)
{
foreach (var p in parameters)
{
p.Direction = direction;
statement.Parameters.Add(p);
}
}
return statement;
}
public static T InputParameters<T>(this T statement, IEnumerable<Parameter> parameters)
where T : IProcedureStatement
{
return statement.Parameters(System.Data.ParameterDirection.Input, parameters);
}
public static T InputOutputParameters<T>(this T statement, IEnumerable<Parameter> parameters)
where T : IProcedureStatement
{
return statement.Parameters(System.Data.ParameterDirection.InputOutput, parameters);
}
public static T OutputParameters<T>(this T statement, IEnumerable<Parameter> parameters)
where T : IProcedureStatement
{
return statement.Parameters(System.Data.ParameterDirection.Output, parameters);
}
public static T Recompile<T>(this T statement, bool recompile = true) where T : IProcedureStatement
{
statement.Recompile = recompile;
return statement;
}
public static ExecuteProcedureStatement Recompile(this ExecuteProcedureStatement statement,
bool recompile = true)
{
statement.Recompile = recompile;
return statement;
}
public static DropFunctionStatement Cascade(this DropFunctionStatement statement)
{
statement.IsCascade = true;
return statement;
}
public static DropFunctionStatement Restrict(this DropFunctionStatement statement)
{
statement.IsCascade = false;
return statement;
}
public static DropFunctionStatement ReturnValue(this DropFunctionStatement statement, Parameter parameter)
{
statement.ReturnValue = parameter;
return statement;
}
#endregion Stored Procedure
#region CAST
public static CastToken CastAs(this ExpressionToken token, CommonDbType type)
{
return new CastToken
{
Token = token,
DbType = type
};
}
public static CastToken CastAs(this ExpressionToken token, CommonDbType type, int length)
{
return new CastToken
{
Token = token,
DbType = type,
Length = length
};
}
public static CastToken CastAs(this ExpressionToken token, CommonDbType type, byte precision, byte scale)
{
return new CastToken
{
Token = token,
DbType = type,
Precision = precision,
Scale = scale
};
}
#endregion CAST
public static ExecuteStatement Name(this ExecuteStatement statement,
string name)
{
statement.Name = name;
return statement;
}
public static PrepareStatement Name(this PrepareStatement statement, Name name)
{
statement.Name = name;
return statement;
}
public static PrepareStatement From(this PrepareStatement statement, Name targetFrom)
{
statement.Target.Name = targetFrom;
return statement;
}
public static PrepareStatement From(this PrepareStatement statement, IStatement targetFrom)
{
statement.Target.Target = targetFrom;
return statement;
}
public static DeallocateStatement Name(this DeallocateStatement statement, Name name)
{
statement.Name = name;
return statement;
}
public static AddForeignKeyStatement AddColumn(this AddForeignKeyStatement table, Name column, Name foreignColumn)
{
table.Columns.Add(new ForeignKeyColumn
{
Name = column,
ReferencedName = foreignColumn
});
return table;
}
}
} | 35.177227 | 129 | 0.580488 | [
"MIT"
] | oshpak92/fluid-sql | C#/TTRider.FluidSQL/FluidExtensions.cs | 114,926 | C# |
//BY DX4D
using UnityEngine;
namespace OpenMMO
{
[RequireComponent(typeof(PlayerAccount))]
[RequireComponent(typeof(CharacterProfile))]
[RequireComponent(typeof(DisallowMultipleComponent))]
public class PlayableCharacter : MonoBehaviour
{
[SerializeField] CharacterProfile _profile = null;
public CharacterProfile profile { get { return _profile; } }
[SerializeField] PlayerAccount _account = null;
public PlayerAccount account { get { return _account; } }
private void OnValidate()
{
if (!_profile) _profile = GetComponent<CharacterProfile>();
if (!_account) _account = GetComponent<PlayerAccount>();
}
}
} | 31.043478 | 71 | 0.670868 | [
"MIT"
] | 10allday/OpenMMO | Plugins/Addons/GameSystems/CharacterSystem/PlayableCharacter/PlayableCharacter.cs | 714 | C# |
// Copyright 2020 Energinet DataHub A/S
//
// Licensed under the Apache License, Version 2.0 (the "License2");
// 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 Energinet.DataHub.MeteringPoints.Domain.SeedWork;
namespace Energinet.DataHub.MeteringPoints.Application.Validation.ValidationErrors
{
public class MeasureUnitTypeInvalidValueValidationError : ValidationError
{
public MeasureUnitTypeInvalidValueValidationError(string measureUnitType, string gsrnNumber)
{
MeasureUnitType = measureUnitType;
GsrnNumber = gsrnNumber;
}
public string MeasureUnitType { get; }
public string GsrnNumber { get; }
}
}
| 35.34375 | 100 | 0.734748 | [
"Apache-2.0"
] | Energinet-DataHub/geh-metering-point | source/Energinet.DataHub.MeteringPoints.Application/Validation/ValidationErrors/MeasureUnitTypeInvalidValueValidationError.cs | 1,133 | C# |
using System;
class strokePersegi {
static void Main() {
Console.Write("Masukan Lebar Persegi : ");
int x = int.Parse(Console.ReadLine());
for(int j = 0; j <= x; j++){
Console.Write("* ");
}
Console.Write("\n");
for(int i = 0; i <= (x-2); i++){
Console.Write("* ");
for(int j = 0; j <= (x-2); j++){
Console.Write(" ");
}
Console.Write("*\n");
}
for(int k = 0; k <= x; k++){
Console.Write("* ");
}
}
}
| 20.68 | 46 | 0.427466 | [
"MIT"
] | shabriocahyo/mini-projects-compilation | Persegi (Stroke)/C#/persegi-stroke-i.cs | 517 | C# |
#region
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web.Script.Serialization;
using LegendaryClient.Logic.SQLite;
#endregion
namespace LegendaryClient.Logic.JSON
{
public static class Masteries
{
public static List<masteries> PopulateMasteries()
{
var masteryList = new List<masteries>();
string masteryJson =
File.ReadAllText(Path.Combine(Client.ExecutingDirectory, "Assets", "data", "en_US", "mastery.json"));
var serializer = new JavaScriptSerializer();
var deserializedJson = serializer.Deserialize<Dictionary<string, object>>(masteryJson);
var masteryData = deserializedJson["data"] as Dictionary<string, object>;
var treeData = deserializedJson["tree"] as Dictionary<string, object>;
if (masteryData != null)
foreach (var mastery in masteryData)
{
var singularMasteryData = mastery.Value as Dictionary<string, object>;
var newMastery = new masteries {id = Convert.ToInt32(mastery.Key)};
if (singularMasteryData != null)
{
newMastery.name = singularMasteryData["name"] as string;
newMastery.description = singularMasteryData["description"] as ArrayList;
newMastery.ranks = (int) singularMasteryData["ranks"];
newMastery.prereq = Convert.ToInt32(singularMasteryData["prereq"]);
var imageData = singularMasteryData["image"] as Dictionary<string, object>;
if (imageData != null)
{
string uriSource = Path.Combine(Client.ExecutingDirectory, "Assets", "mastery",
(string) imageData["full"]);
newMastery.icon = Client.GetImage(uriSource);
}
}
masteryList.Add(newMastery);
}
if (treeData == null)
return masteryList;
foreach (var tree in treeData)
{
var list = (ArrayList) tree.Value;
int i;
for (i = 0; i < list.Count; i++)
{
foreach (masteries tempMastery in from Dictionary<string, object> x in (ArrayList) list[i]
where x != null
select Convert.ToInt32(x["masteryId"])
into masteryId
select masteryList.Find(y => y.id == masteryId))
{
tempMastery.treeRow = i;
tempMastery.tree = tree.Key;
}
}
}
return masteryList;
}
}
} | 38.894737 | 117 | 0.519283 | [
"BSD-2-Clause"
] | nongnoobjung/Legendary-Garena | LegendaryClient/Logic/JSON/Masteries.cs | 2,958 | C# |
using Dopple;
using Dopple.InstructionNodes;
using Mono.Cecil.Cil;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace GraphSimilarityByMatching
{
public class GraphSimilarityCalc
{
private static readonly CodeInfo opCodeInfo = new CodeInfo();
public static NodePairings GetDistance(List<InstructionNode> sourceGraph, List<InstructionNode> imageGraph)
{
List<LabeledVertex> sourceGraphLabeled = GetLabeled(sourceGraph);
List<LabeledVertex> imageGraphLabeled = GetLabeled(imageGraph);
var retNodes = sourceGraph.Where(x => VertexScorer.OutDataCodes.Contains(x.Instruction.OpCode.Code));
var backRetTree = retNodes.SelectMany(x => BackSearcher.GetBackDataTree(x)).Distinct().Concat(retNodes).ToList();
backRetTree.AddRange(backRetTree.ToList().SelectMany(x => x.BranchProperties.Branches.Select(y => y.OriginatingNode)));
var backRetTreeIndexes = backRetTree.Select(x => x.InstructionIndex).ToList();
foreach(var backRetNode in sourceGraphLabeled.Where(x => backRetTreeIndexes.Contains(x.Index)))
{
backRetNode.IsInReturnBackTree = true;
}
NodePairings bestMatch = GetPairings(sourceGraphLabeled, imageGraphLabeled);
object lockObject = new object();
//TODO change back to 10
Parallel.For(1, 1, (i) =>
{
NodePairings pairing = GetPairings(sourceGraphLabeled, imageGraphLabeled);
if (pairing.TotalScore >1)
{ throw new Exception(""); }
lock(lockObject)
{
if (pairing.TotalScore > bestMatch.TotalScore)
{
bestMatch = pairing;
}
}
});
bestMatch.SourceSelfPairings = GetGraphSelfScore(sourceGraphLabeled);
bestMatch.ImageSelfPairings = GetGraphSelfScore(imageGraphLabeled);
return bestMatch ;
}
private static NodePairings GetPairings(List<LabeledVertex> sourceGraphLabeled, List<LabeledVertex> imageGraphLabeled)
{
NodePairings nodePairings = new NodePairings(sourceGraph: sourceGraphLabeled, imageGraph: imageGraphLabeled);
Random rnd = new Random();
Dictionary<Code[], IEnumerable<LabeledVertex>> sourceGraphGrouped;
Dictionary<Code[], IEnumerable<LabeledVertex>> imageGraphGrouped;
GetGrouped(sourceGraphLabeled: sourceGraphLabeled, imageGraphLabeled: imageGraphLabeled, sourceGraphGrouped: out sourceGraphGrouped, imageGraphGrouped: out imageGraphGrouped);
//Parallel.ForEach(sourceGraphGrouped.Keys, (codeGroup) =>
foreach (var codeGroup in sourceGraphGrouped.Keys)
{
//not gonna lock for now
foreach (var sourceGraphVertex in sourceGraphGrouped[codeGroup])
{
VertexMatch winningPair;
if (!imageGraphGrouped.ContainsKey(codeGroup))
{
winningPair = null;
}
//Parallel.ForEach(imageGraphGrouped[codeGroup].OrderBy(x => rnd.Next()).ToList(), (imageGraphCandidate) =>
else
{
var vertexPossiblePairings = new ConcurrentBag<VertexMatch>();
foreach (var imageGraphCandidate in imageGraphGrouped[codeGroup].OrderBy(x => rnd.Next()).ToList())
{
vertexPossiblePairings.Add(new VertexMatch() { SourceGraphVertex = sourceGraphVertex, ImageGraphVertex = imageGraphCandidate, Score = VertexScorer.GetScore(sourceGraphVertex, imageGraphCandidate, nodePairings) });
}
winningPair = vertexPossiblePairings.Where(x => x.Score > 0).OrderByDescending(x => x.Score).ThenBy(x => rnd.Next()).FirstOrDefault();
}
//});
if (winningPair != null)
{
lock (nodePairings.Pairings)
{
winningPair.NormalizedScore = winningPair.Score / VertexScorer.GetSelfScore(winningPair.SourceGraphVertex);
nodePairings.Pairings[winningPair.ImageGraphVertex].Add(winningPair);
nodePairings.TotalScore += winningPair.Score;
}
}
}
}
// });
return nodePairings;
}
private static void GetGrouped(List<LabeledVertex> sourceGraphLabeled, List<LabeledVertex> imageGraphLabeled, out Dictionary<Code[],IEnumerable<LabeledVertex>> sourceGraphGrouped, out Dictionary<Code[], IEnumerable<LabeledVertex>> imageGraphGrouped)
{
sourceGraphGrouped = CodeGroups.CodeGroupLists.AsParallel().ToDictionary(x => x, x => sourceGraphLabeled.Where(y => x.Contains(y.Opcode)));
imageGraphGrouped = CodeGroups.CodeGroupLists.AsParallel().ToDictionary(x => x, x => imageGraphLabeled.Where(y => x.Contains(y.Opcode)));
foreach (var singleCode in sourceGraphLabeled.Except(sourceGraphGrouped.Values.SelectMany(x => x)).GroupBy(x => x.Opcode))
{
var singleCodeArray = new Code[] { singleCode.Key };
sourceGraphGrouped.Add(singleCodeArray, singleCode.ToList());
imageGraphGrouped.Add(singleCodeArray, imageGraphLabeled.Where(x => x.Opcode == singleCode.Key).ToList());
}
return;
}
private static List<LabeledVertex> GetLabeled(List<InstructionNode> graph)
{
var labeledVertexes = graph.AsParallel().Select(x => new LabeledVertex()
{
Opcode = x.Instruction.OpCode.Code,
Operand = x.Instruction.Operand,
Index = x.InstructionIndex,
Method = x.Method,
}).ToList();
Parallel.ForEach(graph, (node) =>
{
AddEdges(node, labeledVertexes);
});
return labeledVertexes;
}
private static List<LabeledVertex> GetBackSingleUnitTree(LabeledVertex frontMostInSingleUnit)
{
List<LabeledVertex> backTree = new List<LabeledVertex>();
Queue<LabeledVertex> backRelated = new Queue<LabeledVertex>();
foreach (var backSingleUnit in frontMostInSingleUnit.BackEdges.Where(x => x.EdgeType == EdgeType.SingleUnit))
{
backRelated.Enqueue(backSingleUnit.SourceVertex);
}
while (backRelated.Count > 0)
{
var currNode = backRelated.Dequeue();
backTree.Add(currNode);
foreach(var backSingleUnit in currNode.BackEdges.Where(x => x.EdgeType == EdgeType.SingleUnit))
{
backRelated.Enqueue(backSingleUnit.SourceVertex);
}
}
return backTree;
}
private static void AddEdges(InstructionNode node, List<LabeledVertex> labeledVertexes)
{
LabeledVertex vertex = labeledVertexes[node.InstructionIndex];
foreach (var dataFlowBackVertex in node.DataFlowBackRelated)
{
vertex.BackEdges.Add(new LabeledEdge()
{
EdgeType = EdgeType.DataFlow,
Index = dataFlowBackVertex.ArgIndex,
SourceVertex = labeledVertexes[dataFlowBackVertex.Argument.InstructionIndex],
DestinationVertex = vertex
});
}
foreach (var branch in node.BranchProperties.Branches)
{
vertex.BackEdges.Add(new LabeledEdge()
{
EdgeType = EdgeType.ProgramFlowAffecting,
Index = (int) branch.MergeNodeBranchIndex,
SourceVertex = labeledVertexes[branch.OriginatingNode.InstructionIndex],
DestinationVertex = vertex
});
}
foreach (var dataFlowBackVertex in node.DataFlowForwardRelated)
{
vertex.ForwardEdges.Add(new LabeledEdge()
{
EdgeType = EdgeType.DataFlow,
Index = dataFlowBackVertex.ArgIndex,
SourceVertex = vertex,
DestinationVertex = labeledVertexes[dataFlowBackVertex.Argument.InstructionIndex]
});
}
}
public static NodePairings GetGraphSelfScore(List<LabeledVertex> labeledGraph)
{
NodePairings nodePairings = new NodePairings(imageGraph: labeledGraph, sourceGraph: labeledGraph);
foreach (var node in labeledGraph)
{
double score = VertexScorer.GetSelfScore(node);
nodePairings.Pairings[node].Add(new VertexMatch() { SourceGraphVertex = node, ImageGraphVertex = node, Score = score, NormalizedScore = 1 });
nodePairings.TotalScore += score;
}
return nodePairings;
}
}
internal enum SharedSourceOrDest
{
Source,
Dest
}
}
| 46.892157 | 257 | 0.584989 | [
"MIT"
] | simcoster/Dopple | GraphSimilarityByMatching/GraphSimilarityCalc.cs | 9,568 | C# |
namespace Envoice.MongoIdentityServer
{
public class Constants
{
public class TableNames
{
// Configuration
public const string IdentityClaim = "IdentityClaims";
public const string IdentityResource = "IdentityResources";
public const string ApiClaim = "ApiClaims";
public const string ApiResource = "ApiResources";
public const string ApiScope = "ApiScopes";
public const string ApiScopeClaim = "ApiScopeClaims";
public const string ApiSecret = "ApiSecrets";
public const string Client = "Clients";
public const string ClientClaim = "ClientClaims";
public const string ClientCorsOrigin = "ClientCorsOrigins";
public const string ClientGrantType = "ClientGrantTypes";
public const string ClientIdPRestriction = "ClientIdPRestrictions";
public const string ClientPostLogoutRedirectUri = "ClientPostLogoutRedirectUris";
public const string ClientRedirectUri = "ClientRedirectUris";
public const string ClientScopes = "ClientScopes";
public const string ClientSecret = "ClientSecrets";
// Operational
public const string PersistedGrant = "PersistedGrants";
}
}
}
| 41.5 | 93 | 0.648343 | [
"MIT"
] | christophla/Envoice.MongoIdentityServer | src/Envoice.MongoIdentityServer/Constants.cs | 1,330 | C# |
using System;
namespace SIT.Microblog.Entities
{
public class Post
{
public int Id { get; set; }
public string Title { get; set; }
public DateTime Created { get; set; }
public int UserId { get; set; }
}
} | 18.583333 | 39 | 0.641256 | [
"MIT"
] | diggingforfire/aspnetcore-microblog | src/SIT.Microblog.Entities/Post.cs | 225 | C# |
/*******************************************************************************
* Copyright 2012-2019 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.
* *****************************************************************************
*
* AWS Tools for Windows (TM) PowerShell (TM)
*
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Management.Automation;
using System.Text;
using Amazon.PowerShell.Common;
using Amazon.Runtime;
using Amazon.Organizations;
using Amazon.Organizations.Model;
namespace Amazon.PowerShell.Cmdlets.ORG
{
/// <summary>
/// Retrieves the list of all policies in an organization of a specified type.
///
/// <note><para>
/// Always check the <code>NextToken</code> response parameter for a <code>null</code>
/// value when calling a <code>List*</code> operation. These operations can occasionally
/// return an empty set of results even when there are more results available. The <code>NextToken</code>
/// response parameter value is <code>null</code><i>only</i> when there are no more results
/// to display.
/// </para></note><para>
/// This operation can be called only from the organization's master account.
/// </para><br/><br/>This cmdlet automatically pages all available results to the pipeline - parameters related to iteration are only needed if you want to manually control the paginated output. To disable autopagination, use -NoAutoIteration.
/// </summary>
[Cmdlet("Get", "ORGPolicyList")]
[OutputType("Amazon.Organizations.Model.PolicySummary")]
[AWSCmdlet("Calls the AWS Organizations ListPolicies API operation.", Operation = new[] {"ListPolicies"}, SelectReturnType = typeof(Amazon.Organizations.Model.ListPoliciesResponse))]
[AWSCmdletOutput("Amazon.Organizations.Model.PolicySummary or Amazon.Organizations.Model.ListPoliciesResponse",
"This cmdlet returns a collection of Amazon.Organizations.Model.PolicySummary objects.",
"The service call response (type Amazon.Organizations.Model.ListPoliciesResponse) can also be referenced from properties attached to the cmdlet entry in the $AWSHistory stack."
)]
public partial class GetORGPolicyListCmdlet : AmazonOrganizationsClientCmdlet, IExecutor
{
#region Parameter Filter
/// <summary>
/// <para>
/// <para>Specifies the type of policy that you want to include in the response.</para>
/// </para>
/// </summary>
#if !MODULAR
[System.Management.Automation.Parameter(Position = 0, ValueFromPipelineByPropertyName = true, ValueFromPipeline = true)]
#else
[System.Management.Automation.Parameter(Position = 0, ValueFromPipelineByPropertyName = true, ValueFromPipeline = true, Mandatory = true)]
[System.Management.Automation.AllowNull]
#endif
[Amazon.PowerShell.Common.AWSRequiredParameter]
[AWSConstantClassSource("Amazon.Organizations.PolicyType")]
public Amazon.Organizations.PolicyType Filter { get; set; }
#endregion
#region Parameter MaxResult
/// <summary>
/// <para>
/// <para>(Optional) Use this to limit the number of results you want included per page in the
/// response. If you do not include this parameter, it defaults to a value that is specific
/// to the operation. If additional items exist beyond the maximum you specify, the <code>NextToken</code>
/// response element is present and has a value (is not null). Include that value as the
/// <code>NextToken</code> request parameter in the next call to the operation to get
/// the next part of the results. Note that Organizations might return fewer results than
/// the maximum even when there are more results available. You should check <code>NextToken</code>
/// after every operation to ensure that you receive all of the results.</para>
/// </para>
/// <para>
/// <br/><b>Note:</b> In AWSPowerShell and AWSPowerShell.NetCore this parameter is used to limit the total number of items returned by the cmdlet.
/// <br/>In AWS.Tools this parameter is simply passed to the service to specify how many items should be returned by each service call.
/// <br/>Pipe the output of this cmdlet into Select-Object -First to terminate retrieving data pages early and control the number of items returned.
/// </para>
/// </summary>
[System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)]
[Alias("MaxItems","MaxResults")]
public int? MaxResult { get; set; }
#endregion
#region Parameter NextToken
/// <summary>
/// <para>
/// <para>Use this parameter if you receive a <code>NextToken</code> response in a previous
/// request that indicates that there is more output available. Set it to the value of
/// the previous call's <code>NextToken</code> response to indicate where the output should
/// continue from.</para>
/// </para>
/// <para>
/// <br/><b>Note:</b> This parameter is only used if you are manually controlling output pagination of the service API call.
/// <br/>In order to manually control output pagination, use '-NextToken $null' for the first call and '-NextToken $AWSHistory.LastServiceResponse.NextToken' for subsequent calls.
/// </para>
/// </summary>
[System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)]
public System.String NextToken { get; set; }
#endregion
#region Parameter Select
/// <summary>
/// Use the -Select parameter to control the cmdlet output. The default value is 'Policies'.
/// Specifying -Select '*' will result in the cmdlet returning the whole service response (Amazon.Organizations.Model.ListPoliciesResponse).
/// Specifying the name of a property of type Amazon.Organizations.Model.ListPoliciesResponse will result in that property being returned.
/// Specifying -Select '^ParameterName' will result in the cmdlet returning the selected cmdlet parameter value.
/// </summary>
[System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)]
public string Select { get; set; } = "Policies";
#endregion
#region Parameter PassThru
/// <summary>
/// Changes the cmdlet behavior to return the value passed to the Filter parameter.
/// The -PassThru parameter is deprecated, use -Select '^Filter' instead. This parameter will be removed in a future version.
/// </summary>
[System.Obsolete("The -PassThru parameter is deprecated, use -Select '^Filter' instead. This parameter will be removed in a future version.")]
[System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)]
public SwitchParameter PassThru { get; set; }
#endregion
#region Parameter NoAutoIteration
/// <summary>
/// By default the cmdlet will auto-iterate and retrieve all results to the pipeline by performing multiple
/// service calls. If set, the cmdlet will retrieve only the next 'page' of results using the value of NextToken
/// as the start point.
/// </summary>
[System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)]
public SwitchParameter NoAutoIteration { get; set; }
#endregion
protected override void ProcessRecord()
{
base.ProcessRecord();
var context = new CmdletContext();
// allow for manipulation of parameters prior to loading into context
PreExecutionContextLoad(context);
#pragma warning disable CS0618, CS0612 //A class member was marked with the Obsolete attribute
if (ParameterWasBound(nameof(this.Select)))
{
context.Select = CreateSelectDelegate<Amazon.Organizations.Model.ListPoliciesResponse, GetORGPolicyListCmdlet>(Select) ??
throw new System.ArgumentException("Invalid value for -Select parameter.", nameof(this.Select));
if (this.PassThru.IsPresent)
{
throw new System.ArgumentException("-PassThru cannot be used when -Select is specified.", nameof(this.Select));
}
}
else if (this.PassThru.IsPresent)
{
context.Select = (response, cmdlet) => this.Filter;
}
#pragma warning restore CS0618, CS0612 //A class member was marked with the Obsolete attribute
context.Filter = this.Filter;
#if MODULAR
if (this.Filter == null && ParameterWasBound(nameof(this.Filter)))
{
WriteWarning("You are passing $null as a value for parameter Filter which is marked as required. In case you believe this parameter was incorrectly marked as required, report this by opening an issue at https://github.com/aws/aws-tools-for-powershell/issues.");
}
#endif
context.MaxResult = this.MaxResult;
#if !MODULAR
if (ParameterWasBound(nameof(this.MaxResult)) && this.MaxResult.HasValue)
{
WriteWarning("AWSPowerShell and AWSPowerShell.NetCore use the MaxResult parameter to limit the total number of items returned by the cmdlet." +
" This behavior is obsolete and will be removed in a future version of these modules. Pipe the output of this cmdlet into Select-Object -First to terminate" +
" retrieving data pages early and control the number of items returned. AWS.Tools already implements the new behavior of simply passing MaxResult" +
" to the service to specify how many items should be returned by each service call.");
}
#endif
context.NextToken = this.NextToken;
// allow further manipulation of loaded context prior to processing
PostExecutionContextLoad(context);
var output = Execute(context) as CmdletOutput;
ProcessOutput(output);
}
#region IExecutor Members
#if MODULAR
public object Execute(ExecutorContext context)
{
var cmdletContext = context as CmdletContext;
#pragma warning disable CS0618, CS0612 //A class member was marked with the Obsolete attribute
var useParameterSelect = this.Select.StartsWith("^") || this.PassThru.IsPresent;
#pragma warning restore CS0618, CS0612 //A class member was marked with the Obsolete attribute
// create request and set iteration invariants
var request = new Amazon.Organizations.Model.ListPoliciesRequest();
if (cmdletContext.Filter != null)
{
request.Filter = cmdletContext.Filter;
}
if (cmdletContext.MaxResult != null)
{
request.MaxResults = AutoIterationHelpers.ConvertEmitLimitToServiceTypeInt32(cmdletContext.MaxResult.Value);
}
// Initialize loop variant and commence piping
var _nextToken = cmdletContext.NextToken;
var _userControllingPaging = this.NoAutoIteration.IsPresent || ParameterWasBound(nameof(this.NextToken));
var client = Client ?? CreateClient(_CurrentCredentials, _RegionEndpoint);
do
{
request.NextToken = _nextToken;
CmdletOutput output;
try
{
var response = CallAWSServiceOperation(client, request);
object pipelineOutput = null;
if (!useParameterSelect)
{
pipelineOutput = cmdletContext.Select(response, this);
}
output = new CmdletOutput
{
PipelineOutput = pipelineOutput,
ServiceResponse = response
};
_nextToken = response.NextToken;
}
catch (Exception e)
{
output = new CmdletOutput { ErrorResponse = e };
}
ProcessOutput(output);
} while (!_userControllingPaging && AutoIterationHelpers.HasValue(_nextToken));
if (useParameterSelect)
{
WriteObject(cmdletContext.Select(null, this));
}
return null;
}
#else
public object Execute(ExecutorContext context)
{
var cmdletContext = context as CmdletContext;
var useParameterSelect = this.Select.StartsWith("^") || this.PassThru.IsPresent;
// create request and set iteration invariants
var request = new Amazon.Organizations.Model.ListPoliciesRequest();
if (cmdletContext.Filter != null)
{
request.Filter = cmdletContext.Filter;
}
// Initialize loop variants and commence piping
System.String _nextToken = null;
int? _emitLimit = null;
int _retrievedSoFar = 0;
if (AutoIterationHelpers.HasValue(cmdletContext.NextToken))
{
_nextToken = cmdletContext.NextToken;
}
if (AutoIterationHelpers.HasValue(cmdletContext.MaxResult))
{
// The service has a maximum page size of 20. If the user has
// asked for more items than page max, and there is no page size
// configured, we rely on the service ignoring the set maximum
// and giving us 20 items back. If a page size is set, that will
// be used to configure the pagination.
// We'll make further calls to satisfy the user's request.
_emitLimit = cmdletContext.MaxResult;
}
var _userControllingPaging = this.NoAutoIteration.IsPresent || ParameterWasBound(nameof(this.NextToken));
var client = Client ?? CreateClient(_CurrentCredentials, _RegionEndpoint);
do
{
request.NextToken = _nextToken;
if (_emitLimit.HasValue)
{
int correctPageSize = AutoIterationHelpers.Min(20, _emitLimit.Value);
request.MaxResults = AutoIterationHelpers.ConvertEmitLimitToInt32(correctPageSize);
}
CmdletOutput output;
try
{
var response = CallAWSServiceOperation(client, request);
object pipelineOutput = null;
if (!useParameterSelect)
{
pipelineOutput = cmdletContext.Select(response, this);
}
output = new CmdletOutput
{
PipelineOutput = pipelineOutput,
ServiceResponse = response
};
int _receivedThisCall = response.Policies.Count;
_nextToken = response.NextToken;
_retrievedSoFar += _receivedThisCall;
if (_emitLimit.HasValue)
{
_emitLimit -= _receivedThisCall;
}
}
catch (Exception e)
{
if (_retrievedSoFar == 0 || !_emitLimit.HasValue)
{
output = new CmdletOutput { ErrorResponse = e };
}
else
{
break;
}
}
ProcessOutput(output);
} while (!_userControllingPaging && AutoIterationHelpers.HasValue(_nextToken) && (!_emitLimit.HasValue || _emitLimit.Value >= 1));
if (useParameterSelect)
{
WriteObject(cmdletContext.Select(null, this));
}
return null;
}
#endif
public ExecutorContext CreateContext()
{
return new CmdletContext();
}
#endregion
#region AWS Service Operation Call
private Amazon.Organizations.Model.ListPoliciesResponse CallAWSServiceOperation(IAmazonOrganizations client, Amazon.Organizations.Model.ListPoliciesRequest request)
{
Utils.Common.WriteVerboseEndpointMessage(this, client.Config, "AWS Organizations", "ListPolicies");
try
{
#if DESKTOP
return client.ListPolicies(request);
#elif CORECLR
return client.ListPoliciesAsync(request).GetAwaiter().GetResult();
#else
#error "Unknown build edition"
#endif
}
catch (AmazonServiceException exc)
{
var webException = exc.InnerException as System.Net.WebException;
if (webException != null)
{
throw new Exception(Utils.Common.FormatNameResolutionFailureMessage(client.Config, webException.Message), webException);
}
throw;
}
}
#endregion
internal partial class CmdletContext : ExecutorContext
{
public Amazon.Organizations.PolicyType Filter { get; set; }
public int? MaxResult { get; set; }
public System.String NextToken { get; set; }
public System.Func<Amazon.Organizations.Model.ListPoliciesResponse, GetORGPolicyListCmdlet, object> Select { get; set; } =
(response, cmdlet) => response.Policies;
}
}
}
| 48.032581 | 277 | 0.589356 | [
"Apache-2.0"
] | 5u5hma/aws-tools-for-powershell | modules/AWSPowerShell/Cmdlets/Organizations/Basic/Get-ORGPolicyList-Cmdlet.cs | 19,165 | C# |
/*
* Domain Public API
*
* See https://developer.domain.com.au for more information
*
* The version of the OpenAPI document: v1
* Contact: api@domain.com.au
* Generated by: https://github.com/openapitools/openapi-generator.git
*/
using System;
using System.IO;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Reflection;
using RestSharp;
using Xunit;
using Domain.Api.V1.Client;
using Domain.Api.V1.Api;
// uncomment below to import models
//using Domain.Api.V1.Model;
namespace Domain.Api.V1.Test.Api
{
/// <summary>
/// Class for testing PropertiesApi
/// </summary>
/// <remarks>
/// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech).
/// Please update the test case below to test the API endpoint.
/// </remarks>
public class PropertiesApiTests : IDisposable
{
private PropertiesApi instance;
public PropertiesApiTests()
{
instance = new PropertiesApi();
}
public void Dispose()
{
// Cleanup when everything is done.
}
/// <summary>
/// Test an instance of PropertiesApi
/// </summary>
[Fact]
public void InstanceTest()
{
// TODO uncomment below to test 'IsType' PropertiesApi
//Assert.IsType<PropertiesApi>(instance);
}
/// <summary>
/// Test PropertiesGet
/// </summary>
[Fact]
public void PropertiesGetTest()
{
// TODO uncomment below to test the method and replace null with proper value
//string id = null;
//var response = instance.PropertiesGet(id);
//Assert.IsType<DomainPublicAdapterWebApiModelsV1PropertiesProperty>(response);
}
/// <summary>
/// Test PropertiesGetPriceEstimate
/// </summary>
[Fact]
public void PropertiesGetPriceEstimateTest()
{
// TODO uncomment below to test the method and replace null with proper value
//string id = null;
//var response = instance.PropertiesGetPriceEstimate(id);
//Assert.IsType<DomainPublicAdapterWebApiModelsV1PropertiesPriceEstimate>(response);
}
/// <summary>
/// Test PropertiesSuggest
/// </summary>
[Fact]
public void PropertiesSuggestTest()
{
// TODO uncomment below to test the method and replace null with proper value
//string terms = null;
//int? pageSize = null;
//LocationTypeaheadV1PropertySuggestionChannel? channel = null;
//var response = instance.PropertiesSuggest(terms, pageSize, channel);
//Assert.IsType<List<LocationTypeaheadV1PropertySuggestion>>(response);
}
}
}
| 29.845361 | 99 | 0.613817 | [
"MIT"
] | neildobson-au/InvestOz | src/Integrations/Domain/Domain.Api.V1/src/Domain.Api.V1.Test/Api/PropertiesApiTests.cs | 2,895 | C# |
using CliFx.Exceptions;
using CliWrap;
using CliWrap.Buffered;
using Husky.Services.Contracts;
using Husky.Stdout;
using Husky.Utils;
namespace Husky.Services;
public class Git : IGit
{
private readonly ICliWrap _cliWrap;
private readonly AsyncLazy<string> _currentBranch;
private readonly AsyncLazy<string> _gitDirRelativePath;
private readonly AsyncLazy<string[]> _GitFiles;
private readonly AsyncLazy<string> _gitPath;
private readonly AsyncLazy<string> _huskyPath;
private readonly AsyncLazy<string[]> _lastCommitFiles;
private readonly AsyncLazy<string[]> _stagedFiles;
public Git(ICliWrap cliWrap)
{
_cliWrap = cliWrap;
_gitPath = new AsyncLazy<string>(GetGitPath);
_huskyPath = new AsyncLazy<string>(GetHuskyPath);
_stagedFiles = new AsyncLazy<string[]>(GetStagedFiles);
_GitFiles = new AsyncLazy<string[]>(GetGitFiles);
_lastCommitFiles = new AsyncLazy<string[]>(GetLastCommitFiles);
_currentBranch = new AsyncLazy<string>(GetCurrentBranch);
_gitDirRelativePath = new AsyncLazy<string>(GetGitDirRelativePath);
}
public async Task<string[]> GetDiffNameOnlyAsync()
{
try
{
var result = await ExecBufferedAsync("diff --name-only");
if (result.ExitCode != 0)
throw new Exception($"Exit code: {result.ExitCode}"); // break execution
return result.StandardOutput
.Trim()
.Split(new[] { "\r\n", "\r", "\n" }, StringSplitOptions.RemoveEmptyEntries);
}
catch (Exception e)
{
e.Message.LogVerbose(ConsoleColor.DarkRed);
throw new CommandException("git diff failed", innerException: e);
}
}
public async Task<string[]> GetStagedFilesAsync()
{
return await _stagedFiles;
}
public async Task<string[]> GitFilesAsync()
{
return await _GitFiles;
}
public async Task<string[]> GetLastCommitFilesAsync()
{
return await _lastCommitFiles;
}
public async Task<string> GetGitPathAsync()
{
return await _gitPath;
}
public async Task<string> GetGitDirRelativePathAsync()
{
return await _gitDirRelativePath;
}
public async Task<string> GetCurrentBranchAsync()
{
return await _currentBranch;
}
public async Task<string> GetHuskyPathAsync()
{
return await _huskyPath;
}
public async Task<string[]> GetDiffStagedRecord()
{
try
{
var result = await ExecBufferedAsync(
"diff-index --cached --diff-filter=AM --no-renames HEAD"
);
if (result.ExitCode != 0)
throw new Exception($"Exit code: {result.ExitCode}"); // break execution
return result.StandardOutput
.Trim()
.Split(new[] { "\r\n", "\r", "\n" }, StringSplitOptions.RemoveEmptyEntries);
}
catch (Exception e)
{
e.Message.LogVerbose(ConsoleColor.DarkRed);
throw new CommandException("Could not find the staged files", innerException: e);
}
}
private async Task<string> GetGitDirRelativePath()
{
try
{
var result = await ExecBufferedAsync("rev-parse --path-format=relative --git-dir");
if (result.ExitCode != 0)
throw new Exception($"Exit code: {result.ExitCode}"); // break execution
return result.StandardOutput.Trim();
}
catch (Exception e)
{
e.Message.LogVerbose(ConsoleColor.DarkRed);
throw new CommandException("Could not find git directory", innerException: e);
}
}
private async Task<string> GetCurrentBranch()
{
try
{
var result = await ExecBufferedAsync("branch --show-current");
if (result.ExitCode != 0)
throw new Exception($"Exit code: {result.ExitCode}"); // break execution
return result.StandardOutput.Trim();
}
catch (Exception e)
{
e.Message.LogVerbose(ConsoleColor.DarkRed);
throw new CommandException("Could not find git path", innerException: e);
}
}
public Task<CommandResult> ExecAsync(string args)
{
return _cliWrap.ExecDirectAsync("git", args);
}
public Task<BufferedCommandResult> ExecBufferedAsync(string args)
{
return _cliWrap.ExecBufferedAsync("git", args);
}
private async Task<string> GetHuskyPath()
{
try
{
var result = await ExecBufferedAsync("config --get core.hooksPath");
if (result.ExitCode != 0)
throw new Exception($"Exit code: {result.ExitCode}"); // break execution
return result.StandardOutput.Trim();
}
catch (Exception e)
{
e.Message.LogVerbose(ConsoleColor.DarkRed);
throw new CommandException("Could not find Husky path", innerException: e);
}
}
private async Task<string> GetGitPath()
{
try
{
var result = await ExecBufferedAsync("rev-parse --show-toplevel");
if (result.ExitCode != 0)
throw new Exception($"Exit code: {result.ExitCode}"); // break execution
return result.StandardOutput.Trim();
}
catch (Exception e)
{
e.Message.LogVerbose(ConsoleColor.DarkRed);
throw new CommandException("Could not find git path", innerException: e);
}
}
private async Task<string[]> GetLastCommitFiles()
{
try
{
var result = await ExecBufferedAsync("diff --diff-filter=d --name-only HEAD^");
if (result.ExitCode != 0)
throw new Exception($"Exit code: {result.ExitCode}"); // break execution
return result.StandardOutput
.Trim()
.Split(new[] { "\r\n", "\r", "\n" }, StringSplitOptions.RemoveEmptyEntries);
}
catch (Exception e)
{
e.Message.LogVerbose(ConsoleColor.DarkRed);
throw new CommandException("Could not find the last commit files", innerException: e);
}
}
private async Task<string[]> GetStagedFiles()
{
try
{
// '--diff-filter=AM', # select only file additions and modifications
var result = await ExecBufferedAsync(
"diff-index --cached --diff-filter=AM --no-renames --name-only HEAD"
);
if (result.ExitCode != 0)
throw new Exception($"Exit code: {result.ExitCode}"); // break execution
return result.StandardOutput
.Trim()
.Split(new[] { "\r\n", "\r", "\n" }, StringSplitOptions.RemoveEmptyEntries);
}
catch (Exception e)
{
e.Message.LogVerbose(ConsoleColor.DarkRed);
throw new CommandException("Could not find the staged files", innerException: e);
}
}
private async Task<string[]> GetGitFiles()
{
try
{
var result = await ExecBufferedAsync("ls-files");
if (result.ExitCode != 0)
throw new Exception($"Exit code: {result.ExitCode}"); // break execution
return result.StandardOutput
.Trim()
.Split(new[] { "\r\n", "\r", "\n" }, StringSplitOptions.RemoveEmptyEntries);
}
catch (Exception e)
{
e.Message.LogVerbose(ConsoleColor.DarkRed);
throw new CommandException("Could not find the committed files", innerException: e);
}
}
}
| 29.890244 | 95 | 0.617299 | [
"MIT"
] | Xemrox/Husky.Net | src/Husky/Services/Git.cs | 7,353 | C# |
// Copyright (c) Brock Allen & Dominick Baier. All rights reserved.
// Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information.
using IdentityModel;
using IdentityServer4.Configuration;
using IdentityServer4.Extensions;
using IdentityServer4.Services;
using IdentityServer4.Stores;
using IdentityServer4.Validation;
using Microsoft.Extensions.Logging;
using Microsoft.IdentityModel.Tokens;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Threading.Tasks;
namespace IdentityServer4.ResponseHandling
{
/// <summary>
/// Default implementation of the discovery endpoint response generator
/// </summary>
/// <seealso cref="IdentityServer4.ResponseHandling.IDiscoveryResponseGenerator" />
public class DiscoveryResponseGenerator : IDiscoveryResponseGenerator
{
/// <summary>
/// The options
/// </summary>
protected readonly IdentityServerOptions Options;
/// <summary>
/// The extension grants validator
/// </summary>
protected readonly ExtensionGrantValidator ExtensionGrants;
/// <summary>
/// The key material service
/// </summary>
protected readonly IKeyMaterialService Keys;
/// <summary>
/// The resource owner validator
/// </summary>
protected readonly IResourceOwnerPasswordValidator ResourceOwnerValidator;
/// <summary>
/// The resource store
/// </summary>
protected readonly IResourceStore ResourceStore;
/// <summary>
/// The secret parsers
/// </summary>
protected readonly SecretParser SecretParsers;
/// <summary>
/// The logger
/// </summary>
protected readonly ILogger Logger;
/// <summary>
/// Initializes a new instance of the <see cref="DiscoveryResponseGenerator"/> class.
/// </summary>
/// <param name="options">The options.</param>
/// <param name="resourceStore">The resource store.</param>
/// <param name="keys">The keys.</param>
/// <param name="extensionGrants">The extension grants.</param>
/// <param name="secretParsers">The secret parsers.</param>
/// <param name="resourceOwnerValidator">The resource owner validator.</param>
/// <param name="logger">The logger.</param>
public DiscoveryResponseGenerator(
IdentityServerOptions options,
IResourceStore resourceStore,
IKeyMaterialService keys,
ExtensionGrantValidator extensionGrants,
SecretParser secretParsers,
IResourceOwnerPasswordValidator resourceOwnerValidator,
ILogger<DiscoveryResponseGenerator> logger)
{
Options = options;
ResourceStore = resourceStore;
Keys = keys;
ExtensionGrants = extensionGrants;
SecretParsers = secretParsers;
ResourceOwnerValidator = resourceOwnerValidator;
Logger = logger;
}
/// <summary>
/// Creates the discovery document.
/// </summary>
/// <param name="baseUrl">The base URL.</param>
/// <param name="issuerUri">The issuer URI.</param>
public virtual async Task<Dictionary<string, object>> CreateDiscoveryDocumentAsync(string baseUrl, string issuerUri)
{
var entries = new Dictionary<string, object>
{
{ OidcConstants.Discovery.Issuer, issuerUri }
};
// jwks
if (Options.Discovery.ShowKeySet)
{
if ((await Keys.GetValidationKeysAsync()).Any())
{
entries.Add(OidcConstants.Discovery.JwksUri, baseUrl + Constants.ProtocolRoutePaths.DiscoveryWebKeys);
}
}
// endpoints
if (Options.Discovery.ShowEndpoints)
{
if (Options.Endpoints.EnableAuthorizeEndpoint)
{
entries.Add(OidcConstants.Discovery.AuthorizationEndpoint, baseUrl + Constants.ProtocolRoutePaths.Authorize);
}
if (Options.Endpoints.EnableTokenEndpoint)
{
entries.Add(OidcConstants.Discovery.TokenEndpoint, baseUrl + Constants.ProtocolRoutePaths.Token);
}
if (Options.Endpoints.EnableUserInfoEndpoint)
{
entries.Add(OidcConstants.Discovery.UserInfoEndpoint, baseUrl + Constants.ProtocolRoutePaths.UserInfo);
}
if (Options.Endpoints.EnableEndSessionEndpoint)
{
entries.Add(OidcConstants.Discovery.EndSessionEndpoint, baseUrl + Constants.ProtocolRoutePaths.EndSession);
}
if (Options.Endpoints.EnableCheckSessionEndpoint)
{
entries.Add(OidcConstants.Discovery.CheckSessionIframe, baseUrl + Constants.ProtocolRoutePaths.CheckSession);
}
if (Options.Endpoints.EnableTokenRevocationEndpoint)
{
entries.Add(OidcConstants.Discovery.RevocationEndpoint, baseUrl + Constants.ProtocolRoutePaths.Revocation);
}
if (Options.Endpoints.EnableIntrospectionEndpoint)
{
entries.Add(OidcConstants.Discovery.IntrospectionEndpoint, baseUrl + Constants.ProtocolRoutePaths.Introspection);
}
}
// logout
if (Options.Endpoints.EnableEndSessionEndpoint)
{
entries.Add(OidcConstants.Discovery.FrontChannelLogoutSupported, true);
entries.Add(OidcConstants.Discovery.FrontChannelLogoutSessionSupported, true);
entries.Add(OidcConstants.Discovery.BackChannelLogoutSupported, true);
entries.Add(OidcConstants.Discovery.BackChannelLogoutSessionSupported, true);
}
// scopes and claims
if (Options.Discovery.ShowIdentityScopes ||
Options.Discovery.ShowApiScopes ||
Options.Discovery.ShowClaims)
{
var resources = await ResourceStore.GetAllEnabledResourcesAsync();
var scopes = new List<string>();
// scopes
if (Options.Discovery.ShowIdentityScopes)
{
scopes.AddRange(resources.IdentityResources.Where(x => x.ShowInDiscoveryDocument).Select(x => x.Name));
}
if (Options.Discovery.ShowApiScopes)
{
var apiScopes = from api in resources.ApiResources
from scope in api.Scopes
where scope.ShowInDiscoveryDocument
select scope.Name;
scopes.AddRange(apiScopes);
scopes.Add(IdentityServerConstants.StandardScopes.OfflineAccess);
}
if (scopes.Any())
{
entries.Add(OidcConstants.Discovery.ScopesSupported, scopes.ToArray());
}
// claims
if (Options.Discovery.ShowClaims)
{
var claims = new List<string>();
// add non-hidden identity scopes related claims
claims.AddRange(resources.IdentityResources.Where(x => x.ShowInDiscoveryDocument).SelectMany(x => x.UserClaims));
// add non-hidden api scopes related claims
foreach (var resource in resources.ApiResources)
{
claims.AddRange(resource.UserClaims);
foreach (var scope in resource.Scopes)
{
if (scope.ShowInDiscoveryDocument)
{
claims.AddRange(scope.UserClaims);
}
}
}
entries.Add(OidcConstants.Discovery.ClaimsSupported, claims.Distinct().ToArray());
}
}
// grant types
if (Options.Discovery.ShowGrantTypes)
{
var standardGrantTypes = new List<string>
{
OidcConstants.GrantTypes.AuthorizationCode,
OidcConstants.GrantTypes.ClientCredentials,
OidcConstants.GrantTypes.RefreshToken,
OidcConstants.GrantTypes.Implicit
};
if (!(ResourceOwnerValidator is NotSupportedResourceOwnerPasswordValidator))
{
standardGrantTypes.Add(OidcConstants.GrantTypes.Password);
}
var showGrantTypes = new List<string>(standardGrantTypes);
if (Options.Discovery.ShowExtensionGrantTypes)
{
showGrantTypes.AddRange(ExtensionGrants.GetAvailableGrantTypes());
}
entries.Add(OidcConstants.Discovery.GrantTypesSupported, showGrantTypes.ToArray());
}
// response types
if (Options.Discovery.ShowResponseTypes)
{
entries.Add(OidcConstants.Discovery.ResponseTypesSupported, Constants.SupportedResponseTypes.ToArray());
}
// response modes
if (Options.Discovery.ShowResponseModes)
{
entries.Add(OidcConstants.Discovery.ResponseModesSupported, Constants.SupportedResponseModes.ToArray());
}
// misc
if (Options.Discovery.ShowTokenEndpointAuthenticationMethods)
{
entries.Add(OidcConstants.Discovery.TokenEndpointAuthenticationMethodsSupported, SecretParsers.GetAvailableAuthenticationMethods().ToArray());
}
entries.Add(OidcConstants.Discovery.SubjectTypesSupported, new[] { "public" });
entries.Add(OidcConstants.Discovery.IdTokenSigningAlgorithmsSupported, new[] { Constants.SigningAlgorithms.RSA_SHA_256 });
entries.Add(OidcConstants.Discovery.CodeChallengeMethodsSupported, new[] { OidcConstants.CodeChallengeMethods.Plain, OidcConstants.CodeChallengeMethods.Sha256 });
// custom entries
if (!Options.Discovery.CustomEntries.IsNullOrEmpty())
{
foreach (var customEntry in Options.Discovery.CustomEntries)
{
if (entries.ContainsKey(customEntry.Key))
{
Logger.LogError("Discovery custom entry {key} cannot be added, because it already exists.", customEntry.Key);
}
else
{
if (customEntry.Value is string customValueString)
{
if (customValueString.StartsWith("~/") && Options.Discovery.ExpandRelativePathsInCustomEntries)
{
entries.Add(customEntry.Key, baseUrl + customValueString.Substring(2));
continue;
}
}
entries.Add(customEntry.Key, customEntry.Value);
}
}
}
return entries;
}
/// <summary>
/// Creates the JWK document.
/// </summary>
public virtual async Task<IEnumerable<Models.JsonWebKey>> CreateJwkDocumentAsync()
{
var webKeys = new List<Models.JsonWebKey>();
var signingCredentials = await Keys.GetSigningCredentialsAsync();
var algorithm = signingCredentials?.Algorithm ?? Constants.SigningAlgorithms.RSA_SHA_256;
foreach (var key in await Keys.GetValidationKeysAsync())
{
if (key is X509SecurityKey x509Key)
{
var cert64 = Convert.ToBase64String(x509Key.Certificate.RawData);
var thumbprint = Base64Url.Encode(x509Key.Certificate.GetCertHash());
var pubKey = x509Key.PublicKey as RSA;
var parameters = pubKey.ExportParameters(false);
var exponent = Base64Url.Encode(parameters.Exponent);
var modulus = Base64Url.Encode(parameters.Modulus);
var webKey = new Models.JsonWebKey
{
kty = "RSA",
use = "sig",
kid = x509Key.KeyId,
x5t = thumbprint,
e = exponent,
n = modulus,
x5c = new[] { cert64 },
alg = algorithm
};
webKeys.Add(webKey);
continue;
}
if (key is RsaSecurityKey rsaKey)
{
var parameters = rsaKey.Rsa?.ExportParameters(false) ?? rsaKey.Parameters;
var exponent = Base64Url.Encode(parameters.Exponent);
var modulus = Base64Url.Encode(parameters.Modulus);
var webKey = new Models.JsonWebKey
{
kty = "RSA",
use = "sig",
kid = rsaKey.KeyId,
e = exponent,
n = modulus,
alg = algorithm
};
webKeys.Add(webKey);
}
}
return webKeys;
}
}
}
| 39.727273 | 174 | 0.549914 | [
"Apache-2.0"
] | Aratirn/IdentityServer4 | src/IdentityServer4/ResponseHandling/DiscoveryResponseGenerator.cs | 13,986 | C# |
using System.Collections.Generic;
using System.Threading.Tasks;
using AutoMapper;
using Microservice.Core.Extensions;
using Microservice.Core.Model;
using Microservice.Core.Service.Contracts;
using Microsoft.AspNetCore.Mvc;
namespace Microservice.Core.Api.Controllers
{
public class MSQuerableController<TQuery, TServiceQuery, TModel, TSDO> : MSController<TModel, TSDO>
where TQuery : class
where TServiceQuery : class
where TModel : class
where TSDO : class
{
private readonly IQuerableService<TServiceQuery, TSDO> _service;
public MSQuerableController(IQuerableService<TServiceQuery, TSDO> service, IMapper mapper, IPropertyHelper<TModel> propertyHelper)
: base(service: service, mapper: mapper, propertyHelper: propertyHelper)
{
_service = service;
}
[HttpGet]
[ProducesResponseType(statusCode: 200)]
[ProducesResponseType(statusCode: 404)]
public async Task<IActionResult> Get(ResourceRequest<TQuery> resourceRequest)
{
var serviceResourceRequest = Mapper.Map<ResourceRequest<TServiceQuery>>(source: resourceRequest);
var response = await _service.Get(request: serviceResourceRequest);
var multipleResource = Mapper.Map<ICollection<TModel>>(source: response.Items);
return Ok(value: multipleResource);
}
}
} | 36.307692 | 139 | 0.702684 | [
"MIT"
] | Aliaksandr-Huzen/Microservice-Template | sources/Microservice.Core.Api/Controllers/MSQuerableController.cs | 1,418 | C# |
using RobotService.Models.Robots.Contracts;
using System;
using System.Collections.Generic;
using System.Text;
namespace RobotService.Models.Procedures
{
public class Rest : Procedure
{
public override void DoService(IRobot robot, int procedureTime)
{
base.DoService(robot, procedureTime);
robot.Happiness -= 3;
robot.Energy += 10;
this.Robots.Add(robot);
}
}
}
| 23.578947 | 71 | 0.636161 | [
"MIT"
] | martinsivanov/CSharp-Advanced-September-2020 | C # OOP/Exams/C# OOP Retake Exam - 16 Apr 2020/RobotService/Models/Procedures/Rest.cs | 450 | C# |
using System;
namespace NBT.Business.Models.Tags
{
public class TAG_Long : NamedTAG<long>
{
public TAG_Long() : base(TagType.Long)
{
}
}
} | 13.692308 | 46 | 0.567416 | [
"MIT"
] | mhollebecq/MinecraftRegion.net | NBT.Business/Models/Tags/TAG_Long.cs | 180 | C# |
/// <summary>
/// Author: Krzysztof Dobrzyński
/// Project: Chemistry.NET
/// Source: https://github.com/Sejoslaw/Chemistry.NET
/// </summary>
using Chemistry.NET.Elements.Models;
namespace Chemistry.NET.Compounds.Models
{
public partial class ChemicalCompound : IOrganicCompound
{
public bool IsOrganic => ContainsBond(CommonElements.Carbon, CommonElements.Hydrogen);
}
}
| 24.6875 | 94 | 0.729114 | [
"MIT"
] | Sejoslaw/Chemistry.NET | Chemistry.NET/Compounds/ModelsLogics/ChemicalCompound_Organic.cs | 396 | 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.AzureNextGen.Solutions.V20200821Preview
{
public static class GetApplication
{
public static Task<GetApplicationResult> InvokeAsync(GetApplicationArgs args, InvokeOptions? options = null)
=> Pulumi.Deployment.Instance.InvokeAsync<GetApplicationResult>("azure-nextgen:solutions/v20200821preview:getApplication", args ?? new GetApplicationArgs(), options.WithVersion());
}
public sealed class GetApplicationArgs : Pulumi.InvokeArgs
{
/// <summary>
/// The name of the managed application.
/// </summary>
[Input("applicationName", required: true)]
public string ApplicationName { get; set; } = null!;
/// <summary>
/// The name of the resource group. The name is case insensitive.
/// </summary>
[Input("resourceGroupName", required: true)]
public string ResourceGroupName { get; set; } = null!;
public GetApplicationArgs()
{
}
}
[OutputType]
public sealed class GetApplicationResult
{
/// <summary>
/// The fully qualified path of managed application definition Id.
/// </summary>
public readonly string? ApplicationDefinitionId;
/// <summary>
/// The collection of managed application artifacts.
/// </summary>
public readonly ImmutableArray<Outputs.ApplicationArtifactResponse> Artifacts;
/// <summary>
/// The read-only authorizations property that is retrieved from the application package.
/// </summary>
public readonly ImmutableArray<Outputs.ApplicationAuthorizationResponse> Authorizations;
/// <summary>
/// The managed application billing details.
/// </summary>
public readonly Outputs.ApplicationBillingDetailsDefinitionResponse BillingDetails;
/// <summary>
/// The client entity that created the JIT request.
/// </summary>
public readonly Outputs.ApplicationClientDetailsResponse CreatedBy;
/// <summary>
/// The read-only customer support property that is retrieved from the application package.
/// </summary>
public readonly Outputs.ApplicationPackageContactResponse CustomerSupport;
/// <summary>
/// The identity of the resource.
/// </summary>
public readonly Outputs.IdentityResponse? Identity;
/// <summary>
/// The managed application Jit access policy.
/// </summary>
public readonly Outputs.ApplicationJitAccessPolicyResponse? JitAccessPolicy;
/// <summary>
/// The kind of the managed application. Allowed values are MarketPlace and ServiceCatalog.
/// </summary>
public readonly string Kind;
/// <summary>
/// Resource location
/// </summary>
public readonly string? Location;
/// <summary>
/// ID of the resource that manages this resource.
/// </summary>
public readonly string? ManagedBy;
/// <summary>
/// The managed resource group Id.
/// </summary>
public readonly string? ManagedResourceGroupId;
/// <summary>
/// The managed application management mode.
/// </summary>
public readonly string ManagementMode;
/// <summary>
/// Resource name
/// </summary>
public readonly string Name;
/// <summary>
/// Name and value pairs that define the managed application outputs.
/// </summary>
public readonly object Outputs;
/// <summary>
/// Name and value pairs that define the managed application parameters. It can be a JObject or a well formed JSON string.
/// </summary>
public readonly object? Parameters;
/// <summary>
/// The plan information.
/// </summary>
public readonly Outputs.PlanResponse? Plan;
/// <summary>
/// The managed application provisioning state.
/// </summary>
public readonly string ProvisioningState;
/// <summary>
/// The publisher tenant Id.
/// </summary>
public readonly string PublisherTenantId;
/// <summary>
/// The SKU of the resource.
/// </summary>
public readonly Outputs.SkuResponse? Sku;
/// <summary>
/// The read-only support URLs property that is retrieved from the application package.
/// </summary>
public readonly Outputs.ApplicationPackageSupportUrlsResponse SupportUrls;
/// <summary>
/// Resource tags
/// </summary>
public readonly ImmutableDictionary<string, string>? Tags;
/// <summary>
/// Resource type
/// </summary>
public readonly string Type;
/// <summary>
/// The client entity that last updated the JIT request.
/// </summary>
public readonly Outputs.ApplicationClientDetailsResponse UpdatedBy;
[OutputConstructor]
private GetApplicationResult(
string? applicationDefinitionId,
ImmutableArray<Outputs.ApplicationArtifactResponse> artifacts,
ImmutableArray<Outputs.ApplicationAuthorizationResponse> authorizations,
Outputs.ApplicationBillingDetailsDefinitionResponse billingDetails,
Outputs.ApplicationClientDetailsResponse createdBy,
Outputs.ApplicationPackageContactResponse customerSupport,
Outputs.IdentityResponse? identity,
Outputs.ApplicationJitAccessPolicyResponse? jitAccessPolicy,
string kind,
string? location,
string? managedBy,
string? managedResourceGroupId,
string managementMode,
string name,
object outputs,
object? parameters,
Outputs.PlanResponse? plan,
string provisioningState,
string publisherTenantId,
Outputs.SkuResponse? sku,
Outputs.ApplicationPackageSupportUrlsResponse supportUrls,
ImmutableDictionary<string, string>? tags,
string type,
Outputs.ApplicationClientDetailsResponse updatedBy)
{
ApplicationDefinitionId = applicationDefinitionId;
Artifacts = artifacts;
Authorizations = authorizations;
BillingDetails = billingDetails;
CreatedBy = createdBy;
CustomerSupport = customerSupport;
Identity = identity;
JitAccessPolicy = jitAccessPolicy;
Kind = kind;
Location = location;
ManagedBy = managedBy;
ManagedResourceGroupId = managedResourceGroupId;
ManagementMode = managementMode;
Name = name;
Outputs = outputs;
Parameters = parameters;
Plan = plan;
ProvisioningState = provisioningState;
PublisherTenantId = publisherTenantId;
Sku = sku;
SupportUrls = supportUrls;
Tags = tags;
Type = type;
UpdatedBy = updatedBy;
}
}
}
| 34.856481 | 192 | 0.617081 | [
"Apache-2.0"
] | test-wiz-sec/pulumi-azure-nextgen | sdk/dotnet/Solutions/V20200821Preview/GetApplication.cs | 7,529 | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.