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
sequence | repository_name
stringlengths 7
92
| path
stringlengths 3
249
| size
int64 5
1.04M
| lang
stringclasses 2
values |
---|---|---|---|---|---|---|---|---|
using System;
using System.Collections.Generic;
using System.Text;
using Game.Logic.AI;
using Game.Logic.Phy.Object;
using Game.Logic;
using System.Drawing;
using Game.Logic.Actions;
using Bussiness;
using Game.Logic.Effects;
namespace GameServerScript.AI.NPC
{
public class FiveNormalThirdNpc2 : ABrain
{
protected Player m_targer;
int round = 0;
public override void OnBeginSelfTurn()
{
base.OnBeginSelfTurn();
}
public override void OnBeginNewTurn()
{
base.OnBeginNewTurn();
m_body.CurrentDamagePlus = 1;
m_body.CurrentShootMinus = 1;
if (m_targer == null)
{
m_targer = ((PVEGame)Game).FindPlayer((int)Body.Properties1);
}
}
public override void OnCreated()
{
base.OnCreated();
}
public override void OnStartAttacking()
{
base.OnStartAttacking();
if (round == 1)
{
KillAttack();
}
round++;
}
private void KillAttack()
{
((PVEGame)Game).SendObjectFocus(Body, 1, 1000, 0);
Body.PlayMovie("beatA", 1500, 0);
m_targer.Die(3000);
Body.CallFuction(new LivingCallBack(CheckState), 4000);
}
private void CheckState()
{
if (m_targer.IsLiving == false)
{
DieState();
}
}
private void DieState()
{
if (Body.IsLiving)
{
Body.PlayMovie("die", 500, 2000);
Body.Die(1000);
}
}
public override void OnDie()
{
if(m_targer.IsLiving)
{
m_targer.BoltMove(((Point)Body.Properties2).X, ((Point)Body.Properties2).Y, 0);
}
m_targer.SetVisible(true);
m_targer.BlockTurn = false;
}
public override void OnStopAttacking()
{
base.OnStopAttacking();
}
}
}
| 22.893617 | 95 | 0.494424 | [
"MIT"
] | HuyTruong19x/DDTank4.1 | Source Server/Game.Server.Scripts/AI/NPC/FiveNormalThirdNpc2.cs | 2,154 | C# |
// Crest Ocean System
// This file is subject to the MIT License as seen in the root of this folder structure (LICENSE)
using UnityEditor;
using UnityEngine;
using UnityEngine.Experimental.Rendering;
namespace Crest
{
[CreateAssetMenu(fileName = "SimSettingsAnimatedWaves", menuName = "Crest/Animated Waves Sim Settings", order = 10000)]
[HelpURL(k_HelpURL)]
public partial class SimSettingsAnimatedWaves : SimSettingsBase
{
/// <summary>
/// The version of this asset. Can be used to migrate across versions. This value should
/// only be changed when the editor upgrades the version.
/// </summary>
[SerializeField, HideInInspector]
#pragma warning disable 414
int _version = 0;
#pragma warning restore 414
public const string k_HelpURL = Internal.Constants.HELP_URL_BASE_USER + "ocean-simulation.html" + Internal.Constants.HELP_URL_RP + "#animated-waves-settings";
[Tooltip("How much waves are dampened in shallow water."), SerializeField, Range(0f, 1f)]
float _attenuationInShallows = 0.95f;
public float AttenuationInShallows => _attenuationInShallows;
[Tooltip("Any water deeper than this will receive full wave strength. The lower the value, the less effective the depth cache will be at attenuating very large waves. Set to the maximum value (1,000) to disable.")]
[SerializeField, Range(1f, LodDataMgrSeaFloorDepth.k_DepthBaseline)]
float _shallowsMaxDepth = LodDataMgrSeaFloorDepth.k_DepthBaseline;
public float MaximumAttenuationDepth => _shallowsMaxDepth;
public enum CollisionSources
{
None,
GerstnerWavesCPU,
ComputeShaderQueries,
BakedFFT
}
[Tooltip("Where to obtain ocean shape on CPU for physics / gameplay."), SerializeField]
CollisionSources _collisionSource = CollisionSources.ComputeShaderQueries;
public CollisionSources CollisionSource { get => _collisionSource; set => _collisionSource = value; }
[Tooltip("Maximum number of wave queries that can be performed when using ComputeShaderQueries.")]
[Predicated("_collisionSource", true, (int)CollisionSources.ComputeShaderQueries), SerializeField, DecoratedField]
int _maxQueryCount = QueryBase.MAX_QUERY_COUNT_DEFAULT;
public int MaxQueryCount => _maxQueryCount;
[Tooltip("Whether to use a graphics shader for combining the wave cascades together. Disabling this uses a compute shader instead which doesn't need to copy back and forth between targets, but it may not work on some GPUs, in particular pre-DX11.3 hardware, which do not support typed UAV loads. The fail behaviour is a flat ocean."), SerializeField]
bool _pingPongCombinePass = true;
public bool PingPongCombinePass => _pingPongCombinePass;
[Tooltip("The render texture format to use for the wave simulation. It should only be changed if you need more precision. See the documentation for information.")]
public GraphicsFormat _renderTextureGraphicsFormat = GraphicsFormat.R16G16B16A16_SFloat;
#if CREST_UNITY_MATHEMATICS
[Predicated("_collisionSource", true, (int)CollisionSources.BakedFFT), DecoratedField]
public FFTBakedData _bakedFFTData;
#endif // CREST_UNITY_MATHEMATICS
public override void AddToSettingsHash(ref int settingsHash)
{
base.AddToSettingsHash(ref settingsHash);
Hashy.AddInt((int)_renderTextureGraphicsFormat, ref settingsHash);
Hashy.AddBool(Helpers.IsMotionVectorsEnabled(), ref settingsHash);
Hashy.AddInt((int)_collisionSource, ref settingsHash);
}
/// <summary>
/// Provides ocean shape to CPU.
/// </summary>
public ICollProvider CreateCollisionProvider()
{
ICollProvider result = null;
switch (_collisionSource)
{
case CollisionSources.None:
result = new CollProviderNull();
break;
case CollisionSources.GerstnerWavesCPU:
result = FindObjectOfType<ShapeGerstnerBatched>();
break;
case CollisionSources.ComputeShaderQueries:
if (!OceanRenderer.RunningWithoutGPU)
{
result = new QueryDisplacements();
}
else
{
Debug.LogError("Crest: Compute shader queries not supported in headless/batch mode. To resolve, assign an Animated Wave Settings asset to the OceanRenderer component and set the Collision Source to be a CPU option.");
}
break;
#if CREST_UNITY_MATHEMATICS
case CollisionSources.BakedFFT:
result = new CollProviderBakedFFT(_bakedFFTData);
break;
#endif // CREST_UNITY_MATHEMATICS
}
if (result == null)
{
// This should not be hit, but can be if compute shaders aren't loaded correctly.
// They will print out appropriate errors. Don't just return null and have null reference
// exceptions spamming the logs.
return new CollProviderNull();
}
return result;
}
public IFlowProvider CreateFlowProvider(OceanRenderer ocean)
{
// Flow is GPU only, and can only be queried using the compute path
if (ocean._lodDataFlow != null)
{
return new QueryFlow();
}
return new FlowProviderNull();
}
}
#if UNITY_EDITOR
public partial class SimSettingsAnimatedWaves : IValidated
{
public override bool Validate(OceanRenderer ocean, ValidatedHelper.ShowMessage showMessage)
{
var isValid = base.Validate(ocean, showMessage);
if (_collisionSource == CollisionSources.GerstnerWavesCPU && showMessage != ValidatedHelper.DebugLog)
{
showMessage
(
"<i>Gerstner Waves CPU</i> has significant drawbacks. It does not include wave attenuation from " +
"water depth or any custom rendered shape. It does not support multiple " +
"<i>GerstnerWavesBatched</i> components including cross blending. Please read the user guide for more information.",
"Set collision source to ComputeShaderQueries",
ValidatedHelper.MessageType.Info, this
);
}
else if (_collisionSource == CollisionSources.None)
{
showMessage
(
"Collision Source in Animated Waves Settings is set to None. The floating objects in the scene will use a flat horizontal plane.",
"Set collision source to ComputeShaderQueries.",
ValidatedHelper.MessageType.Warning, this,
FixSetCollisionSourceToCompute
);
}
else if (_collisionSource == CollisionSources.BakedFFT)
{
#if CREST_UNITY_MATHEMATICS
if (_bakedFFTData != null)
{
if (!Mathf.Approximately(_bakedFFTData._parameters._windSpeed * 3.6f, ocean._globalWindSpeed))
{
showMessage
(
$"Wind speed on ocean component {ocean._globalWindSpeed} does not match wind speed of baked FFT data {_bakedFFTData._parameters._windSpeed * 3.6f}, collision shape may not match visual surface.",
$"Set global wind speed on ocean component to {_bakedFFTData._parameters._windSpeed * 3.6f}.",
ValidatedHelper.MessageType.Warning, ocean,
FixOceanWindSpeed
);
}
}
#else // CREST_UNITY_MATHEMATICS
showMessage
(
"The <i>Unity Mathematics (com.unity.mathematics)</i> package is required for baked collisions.",
"Add the <i>Unity Mathematics</i> package.",
ValidatedHelper.MessageType.Error, this,
ValidatedHelper.FixAddMissingMathPackage
);
isValid = false;
#endif // CREST_UNITY_MATHEMATICS
#if !CREST_UNITY_BURST
showMessage
(
"The <i>Unity Burst (com.unity.burst)</i> package will greatly improve performance.",
"Add the <i>Unity Burst</i> package.",
ValidatedHelper.MessageType.Warning, this,
ValidatedHelper.FixAddMissingBurstPackage
);
#endif // CREST_UNITY_BURST
}
return isValid;
}
internal static void FixSetCollisionSourceToCompute(SerializedObject settingsObject)
{
if (OceanRenderer.Instance != null && OceanRenderer.Instance._simSettingsAnimatedWaves != null)
{
Undo.RecordObject(OceanRenderer.Instance._simSettingsAnimatedWaves, "Set collision source to compute");
OceanRenderer.Instance._simSettingsAnimatedWaves.CollisionSource = CollisionSources.ComputeShaderQueries;
EditorUtility.SetDirty(OceanRenderer.Instance._simSettingsAnimatedWaves);
}
}
#if CREST_UNITY_MATHEMATICS
internal static void FixOceanWindSpeed(SerializedObject settingsObject)
{
if (OceanRenderer.Instance != null
&& OceanRenderer.Instance._simSettingsAnimatedWaves != null
&& OceanRenderer.Instance._simSettingsAnimatedWaves._bakedFFTData != null)
{
Undo.RecordObject(OceanRenderer.Instance, "Set global wind speed to match baked data");
OceanRenderer.Instance._globalWindSpeed = OceanRenderer.Instance._simSettingsAnimatedWaves._bakedFFTData._parameters._windSpeed * 3.6f;
EditorUtility.SetDirty(OceanRenderer.Instance);
}
}
#endif // CREST_UNITY_MATHEMATICS
}
[CustomEditor(typeof(SimSettingsAnimatedWaves), true), CanEditMultipleObjects]
class SimSettingsAnimatedWavesEditor : SimSettingsBaseEditor
{
public override void OnInspectorGUI()
{
EditorGUILayout.Space();
if (GUILayout.Button("Open Online Help Page"))
{
Application.OpenURL(SimSettingsAnimatedWaves.k_HelpURL);
}
EditorGUILayout.Space();
base.OnInspectorGUI();
}
}
#endif // UNITY_EDITOR
}
| 45.389121 | 358 | 0.622972 | [
"MIT"
] | Libertus-Lab/crest | crest/Assets/Crest/Crest/Scripts/LodData/Settings/SimSettingsAnimatedWaves.cs | 10,850 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using AbpAntDesignDemo.Permissions;
using AutoMapper;
using Microsoft.AspNetCore.Authorization;
using Volo.Abp.Application.Dtos;
using Volo.Abp.Domain.Repositories;
namespace AbpAntDesignDemo.Authors
{
[Authorize(AbpAntDesignDemoPermissions.Authors.Default)]
public class AuthorAppService : AbpAntDesignDemoAppService, IAuthorAppService
{
private readonly IAuthorRepository _authorRepository;
private readonly AuthorManager _authorManager;
public AuthorAppService(
IAuthorRepository authorRepository,
AuthorManager authorManager)
{
_authorRepository = authorRepository;
_authorManager = authorManager;
}
public async Task<AuthorDto> GetAsync(Guid id)
{
var author = await _authorRepository.GetAsync(id);
return ObjectMapper.Map<Author, AuthorDto>(author);
}
public async Task<PagedResultDto<AuthorDto>> GetListAsync(GetAuthorListDto input)
{
if (input.Sorting.IsNullOrWhiteSpace())
{
input.Sorting = nameof(Author.Name);
}
var authors = await _authorRepository.GetListAsync(
input.SkipCount,
input.MaxResultCount,
input.Sorting,
input.Filter
);
var totalCount = input.Filter == null
? await _authorRepository.CountAsync()
: await _authorRepository.CountAsync(author => author.Name.Contains(input.Filter));
return new PagedResultDto<AuthorDto>(
totalCount,
ObjectMapper.Map<List<Author>, List<AuthorDto>>(authors)
);
}
[Authorize(AbpAntDesignDemoPermissions.Authors.Create)]
public async Task<AuthorDto> CreateAsync(CreateAuthorDto input)
{
var author = await _authorManager.CreateAsync(
input.Name,
input.BirthDate,
input.ShortBio
);
await _authorRepository.InsertAsync(author);
return ObjectMapper.Map<Author, AuthorDto>(author);
}
[Authorize(AbpAntDesignDemoPermissions.Authors.Edit)]
public async Task UpdateAsync(Guid id, UpdateAuthorDto input)
{
var author = await _authorRepository.GetAsync(id);
if (author.Name != input.Name)
{
await _authorManager.ChangeNameAsync(author, input.Name);
}
author.BirthDate = input.BirthDate;
author.ShortBio = input.ShortBio;
await _authorRepository.UpdateAsync(author);
}
[Authorize(AbpAntDesignDemoPermissions.Authors.Delete)]
public async Task DeleteAsync(Guid id)
{
await _authorRepository.DeleteAsync(id);
}
}
}
| 31.797872 | 99 | 0.619605 | [
"MIT"
] | pauljohn21/AntDesignBlazorServer | demo/src/AbpAntDesignDemo.Application/Authors/AuthorAppService.cs | 2,991 | C# |
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Npgsql;
namespace Discount.API.Extensions
{
public static class HostExtensions
{
public static IHost MigrateDatabase<TContext>(this IHost host, int? retry = 0)
{
int retryForAvailability = retry.Value;
using (var scope = host.Services.CreateScope())
{
var services = scope.ServiceProvider;
var configuration = services.GetRequiredService<IConfiguration>();
var logger = services.GetRequiredService<ILogger<TContext>>();
try
{
string connStr = configuration.GetValue<string>("DatabaseSettings:ConnectionString");
logger.LogInformation($"Migrating postresql database with connection string:{connStr}.");
using var connection = new NpgsqlConnection(connStr);
connection.Open();
using var command = new NpgsqlCommand
{
Connection = connection
};
command.CommandText = "DROP TABLE IF EXISTS Coupon";
command.ExecuteNonQuery();
command.CommandText = @"CREATE TABLE Coupon(Id SERIAL PRIMARY KEY,
ProductName VARCHAR(24) NOT NULL,
Description TEXT,
Amount INT)";
command.ExecuteNonQuery();
command.CommandText = "INSERT INTO Coupon(ProductName, Description, Amount) VALUES('IPhone X', 'IPhone Discount', 159);";
command.ExecuteNonQuery();
command.CommandText = "INSERT INTO Coupon(ProductName, Description, Amount) VALUES('Samsung 10', 'Samsung Discount', 109);";
command.ExecuteNonQuery();
logger.LogInformation("Migrated postresql database.");
}
catch (NpgsqlException ex)
{
logger.LogError(ex, $"An error occurred while migrating the postresql database, ex:{ex.Message}");
if (retryForAvailability < 50)
{
retryForAvailability++;
System.Threading.Thread.Sleep(2000);
MigrateDatabase<TContext>(host, retryForAvailability);
}
}
}
return host;
}
}
} | 41.059701 | 144 | 0.520901 | [
"MIT"
] | vpantea/AspnetMicroservices | src/Services/Discount/Discount.API/Extensions/HostExtensions.cs | 2,753 | C# |
using NBi.Core.ResultSet;
using NBi.Xml.Items.ResultSet;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Serialization;
namespace NBi.Xml.Items.Alteration.Projection
{
public abstract class AbstractProjectionXml : AlterationXml
{
[XmlElement("column")]
public List<ColumnDefinitionLightXml> Columns { get; set; } = new List<ColumnDefinitionLightXml>();
}
}
| 26.222222 | 107 | 0.752119 | [
"Apache-2.0"
] | TheAutomatingMrLynch/NBi | NBi.Xml/Items/Alteration/Projection/AbstractProjectionXml.cs | 474 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
namespace Paillave.Etl.Core
{
public class JobDefinitionStructure
{
private class NodeDescription : INodeDescription
{
public NodeDescription(INodeDescription nodeContext)
{
this.NodeName = nodeContext.NodeName;
this.TypeName = nodeContext.TypeName;
this.PerformanceImpact = nodeContext.PerformanceImpact;
this.MemoryFootPrint = nodeContext.MemoryFootPrint;
}
public string NodeName { get; }
public string TypeName { get; }
public ProcessImpact PerformanceImpact { get; }
public ProcessImpact MemoryFootPrint { get; }
public bool IsRootNode => false;
}
public JobDefinitionStructure(List<StreamToNodeLink> streamToNodeLinks, List<INodeDescription> nodes, string sourceNodeName)
{
this.Nodes = nodes.Select(i => (INodeDescription)new NodeDescription(i)).Where(i => !i.IsRootNode).ToList();
this.StreamToNodeLinks = streamToNodeLinks
.Join(this.Nodes, i => i.SourceNodeName, i => i.NodeName, (i, j) => i)
.Join(this.Nodes, i => i.TargetNodeName, i => i.NodeName, (i, j) => i)
.ToList();
// TODO: Redo total PerformanceImpact and MemoryFootPrint computation as it is completely not accurate
this.PerformanceImpact = this.Nodes.Count == 0 ? ProcessImpact.Light : (ProcessImpact)Math.Round(this.Nodes.Average(i => (decimal)i.PerformanceImpact));
this.MemoryFootPrint = this.Nodes.Count == 0 ? ProcessImpact.Light : (ProcessImpact)Math.Round(this.Nodes.Average(i => (decimal)i.MemoryFootPrint));
}
public List<StreamToNodeLink> StreamToNodeLinks { get; }
public List<INodeDescription> Nodes { get; }
public ProcessImpact PerformanceImpact { get; }
public ProcessImpact MemoryFootPrint { get; }
}
}
| 43.12766 | 164 | 0.639862 | [
"MIT"
] | paillave/Etl.Net | src/Paillave.Etl/Core/JobDefinitionStructure.cs | 2,029 | C# |
using AspNetCoreTemplate.Data.Common.Repositories;
using AspNetCoreTemplate.Data.Models;
using AspNetCoreTemplate.Services.Data.Contracts;
using AspNetCoreTemplate.Services.Mapping;
using Microsoft.EntityFrameworkCore;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace AspNetCoreTemplate.Services.Data.Services
{
public class CitiesService : ICitiesService
{
private readonly IRepository<City> _repo;
public CitiesService(IRepository<City> repo)
{
this._repo = repo;
}
public async Task<IEnumerable<T>> GetAllAsync<T>()
{
var cities =
await this._repo
.All()
.OrderBy(x => x.Id)
.To<T>().ToListAsync();
return cities;
}
public async Task AddAsync(string name)
{
await this._repo.AddAsync(new City
{
Name = name,
});
await this._repo.SaveChangesAsync();
}
public async Task DeleteAsync(int id)
{
var city =
await this._repo
.AllAsNoTracking()
.Where(x => x.Id == id)
.FirstOrDefaultAsync();
this._repo.Delete(city);
await this._repo.SaveChangesAsync();
}
}
}
| 26.673077 | 58 | 0.563086 | [
"MIT"
] | mirakis97/OnlineCosmeticSalon | OnlineCosmeticSalon.Web/Services/AspNetCoreTemplate.Services.Data/Services/CitiesService.cs | 1,389 | C# |
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Threading.Tasks;
using Competitions.EntityModels;
using Competitions.Mappers;
using Competitions.Models;
using Tennis.Mappers;
namespace Competitions.Services
{
/// <summary>
/// This represents the service entity for districts.
/// </summary>
public class DistrictService : IDistrictService
{
private readonly ICompetitionDbContext _dbContext;
private readonly IMapperFactory _mapperFactory;
private bool _disposed;
/// <summary>
/// Initialises a new instance of the <see cref="DistrictService"/> class.
/// </summary>
/// <param name="dbContext"><see cref="ICompetitionDbContext"/> instance.</param>
/// <param name="mapperFactory"><see cref="IMapperFactory"/> instance.</param>
/// <exception cref="ArgumentNullException"><paramref name="dbContext"/> is <see langword="null" />.</exception>
/// <exception cref="ArgumentNullException"><paramref name="mapperFactory"/> is <see langword="null" />.</exception>
public DistrictService(ICompetitionDbContext dbContext, IMapperFactory mapperFactory)
{
if (dbContext == null)
{
throw new ArgumentNullException(nameof(dbContext));
}
this._dbContext = dbContext;
if (mapperFactory == null)
{
throw new ArgumentNullException(nameof(mapperFactory));
}
this._mapperFactory = mapperFactory;
}
/// <summary>
/// Gets the list of districts.
/// </summary>
/// <returns>Returns the list of districts.</returns>
public async Task<List<DistrictModel>> GetDistrictsAsync()
{
var results = await this._dbContext.Districts.OrderBy(p => p.Name).ToListAsync().ConfigureAwait(false);
using (var mapper = this._mapperFactory.Get<DistrictToDistrictModelMapper>())
{
var districts = mapper.Map<List<DistrictModel>>(results);
return districts;
}
}
/// <summary>
/// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
/// </summary>
public void Dispose()
{
if (this._disposed)
{
return;
}
this._disposed = true;
}
}
}
| 31.911392 | 124 | 0.605712 | [
"MIT"
] | justinyoo/Tennis | src/Competitions.Services/DistrictService.cs | 2,523 | C# |
/************************************************************************************
Copyright : Copyright (c) Facebook Technologies, LLC and its affiliates. All rights reserved.
Licensed under the Oculus Utilities SDK License Version 1.31 (the "License"); you may not use
the Utilities SDK except in compliance with the License, which is provided at the time of installation
or download, or which otherwise accompanies this software in either electronic or hard copy form.
You may obtain a copy of the License at
https://developer.oculus.com/licenses/utilities-1.31
Unless required by applicable law or agreed to in writing, the Utilities SDK 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;
using System.Collections.Generic;
using UnityEngine;
public class OVRHeadsetEmulator : MonoBehaviour {
public enum OpMode
{
Off,
EditorOnly,
AlwaysOn
}
public OpMode opMode = OpMode.EditorOnly;
public bool resetHmdPoseOnRelease = true;
public bool resetHmdPoseByMiddleMouseButton = true;
public KeyCode[] activateKeys = new KeyCode[] { KeyCode.LeftControl, KeyCode.RightControl };
public KeyCode[] pitchKeys = new KeyCode[] { KeyCode.LeftAlt, KeyCode.RightAlt };
OVRManager manager;
const float MOUSE_SCALE_X = -2.0f;
const float MOUSE_SCALE_X_PITCH = -2.0f;
const float MOUSE_SCALE_Y = 2.0f;
const float MOUSE_SCALE_HEIGHT = 1.0f;
const float MAX_ROLL = 85.0f;
private bool lastFrameEmulationActivated = false;
private Vector3 recordedHeadPoseRelativeOffsetTranslation;
private Vector3 recordedHeadPoseRelativeOffsetRotation;
private bool hasSentEvent = false;
// Use this for initialization
void Start () {
Cursor.lockState = CursorLockMode.None;
manager = OVRManager.instance;
recordedHeadPoseRelativeOffsetTranslation = manager.headPoseRelativeOffsetTranslation;
recordedHeadPoseRelativeOffsetRotation = manager.headPoseRelativeOffsetRotation;
}
// Update is called once per frame
void Update () {
bool emulationActivated = IsEmulationActivated();
if (emulationActivated)
{
Cursor.lockState = CursorLockMode.Locked;
if (!lastFrameEmulationActivated && resetHmdPoseOnRelease)
{
manager.headPoseRelativeOffsetTranslation = recordedHeadPoseRelativeOffsetTranslation;
manager.headPoseRelativeOffsetRotation = recordedHeadPoseRelativeOffsetRotation;
}
if (resetHmdPoseByMiddleMouseButton && Input.GetMouseButton(2))
{
manager.headPoseRelativeOffsetTranslation = Vector3.zero;
manager.headPoseRelativeOffsetRotation = Vector3.zero;
}
else
{
Vector3 emulatedTranslation = manager.headPoseRelativeOffsetTranslation;
float deltaMouseScrollWheel = Input.GetAxis("Mouse ScrollWheel");
float emulatedHeight = deltaMouseScrollWheel * MOUSE_SCALE_HEIGHT;
emulatedTranslation.y += emulatedHeight;
manager.headPoseRelativeOffsetTranslation = emulatedTranslation;
float deltaX = Input.GetAxis("Mouse X");
float deltaY = Input.GetAxis("Mouse Y");
Vector3 emulatedAngles = manager.headPoseRelativeOffsetRotation;
float emulatedRoll = emulatedAngles.x;
float emulatedYaw = emulatedAngles.y;
float emulatedPitch = emulatedAngles.z;
if (IsTweakingPitch())
{
emulatedPitch += deltaX * MOUSE_SCALE_X_PITCH;
}
else
{
emulatedRoll += deltaY * MOUSE_SCALE_Y;
emulatedYaw += deltaX * MOUSE_SCALE_X;
}
manager.headPoseRelativeOffsetRotation = new Vector3(emulatedRoll, emulatedYaw, emulatedPitch);
}
if (!hasSentEvent)
{
OVRPlugin.SendEvent("headset_emulator", "activated");
hasSentEvent = true;
}
}
else
{
Cursor.lockState = CursorLockMode.None;
if (lastFrameEmulationActivated)
{
recordedHeadPoseRelativeOffsetTranslation = manager.headPoseRelativeOffsetTranslation;
recordedHeadPoseRelativeOffsetRotation = manager.headPoseRelativeOffsetRotation;
if (resetHmdPoseOnRelease)
{
manager.headPoseRelativeOffsetTranslation = Vector3.zero;
manager.headPoseRelativeOffsetRotation = Vector3.zero;
}
}
}
lastFrameEmulationActivated = emulationActivated;
}
bool IsEmulationActivated()
{
if (opMode == OpMode.Off)
{
return false;
}
else if (opMode == OpMode.EditorOnly && !Application.isEditor)
{
return false;
}
foreach (KeyCode key in activateKeys)
{
if (Input.GetKey(key))
return true;
}
return false;
}
bool IsTweakingPitch()
{
if (!IsEmulationActivated())
return false;
foreach (KeyCode key in pitchKeys)
{
if (Input.GetKey(key))
return true;
}
return false;
}
}
| 30.646341 | 103 | 0.70772 | [
"MIT"
] | S0leSurvivor/TemboVR | Assets/Oculus/VR/Scripts/OVRHeadsetEmulator.cs | 5,026 | C# |
using KixPlay_Backend.Data.Entities;
using KixPlay_Backend.Models;
namespace KixPlay_Backend.Services.Repositories.Interfaces
{
public interface IMovieRepository : IMediaRepository<Movie, MovieDetailsModel>
{
}
}
| 22.7 | 82 | 0.797357 | [
"MIT"
] | fusedbloxxer/kixplay-backend | Services/Repositories/Interfaces/IMovieRepository.cs | 229 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.42000
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace SimpleGuiExample.Properties {
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "14.0.0.0")]
internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase {
private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings())));
public static Settings Default {
get {
return defaultInstance;
}
}
}
}
| 39.666667 | 151 | 0.583567 | [
"MIT"
] | thermofisherlsms/iapi | examples/exactive/SimpleGuiExample/Properties/Settings.Designer.cs | 1,073 | C# |
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using HotChocolate;
using StrawberryShake.CodeGeneration.CSharp.Builders;
using StrawberryShake.CodeGeneration.CSharp.Extensions;
using StrawberryShake.CodeGeneration.Descriptors;
using StrawberryShake.CodeGeneration.Descriptors.Operations;
using StrawberryShake.CodeGeneration.Descriptors.TypeDescriptors;
using StrawberryShake.CodeGeneration.Extensions;
using StrawberryShake.Tools.Configuration;
using static StrawberryShake.CodeGeneration.Descriptors.NamingConventions;
namespace StrawberryShake.CodeGeneration.CSharp.Generators
{
public class DependencyInjectionGenerator : CodeGenerator<DependencyInjectionDescriptor>
{
private const string _sessionPool = "sessionPool";
private const string _services = "services";
private const string _strategy = "strategy";
private const string _parentServices = "parentServices";
private const string _profile = "profile";
private const string _clientFactory = "clientFactory";
private const string _serviceCollection = "serviceCollection";
private const string _sp = "sp";
private const string _ct = "ct";
private static readonly string[] _builtInSerializers =
{
TypeNames.StringSerializer,
TypeNames.BooleanSerializer,
TypeNames.ByteSerializer,
TypeNames.ShortSerializer,
TypeNames.IntSerializer,
TypeNames.LongSerializer,
TypeNames.FloatSerializer,
TypeNames.DecimalSerializer,
TypeNames.UrlSerializer,
TypeNames.UuidSerializer,
TypeNames.IdSerializer,
TypeNames.DateTimeSerializer,
TypeNames.DateSerializer,
TypeNames.ByteArraySerializer,
TypeNames.TimeSpanSerializer,
TypeNames.JsonSerializer
};
protected override void Generate(
DependencyInjectionDescriptor descriptor,
CSharpSyntaxGeneratorSettings settings,
CodeWriter writer,
out string fileName,
out string? path,
out string ns)
{
fileName = CreateServiceCollectionExtensions(descriptor.Name);
path = DependencyInjection;
ns = TypeNames.DependencyInjectionNamespace;
ClassBuilder factory = ClassBuilder
.New(fileName)
.SetStatic()
.SetAccessModifier(AccessModifier.Public);
MethodBuilder addClientMethod = factory
.AddMethod($"Add{descriptor.Name}")
.SetPublic()
.SetStatic()
.SetReturnType(
TypeNames.IClientBuilder.WithGeneric(descriptor.StoreAccessor.RuntimeType))
.AddParameter(
_services,
x => x.SetThis().SetType(TypeNames.IServiceCollection))
.AddParameter(
_strategy,
x => x.SetType(TypeNames.ExecutionStrategy)
.SetDefault(TypeNames.ExecutionStrategy + "." + "NetworkOnly"))
.AddCode(GenerateMethodBody(settings, descriptor));
if (descriptor.TransportProfiles.Count > 1)
{
addClientMethod
.AddParameter(_profile)
.SetType(CreateProfileEnumReference(descriptor))
.SetDefault(CreateProfileEnumReference(descriptor) + "." +
descriptor.TransportProfiles[0].Name);
}
foreach (var profile in descriptor.TransportProfiles)
{
GenerateClientForProfile(settings, factory, descriptor, profile);
}
factory.AddClass(_clientServiceProvider);
factory.Build(writer);
}
private static void GenerateClientForProfile(
CSharpSyntaxGeneratorSettings settings,
ClassBuilder factory,
DependencyInjectionDescriptor descriptor,
TransportProfile profile)
{
factory
.AddMethod("ConfigureClient" + profile.Name)
.SetPrivate()
.SetStatic()
.SetReturnType(TypeNames.IServiceCollection)
.AddParameter(_parentServices, x => x.SetType(TypeNames.IServiceProvider))
.AddParameter(_services, x => x.SetType(TypeNames.ServiceCollection))
.AddParameter(
_strategy,
x => x.SetType(TypeNames.ExecutionStrategy)
.SetDefault(TypeNames.ExecutionStrategy + "." + "NetworkOnly"))
.AddCode(GenerateInternalMethodBody(settings, descriptor, profile));
}
private static ICode GenerateClientServiceProviderFactory(
DependencyInjectionDescriptor descriptor)
{
CodeBlockBuilder codeBuilder = CodeBlockBuilder.New();
if (descriptor.TransportProfiles.Count == 1)
{
return codeBuilder
.AddCode(
MethodCallBuilder
.New()
.SetMethodName("ConfigureClient" + descriptor.TransportProfiles[0].Name)
.AddArgument(_sp)
.AddArgument(_serviceCollection)
.AddArgument(_strategy))
.AddEmptyLine()
.AddCode(MethodCallBuilder
.New()
.SetReturn()
.SetNew()
.SetMethodName("ClientServiceProvider")
.SetWrapArguments()
.AddArgument(MethodCallBuilder
.Inline()
.SetMethodName(TypeNames.BuildServiceProvider)
.AddArgument(_serviceCollection)));
}
IfBuilder ifProfile = IfBuilder.New();
var enumName = CreateProfileEnumReference(descriptor);
for (var index = 0; index < descriptor.TransportProfiles.Count; index++)
{
TransportProfile profile = descriptor.TransportProfiles[index];
IfBuilder currentIf = ifProfile;
if (index != 0)
{
currentIf = IfBuilder.New();
ifProfile.AddIfElse(currentIf);
}
currentIf
.SetCondition($"{_profile} == {enumName}.{profile.Name}")
.AddCode(
MethodCallBuilder
.New()
.SetMethodName("ConfigureClient" + profile.Name)
.AddArgument(_sp)
.AddArgument(_serviceCollection)
.AddArgument(_strategy));
}
return codeBuilder
.AddCode(ifProfile)
.AddEmptyLine()
.AddCode(MethodCallBuilder
.New()
.SetReturn()
.SetNew()
.SetMethodName("ClientServiceProvider")
.SetWrapArguments()
.AddArgument(MethodCallBuilder
.Inline()
.SetMethodName(TypeNames.BuildServiceProvider)
.AddArgument(_serviceCollection)));
}
private static string CreateProfileEnumReference(DependencyInjectionDescriptor descriptor)
{
var rootNamespace = descriptor.ClientDescriptor.RuntimeType.Namespace;
return $"{rootNamespace}.{CreateClientProfileKind(descriptor.Name)}";
}
private static ICode GenerateMethodBody(
CSharpSyntaxGeneratorSettings settings,
DependencyInjectionDescriptor descriptor) =>
CodeBlockBuilder
.New()
.AddCode(
AssignmentBuilder
.New()
.SetLefthandSide($"var {_serviceCollection}")
.SetRighthandSide(MethodCallBuilder
.Inline()
.SetNew()
.SetMethodName(TypeNames.ServiceCollection)))
.AddMethodCall(x => x
.SetMethodName(TypeNames.AddSingleton)
.AddArgument(_services)
.AddArgument(LambdaBuilder
.New()
.SetBlock(true)
.AddArgument(_sp)
.SetCode(GenerateClientServiceProviderFactory(descriptor))))
.AddEmptyLine()
.AddCode(RegisterStoreAccessor(settings, descriptor.StoreAccessor))
.AddEmptyLine()
.ForEach(
descriptor.Operations,
(builder, operation) =>
builder.AddCode(ForwardSingletonToClientServiceProvider(
operation.RuntimeType.ToString())))
.AddEmptyLine()
.AddCode(ForwardSingletonToClientServiceProvider(
descriptor.ClientDescriptor.RuntimeType.ToString()))
.AddCode(ForwardSingletonToClientServiceProvider(
descriptor.ClientDescriptor.InterfaceType.ToString()))
.AddEmptyLine()
.AddMethodCall(x => x
.SetReturn()
.SetNew()
.SetMethodName(
TypeNames.ClientBuilder.WithGeneric(descriptor.StoreAccessor.RuntimeType))
.AddArgument(descriptor.Name.AsStringToken())
.AddArgument(_services)
.AddArgument(_serviceCollection));
private static ICode RegisterSerializerResolver() =>
MethodCallBuilder
.New()
.SetMethodName(TypeNames.AddSingleton)
.AddGeneric(TypeNames.ISerializerResolver)
.AddArgument(_services)
.AddArgument(LambdaBuilder
.New()
.AddArgument(_sp)
.SetCode(
MethodCallBuilder
.Inline()
.SetNew()
.SetMethodName(TypeNames.SerializerResolver)
.SetWrapArguments()
.AddArgument(MethodCallBuilder
.Inline()
.SetMethodName(TypeNames.Concat)
.AddArgument(
MethodCallBuilder
.Inline()
.SetMethodName(TypeNames.GetRequiredService)
.SetWrapArguments()
.AddGeneric(
TypeNames.IEnumerable.WithGeneric(
TypeNames.ISerializer))
.AddArgument(_parentServices))
.AddArgument(MethodCallBuilder
.Inline()
.SetMethodName(TypeNames.GetRequiredService)
.SetWrapArguments()
.AddGeneric(
TypeNames.IEnumerable.WithGeneric(TypeNames.ISerializer))
.AddArgument(_sp)))));
private static ICode RegisterStoreAccessor(
CSharpSyntaxGeneratorSettings settings,
StoreAccessorDescriptor storeAccessor)
{
if (settings.IsStoreDisabled())
{
return MethodCallBuilder
.New()
.SetMethodName(TypeNames.AddSingleton)
.AddArgument(_services)
.AddArgument(LambdaBuilder
.New()
.AddArgument(_sp)
.SetCode(MethodCallBuilder
.Inline()
.SetNew()
.SetMethodName(storeAccessor.RuntimeType.ToString())));
}
return MethodCallBuilder
.New()
.SetMethodName(TypeNames.AddSingleton)
.AddArgument(_services)
.AddArgument(LambdaBuilder
.New()
.AddArgument(_sp)
.SetCode(MethodCallBuilder
.Inline()
.SetNew()
.SetMethodName(storeAccessor.RuntimeType.ToString())
.AddArgument(MethodCallBuilder
.Inline()
.SetMethodName(TypeNames.GetRequiredService)
.SetWrapArguments()
.AddArgument(MethodCallBuilder
.Inline()
.SetMethodName(TypeNames.GetRequiredService)
.AddGeneric("ClientServiceProvider")
.AddArgument(_sp))
.AddGeneric(TypeNames.IOperationStore))
.AddArgument(MethodCallBuilder
.Inline()
.SetMethodName(TypeNames.GetRequiredService)
.SetWrapArguments()
.AddArgument(MethodCallBuilder
.Inline()
.SetMethodName(TypeNames.GetRequiredService)
.AddGeneric("ClientServiceProvider")
.AddArgument(_sp))
.AddGeneric(TypeNames.IEntityStore))
.AddArgument(MethodCallBuilder
.Inline()
.SetMethodName(TypeNames.GetRequiredService)
.SetWrapArguments()
.AddArgument(MethodCallBuilder
.Inline()
.SetMethodName(TypeNames.GetRequiredService)
.AddGeneric("ClientServiceProvider")
.AddArgument(_sp))
.AddGeneric(TypeNames.IEntityIdSerializer))
.AddArgument(MethodCallBuilder
.Inline()
.SetMethodName(TypeNames.GetRequiredService)
.SetWrapArguments()
.AddArgument(MethodCallBuilder
.Inline()
.SetMethodName(TypeNames.GetRequiredService)
.AddGeneric("ClientServiceProvider")
.AddArgument(_sp))
.AddGeneric(
TypeNames.IEnumerable.WithGeneric(
TypeNames.IOperationRequestFactory)))
.AddArgument(MethodCallBuilder
.Inline()
.SetMethodName(TypeNames.GetRequiredService)
.SetWrapArguments()
.AddArgument(MethodCallBuilder
.Inline()
.SetMethodName(TypeNames.GetRequiredService)
.AddGeneric("ClientServiceProvider")
.AddArgument(_sp))
.AddGeneric(
TypeNames.IEnumerable.WithGeneric(
TypeNames.IOperationResultDataFactory)))));
}
private static ICode ForwardSingletonToClientServiceProvider(string generic) =>
MethodCallBuilder
.New()
.SetMethodName(TypeNames.AddSingleton)
.AddArgument(_services)
.AddArgument(LambdaBuilder
.New()
.AddArgument(_sp)
.SetCode(MethodCallBuilder
.Inline()
.SetMethodName(TypeNames.GetRequiredService)
.SetWrapArguments()
.AddArgument(MethodCallBuilder
.Inline()
.SetMethodName(TypeNames.GetRequiredService)
.AddGeneric("ClientServiceProvider")
.AddArgument(_sp))
.AddGeneric(generic)));
private static ICode GenerateInternalMethodBody(
CSharpSyntaxGeneratorSettings settings,
DependencyInjectionDescriptor descriptor,
TransportProfile profile)
{
var rootNamespace = descriptor.ClientDescriptor.RuntimeType.Namespace;
var hasSubscriptions =
descriptor.Operations.OfType<SubscriptionOperationDescriptor>().Any();
var hasQueries =
descriptor.Operations.OfType<QueryOperationDescriptor>().Any();
var hasMutations =
descriptor.Operations.OfType<MutationOperationDescriptor>().Any();
CodeBlockBuilder body = CodeBlockBuilder
.New()
.AddCode(CreateBaseCode(settings));
var generatedConnections = new HashSet<TransportType>();
if (hasSubscriptions)
{
generatedConnections.Add(profile.Subscription);
body.AddCode(
RegisterConnection(profile.Subscription, descriptor.Name));
}
if (hasQueries && !generatedConnections.Contains(profile.Query))
{
generatedConnections.Add(profile.Query);
body.AddCode(RegisterConnection(profile.Query, descriptor.Name));
}
if (hasMutations && !generatedConnections.Contains(profile.Mutation))
{
generatedConnections.Add(profile.Mutation);
body.AddCode(RegisterConnection(profile.Mutation, descriptor.Name));
}
body.AddEmptyLine();
foreach (var typeDescriptor in descriptor.TypeDescriptors
.OfType<INamedTypeDescriptor>())
{
if (typeDescriptor.Kind == TypeKind.Entity && !typeDescriptor.IsInterface())
{
INamedTypeDescriptor namedTypeDescriptor =
(INamedTypeDescriptor)typeDescriptor.NamedType();
NameString className = namedTypeDescriptor.ExtractMapperName();
var interfaceName =
TypeNames.IEntityMapper.WithGeneric(
namedTypeDescriptor.ExtractType().ToString(),
$"{rootNamespace}.{typeDescriptor.RuntimeType.Name}");
body.AddMethodCall()
.SetMethodName(TypeNames.AddSingleton)
.AddGeneric(interfaceName)
.AddGeneric($"{CreateStateNamespace(rootNamespace)}.{className}")
.AddArgument(_services);
}
}
body.AddEmptyLine();
foreach (var enumType in descriptor.EnumTypeDescriptor)
{
body.AddMethodCall()
.SetMethodName(TypeNames.AddSingleton)
.AddGeneric(TypeNames.ISerializer)
.AddGeneric(CreateEnumParserName($"{rootNamespace}.{enumType.Name}"))
.AddArgument(_services);
}
foreach (var serializer in _builtInSerializers)
{
body.AddMethodCall()
.SetMethodName(TypeNames.AddSingleton)
.AddGeneric(TypeNames.ISerializer)
.AddGeneric(serializer)
.AddArgument(_services);
}
var stringTypeInfo = new RuntimeTypeInfo(TypeNames.String);
foreach (var scalar in descriptor.TypeDescriptors.OfType<ScalarTypeDescriptor>())
{
if (scalar.RuntimeType.Equals(stringTypeInfo) &&
scalar.SerializationType.Equals(stringTypeInfo) &&
!BuiltInScalarNames.IsBuiltInScalar(scalar.Name))
{
body.AddMethodCall()
.SetMethodName(TypeNames.AddSingleton)
.AddGeneric(TypeNames.ISerializer)
.AddArgument(_services)
.AddArgument(MethodCallBuilder
.Inline()
.SetNew()
.SetMethodName(TypeNames.StringSerializer)
.AddArgument(scalar.Name.AsStringToken()));
}
}
foreach (var inputTypeDescriptor in descriptor.TypeDescriptors
.Where(x => x.Kind is TypeKind.Input))
{
var formatter =
CreateInputValueFormatter(
(InputObjectTypeDescriptor)inputTypeDescriptor.NamedType());
body.AddMethodCall()
.SetMethodName(TypeNames.AddSingleton)
.AddGeneric(TypeNames.ISerializer)
.AddGeneric($"{rootNamespace}.{formatter}")
.AddArgument(_services);
}
body.AddCode(RegisterSerializerResolver());
body.AddEmptyLine();
foreach (var operation in descriptor.Operations)
{
if (!(operation.ResultTypeReference is InterfaceTypeDescriptor typeDescriptor))
{
continue;
}
TransportType operationKind = operation switch
{
SubscriptionOperationDescriptor => profile.Subscription,
QueryOperationDescriptor => profile.Query,
MutationOperationDescriptor => profile.Mutation,
_ => throw ThrowHelper.DependencyInjection_InvalidOperationKind(operation)
};
string connectionKind = operationKind switch
{
TransportType.Http => TypeNames.IHttpConnection,
TransportType.WebSocket => TypeNames.IWebSocketConnection,
TransportType.InMemory => TypeNames.IInMemoryConnection,
var v => throw ThrowHelper.DependencyInjection_InvalidTransportType(v)
};
string operationName = operation.Name;
string fullName = operation.RuntimeType.ToString();
string operationInterfaceName = operation.InterfaceType.ToString();
string resultInterface = typeDescriptor.RuntimeType.ToString();
// The factories are generated based on the concrete result type, which is the
// only implementee of the result type interface.
var factoryName =
CreateResultFactoryName(
typeDescriptor.ImplementedBy.First().RuntimeType.Name);
var builderName = CreateResultBuilderName(operationName);
body.AddCode(
RegisterOperation(
settings,
connectionKind,
fullName,
operationInterfaceName,
resultInterface,
$"{CreateStateNamespace(operation.RuntimeType.Namespace)}.{factoryName}",
$"{CreateStateNamespace(operation.RuntimeType.Namespace)}.{builderName}"));
}
if (settings.IsStoreEnabled())
{
body.AddCode(
MethodCallBuilder
.New()
.SetMethodName(TypeNames.AddSingleton)
.AddGeneric(TypeNames.IEntityIdSerializer)
.AddGeneric(descriptor.EntityIdFactoryDescriptor.Type.ToString())
.AddArgument(_services));
}
body.AddCode(
MethodCallBuilder
.New()
.SetMethodName(TypeNames.AddSingleton)
.AddGeneric(descriptor.ClientDescriptor.RuntimeType.ToString())
.AddArgument(_services));
body.AddCode(
MethodCallBuilder
.New()
.SetMethodName(TypeNames.AddSingleton)
.AddGeneric(descriptor.ClientDescriptor.InterfaceType.ToString())
.AddArgument(_services)
.AddArgument(LambdaBuilder
.New()
.AddArgument(_sp)
.SetCode(MethodCallBuilder
.Inline()
.SetMethodName(TypeNames.GetRequiredService)
.AddGeneric(descriptor.ClientDescriptor.RuntimeType.ToString())
.AddArgument(_sp))));
body.AddLine($"return {_services};");
return body;
}
private static ICode RegisterOperation(
CSharpSyntaxGeneratorSettings settings,
string connectionKind,
string operationFullName,
string operationInterfaceName,
string resultInterface,
string factory,
string resultBuilder)
{
return CodeBlockBuilder
.New()
.AddCode(
MethodCallBuilder
.New()
.SetMethodName(TypeNames.AddSingleton)
.AddGeneric(
TypeNames.IOperationResultDataFactory.WithGeneric(resultInterface))
.AddGeneric(factory)
.AddArgument(_services))
.AddCode(
MethodCallBuilder
.New()
.SetMethodName(TypeNames.AddSingleton)
.AddGeneric(TypeNames.IOperationResultDataFactory)
.AddArgument(_services)
.AddArgument(LambdaBuilder
.New()
.AddArgument(_sp)
.SetCode(MethodCallBuilder
.Inline()
.SetMethodName(TypeNames.GetRequiredService)
.AddGeneric(
TypeNames.IOperationResultDataFactory
.WithGeneric(resultInterface))
.AddArgument(_sp))))
.AddCode(
MethodCallBuilder
.New()
.SetMethodName(TypeNames.AddSingleton)
.AddGeneric(TypeNames.IOperationRequestFactory)
.AddArgument(_services)
.AddArgument(LambdaBuilder
.New()
.AddArgument(_sp)
.SetCode(MethodCallBuilder
.Inline()
.SetMethodName(TypeNames.GetRequiredService)
.AddGeneric(operationInterfaceName)
.AddArgument(_sp))))
.AddCode(MethodCallBuilder
.New()
.SetMethodName(TypeNames.AddSingleton)
.AddGeneric(
TypeNames.IOperationResultBuilder
.WithGeneric(TypeNames.JsonDocument, resultInterface))
.AddGeneric(resultBuilder)
.AddArgument(_services))
.AddCode(
MethodCallBuilder
.New()
.SetMethodName(TypeNames.AddSingleton)
.AddGeneric(TypeNames.IOperationExecutor.WithGeneric(resultInterface))
.AddArgument(_services)
.AddArgument(LambdaBuilder
.New()
.AddArgument(_sp)
.SetCode(MethodCallBuilder
.Inline()
.SetNew()
.SetMethodName(settings.IsStoreEnabled()
? TypeNames.OperationExecutor
: TypeNames.StorelessOperationExecutor)
.AddGeneric(TypeNames.JsonDocument)
.AddGeneric(resultInterface)
.AddArgument(
MethodCallBuilder
.Inline()
.SetMethodName(TypeNames.GetRequiredService)
.AddGeneric(connectionKind)
.AddArgument(_sp))
.AddArgument(
LambdaBuilder
.New()
.SetCode(
MethodCallBuilder
.Inline()
.SetMethodName(
TypeNames.GetRequiredService)
.AddGeneric(
TypeNames.IOperationResultBuilder.WithGeneric(
TypeNames.JsonDocument,
resultInterface))
.AddArgument(_sp)))
.If(settings.IsStoreEnabled(),
x => x
.AddArgument(
MethodCallBuilder
.Inline()
.SetMethodName(TypeNames.GetRequiredService)
.AddGeneric(TypeNames.IOperationStore)
.AddArgument(_sp))
.AddArgument(_strategy)))))
.AddCode(MethodCallBuilder
.New()
.SetMethodName(TypeNames.AddSingleton)
.AddGeneric(operationFullName)
.AddArgument(_services))
.AddCode(MethodCallBuilder
.New()
.SetMethodName(TypeNames.AddSingleton)
.AddGeneric(operationInterfaceName)
.AddArgument(_services)
.AddArgument(LambdaBuilder
.New()
.AddArgument(_sp)
.SetCode(MethodCallBuilder
.Inline()
.SetMethodName(TypeNames.GetRequiredService)
.AddGeneric(operationFullName)
.AddArgument(_sp))));
}
private static ICode RegisterHttpConnection(string clientName) =>
MethodCallBuilder
.New()
.SetMethodName(TypeNames.AddSingleton)
.AddArgument(_services)
.AddGeneric(TypeNames.IHttpConnection)
.AddArgument(LambdaBuilder
.New()
.AddArgument(_sp)
.SetBlock(true)
.SetCode(CodeBlockBuilder
.New()
.AddCode(AssignmentBuilder
.New()
.SetLefthandSide($"var {_clientFactory}")
.SetRighthandSide(MethodCallBuilder
.Inline()
.SetMethodName(TypeNames.GetRequiredService)
.AddGeneric(TypeNames.IHttpClientFactory)
.AddArgument(_parentServices)))
.AddCode(MethodCallBuilder
.New()
.SetReturn()
.SetNew()
.SetMethodName(TypeNames.HttpConnection)
.AddArgument(LambdaBuilder
.New()
.SetCode(MethodCallBuilder
.Inline()
.SetMethodName(
_clientFactory,
nameof(IHttpClientFactory.CreateClient))
.AddArgument(clientName.AsStringToken()))))));
private static ICode RegisterConnection(TransportType transportProfile, string clientName)
{
return transportProfile switch
{
TransportType.WebSocket => RegisterWebSocketConnection(clientName),
TransportType.Http => RegisterHttpConnection(clientName),
TransportType.InMemory => RegisterInMemoryConnection(clientName),
{ } v => throw ThrowHelper.DependencyInjection_InvalidTransportType(v)
};
}
private static ICode RegisterInMemoryConnection(string clientName)
{
return MethodCallBuilder
.New()
.SetMethodName(TypeNames.AddSingleton)
.AddGeneric(TypeNames.IInMemoryConnection)
.AddArgument(_services)
.AddArgument(LambdaBuilder
.New()
.AddArgument(_sp)
.SetBlock(true)
.SetCode(CodeBlockBuilder
.New()
.AddCode(AssignmentBuilder
.New()
.SetLefthandSide($"var {_clientFactory}")
.SetRighthandSide(MethodCallBuilder
.Inline()
.SetMethodName(TypeNames.GetRequiredService)
.AddGeneric(TypeNames.IInMemoryClientFactory)
.AddArgument(_parentServices)))
.AddCode(MethodCallBuilder
.New()
.SetReturn()
.SetNew()
.SetMethodName(TypeNames.InMemoryConnection)
.AddArgument(LambdaBuilder
.New()
.SetAsync()
.AddArgument(_ct)
.SetCode(MethodCallBuilder
.Inline()
.SetAwait()
.SetMethodName(_clientFactory, "CreateAsync")
.AddArgument(clientName.AsStringToken())
.AddArgument(_ct))))));
}
private static ICode RegisterWebSocketConnection(string clientName) =>
MethodCallBuilder
.New()
.SetMethodName(TypeNames.AddSingleton)
.AddGeneric(TypeNames.IWebSocketConnection)
.AddArgument(_services)
.AddArgument(LambdaBuilder
.New()
.AddArgument(_sp)
.SetBlock(true)
.SetCode(CodeBlockBuilder
.New()
.AddCode(AssignmentBuilder
.New()
.SetLefthandSide($"var {_sessionPool}")
.SetRighthandSide(MethodCallBuilder
.Inline()
.SetMethodName(TypeNames.GetRequiredService)
.AddGeneric(TypeNames.ISessionPool)
.AddArgument(_parentServices)))
.AddCode(MethodCallBuilder
.New()
.SetReturn()
.SetNew()
.SetMethodName(TypeNames.WebSocketConnection)
.AddArgument(LambdaBuilder
.New()
.SetAsync()
.AddArgument(_ct)
.SetCode(MethodCallBuilder
.Inline()
.SetAwait()
.SetMethodName(_sessionPool, "CreateAsync")
.AddArgument(clientName.AsStringToken())
.AddArgument(_ct))))));
private static ICode CreateBaseCode(CSharpSyntaxGeneratorSettings settings)
{
if (settings.IsStoreDisabled())
{
return CodeBlockBuilder.New();
}
return CodeBlockBuilder
.New()
.AddCode(MethodCallBuilder
.New()
.SetMethodName(TypeNames.TryAddSingleton)
.AddGeneric(TypeNames.IEntityStore)
.AddGeneric(TypeNames.EntityStore)
.AddArgument(_services))
.AddCode(MethodCallBuilder
.New()
.SetMethodName(TypeNames.TryAddSingleton)
.AddGeneric(TypeNames.IOperationStore)
.AddArgument(_services)
.AddArgument(LambdaBuilder
.New()
.AddArgument(_sp)
.SetCode(MethodCallBuilder
.Inline()
.SetNew()
.SetMethodName(TypeNames.OperationStore)
.AddArgument(MethodCallBuilder
.Inline()
.SetMethodName(TypeNames.GetRequiredService)
.AddGeneric(TypeNames.IEntityStore)
.AddArgument(_sp)))));
}
private static string _clientServiceProvider = @"
private class ClientServiceProvider
: System.IServiceProvider
, System.IDisposable
{
private readonly System.IServiceProvider _provider;
public ClientServiceProvider(System.IServiceProvider provider)
{
_provider = provider;
}
public object? GetService(System.Type serviceType)
{
return _provider.GetService(serviceType);
}
public void Dispose()
{
if (_provider is System.IDisposable d)
{
d.Dispose();
}
}
}
";
}
}
| 45.237557 | 100 | 0.473868 | [
"MIT"
] | dkapellusch/hotchocolate | src/StrawberryShake/CodeGeneration/src/CodeGeneration.CSharp/Generators/DependencyInjectionGenerator.cs | 39,990 | C# |
using System;
using UnityEngine;
using UnityEditor.XR.ARSubsystems.InternalBridge;
using UnityEngine.XR.ARSubsystems;
namespace UnityEditor.XR.ARSubsystems
{
[CustomEditor(typeof(XRReferenceImageLibrary))]
class XRReferenceImageLibraryEditor : Editor
{
static class Content
{
static readonly int s_AddImageControlId;
static readonly GUIContent s_AddButtonContent;
static readonly GUIContent s_RemoveButtonContent;
static Content()
{
s_AddButtonContent = new GUIContent("Add Image");
s_AddImageControlId = GUIUtility.GetControlID(s_AddButtonContent, FocusType.Keyboard);
s_RemoveButtonContent = new GUIContent(
string.Empty,
EditorGUIUtility.FindTexture("d_winbtn_win_close"),
"Remove this image from the database");
}
public static readonly GUIContent keepTexture = new GUIContent(
"Keep Texture at Runtime",
"If enabled, the texture will be available in the Player. Otherwise, the texture will be null in the Player.");
public static readonly GUIContent name = new GUIContent(
"Name",
"The name of the reference image. This can useful for matching detected images with their reference image at runtime.");
public static readonly GUIContent specifySize = new GUIContent(
"Specify Size",
"If enabled, you can specify the physical dimensions of the image in meters. Some platforms require this.");
public static readonly GUIContent sizePixels = new GUIContent(
"Texture Size (pixels)",
"The texture dimensions, in pixels.");
public static readonly GUIContent sizeMeters = new GUIContent(
"Physical Size (meters)",
"The dimensions of the physical image, in meters.");
public static int addImageControlId
{
get
{
return s_AddImageControlId;
}
}
public static bool addButton
{
get
{
return GUILayout.Button(s_AddButtonContent);
}
}
public static bool removeButton
{
get
{
return GUI.Button(
GUILayoutUtility.GetRect(s_RemoveButtonContent, GUI.skin.button, GUILayout.ExpandWidth(false)),
s_RemoveButtonContent,
GUI.skin.button);
}
}
}
SerializedProperty m_ReferenceImages;
void OnEnable()
{
m_ReferenceImages = serializedObject.FindProperty("m_Images");
}
public override void OnInspectorGUI()
{
serializedObject.Update();
int indexToRemove = -1;
for (int i = 0; i < m_ReferenceImages.arraySize; ++i)
{
var shouldRemove = ReferenceImageField(i);
if (shouldRemove)
{
indexToRemove = i;
}
EditorGUILayout.Separator();
if (i < m_ReferenceImages.arraySize - 1)
EditorGUILayout.LabelField(string.Empty, GUI.skin.horizontalSlider);
}
if (indexToRemove > -1)
m_ReferenceImages.DeleteArrayElementAtIndex(indexToRemove);
serializedObject.ApplyModifiedProperties();
if (Content.addButton)
{
Undo.RecordObject(target, "Add reference image");
(target as XRReferenceImageLibrary).Add();
EditorUtility.SetDirty(target);
}
}
/// <summary>
/// Generates the GUI for a reference image at index <paramref name="index"/>.
/// </summary>
/// <param name="index">The index of the reference image in the <see cref="XRReferenceImageLibrary"/>.</param>
/// <returns>True if the image should be removed.</returns>
bool ReferenceImageField(int index)
{
var library = target as XRReferenceImageLibrary;
var referenceImageProperty = m_ReferenceImages.GetArrayElementAtIndex(index);
var sizeProperty = referenceImageProperty.FindPropertyRelative("m_Size");
var specifySizeProperty = referenceImageProperty.FindPropertyRelative("m_SpecifySize");
var nameProperty = referenceImageProperty.FindPropertyRelative("m_Name");
var referenceImage = library[index];
var texturePath = AssetDatabase.GUIDToAssetPath(referenceImage.textureGuid.ToString("N"));
var texture = AssetDatabase.LoadAssetAtPath<Texture2D>(texturePath);
bool shouldRemove = false;
bool wasTextureUpdated = false;
using (new EditorGUILayout.HorizontalScope())
{
using (var textureCheck = new EditorGUI.ChangeCheckScope())
{
texture = TextureField(texture);
wasTextureUpdated = textureCheck.changed;
}
shouldRemove = Content.removeButton;
}
EditorGUILayout.PropertyField(nameProperty, Content.name);
EditorGUILayout.PropertyField(specifySizeProperty, Content.specifySize);
if (specifySizeProperty.boolValue)
{
using (new EditorGUI.IndentLevelScope())
{
using (new EditorGUI.DisabledScope(true))
{
var imageDimensions = (texture == null) ? Vector2Int.zero : GetTextureSize(texture);
EditorGUILayout.Vector2IntField(Content.sizePixels, imageDimensions);
}
using (var changeCheck = new EditorGUI.ChangeCheckScope())
{
EditorGUILayout.PropertyField(sizeProperty, Content.sizeMeters);
// Prevent dimensions from going below zero.
var size = new Vector2(
Mathf.Max(0f, sizeProperty.vector2Value.x),
Mathf.Max(0f, sizeProperty.vector2Value.y));
if ((sizeProperty.vector2Value.x < 0f) ||
(sizeProperty.vector2Value.y < 0f))
{
sizeProperty.vector2Value = size;
}
if (changeCheck.changed)
{
if (texture == null)
{
// If the texture is null, then we just set whatever the user specifies
sizeProperty.vector2Value = size;
}
else
{
// Otherwise, maintain the aspect ratio
var delta = referenceImage.size - size;
delta = new Vector2(Mathf.Abs(delta.x), Mathf.Abs(delta.y));
// Determine which dimension has changed and compute the unchanged dimension
if (delta.x > delta.y)
{
sizeProperty.vector2Value = SizeFromWidth(texture, size);
}
else if (delta.y > 0f)
{
sizeProperty.vector2Value = SizeFromHeight(texture, size);
}
}
}
else if (wasTextureUpdated && texture != null)
{
// If the texture changed, re-compute width / height
if (size.x == 0f)
{
sizeProperty.vector2Value = SizeFromHeight(texture, size);
}
else
{
sizeProperty.vector2Value = SizeFromWidth(texture, size);
}
}
}
if ((sizeProperty.vector2Value.x <= 0f) || (sizeProperty.vector2Value.y <= 0f))
{
EditorGUILayout.HelpBox("Dimensions must be greater than zero.", MessageType.Warning);
}
}
}
using (new EditorGUI.DisabledScope(texture == null))
using (var changeCheck = new EditorGUI.ChangeCheckScope())
{
bool keepTexture = EditorGUILayout.Toggle(Content.keepTexture, referenceImage.texture != null);
if (changeCheck.changed || wasTextureUpdated)
{
// Auto-populate the name from the texture's name if it is not set already.
if (string.IsNullOrEmpty(nameProperty.stringValue) && texture != null)
{
nameProperty.stringValue = texture.name;
}
// Apply properties for anything that may have been modified, otherwise
// the texture change may be overwritten.
serializedObject.ApplyModifiedProperties();
// Create an undo entry, modify, set dirty
Undo.RecordObject(target, "Update reference image texture");
library.SetTexture(index, texture, keepTexture);
EditorUtility.SetDirty(target);
}
}
return shouldRemove;
}
/// <summary>
/// Computes a new size using the width and aspect ratio from the Texture2D.
/// Width remains the same as before; height is recalculated.
/// </summary>
static Vector2 SizeFromWidth(Texture2D texture, Vector2 size)
{
var textureSize = GetTextureSize(texture);
return new Vector2(size.x, size.x * (float)textureSize.y / (float)textureSize.x);
}
/// <summary>
/// Computes a new size using the height and aspect ratio from the Texture2D.
/// Height remains the same as before; width is recalculated.
/// </summary>
static Vector2 SizeFromHeight(Texture2D texture, Vector2 size)
{
var textureSize = GetTextureSize(texture);
return new Vector2(size.y * (float)textureSize.x / (float)textureSize.y, size.y);
}
static Vector2Int GetTextureSize(Texture2D texture)
{
if (texture == null)
throw new ArgumentNullException("texture");
var textureImporter = AssetImporter.GetAtPath(AssetDatabase.GetAssetPath(texture)) as TextureImporter;
if (textureImporter == null)
{
return new Vector2Int(texture.width, texture.height);
}
else
{
return TextureImporterInternals.GetSourceTextureDimensions(textureImporter);
}
}
static Texture2D TextureField(Texture2D texture)
{
const int k_MaxSideLength = 64;
int width = k_MaxSideLength, height = k_MaxSideLength;
if (texture != null)
{
var textureSize = GetTextureSize(texture);
if (textureSize.x > textureSize.y)
height = width * textureSize.y / textureSize.x;
else
width = height * textureSize.x / textureSize.y;
}
return (Texture2D)EditorGUILayout.ObjectField(
texture,
typeof(Texture2D),
true,
GUILayout.Width(width),
GUILayout.Height(height));
}
}
}
| 40.485149 | 136 | 0.516997 | [
"Unlicense"
] | 23SAMY23/Meet-and-Greet-MR | Meet & Greet MR (AR)/Library/PackageCache/[email protected]/Editor/XRReferenceImageLibraryEditor.cs | 12,269 | C# |
using EasyML.Exceptions;
using EasyML.Models;
using Microsoft.ML;
using Microsoft.ML.AutoML;
using Microsoft.ML.Data;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
namespace EasyML.Regression
{
/// <summary>
/// Implements a machine learning system based on regression algorithms
/// </summary>
/// <typeparam name="TData">System's data type</typeparam>
public sealed class RegressionSystem<TData> : IMLSystem<TData, Prediction>
where TData : class
{
/// <summary>
/// Minimal number of dataset's rows to train system
/// </summary>
public const int MIN_DATASET_ROWS = 5;
/// <summary>
/// Current ML context
/// </summary>
private readonly MLContext _context;
/// <inheritdoc/>
public Configuration<TData> Configuration { get; private set; }
/// <inheritdoc/>
public IEnumerable<TData> TrainingSet { get; private set; }
/// <inheritdoc/>
public IEnumerable<TData> EvaluationSet { get; private set; }
private ITransformer? TrainedModel { get; set; }
private IDataView TransformedTrainingSet { get; set; }
private IDataView TransformedEvaluationSet { get; set; }
private Stream SavedModel { get; set; }
/// <summary>
/// Ctor.
/// </summary>
/// <param name="configuration">System's configuration</param>
/// <exception cref="ArgumentNullException"></exception>
/// <exception cref="ArgumentException"></exception>
private RegressionSystem(Configuration<TData> configuration)
{
CheckTData();
Configuration = configuration ?? throw new ArgumentNullException(nameof(configuration));
_context = new MLContext();
TrainingSet = new List<TData>();
EvaluationSet = new List<TData>();
}
/// <summary>
/// Ctor.
/// </summary>
/// <param name="savedModel">Saved model</param>
/// <param name="configuration">System's configuration</param>
/// <exception cref="ArgumentNullException"></exception>
/// <exception cref="ArgumentException"></exception>
private RegressionSystem(Stream savedModel,
Configuration<TData> configuration)
: this(configuration)
{
SavedModel = savedModel ?? throw new ArgumentNullException(nameof(savedModel));
try
{
TrainedModel = _context.Model.Load(savedModel, out _);
}
catch (Exception ex)
{
throw new ModelNotValidException($"Model content is not valid. More information: {ex.Message}", ex);
}
}
/// <summary>
/// Checks if TData structure is valid
/// </summary>
/// <exception cref="ArgumentException"></exception>
private void CheckTData()
{
foreach (var prop in typeof(TData).GetProperties())
{
if (prop.PropertyType != typeof(string) &&
prop.PropertyType != typeof(bool) &&
prop.PropertyType != typeof(Single))
throw new ArgumentException($"Type of property {prop.Name} is not supported. Only string, bool and Single are allowed.");
}
}
#region Train
/// <inheritdoc/>
public async Task<TrainingResult> TrainAsync(IEnumerable<TData> dataset)
{
if (dataset == null || !dataset.Any())
throw new ArgumentNullException(nameof(dataset));
if (dataset.Count() < MIN_DATASET_ROWS)
throw new ArgumentOutOfRangeException(nameof(dataset));
var trainingSetSize = Convert.ToInt32(dataset.Count() * (1 - Configuration.EvaluationSetPercentage));
TrainingSet = dataset.Take(trainingSetSize);
EvaluationSet = dataset.Skip(trainingSetSize);
return await GeneratedTrainedModel(dataset);
}
/// <inheritdoc/>
public async Task<TrainingResult> UpdateAndTrainAsync(IEnumerable<TData> newData)
{
if (newData == null || !newData.Any())
throw new ArgumentNullException(nameof(newData));
TrainingSet = TrainingSet.Concat(newData);
return await GeneratedTrainedModel(TrainingSet);
}
/// <summary>
/// Trains, evaluates and stores a trained model
/// </summary>
/// <param name="dataset">A dataset to train the system. Minimal number of rows: <see cref="MIN_DATASET_ROWS"/></param>
/// <returns>Training result</returns>
private async Task<TrainingResult> GeneratedTrainedModel(IEnumerable<TData> dataset)
{
var result = new TrainingResult();
RegressionResult regression = null;
var step = "Training system...";
try
{
regression = await CreateRegression(trainingData: _context.Data.LoadFromEnumerable(dataset),
maxTrainingTimeInSeconds: Configuration.MaxTrainingTimeInSeconds);
result.TestedAlgorithms = regression.TestedAlgorithms;
result.SelectedAlgorithm = regression.SelectedAlgorithm;
step = "Evaluating trained model...";
TrainedModel = Evaluate(EvaluationSet, regression.Result);
step = "Saving trained model...";
SavedModel = Export();
}
catch (Exception ex)
{
result.Error = new MLEngineException($"Error in step '{step}'. More information: {ex.Message}", ex);
}
result.Result = regression.Result != null &&
TrainedModel != null &&
result.Error == null;
return result;
}
private async Task<RegressionResult> CreateRegression(IDataView trainingData,
uint maxTrainingTimeInSeconds)
{
TransformedTrainingSet = trainingData;
//ConsoleHelper.ShowDataViewInConsole(mlContext, trainingDataView);
// STEP 2: Initialize our user-defined progress handler that AutoML will
// invoke after each model it produces and evaluates.
//var progressHandler = new RegressionProgressHandler();
// STEP 3: Run AutoML regression experiment
//ConsoleHelper.ConsoleWriteHeader("=============== Training the model ===============");
//Console.WriteLine($"Running AutoML regression experiment for {maxTrainingTimeInSeconds} seconds...");
return await Task.Factory.StartNew(() =>
{
var result = new RegressionResult();
try
{
var regression = _context.Auto()
.CreateRegressionExperiment(maxTrainingTimeInSeconds)
.Execute(TransformedTrainingSet, labelColumnName: Configuration.PredictionColumnName);//, progressHandler: progressHandler);
result.Result = regression;
result.TestedAlgorithms = GetTrainersByRSquared(regression);
result.SelectedAlgorithm = regression.BestRun.TrainerName;
}
catch (Exception ex)
{
result.Error = ex;
}
return result;
});
}
private IEnumerable<Trainer> GetTrainersByRSquared(ExperimentResult<RegressionMetrics> experimentResult)
{
var topRuns = experimentResult.RunDetails
.Where(r => r.ValidationMetrics != null && !double.IsNaN(r.ValidationMetrics.RSquared))
.OrderByDescending(r => r.ValidationMetrics.RSquared);
var result = new List<Trainer>(topRuns.Count());
for (var i = 0; i < topRuns.Count(); i++)
{
var run = topRuns.ElementAt(i);
result.Add(run.ValidationMetrics.GetTrainerInfo(run.TrainerName, run.RuntimeInSeconds));
}
return result;
}
private ITransformer Evaluate(IEnumerable<TData> testData,
ExperimentResult<RegressionMetrics> model)
{
IDataView testDataView = _context.Data.LoadFromEnumerable(testData);
RunDetail<RegressionMetrics> best = model.BestRun;
ITransformer trainedModel = best.Model;
TransformedEvaluationSet = trainedModel.Transform(testDataView);
var answerObj = new Prediction();
var metrics = _context.Regression.Evaluate(TransformedEvaluationSet, labelColumnName: Configuration.PredictionColumnName, scoreColumnName: nameof(answerObj.Score));
return trainedModel;
}
#endregion Train
/// <inheritdoc/>
public Prediction Predict(TData question)
{
if (question == null)
throw new ArgumentNullException(nameof(question));
if (_context == null ||
TrainedModel == null)
throw new SystemNotTrainedException();
var predEngine = _context.Model.CreatePredictionEngine<TData, Prediction>(TrainedModel);
return predEngine.Predict(question);
}
#region Export
/// <inheritdoc/>
public Stream Export()
{
return Export(() =>
{
var result = new MemoryStream();
_context.Model.Save(TrainedModel, TransformedTrainingSet.Schema, result);
return result;
});
}
/// <inheritdoc/>
public void Export(string savedModelPath)
{
var stream = Export();
stream.Seek(0, SeekOrigin.Begin);
using (var fs = new FileStream(savedModelPath, FileMode.OpenOrCreate))
{
stream.CopyTo(fs);
}
}
private T Export<T>(Func<T> exportFunc)
{
ValidateExport();
return exportFunc();
}
private void ValidateExport()
{
if (TrainedModel == null ||
_context == null ||
TransformedTrainingSet == null)
throw new SystemNotTrainedException();
}
#endregion Export
#region Factory
/// <summary>
/// Creates a new machine learning system
/// </summary>
/// <param name="configuration">System's configuration</param>
/// <returns>Machine learning system</returns>
/// <exception cref="ArgumentException"></exception>
/// <exception cref="ArgumentNullException"></exception>
public static RegressionSystem<TData> Create(Configuration<TData> configuration)
=> new RegressionSystem<TData>(configuration: configuration);
/// <summary>
/// Creates a new machine learning system from a previously saved trained model. This methods does not restore the data, only the trained model to ask for predictions
/// </summary>
/// <param name="savedModel">Saved model</param>
/// <param name="configuration">System's configuration</param>
/// <returns>Machine learning system</returns>
/// <exception cref="ArgumentException"></exception>
/// <exception cref="ArgumentNullException"></exception>
public static RegressionSystem<TData> Load(Stream savedModel, Configuration<TData> configuration)
=> new RegressionSystem<TData>(savedModel: savedModel, configuration: configuration);
/// <summary>
/// Creates a new machine learning system from a previously saved trained model. This methods does not restore the data, only the trained model to ask for predictions
/// </summary>
/// <param name="saveModelPath">Complete path to saved model</param>
/// <param name="configuration">System's configuration</param>
/// <returns>Machine learning system</returns>
/// <exception cref="ArgumentException"></exception>
/// <exception cref="ArgumentNullException"></exception>
/// <exception cref="FileNotFoundException"></exception>
/// <exception cref="Exception"></exception>
public static RegressionSystem<TData> Load(string saveModelPath, Configuration<TData> configuration)
{
if (!File.Exists(saveModelPath))
throw new FileNotFoundException(nameof(saveModelPath));
var str = new FileStream(saveModelPath, FileMode.Open);
return new RegressionSystem<TData>(savedModel: str,
configuration: configuration);
}
#endregion Factory
}
}
| 33.234568 | 168 | 0.710253 | [
"MIT"
] | yeyopepe/EasyML | EasyML/Regression/RegressionSystem.cs | 10,770 | C# |
namespace MyChess;
public enum PieceRank
{
None = 0,
Pawn = 1,
Knight = 2,
Bishop = 4,
Rook = 8,
Queen = 16,
King = 32
}
| 12.538462 | 22 | 0.472393 | [
"MIT"
] | JanneMattila/chess | src/MyChess/PieceRank.cs | 165 | C# |
using System.Collections.Generic;
using System.IO;
using TriggersTools.CatSystem2;
namespace Grisaia.Categories.Sprites {
/// <summary>
/// The class for a list of sprite parts for the specified type Id. (The number of padded 0's + 1)
/// </summary>
internal sealed class SpritePartList : SpriteElement<int, SpritePartList>, ISpritePartList {
#region Fields
/// <summary>
/// Gets the list of sprite parts.
/// </summary>
public List<ISpritePart> List { get; } = new List<ISpritePart>();
IReadOnlyList<ISpritePart> ISpritePartList.List => List;
#endregion
#region Properties
/// <summary>
/// Gets the number of sprite parts in this list for this type.
/// </summary>
public int Count => List.Count;
#endregion
#region Accessors
/// <summary>
/// Gets the sprite part with the specified Id in the category.
/// </summary>
/// <param name="id">The Id of the sprite part to get.</param>
/// <returns>The sprite part with the specified Id.</returns>
public ISpritePart Get(int id) {
ISpritePart part = List.Find(p => p.Id == id);
return part ?? throw new KeyNotFoundException($"Could not find key \"{id}\"!");
}
/// <summary>
/// Tries to get the sprite part with the specified Id in the category.
/// </summary>
/// <param name="id">The Id of the sprite part to get.</param>
/// <param name="value">The output sprite part if one was found, otherwise null.</param>
/// <returns>True if an sprite part with the Id was found, otherwise null.</returns>
public bool TryGetValue(int id, out ISpritePart part) {
part = List.Find(p => p.Id == id);
return part != null;
}
/// <summary>
/// Gets if the category contains an sprite part with the specified Id.
/// </summary>
/// <param name="id">The Id to check for an sprite part with.</param>
/// <returns>True if an sprite part exists with the specified Id, otherwise null.</returns>
public bool ContainsKey(int id) => List.Find(p => p.Id == id) != null;
#endregion
#region ToString Override
/// <summary>
/// Gets the string representation of the sprite part list.
/// </summary>
/// <returns>The sprite part list's string representation.</returns>
public override string ToString() => $"Type={Id}, Count={Count}";
#endregion
}
/// <summary>
/// The class for a single sprite part with the specified Id for it's associated type Id.
/// (The number after the padded 0's)
/// </summary>
internal sealed class SpritePart : SpriteElement<int, SpritePart>, ISpritePart {
#region Fields
/// <summary>
/// Gets the file name for this sprite part.
/// </summary>
public string FileName { get; set; }
/// <summary>
/// Gets the cached Hg3 data for this sprite. This is null if not cached.
/// </summary>
public HgxImage Hg3 { get; set; }
#endregion
#region ToString Override
/// <summary>
/// Gets the string representation of the sprite part.
/// </summary>
/// <returns>The sprite part's string representation.</returns>
public override string ToString() => FileName;
#endregion
/*#region Helpers
/// <summary>
/// Gets the file name for the sprite with the specified image and frame indecies.
/// </summary>
/// <param name="imgIndex">
/// The first index, which is assocaited to an <see cref="Hg3.ImageIndex"/>.
/// </param>
/// <param name="frmIndex">
/// The second index, which is associated to a frame inside an <see cref="Hg3Image"/>.
/// </param>
/// <returns>The file name of the frame.</returns>
public string GetFrameFileName(int imgIndex, int frmIndex) {
return Hg3.GetFrameFileName(imgIndex, frmIndex);
}
/// <summary>
/// Gets the file path for the sprite with the specified image and frame indecies.
/// </summary>
/// <param name="directory">The directory of the <see cref="Hg3"/> images.</param>
/// <param name="imgIndex">
/// The first index, which is assocaited to an <see cref="Hg3.ImageIndex"/>.
/// </param>
/// <param name="frmIndex">
/// The second index, which is associated to a frame inside an <see cref="Hg3Image"/>.
/// </param>
/// <returns>The file path of the frame.</returns>
public string GetFrameFilePath(string directory, int imgIndex, int frmIndex) {
return Hg3.GetFrameFilePath(directory, imgIndex, frmIndex);
}
#endregion*/
}
}
| 33.430769 | 100 | 0.665439 | [
"MIT"
] | trigger-death/GrisaiaSpriteViewer | GrisaiaCategorization/Categories/Sprites/SpriteParts.cs | 4,348 | C# |
// Copyright (c) 2007-2011 SlimDX Group
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using System;
namespace SlimDX.Generator
{
class StringFormatter : Formatter
{
#region Interface
/// <summary>
/// Gets the code for declaring the specified model as a parameter to a managed method.
/// </summary>
/// <param name="model">The model.</param>
/// <returns>The code.</returns>
public string GetFormalParameterCode(ParameterModel model)
{
return string.Format("System.String {0}", model.Name);
}
/// <summary>
/// Gets the code for passing the specified model as parameter to a trampoline method.
/// </summary>
/// <param name="model">The model.</param>
/// <returns>The code.</returns>
public string GetTrampolineParameterCode(ParameterModel model)
{
return string.Format("_{0}", model.Name);
}
/// <summary>
/// Gets the code for setup of local variables related to the specified parameter.
/// </summary>
/// <param name="marshaller">The marshalling service interface.</param>
/// <param name="model">The model.</param>
/// <returns>The code.</returns>
public string GetLocalVariableSetupCode(MarshallingService marshaller, ParameterModel model)
{
return string.Format("System.IntPtr _{0} = System.Runtime.InteropServices.Marshal.StringToHGlobalAnsi({0});", model.Name);
}
/// <summary>
/// Gets the code for cleanup of local variables related to the specified parameter.
/// </summary>
/// <param name="model">The model.</param>
/// <returns>The code.</returns>
public string GetLocalVariableCleanupCode(ParameterModel model)
{
return string.Format("System.Runtime.InteropServices.Marshal.FreeHGlobal(_{0});", model.Name);
}
#endregion
}
}
| 38.90411 | 126 | 0.705986 | [
"MIT"
] | SlimDX/SlimDX-v2 | Source/Tools/Generator/Formatter/StringFormatter.cs | 2,842 | C# |
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using SmartSql;
using SmartSql.Abstractions.Config;
using SmartSql.Logging;
using SmartSql.Options;
using System;
using System.Collections.Generic;
using System.Text;
namespace Microsoft.Extensions.DependencyInjection
{
public static class SmartSqlOptionsExtensions
{
public static void AddSmartSqlOptionLoader(this IServiceCollection services)
{
services.AddSingleton<IConfigLoader>((sp) =>
{
var loggerFactory = sp.GetService<ILoggerFactory>() ?? NoneLoggerFactory.Instance;
var optionsMonitor = sp.GetService<IOptionsMonitor<SmartSqlConfigOptions>>();
var _configLoader = new OptionConfigLoader(optionsMonitor.CurrentValue, loggerFactory);
SmartSqlOptions smartSqlOptions = new SmartSqlOptions
{
ConfigLoader = _configLoader,
LoggerFactory = loggerFactory
};
if (optionsMonitor.CurrentValue.Settings.IsWatchConfigFile)
{
optionsMonitor.OnChange((ops, name) =>
{
_configLoader.TriggerChanged(ops);
});
}
return _configLoader;
});
}
public static void AddSmartSqlOption(this IServiceCollection services)
{
services.AddSmartSqlOptionLoader();
services.AddSmartSql(sp =>
{
var loggerFactory = sp.GetService<ILoggerFactory>() ?? NoneLoggerFactory.Instance;
var _configLoader = sp.GetRequiredService<IConfigLoader>();
return new SmartSqlOptions
{
ConfigLoader = _configLoader,
LoggerFactory = loggerFactory
};
});
}
public static void UserOptions(this SmartSqlOptions smartSqlOptions, IServiceProvider sp)
{
var _configLoader = sp.GetRequiredService<IConfigLoader>();
smartSqlOptions.ConfigLoader = _configLoader;
}
}
}
| 37.084746 | 103 | 0.596892 | [
"Apache-2.0"
] | kuxingsheng/SmartSql | src/SmartSql.Options/SmartSqlOptionsExtensions.cs | 2,190 | C# |
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using AutoMapper;
using MediatR;
using Microsoft.EntityFrameworkCore;
using WizardWorld.Persistance;
namespace WizardWorld.Application.Requests.Ingredients.Queries.GetIngredients {
public class GetIngredientsQueryHandler : IRequestHandler<GetIngredientsQuery, List<IngredientDto>> {
private readonly ApplicationDbContext _context;
private readonly IMapper _mapper;
public GetIngredientsQueryHandler(ApplicationDbContext context, IMapper mapper) {
_context = context;
_mapper = mapper;
}
public async Task<List<IngredientDto>> Handle(GetIngredientsQuery request, CancellationToken cancellationToken) {
return await _context.Ingredients
.AsNoTracking()
.Include(a => a.Elixirs)
.Where(a => (string.IsNullOrEmpty(request.Name) || a.Name.StartsWith(request.Name)))
.Select(a => _mapper.Map<IngredientDto>(a)).ToListAsync(cancellationToken);
}
}
} | 39.607143 | 121 | 0.706943 | [
"MIT"
] | MossPiglets/WizardWorldAPI | WizardWorldApi/WizardWorld.Application/Requests/Ingredients/Queries/GetIngredients/GetIngredientsQueryHandler.cs | 1,111 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.ComponentModel;
using System.Drawing;
using System.Windows.Forms.Layout;
namespace System.Windows.Forms
{
/// <summary>
/// ToolStripItem that can host Controls.
/// </summary>
public partial class ToolStripControlHost : ToolStripItem
{
private Control _control;
private int _suspendSyncSizeCount;
private ContentAlignment _controlAlign = ContentAlignment.MiddleCenter;
private bool _inSetVisibleCore;
internal static readonly object s_gotFocusEvent = new object();
internal static readonly object s_lostFocusEvent = new object();
internal static readonly object s_keyDownEvent = new object();
internal static readonly object s_keyPressEvent = new object();
internal static readonly object s_keyUpEvent = new object();
internal static readonly object s_enterEvent = new object();
internal static readonly object s_leaveEvent = new object();
internal static readonly object s_validatedEvent = new object();
internal static readonly object s_validatingEvent = new object();
/// <summary>
/// Constructs a ToolStripControlHost
/// </summary>
public ToolStripControlHost(Control c)
{
_control = c.OrThrowIfNullWithMessage(SR.ControlCannotBeNull);
SyncControlParent();
c.Visible = true;
SetBounds(c.Bounds);
// now that we have a control set in, update the bounds.
Rectangle bounds = Bounds;
CommonProperties.UpdateSpecifiedBounds(c, bounds.X, bounds.Y, bounds.Width, bounds.Height);
c.ToolStripControlHost = this;
OnSubscribeControlEvents(c);
}
public ToolStripControlHost(Control c, string name) : this(c)
{
Name = name;
}
public override Color BackColor
{
get => Control.BackColor;
set => Control.BackColor = value;
}
/// <summary>
/// Gets or sets the image that is displayed on a <see cref="Label"/>.
/// </summary>
[Localizable(true)]
[SRCategory(nameof(SR.CatAppearance))]
[SRDescription(nameof(SR.ToolStripItemImageDescr))]
[DefaultValue(null)]
public override Image BackgroundImage
{
get => Control.BackgroundImage;
set => Control.BackgroundImage = value;
}
[SRCategory(nameof(SR.CatAppearance))]
[DefaultValue(ImageLayout.Tile)]
[Localizable(true)]
[SRDescription(nameof(SR.ControlBackgroundImageLayoutDescr))]
public override ImageLayout BackgroundImageLayout
{
get => Control.BackgroundImageLayout;
set => Control.BackgroundImageLayout = value;
}
/// <summary>
/// Overriden to return value from Control.CanSelect.
/// </summary>
public override bool CanSelect
{
get
{
if (_control is not null)
{
return (DesignMode || Control.CanSelect);
}
return false;
}
}
[SRCategory(nameof(SR.CatFocus))]
[DefaultValue(true)]
[SRDescription(nameof(SR.ControlCausesValidationDescr))]
public bool CausesValidation
{
get => Control.CausesValidation;
set => Control.CausesValidation = value;
}
[DefaultValue(ContentAlignment.MiddleCenter)]
[Browsable(false)]
public ContentAlignment ControlAlign
{
get => _controlAlign;
set
{
SourceGenerated.EnumValidator.Validate(value);
if (_controlAlign != value)
{
_controlAlign = value;
OnBoundsChanged();
}
}
}
/// <summary>
/// The control that this item is hosting.
/// </summary>
[Browsable(false)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public Control Control => _control;
internal AccessibleObject ControlAccessibilityObject => Control?.AccessibilityObject;
/// <summary>
/// Deriving classes can override this to configure a default size for their control.
/// This is more efficient than setting the size in the control's constructor.
/// </summary>
protected override Size DefaultSize
{
get
{
if (Control is not null)
{
// When you create the control - it sets up its size as its default size.
// Since the property is protected we don't know for sure, but this is a pretty good guess.
return Control.Size;
}
return base.DefaultSize;
}
}
[Browsable(false)]
[EditorBrowsable(EditorBrowsableState.Never)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public new ToolStripItemDisplayStyle DisplayStyle
{
get => base.DisplayStyle;
set => base.DisplayStyle = value;
}
[Browsable(false)]
[EditorBrowsable(EditorBrowsableState.Never)]
public new event EventHandler DisplayStyleChanged
{
add => Events.AddHandler(s_displayStyleChangedEvent, value);
remove => Events.RemoveHandler(s_displayStyleChangedEvent, value);
}
/// <summary>
/// For control hosts, this property has no effect
/// as they get their own clicks. Use ControlStyles.StandardClick
/// instead.
/// </summary>
[DefaultValue(false)]
[Browsable(false)]
[EditorBrowsable(EditorBrowsableState.Never)]
public new bool DoubleClickEnabled
{
get => base.DoubleClickEnabled;
set => base.DoubleClickEnabled = value;
}
public override Font Font
{
get => Control.Font;
set => Control.Font = value;
}
public override bool Enabled
{
get => Control.Enabled;
set => Control.Enabled = value;
}
[SRCategory(nameof(SR.CatFocus))]
[SRDescription(nameof(SR.ControlOnEnterDescr))]
public event EventHandler Enter
{
add => Events.AddHandler(s_enterEvent, value);
remove => Events.RemoveHandler(s_enterEvent, value);
}
[Browsable(false)]
[EditorBrowsable(EditorBrowsableState.Always)]
public virtual bool Focused => Control.Focused;
public override Color ForeColor
{
get => Control.ForeColor;
set => Control.ForeColor = value;
}
[SRCategory(nameof(SR.CatFocus))]
[SRDescription(nameof(SR.ToolStripItemOnGotFocusDescr))]
[Browsable(false)]
[EditorBrowsable(EditorBrowsableState.Advanced)]
public event EventHandler GotFocus
{
add => Events.AddHandler(s_gotFocusEvent, value);
remove => Events.RemoveHandler(s_gotFocusEvent, value);
}
[Browsable(false)]
[EditorBrowsable(EditorBrowsableState.Never)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public override Image Image
{
get => base.Image;
set => base.Image = value;
}
[Browsable(false)]
[EditorBrowsable(EditorBrowsableState.Never)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public new ToolStripItemImageScaling ImageScaling
{
get => base.ImageScaling;
set => base.ImageScaling = value;
}
[Browsable(false)]
[EditorBrowsable(EditorBrowsableState.Never)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public new Color ImageTransparentColor
{
get => base.ImageTransparentColor;
set => base.ImageTransparentColor = value;
}
[Browsable(false)]
[EditorBrowsable(EditorBrowsableState.Never)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public new ContentAlignment ImageAlign
{
get => base.ImageAlign;
set => base.ImageAlign = value;
}
[SRCategory(nameof(SR.CatFocus))]
[SRDescription(nameof(SR.ControlOnLeaveDescr))]
public event EventHandler Leave
{
add => Events.AddHandler(s_leaveEvent, value);
remove => Events.RemoveHandler(s_leaveEvent, value);
}
/// <summary>
/// Occurs when the control loses focus.
/// </summary>
[SRCategory(nameof(SR.CatFocus))]
[SRDescription(nameof(SR.ToolStripItemOnLostFocusDescr))]
[Browsable(false)]
[EditorBrowsable(EditorBrowsableState.Advanced)]
public event EventHandler LostFocus
{
add => Events.AddHandler(s_lostFocusEvent, value);
remove => Events.RemoveHandler(s_lostFocusEvent, value);
}
/// <summary>
/// Occurs when a key is pressed down while the control has focus.
/// </summary>
[SRCategory(nameof(SR.CatKey))]
[SRDescription(nameof(SR.ControlOnKeyDownDescr))]
public event KeyEventHandler KeyDown
{
add => Events.AddHandler(s_keyDownEvent, value);
remove => Events.RemoveHandler(s_keyDownEvent, value);
}
/// <summary>
/// Occurs when a key is pressed while the control has focus.
/// </summary>
[SRCategory(nameof(SR.CatKey))]
[SRDescription(nameof(SR.ControlOnKeyPressDescr))]
public event KeyPressEventHandler KeyPress
{
add => Events.AddHandler(s_keyPressEvent, value);
remove => Events.RemoveHandler(s_keyPressEvent, value);
}
/// <summary>
/// Occurs when a key is released while the control has focus.
/// </summary>
[SRCategory(nameof(SR.CatKey))]
[SRDescription(nameof(SR.ControlOnKeyUpDescr))]
public event KeyEventHandler KeyUp
{
add => Events.AddHandler(s_keyUpEvent, value);
remove => Events.RemoveHandler(s_keyUpEvent, value);
}
/// <summary>
/// This is used for international applications where the language
/// is written from RightToLeft. When this property is true,
/// control placement and text will be from right to left.
/// </summary>
public override RightToLeft RightToLeft
{
get
{
if (_control is not null)
{
return _control.RightToLeft;
}
return base.RightToLeft;
}
set
{
if (_control is not null)
{
_control.RightToLeft = value;
}
}
}
[Browsable(false)]
[EditorBrowsable(EditorBrowsableState.Never)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public new bool RightToLeftAutoMirrorImage
{
get => base.RightToLeftAutoMirrorImage;
set => base.RightToLeftAutoMirrorImage = value;
}
public override bool Selected => Control is not null && Control.Focused;
public override Size Size
{
get => base.Size;
set
{
Rectangle specifiedBounds = Rectangle.Empty;
if (_control is not null)
{
// we don't normally update the specified bounds, but if someone explicitly sets
// the size we should.
specifiedBounds = _control.Bounds;
specifiedBounds.Size = value;
CommonProperties.UpdateSpecifiedBounds(_control, specifiedBounds.X, specifiedBounds.Y, specifiedBounds.Width, specifiedBounds.Height);
}
base.Size = value;
if (_control is not null)
{
// checking again in case the control has adjusted the size.
Rectangle bounds = _control.Bounds;
if (bounds != specifiedBounds)
{
CommonProperties.UpdateSpecifiedBounds(_control, bounds.X, bounds.Y, bounds.Width, bounds.Height);
}
}
}
}
/// <summary>
/// Overriden to set the Site for the control hosted. This is set at DesignTime when the component is added to the Container.
/// </summary>
[EditorBrowsable(EditorBrowsableState.Advanced)]
public override ISite Site
{
get => base.Site;
set
{
base.Site = value;
if (value is not null)
{
Control.Site = new StubSite(Control, this);
}
else
{
Control.Site = null;
}
}
}
/// <summary>
/// Overriden to modify hosted control's text.
/// </summary>
[DefaultValue("")]
public override string Text
{
get => Control.Text;
set => Control.Text = value;
}
[Browsable(false)]
[EditorBrowsable(EditorBrowsableState.Never)]
public new ContentAlignment TextAlign
{
get => base.TextAlign;
set => base.TextAlign = value;
}
[Browsable(false)]
[EditorBrowsable(EditorBrowsableState.Never)]
[DefaultValue(ToolStripTextDirection.Horizontal)]
public override ToolStripTextDirection TextDirection
{
get => base.TextDirection;
set => base.TextDirection = value;
}
[Browsable(false)]
[EditorBrowsable(EditorBrowsableState.Never)]
public new TextImageRelation TextImageRelation
{
get => base.TextImageRelation;
set => base.TextImageRelation = value;
}
[SRCategory(nameof(SR.CatFocus))]
[SRDescription(nameof(SR.ControlOnValidatingDescr))]
public event CancelEventHandler Validating
{
add => Events.AddHandler(s_validatingEvent, value);
remove => Events.RemoveHandler(s_validatingEvent, value);
}
[SRCategory(nameof(SR.CatFocus))]
[SRDescription(nameof(SR.ControlOnValidatedDescr))]
public event EventHandler Validated
{
add => Events.AddHandler(s_validatedEvent, value);
remove => Events.RemoveHandler(s_validatedEvent, value);
}
/// <summary>
/// Cleans up and destroys the hosted control.
/// </summary>
protected override void Dispose(bool disposing)
{
// Call base first so other things stop trying to talk to the control. This will
// unparent the host item which will cause a SyncControlParent, so the control
// will be correctly unparented before being disposed.
base.Dispose(disposing);
if (disposing && Control is not null)
{
OnUnsubscribeControlEvents(Control);
// we only call control.Dispose if we are NOT being disposed in the finalizer.
Control.Dispose();
_control = null;
}
}
[EditorBrowsable(EditorBrowsableState.Advanced)]
public void Focus() => Control.Focus();
public override Size GetPreferredSize(Size constrainingSize)
{
if (_control is not null)
{
return Control.GetPreferredSize(constrainingSize - Padding.Size) + Padding.Size;
}
return base.GetPreferredSize(constrainingSize);
}
/// Handle* wrappers:
/// We sync the event from the hosted control and call resurface it on ToolStripItem.
private void HandleClick(object sender, EventArgs e) => OnClick(e);
private void HandleBackColorChanged(object sender, EventArgs e) => OnBackColorChanged(e);
private void HandleDoubleClick(object sender, EventArgs e) => OnDoubleClick(e);
private void HandleDragDrop(object sender, DragEventArgs e) => OnDragDrop(e);
private void HandleDragEnter(object sender, DragEventArgs e) => OnDragEnter(e);
private void HandleDragLeave(object sender, EventArgs e) => OnDragLeave(e);
private void HandleDragOver(object sender, DragEventArgs e) => OnDragOver(e);
private void HandleEnter(object sender, EventArgs e) => OnEnter(e);
private void HandleEnabledChanged(object sender, EventArgs e) => OnEnabledChanged(e);
private void HandleForeColorChanged(object sender, EventArgs e) => OnForeColorChanged(e);
private void HandleGiveFeedback(object sender, GiveFeedbackEventArgs e) => OnGiveFeedback(e);
private void HandleGotFocus(object sender, EventArgs e) => OnGotFocus(e);
private void HandleLocationChanged(object sender, EventArgs e) => OnLocationChanged(e);
private void HandleLostFocus(object sender, EventArgs e) => OnLostFocus(e);
private void HandleKeyDown(object sender, KeyEventArgs e) => OnKeyDown(e);
private void HandleKeyPress(object sender, KeyPressEventArgs e) => OnKeyPress(e);
private void HandleKeyUp(object sender, KeyEventArgs e) => OnKeyUp(e);
private void HandleLeave(object sender, EventArgs e) => OnLeave(e);
private void HandleMouseDown(object sender, MouseEventArgs e)
{
OnMouseDown(e);
RaiseMouseEvent(ToolStripItem.s_mouseDownEvent, e);
}
private void HandleMouseEnter(object sender, EventArgs e)
{
OnMouseEnter(e);
RaiseEvent(ToolStripItem.s_mouseEnterEvent, e);
}
private void HandleMouseLeave(object sender, EventArgs e)
{
OnMouseLeave(e);
RaiseEvent(ToolStripItem.s_mouseLeaveEvent, e);
}
private void HandleMouseHover(object sender, EventArgs e)
{
OnMouseHover(e);
RaiseEvent(ToolStripItem.s_mouseHoverEvent, e);
}
private void HandleMouseMove(object sender, MouseEventArgs e)
{
OnMouseMove(e);
RaiseMouseEvent(ToolStripItem.s_mouseMoveEvent, e);
}
private void HandleMouseUp(object sender, MouseEventArgs e)
{
OnMouseUp(e);
RaiseMouseEvent(ToolStripItem.s_mouseUpEvent, e);
}
private void HandlePaint(object sender, PaintEventArgs e)
{
OnPaint(e);
RaisePaintEvent(ToolStripItem.s_paintEvent, e);
}
private void HandleQueryAccessibilityHelp(object sender, QueryAccessibilityHelpEventArgs e)
{
((QueryAccessibilityHelpEventHandler)Events[ToolStripItem.s_queryAccessibilityHelpEvent])?.Invoke(this, e);
}
private void HandleQueryContinueDrag(object sender, QueryContinueDragEventArgs e) => OnQueryContinueDrag(e);
private void HandleRightToLeftChanged(object sender, EventArgs e) => OnRightToLeftChanged(e);
private void HandleResize(object sender, EventArgs e)
{
if (_suspendSyncSizeCount == 0)
{
OnHostedControlResize(e);
}
}
private void HandleTextChanged(object sender, EventArgs e) => OnTextChanged(e);
private void HandleControlVisibleChanged(object sender, EventArgs e)
{
// check the STATE_VISIBLE flag rather than using Control.Visible.
// if we check while it's unparented it will return visible false.
// the easiest way to do this is to use ParticipatesInLayout.
bool controlVisibleStateFlag = ((IArrangedElement)Control).ParticipatesInLayout;
bool itemVisibleStateFlag = ((IArrangedElement)(this)).ParticipatesInLayout;
if (itemVisibleStateFlag != controlVisibleStateFlag)
{
Visible = Control.Visible;
// this should fire the OnVisibleChanged and raise events appropriately.
}
}
private void HandleValidating(object sender, CancelEventArgs e) => OnValidating(e);
private void HandleValidated(object sender, EventArgs e) => OnValidated(e);
internal override void OnAccessibleDescriptionChanged(EventArgs e)
{
Control.AccessibleDescription = AccessibleDescription;
}
internal override void OnAccessibleNameChanged(EventArgs e)
{
Control.AccessibleName = AccessibleName;
}
internal override void OnAccessibleDefaultActionDescriptionChanged(EventArgs e)
{
Control.AccessibleDefaultActionDescription = AccessibleDefaultActionDescription;
}
internal override void OnAccessibleRoleChanged(EventArgs e)
{
Control.AccessibleRole = AccessibleRole;
}
protected virtual void OnEnter(EventArgs e) => RaiseEvent(s_enterEvent, e);
/// <summary>
/// called when the control has lost focus
/// </summary>
protected virtual void OnGotFocus(EventArgs e) => RaiseEvent(s_gotFocusEvent, e);
protected virtual void OnLeave(EventArgs e) => RaiseEvent(s_leaveEvent, e);
/// <summary>
/// called when the control has lost focus
/// </summary>
protected virtual void OnLostFocus(EventArgs e) => RaiseEvent(s_lostFocusEvent, e);
protected virtual void OnKeyDown(KeyEventArgs e) => RaiseKeyEvent(s_keyDownEvent, e);
protected virtual void OnKeyPress(KeyPressEventArgs e) => RaiseKeyPressEvent(s_keyPressEvent, e);
protected virtual void OnKeyUp(KeyEventArgs e) => RaiseKeyEvent(s_keyUpEvent, e);
/// <summary>
/// Called when the items bounds are changed. Here, we update the Control's bounds.
/// </summary>
protected override void OnBoundsChanged()
{
if (!(_control is IArrangedElement element))
{
return;
}
SuspendSizeSync();
Size size = LayoutUtils.DeflateRect(Bounds, Padding).Size;
Rectangle bounds = LayoutUtils.Align(size, Bounds, ControlAlign);
// use BoundsSpecified.None so we don't deal w/specified bounds - this way we can tell what someone has set the size to.
element.SetBounds(bounds, BoundsSpecified.None);
// sometimes a control can ignore the size passed in, use the adjustment
// to re-align.
if (bounds != _control.Bounds)
{
bounds = LayoutUtils.Align(_control.Size, Bounds, ControlAlign);
element.SetBounds(bounds, BoundsSpecified.None);
}
ResumeSizeSync();
}
/// <summary>
/// Called when the control fires its Paint event.
/// </summary>
protected override void OnPaint(PaintEventArgs e)
{
// do nothing....
}
protected internal override void OnLayout(LayoutEventArgs e)
{
// do nothing... called via the controls collection
}
/// <summary>
/// Called when the item's parent has been changed.
/// </summary>
protected override void OnParentChanged(ToolStrip oldParent, ToolStrip newParent)
{
if (oldParent is not null && Owner is null && newParent is null && Control is not null)
{
// if we've really been removed from the item collection,
// politely remove ourselves from the control collection
ReadOnlyControlCollection oldControlCollection
= GetControlCollection(Control.ParentInternal as ToolStrip);
if (oldControlCollection is not null)
{
oldControlCollection.RemoveInternal(Control);
}
}
else
{
SyncControlParent();
}
base.OnParentChanged(oldParent, newParent);
}
/// <summary>
/// The events from the hosted control are subscribed here.
/// Override to add/prevent syncing of control events.
/// NOTE: if you override and hook up events here, you should unhook in OnUnsubscribeControlEvents.
/// </summary>
protected virtual void OnSubscribeControlEvents(Control control)
{
if (control is not null)
{
// Please keep this alphabetized and in sync with Unsubscribe
control.Click += new EventHandler(HandleClick);
control.BackColorChanged += new EventHandler(HandleBackColorChanged);
control.DoubleClick += new EventHandler(HandleDoubleClick);
control.DragDrop += new DragEventHandler(HandleDragDrop);
control.DragEnter += new DragEventHandler(HandleDragEnter);
control.DragLeave += new EventHandler(HandleDragLeave);
control.DragOver += new DragEventHandler(HandleDragOver);
control.Enter += new EventHandler(HandleEnter);
control.EnabledChanged += new EventHandler(HandleEnabledChanged);
control.ForeColorChanged += new EventHandler(HandleForeColorChanged);
control.GiveFeedback += new GiveFeedbackEventHandler(HandleGiveFeedback);
control.GotFocus += new EventHandler(HandleGotFocus);
control.Leave += new EventHandler(HandleLeave);
control.LocationChanged += new EventHandler(HandleLocationChanged);
control.LostFocus += new EventHandler(HandleLostFocus);
control.KeyDown += new KeyEventHandler(HandleKeyDown);
control.KeyPress += new KeyPressEventHandler(HandleKeyPress);
control.KeyUp += new KeyEventHandler(HandleKeyUp);
control.MouseDown += new MouseEventHandler(HandleMouseDown);
control.MouseEnter += new EventHandler(HandleMouseEnter);
control.MouseHover += new EventHandler(HandleMouseHover);
control.MouseLeave += new EventHandler(HandleMouseLeave);
control.MouseMove += new MouseEventHandler(HandleMouseMove);
control.MouseUp += new MouseEventHandler(HandleMouseUp);
control.Paint += new PaintEventHandler(HandlePaint);
control.QueryAccessibilityHelp += new QueryAccessibilityHelpEventHandler(HandleQueryAccessibilityHelp);
control.QueryContinueDrag += new QueryContinueDragEventHandler(HandleQueryContinueDrag);
control.Resize += new EventHandler(HandleResize);
control.RightToLeftChanged += new EventHandler(HandleRightToLeftChanged);
control.TextChanged += new EventHandler(HandleTextChanged);
control.VisibleChanged += new EventHandler(HandleControlVisibleChanged);
control.Validating += new CancelEventHandler(HandleValidating);
control.Validated += new EventHandler(HandleValidated);
}
}
/// <summary>
/// The events from the hosted control are unsubscribed here.
/// Override to unhook events subscribed in OnSubscribeControlEvents.
/// </summary>
protected virtual void OnUnsubscribeControlEvents(Control control)
{
if (control is not null)
{
// Please keep this alphabetized and in sync with Subscribe
control.Click -= new EventHandler(HandleClick);
control.BackColorChanged -= new EventHandler(HandleBackColorChanged);
control.DoubleClick -= new EventHandler(HandleDoubleClick);
control.DragDrop -= new DragEventHandler(HandleDragDrop);
control.DragEnter -= new DragEventHandler(HandleDragEnter);
control.DragLeave -= new EventHandler(HandleDragLeave);
control.DragOver -= new DragEventHandler(HandleDragOver);
control.Enter -= new EventHandler(HandleEnter);
control.EnabledChanged -= new EventHandler(HandleEnabledChanged);
control.ForeColorChanged -= new EventHandler(HandleForeColorChanged);
control.GiveFeedback -= new GiveFeedbackEventHandler(HandleGiveFeedback);
control.GotFocus -= new EventHandler(HandleGotFocus);
control.Leave -= new EventHandler(HandleLeave);
control.LocationChanged -= new EventHandler(HandleLocationChanged);
control.LostFocus -= new EventHandler(HandleLostFocus);
control.KeyDown -= new KeyEventHandler(HandleKeyDown);
control.KeyPress -= new KeyPressEventHandler(HandleKeyPress);
control.KeyUp -= new KeyEventHandler(HandleKeyUp);
control.MouseDown -= new MouseEventHandler(HandleMouseDown);
control.MouseEnter -= new EventHandler(HandleMouseEnter);
control.MouseHover -= new EventHandler(HandleMouseHover);
control.MouseLeave -= new EventHandler(HandleMouseLeave);
control.MouseMove -= new MouseEventHandler(HandleMouseMove);
control.MouseUp -= new MouseEventHandler(HandleMouseUp);
control.Paint -= new PaintEventHandler(HandlePaint);
control.QueryAccessibilityHelp -= new QueryAccessibilityHelpEventHandler(HandleQueryAccessibilityHelp);
control.QueryContinueDrag -= new QueryContinueDragEventHandler(HandleQueryContinueDrag);
control.Resize -= new EventHandler(HandleResize);
control.RightToLeftChanged -= new EventHandler(HandleRightToLeftChanged);
control.TextChanged -= new EventHandler(HandleTextChanged);
control.VisibleChanged -= new EventHandler(HandleControlVisibleChanged);
control.Validating -= new CancelEventHandler(HandleValidating);
control.Validated -= new EventHandler(HandleValidated);
}
}
protected virtual void OnValidating(CancelEventArgs e) => RaiseCancelEvent(s_validatingEvent, e);
protected virtual void OnValidated(EventArgs e) => RaiseEvent(s_validatedEvent, e);
private static ReadOnlyControlCollection GetControlCollection(ToolStrip toolStrip)
=> (ReadOnlyControlCollection)toolStrip?.Controls;
/// <remarks>
/// Ensures the hosted Control is parented to the ToolStrip hosting this ToolStripItem.
/// </remarks>
private void SyncControlParent()
{
ReadOnlyControlCollection newControls = GetControlCollection(ParentInternal);
if (newControls is not null)
{
newControls.AddInternal(Control);
}
}
protected virtual void OnHostedControlResize(EventArgs e)
{
// support for syncing the wrapper when the control size has changed
Size = Control.Size;
}
protected internal override bool ProcessCmdKey(ref Message m, Keys keyData) => false;
protected internal override bool ProcessMnemonic(char charCode)
{
if (_control is not null)
{
return _control.ProcessMnemonic(charCode);
}
return base.ProcessMnemonic(charCode);
}
protected internal override bool ProcessDialogKey(Keys keyData) => false;
protected override void SetVisibleCore(bool visible)
{
// This is needed, because if you try and set set visible to true before the parent is visible,
// we will get called back into here, and set it back to false, since the parent is not visible.
if (_inSetVisibleCore)
{
return;
}
_inSetVisibleCore = true;
Control.SuspendLayout();
try
{
Control.Visible = visible;
}
finally
{
Control.ResumeLayout(false);
// this will go ahead and perform layout.
base.SetVisibleCore(visible);
_inSetVisibleCore = false;
}
}
[EditorBrowsable(EditorBrowsableState.Never)]
public override void ResetBackColor() => Control.ResetBackColor();
[EditorBrowsable(EditorBrowsableState.Never)]
public override void ResetForeColor() => Control.ResetForeColor();
private void SuspendSizeSync() => _suspendSyncSizeCount++;
private void ResumeSizeSync() => _suspendSyncSizeCount--;
internal override bool ShouldSerializeBackColor()
{
if (_control is not null)
{
return _control.ShouldSerializeBackColor();
}
return base.ShouldSerializeBackColor();
}
internal override bool ShouldSerializeForeColor()
{
if (_control is not null)
{
return _control.ShouldSerializeForeColor();
}
return base.ShouldSerializeForeColor();
}
internal override bool ShouldSerializeFont()
{
if (_control is not null)
{
return _control.ShouldSerializeFont();
}
return base.ShouldSerializeFont();
}
internal override bool ShouldSerializeRightToLeft()
{
if (_control is not null)
{
return _control.ShouldSerializeRightToLeft();
}
return base.ShouldSerializeRightToLeft();
}
internal override void OnKeyboardToolTipHook(ToolTip toolTip)
{
base.OnKeyboardToolTipHook(toolTip);
KeyboardToolTipStateMachine.Instance.Hook(Control, toolTip);
}
internal override void OnKeyboardToolTipUnhook(ToolTip toolTip)
{
base.OnKeyboardToolTipUnhook(toolTip);
KeyboardToolTipStateMachine.Instance.Unhook(Control, toolTip);
}
/// <summary>
/// Constructs the new instance of the accessibility object for this ToolStripControlHost ToolStrip item.
/// </summary>
/// <returns>
/// The new instance of the accessibility object for this ToolStripControlHost ToolStrip item
/// </returns>
protected override AccessibleObject CreateAccessibilityInstance()
=> new ToolStripControlHostAccessibleObject(this);
}
}
| 37.970181 | 154 | 0.603691 | [
"MIT"
] | AndreRRR/winforms | src/System.Windows.Forms/src/System/Windows/Forms/ToolStripControlHost.cs | 35,656 | C# |
// SlideEvent.cs
// Script#/Libraries/jQuery/UI
// This source code is subject to terms and conditions of the Apache License, Version 2.0.
//
using System;
using System.Runtime.CompilerServices;
namespace jQueryApi.UI.Widgets {
[Imported]
[IgnoreNamespace]
[ScriptName("Object")]
public sealed class SlideEvent {
[IntrinsicProperty]
public jQueryObject Handle {
get {
return null;
}
set {
}
}
[IntrinsicProperty]
public int Value {
get {
return 0;
}
set {
}
}
[IntrinsicProperty]
public Array Values {
get {
return null;
}
set {
}
}
}
}
| 18.795455 | 90 | 0.476421 | [
"Apache-2.0"
] | doc22940/scriptsharp | src/Libraries/jQuery/jQuery.UI/Widgets/Slider/SlideEvent.cs | 827 | C# |
namespace ForkingVirtualMachine
{
public static class Constants
{
public static readonly byte[] One = new byte[1] { 1 };
public static readonly byte[] Zero = new byte[1] { 0 };
public static readonly byte[] Empty = new byte[0];
public static readonly byte[] True = new byte[1] { byte.MaxValue };
public static readonly byte[] False = Empty;
public const int MAX_REGISTER_SIZE = 1024 * 1024;
public const int MAX_STACK_DEPTH = 256;
public const int MAX_EXE_DEPTH = 256;
public const int MAX_TICKS = 1024;
public const byte MAX_INT_BYTES = 16;
public const byte DEFINE = 1;
public const byte EXECUTE = 0;
}
}
| 24.233333 | 75 | 0.620358 | [
"Unlicense"
] | decoy/ForkingVirtualMachine | ForkingVirtualMachine/Constants.cs | 729 | 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 mediapackage-2017-10-12.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;
using System.Net;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
namespace Amazon.MediaPackage.Model
{
/// <summary>
/// This is the response object from the CreateChannel operation.
/// </summary>
public partial class CreateChannelResponse : AmazonWebServiceResponse
{
private string _arn;
private string _description;
private HlsIngest _hlsIngest;
private string _id;
private Dictionary<string, string> _tags = new Dictionary<string, string>();
/// <summary>
/// Gets and sets the property Arn. The Amazon Resource Name (ARN) assigned to the Channel.
/// </summary>
public string Arn
{
get { return this._arn; }
set { this._arn = value; }
}
// Check to see if Arn property is set
internal bool IsSetArn()
{
return this._arn != null;
}
/// <summary>
/// Gets and sets the property Description. A short text description of the Channel.
/// </summary>
public string Description
{
get { return this._description; }
set { this._description = value; }
}
// Check to see if Description property is set
internal bool IsSetDescription()
{
return this._description != null;
}
/// <summary>
/// Gets and sets the property HlsIngest.
/// </summary>
public HlsIngest HlsIngest
{
get { return this._hlsIngest; }
set { this._hlsIngest = value; }
}
// Check to see if HlsIngest property is set
internal bool IsSetHlsIngest()
{
return this._hlsIngest != null;
}
/// <summary>
/// Gets and sets the property Id. The ID of the Channel.
/// </summary>
public string Id
{
get { return this._id; }
set { this._id = value; }
}
// Check to see if Id property is set
internal bool IsSetId()
{
return this._id != null;
}
/// <summary>
/// Gets and sets the property Tags.
/// </summary>
public Dictionary<string, string> Tags
{
get { return this._tags; }
set { this._tags = value; }
}
// Check to see if Tags property is set
internal bool IsSetTags()
{
return this._tags != null && this._tags.Count > 0;
}
}
} | 28.491525 | 110 | 0.581797 | [
"Apache-2.0"
] | atpyatt/aws-sdk-net | sdk/src/Services/MediaPackage/Generated/Model/CreateChannelResponse.cs | 3,362 | C# |
using UnityEngine;
using System;
using System.Collections.Generic;
public static class EntityManager
{
public static Dictionary<string, Entity> all = new Dictionary<string, Entity>(1000);
public static void RegisterEntity(Entity e)
{
all.Add(e.ID, e);
}
public static void UnRegisterEntity(Entity e)
{
all.Remove(e.ID);
}
public static string get_id()
{
Guid guid = Guid.NewGuid();
string id = guid.ToString();
if (all.ContainsKey(id))
return get_id();
else
return id;
}
public static T GetEntityComponent<T>(this ComponentBase component) where T : ComponentBase
{
if ((object)component == null)
return null;
if ((object)component.Entity == null)
return null;
return component.Entity.GetEntityComponent<T>();
}
}
| 21.804878 | 95 | 0.604027 | [
"MIT"
] | pointcache/uECS | uECS/Assets/uECS/uECS/Core/Entity/EntityManager.cs | 896 | C# |
// Copyright 2022 Google LLC
//
// 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
//
// https://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.
// Generated code. DO NOT EDIT!
namespace Google.Cloud.Dialogflow.Cx.V3.Snippets
{
// [START dialogflow_v3_generated_Changelogs_ListChangelogs_sync_flattened_resourceNames]
using Google.Api.Gax;
using Google.Cloud.Dialogflow.Cx.V3;
using System;
public sealed partial class GeneratedChangelogsClientSnippets
{
/// <summary>Snippet for ListChangelogs</summary>
/// <remarks>
/// This snippet has been automatically generated for illustrative purposes only.
/// It may require modifications to work in your environment.
/// </remarks>
public void ListChangelogsResourceNames()
{
// Create client
ChangelogsClient changelogsClient = ChangelogsClient.Create();
// Initialize request argument(s)
AgentName parent = AgentName.FromProjectLocationAgent("[PROJECT]", "[LOCATION]", "[AGENT]");
// Make the request
PagedEnumerable<ListChangelogsResponse, Changelog> response = changelogsClient.ListChangelogs(parent);
// Iterate over all response items, lazily performing RPCs as required
foreach (Changelog item in response)
{
// Do something with each item
Console.WriteLine(item);
}
// Or iterate over pages (of server-defined size), performing one RPC per page
foreach (ListChangelogsResponse page in response.AsRawResponses())
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (Changelog item in page)
{
// Do something with each item
Console.WriteLine(item);
}
}
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<Changelog> singlePage = response.ReadPage(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (Changelog item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
}
}
// [END dialogflow_v3_generated_Changelogs_ListChangelogs_sync_flattened_resourceNames]
}
| 42.266667 | 120 | 0.636909 | [
"Apache-2.0"
] | AlexandrTrf/google-cloud-dotnet | apis/Google.Cloud.Dialogflow.Cx.V3/Google.Cloud.Dialogflow.Cx.V3.GeneratedSnippets/ChangelogsClient.ListChangelogsResourceNamesSnippet.g.cs | 3,170 | C# |
using MediatR;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
namespace Core.Domain.Notifications
{
public class DomainNotificationHandler : INotificationHandler<DomainNotification>
{
private List<DomainNotification> _notifications;
public DomainNotificationHandler()
{
_notifications = new List<DomainNotification>();
}
public virtual List<DomainNotification> GetNotifications()
{
return _notifications;
}
public Task Handle(DomainNotification message, CancellationToken cancellationToken)
{
_notifications.Add(message);
return Task.CompletedTask;
}
public virtual bool HasNotifications()
{
return _notifications.Any();
}
public virtual void ClearNotifications()
{
_notifications.Clear();
}
public void Dispose()
{
_notifications = new List<DomainNotification>();
}
}
}
| 24.155556 | 91 | 0.624655 | [
"MIT"
] | alexandrebeato/bankflix | server/src/Core.Domain/Notifications/DomainNotificationHandler.cs | 1,089 | C# |
#Tue Nov 30 21:55:12 EST 2021
lib/features/com.ibm.websphere.appserver.org.eclipse.microprofile.faulttolerance-2.0.mf=a0b7ab247cfbff932bfb16dd65bcbb26
dev/api/stable/com.ibm.websphere.org.eclipse.microprofile.faulttolerance.2.0_1.0.59.jar=82a3a85574dfd3841cbef20a8db5c4c0
| 68 | 120 | 0.856618 | [
"MIT"
] | johnojacob99/CSC480-21F | frontend/target/liberty/wlp/lib/features/checksums/com.ibm.websphere.appserver.org.eclipse.microprofile.faulttolerance-2.0.cs | 272 | C# |
using Grasshopper.Kernel;
using Rhino.Geometry;
using System;
using System.Collections.Generic;
namespace ThreePlus.Components.Geometry
{
public class GH_GeoCylinder : GH_GeoPreview
{
/// <summary>
/// Initializes a new instance of the GH_GeoCapsule class.
/// </summary>
public GH_GeoCylinder()
: base("Cylinder Geometry", "Cylinder",
"A Three JS Standard Geometry Cylinder",
Constants.ShortName, "Shapes")
{
}
/// <summary>
/// Registers all the input parameters for this component.
/// </summary>
protected override void RegisterInputParams(GH_Component.GH_InputParamManager pManager)
{
pManager.AddPlaneParameter("Plane", "P", "The plane", GH_ParamAccess.item, Plane.WorldXY);
pManager[0].Optional = true;
pManager.AddNumberParameter("Radius", "R", "The base radius", GH_ParamAccess.item, 10);
pManager[1].Optional = true;
pManager.AddNumberParameter("Height", "H", "The cone height", GH_ParamAccess.item, 20);
pManager[2].Optional = true;
pManager.AddBooleanParameter("Smooth", "S", "Is the cap smoothed", GH_ParamAccess.item, false);
pManager[3].Optional = true;
pManager.AddIntegerParameter("Divisions", "D", "The number of radial divisions", GH_ParamAccess.item, 24);
pManager[4].Optional = true;
}
/// <summary>
/// Registers all the output parameters for this component.
/// </summary>
protected override void RegisterOutputParams(GH_Component.GH_OutputParamManager pManager)
{
pManager.AddGenericParameter("Model Element", "M", "A Three Plus Model", GH_ParamAccess.item);
}
/// <summary>
/// This is the method that actually does the work.
/// </summary>
/// <param name="DA">The DA object is used to retrieve from inputs and store in outputs.</param>
protected override void SolveInstance(IGH_DataAccess DA)
{
Plane plane = Plane.WorldXY;
DA.GetData(0, ref plane);
double radius = 10.0;
DA.GetData(1, ref radius);
double height = 20.0;
DA.GetData(2, ref height);
bool capsule = false;
DA.GetData(3, ref capsule);
int divisions = 24;
DA.GetData(4, ref divisions);
Shape shape = new Shape();
if (capsule)
{
shape = Shape.CapsuleShape(plane, radius, height, divisions);
}
else
{
shape = Shape.CylinderShape(plane, radius, height, divisions);
}
Model model = new Model(shape);
prevModels.Add(model);
DA.SetData(0, model);
}
/// <summary>
/// Provides an Icon for the component.
/// </summary>
protected override System.Drawing.Bitmap Icon
{
get
{
//You can add image files to your project resources and access them like this:
// return Resources.IconForThisComponent;
return Properties.Resources.Three_Shape_Cylinder_01;
}
}
/// <summary>
/// Gets the unique ID for this component. Do not change this ID after release.
/// </summary>
public override Guid ComponentGuid
{
get { return new Guid("fdd8ae15-0b71-45d5-8bd8-2c2520962e31"); }
}
}
} | 35.15534 | 118 | 0.567799 | [
"MIT"
] | interopxyz/ThreePlus | ThreePlus/Components/Geometry/GH_GeoCylinder.cs | 3,623 | C# |
using System;
using Xunit;
using System.Collections.Generic;
namespace q3_LongestNonRepSubstring
{
public class TestLongestNonRepeatingSubstring
{
[Theory]
[InlineData("pwwkew", 3)]
[InlineData("abcabcbb", 3)]
[InlineData("bbbbbbbbbbbbbbbbbbbbbbbbbbb", 1)]
[InlineData("", 0)]
public void TestBruteForce(string testCase, int expResult)
{
var result = SlidingWindow.LengthOfLongestSubstring(testCase);
Assert.Equal(expResult, result);
}
}
public class BruteForceSolution
{
public static int LengthOfLongestSubstring(string s)
{
HashSet<char> probeSet = new HashSet<char>(s.Length);
int maxSubstrLength = 0;
for (int i = 0; i < s.Length && s.Length - i > maxSubstrLength; i++)
{ //Main cursor
probeSet.Clear();
for (int j = i; j < s.Length && !probeSet.Contains(s[j]); j++)
{ //probe cursor
probeSet.Add(s[j]);
}
int substrLength = probeSet.Count;
if (substrLength > maxSubstrLength)
{
maxSubstrLength = substrLength;
}
}
return maxSubstrLength;
}
}
public class SlidingWindow
{
public static int LengthOfLongestSubstring(string s)
{
if(string.IsNullOrEmpty(s)) return 0;
HashSet<char> probeSet = new HashSet<char>(s.Length);
int maxSubstrLength = 0;
for (int cLeft = 0, cRight = 0; cRight < s.Length; cRight++)
{
while(probeSet.Contains(s[cRight]))
{
probeSet.Remove(s[cLeft]); //!! Throw away from left of the window, til the newly discovered char
cLeft++; //Left of the window
}
probeSet.Add(s[cRight]);
maxSubstrLength = Math.Max(maxSubstrLength, cRight - cLeft + 1);
}
return maxSubstrLength;
}
}
//0 1 2 3 4 5 6 7
//p w w k e w
// l r
//[]
//3
}
| 31.957746 | 118 | 0.498457 | [
"MIT"
] | hyha/algo-csharp | q3-LongestNonRepSubstring/UnitTest1.cs | 2,269 | C# |
namespace Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801
{
using Microsoft.Azure.PowerShell.Cmdlets.Functions.Runtime.PowerShell;
/// <summary>
/// A PowerShell PSTypeConverter to support converting to an instance of <see cref="Operation" />
/// </summary>
public partial class OperationTypeConverter : global::System.Management.Automation.PSTypeConverter
{
/// <summary>
/// Determines if the converter can convert the <see cref="sourceValue"/> parameter to the <see cref="destinationType" />
/// parameter.
/// </summary>
/// <param name="sourceValue">the <see cref="System.Object"/> to convert from</param>
/// <param name="destinationType">the <see cref="System.Type" /> to convert to</param>
/// <returns>
/// <c>true</c> if the converter can convert the <see cref="sourceValue"/> parameter to the <see cref="destinationType" />
/// parameter, otherwise <c>false</c>.
/// </returns>
public override bool CanConvertFrom(object sourceValue, global::System.Type destinationType) => CanConvertFrom(sourceValue);
/// <summary>
/// Determines if the converter can convert the <see cref="sourceValue"/> parameter to the <see cref="destinationType" />
/// parameter.
/// </summary>
/// <param name="sourceValue">the <see cref="System.Object" /> instance to check if it can be converted to the <see cref="Operation"
/// /> type.</param>
/// <returns>
/// <c>true</c> if the instance could be converted to a <see cref="Operation" /> type, otherwise <c>false</c>
/// </returns>
public static bool CanConvertFrom(dynamic sourceValue)
{
if (null == sourceValue)
{
return true;
}
global::System.Type type = sourceValue.GetType();
if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type))
{
// we say yest to PSObjects
return true;
}
if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type))
{
// we say yest to Hashtables/dictionaries
return true;
}
try
{
if (null != sourceValue.ToJsonString())
{
return true;
}
}
catch
{
// Not one of our objects
}
try
{
string text = sourceValue.ToString()?.Trim();
return true == text?.StartsWith("{") && true == text?.EndsWith("}") && Microsoft.Azure.PowerShell.Cmdlets.Functions.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.Functions.Runtime.Json.JsonType.Object;
}
catch
{
// Doesn't look like it can be treated as JSON
}
return false;
}
/// <summary>
/// Determines if the <see cref="sourceValue" /> parameter can be converted to the <see cref="destinationType" /> parameter
/// </summary>
/// <param name="sourceValue">the <see cref="System.Object"/> to convert from</param>
/// <param name="destinationType">the <see cref="System.Type" /> to convert to</param>
/// <returns>
/// <c>true</c> if the converter can convert the <see cref="sourceValue" /> parameter to the <see cref="destinationType" />
/// parameter, otherwise <c>false</c>
/// </returns>
public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false;
/// <summary>
/// Converts the <see cref="sourceValue" /> parameter to the <see cref="destinationType" /> parameter using <see cref="formatProvider"
/// /> and <see cref="ignoreCase" />
/// </summary>
/// <param name="sourceValue">the <see cref="System.Object"/> to convert from</param>
/// <param name="destinationType">the <see cref="System.Type" /> to convert to</param>
/// <param name="formatProvider">not used by this TypeConverter.</param>
/// <param name="ignoreCase">when set to <c>true</c>, will ignore the case when converting.</param>
/// <returns>
/// an instance of <see cref="Operation" />, or <c>null</c> if there is no suitable conversion.
/// </returns>
public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => ConvertFrom(sourceValue);
/// <summary>
/// Converts the <see cref="sourceValue" /> parameter to the <see cref="destinationType" /> parameter using <see cref="formatProvider"
/// /> and <see cref="ignoreCase" />
/// </summary>
/// <param name="sourceValue">the value to convert into an instance of <see cref="Operation" />.</param>
/// <returns>
/// an instance of <see cref="Operation" />, or <c>null</c> if there is no suitable conversion.
/// </returns>
public static Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.IOperation ConvertFrom(dynamic sourceValue)
{
if (null == sourceValue)
{
return null;
}
global::System.Type type = sourceValue.GetType();
if (typeof(Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.IOperation).IsAssignableFrom(type))
{
return sourceValue;
}
try
{
return Operation.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());;
}
catch
{
// Unable to use JSON pattern
}
if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type))
{
return Operation.DeserializeFromPSObject(sourceValue);
}
if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type))
{
return Operation.DeserializeFromDictionary(sourceValue);
}
return null;
}
/// <summary>NotImplemented -- this will return <c>null</c></summary>
/// <param name="sourceValue">the <see cref="System.Object"/> to convert from</param>
/// <param name="destinationType">the <see cref="System.Type" /> to convert to</param>
/// <param name="formatProvider">not used by this TypeConverter.</param>
/// <param name="ignoreCase">when set to <c>true</c>, will ignore the case when converting.</param>
/// <returns>will always return <c>null</c>.</returns>
public override object ConvertTo(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => null;
}
} | 50.816901 | 249 | 0.577467 | [
"MIT"
] | 3quanfeng/azure-powershell | src/Functions/generated/api/Models/Api20190801/Operation.TypeConverter.cs | 7,075 | C# |
namespace Skybrud.Social.LinkedIn {
public class LinkedInConstants {
/// <summary>
/// The default fields used when fetching basic profile info.
/// </summary>
/// <see cref="https://developer.linkedin.com/docs/fields/basic-profile" />
public static readonly string[] BasicProfileDefaultFields = new[] {
"id",
"firstName",
"lastName",
"headline",
"num-connections",
"num-connections-capped",
"summary",
"pictureUrl",
"public-profile-url"
};
/// <summary>
/// The default fields used when fetching group posts.
/// </summary>
/// <see cref="https://developer.linkedin.com/documents/groups-fields"/>
public static readonly string[] GroupPostsDefaultFields = new[] {
"id",
"type",
"site-group-post-url",
"creation-timestamp",
"title",
"summary",
"creator",
"likes",
"comments",
"attachment:(image-url,content-domain,content-url,title,summary)",
"relation-to-viewer"
};
}
}
| 29.333333 | 83 | 0.505682 | [
"MIT"
] | abjerner/Skybrud.Social.LinkedIn | src/Skybrud.Social.LinkedIn/LinkedInConstants.cs | 1,234 | C# |
using System.Xml.Linq;
namespace TinyDSL.Xml
{
public static class XDC
{
public static dynamic New(string name, object attributes = null)
{
var element = new XElement(name);
if (attributes != null)
{
SetAttributes(element, attributes);
}
return New(element);
}
public static dynamic New(XElement element)
{
return (dynamic)new XmlDynamicConstructor(element);
}
public static void SetAttributes(XElement child, object arg)
{
var properties = arg.GetType().GetProperties();
foreach (var property in properties)
{
child.SetAttributeValue(property.Name, property.GetValue(arg));
}
}
}
}
| 24.264706 | 79 | 0.541818 | [
"MIT"
] | personball/TinyDSL | src/TinyDSL.Xml/Xml/XDC.cs | 827 | C# |
using DapperExtensions.Mapper;
using NUnit.Framework;
using System;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
namespace DapperExtensions.Test.Mapper
{
[TestFixture]
[Parallelizable(ParallelScope.All)]
public static class AutoClassMapperFixture
{
[TestFixture]
public class AutoClassMapperTableName
{
[Test]
public void Constructor_ReturnsProperName()
{
AutoClassMapper<Foo> m = GetMapper<Foo>();
Assert.AreEqual("Foo", m.TableName);
}
[Test]
public void SettingTableName_ReturnsProperName()
{
AutoClassMapper<Foo> m = GetMapper<Foo>();
m.Table("Barz");
Assert.AreEqual("Barz", m.TableName);
}
[Test]
public void Sets_IdPropertyToKeyWhenFirstProperty()
{
AutoClassMapper<IdIsFirst> m = GetMapper<IdIsFirst>();
var map = m.Properties.Single(p => p.KeyType == KeyType.Guid);
Assert.IsTrue(map.ColumnName == "Id");
}
[Test]
public void Sets_IdPropertyToKeyWhenFoundInClass()
{
AutoClassMapper<IdIsSecond> m = GetMapper<IdIsSecond>();
var map = m.Properties.Single(p => p.KeyType == KeyType.Guid);
Assert.IsTrue(map.ColumnName == "Id");
}
[Test]
public void Sets_IdFirstPropertyEndingInIdWhenNoIdPropertyFound()
{
AutoClassMapper<IdDoesNotExist> m = GetMapper<IdDoesNotExist>();
var map = m.Properties.Single(p => p.KeyType == KeyType.Guid);
Assert.IsTrue(map.ColumnName == "SomeId");
}
private static AutoClassMapper<T> GetMapper<T>() where T : class
{
return new AutoClassMapper<T>();
}
}
[TestFixture]
public class CustomAutoMapperTableName
{
[Test]
public void ReturnsProperPluralization()
{
CustomAutoMapper<Foo> m = GetMapper<Foo>();
Assert.AreEqual("Foo", m.TableName);
}
[Test]
public void ReturnsProperResultsForExceptions()
{
CustomAutoMapper<Foo2> m = GetMapper<Foo2>();
Assert.AreEqual("TheFoo", m.TableName);
}
private static CustomAutoMapper<T> GetMapper<T>() where T : class
{
return new CustomAutoMapper<T>();
}
public class CustomAutoMapper<T> : AutoClassMapper<T> where T : class
{
public override void Table(string tableName)
{
if (tableName.Equals("Foo2", StringComparison.CurrentCultureIgnoreCase))
{
TableName = "TheFoo";
}
else
{
base.Table(tableName);
}
}
}
}
[ExcludeFromCodeCoverage]
private class Foo
{
public Guid Id { get; set; }
public Guid ParentId { get; set; }
}
[ExcludeFromCodeCoverage]
private class Foo2
{
public Guid ParentId { get; set; }
public Guid Id { get; set; }
}
[ExcludeFromCodeCoverage]
private class IdIsFirst
{
public Guid Id { get; set; }
public Guid ParentId { get; set; }
}
[ExcludeFromCodeCoverage]
private class IdIsSecond
{
public Guid ParentId { get; set; }
public Guid Id { get; set; }
}
[ExcludeFromCodeCoverage]
private class IdDoesNotExist
{
public Guid SomeId { get; set; }
public Guid ParentId { get; set; }
}
}
}
| 29.985185 | 92 | 0.502717 | [
"Apache-2.0"
] | balchen/Dapper-Extensions | DapperExtensions.Test/Mapper/AutoClassMapperFixture.cs | 4,050 | C# |
// Copyright (c) DotSpatial Team. All rights reserved.
// Licensed under the MIT license. See License.txt file in the project root for full license information.
using System.ComponentModel.Composition;
using System.Globalization;
namespace DotSpatial.Extensions
{
/// <summary>
/// The IExtension interface represents the shared content between all providers and plugins. This simply acts like
/// an on-off switch for enabling or disabling the extension.
/// </summary>
[InheritedExport]
public interface IExtension
{
#region Properties
/// <summary>
/// Gets the Assembly Qualified FullName.
/// </summary>
string AssemblyQualifiedName { get; }
/// <summary>
/// Gets the author.
/// </summary>
string Author { get; }
/// <summary>
/// Gets the build date.
/// </summary>
string BuildDate { get; }
/// <summary>
/// Gets a value indicating whether [deactivation is allowed].
/// </summary>
/// <value>
/// <c>true</c> if [deactivation is allowed]; otherwise, <c>false</c>.
/// </value>
bool DeactivationAllowed { get; }
/// <summary>
/// Gets the description.
/// </summary>
string Description { get; }
/// <summary>
/// Gets a value indicating whether the extension is active and running.
/// </summary>
bool IsActive { get; }
/// <summary>
/// Gets the name.
/// </summary>
string Name { get; }
/// <summary>
/// Gets the activation priority order.
/// </summary>
int Priority { get; }
/// <summary>
/// Gets the version.
/// </summary>
string Version { get; }
#endregion
#region Methods
/// <summary>
/// Activates this extension
/// </summary>
void Activate();
/// <summary>
/// Deactivates this extension
/// </summary>
void Deactivate();
#endregion
}
} | 26.829268 | 121 | 0.52 | [
"MIT"
] | melofranco/DotSpatial | Source/DotSpatial.Extensions/IExtension.cs | 2,200 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Collections;
using System.ComponentModel;
using System.Data.SqlTypes;
using System.Data.Common;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Text;
using System.Xml;
using System.Xml.Serialization;
namespace System.Data
{
internal enum SchemaFormat
{
Public = 1,
Remoting = 2,
WebService = 3,
RemotingSkipSchema = 4,
WebServiceSkipSchema = 5
}
/// <summary>
/// </summary>
internal sealed class XmlTreeGen
{
private ArrayList? _constraintNames;
private Hashtable? _namespaces;
private Hashtable _autogenerated = default!; // Late-initialized
private Hashtable? _prefixes;
private DataSet? _ds;
private readonly ArrayList _tables = new ArrayList();
private readonly ArrayList _relations = new ArrayList();
private XmlDocument? _dc;
private XmlElement? _sRoot;
private int _prefixCount;
private readonly SchemaFormat _schFormat = SchemaFormat.Public;
private string? _filePath;
private string? _fileName;
private string? _fileExt;
private XmlElement? _dsElement;
private XmlElement? _constraintSeparator;
/// <summary>
/// This converter allows new versions of the framework to write
/// the assembly version of older versions of the framework.
/// </summary>
private Converter<Type, string>? _targetConverter;
internal XmlTreeGen(SchemaFormat format)
{
_schFormat = format;
}
internal static void AddExtendedProperties(PropertyCollection? props, XmlElement node)
{
AddExtendedProperties(props, node, null);
}
internal static void AddExtendedProperties(PropertyCollection? props, XmlElement node, Type? type)
{
if (props != null)
{
foreach (DictionaryEntry entry in props)
{
string s, v;
if (entry.Key is INullable)
{
s = (string)SqlConvert.ChangeTypeForXML(entry.Key, typeof(string));
}
else
{
s = Convert.ToString(entry.Key, CultureInfo.InvariantCulture)!;
}
if (entry.Value is INullable)
{
v = (string)SqlConvert.ChangeTypeForXML(entry.Value, typeof(string));
}
else if (entry.Value is System.Numerics.BigInteger)
{
v = (string)BigIntegerStorage.ConvertFromBigInteger((System.Numerics.BigInteger)entry.Value, typeof(string), CultureInfo.InvariantCulture);
}
else
{
v = Convert.ToString(entry.Value, CultureInfo.InvariantCulture)!;
}
if (type == typeof(DataRelation))
{
s = Keywords.MSD_REL_PREFIX + s;
}
else if (type == typeof(ForeignKeyConstraint))
{
s = Keywords.MSD_FK_PREFIX + s;
}
node.SetAttribute(XmlConvert.EncodeLocalName(s), Keywords.MSPROPNS, v);
}
}
}
[RequiresUnreferencedCode(DataSet.RequiresUnreferencedCodeMessage)]
internal void AddXdoProperties(object? instance, XmlElement root, XmlDocument xd)
{
if (instance == null)
{
return;
}
PropertyDescriptorCollection pds = TypeDescriptor.GetProperties(instance);
if (!((instance is DataSet) || (instance is DataTable) || (instance is DataColumn) || (instance is DataRelation)))
{
return;
}
for (int i = 0; i < pds.Count; i++)
{
AddXdoProperty(pds[i], instance, root, xd);
}
return;
}
[RequiresUnreferencedCode(DataSet.RequiresUnreferencedCodeMessage)]
internal void AddXdoProperty(PropertyDescriptor pd, object instance, XmlElement root, XmlDocument xd)
{
Type type = pd.PropertyType;
bool bisDataColumn = false;
DataColumn? col = null; // it may cause problem to assign null here, I will need to change this.
bool bIsSqlType = false;
bool bImplementsInullable = false;
if (instance is DataColumn)
{
col = (DataColumn)instance;
bisDataColumn = true;
bIsSqlType = col.IsSqlType;
bImplementsInullable = col.ImplementsINullable;
}
if (bImplementsInullable == false &&
type != typeof(string) && // DO NOT REMOVE THIS CHECK
type != typeof(bool) &&
type != typeof(Type) &&
type != typeof(object) &&
type != typeof(CultureInfo) &&
type != typeof(long) &&
type != typeof(int))
{
return;
}
if ((!pd.ShouldSerializeValue(instance) || !ContainsDesignerSerializationVisibleAttribute(pd)) && (bIsSqlType == false))
{
return;
}
object? propInst = pd.GetValue(instance);
if (propInst is InternalDataCollectionBase)
return;
if (propInst is PropertyCollection)
{
return;
}
// SDUB: perf: Why not have this as a table?
// there are several xdo properties that equal to some xml attributes, we should not explicitly ouput them.
if (
string.Equals(pd.Name, "Namespace", StringComparison.Ordinal) ||
string.Equals(pd.Name, "PrimaryKey", StringComparison.Ordinal) ||
string.Equals(pd.Name, "ColumnName", StringComparison.Ordinal) ||
string.Equals(pd.Name, "DefaultValue", StringComparison.Ordinal) ||
string.Equals(pd.Name, "TableName", StringComparison.Ordinal) ||
string.Equals(pd.Name, "DataSetName", StringComparison.Ordinal) ||
string.Equals(pd.Name, "AllowDBNull", StringComparison.Ordinal) ||
string.Equals(pd.Name, "Unique", StringComparison.Ordinal) ||
string.Equals(pd.Name, "NestedInDataSet", StringComparison.Ordinal) ||
string.Equals(pd.Name, "Locale", StringComparison.Ordinal) ||
string.Equals(pd.Name, "CaseSensitive", StringComparison.Ordinal) ||
string.Equals(pd.Name, "RemotingFormat", StringComparison.Ordinal)
)
{
return;
}
if (bisDataColumn)
{
if (string.Equals(pd.Name, "DataType", StringComparison.Ordinal))
{
string dt = XmlDataTypeName(col!.DataType);
if (bIsSqlType || (col.DataType == typeof(System.Numerics.BigInteger)))
{
root.SetAttribute(Keywords.MSD_DATATYPE, Keywords.MSDNS, col.DataType.FullName);
}
else if ((dt.Length == 0) || bImplementsInullable || ((dt == Keywords.XSD_ANYTYPE) && (col.XmlDataType != Keywords.XSD_ANYTYPE)) || (col.DataType == typeof(DateTimeOffset)))
{
// in Whidbey, XmlDataTypeName function changed to return "anyType" for typeof(Object)
// should still always hit this code path for all non-built in types
// to handle version qualified typeof(Object) and other CDT objects correctly
// we must write the output exactly the same way as we read it
SetMSDataAttribute(root, col.DataType);
}
return;
}
if (string.Equals(pd.Name, "Attribute", StringComparison.Ordinal))
{
return;
}
}
string? textValue = pd.Converter.ConvertToString(propInst);
root.SetAttribute(pd.Name, Keywords.MSDNS, textValue);
return;
}
[DynamicDependency(DynamicallyAccessedMemberTypes.PublicParameterlessConstructor | DynamicallyAccessedMemberTypes.PublicFields, typeof(DesignerSerializationVisibilityAttribute))]
[UnconditionalSuppressMessage("ReflectionAnalysis", "IL2026:RequiresUnreferencedCode", Justification = "The DynamicDependency ensures the correct members are preserved.")]
private bool ContainsDesignerSerializationVisibleAttribute(PropertyDescriptor pd) => pd.Attributes.Contains(DesignerSerializationVisibilityAttribute.Visible);
internal static string XmlDataTypeName(Type type)
{
if (type == typeof(char))
return "_"; // has to have SimpleType in this column.
if (type == typeof(byte[]) || type == typeof(SqlBytes))
return "base64Binary"; // has to have SimpleType in this column.
if (type == typeof(DateTime) || type == typeof(SqlDateTime))
return "dateTime";
if (type == typeof(TimeSpan))
return "duration";
if (type == typeof(decimal) || type == typeof(SqlDecimal) || type == typeof(SqlMoney))
return "decimal";
if (type == typeof(int))
return "int";
if (type == typeof(bool) || type == typeof(SqlBoolean))
return "boolean";
if (type == typeof(float) || type == typeof(SqlSingle))
return "float";
if (type == typeof(double) || type == typeof(SqlDouble))
return "double";
if (type == typeof(sbyte) || type == typeof(SqlByte))
return "byte";
if (type == typeof(byte))
return "unsignedByte";
if (type == typeof(short) || type == typeof(SqlInt16))
return "short";
if (type == typeof(int) || type == typeof(SqlInt32))
return "int";
if (type == typeof(long) || type == typeof(SqlInt64))
return "long";
if (type == typeof(ushort))
return "unsignedShort";
if (type == typeof(uint))
return "unsignedInt";
if (type == typeof(ulong))
return "unsignedLong";
if (type == typeof(System.Numerics.BigInteger))
return Keywords.XSD_ANYTYPE; //"integer";
if (type == typeof(Uri))
return "anyURI";
if (type == typeof(SqlBinary))
return "hexBinary";
if (type == typeof(string) || type == typeof(SqlGuid) || type == typeof(SqlString) || type == typeof(SqlChars))
return "string";
if (type == typeof(object) || type == typeof(SqlXml) || type == typeof(DateTimeOffset))
return Keywords.XSD_ANYTYPE;
return string.Empty;
// by default, if we dont map anything, we will map to String
// but I can not make Sql Types that will map to string be unmapped, because in schema , I will miss the second part and won't
// be able to differenciate between string snd SqlString and others that map to String
}
private void GenerateConstraintNames(DataTable table, bool fromTable)
{
// if constraint created obased on relation and it is self related rel. then add constraint
StringBuilder? builder = null;
foreach (Constraint constr in table.Constraints)
{
if (fromTable)
{
if (constr is ForeignKeyConstraint)
{ // if parent table does not exist , no need to create FKConst
if (!_tables.Contains(((ForeignKeyConstraint)constr).RelatedTable))
{
continue;
}
}
}
int nameInt = 0;
string name = constr.ConstraintName;
while (_constraintNames!.Contains(name))
{
if (null == builder)
{
builder = new StringBuilder();
}
builder.Append(table.TableName).Append('_').Append(constr.ConstraintName);
if (0 < nameInt)
{
builder.Append('_').Append(nameInt);
}
nameInt++;
name = builder.ToString();
builder.Length = 0;
}
_constraintNames.Add(name);
constr.SchemaName = name;
}
}
private void GenerateConstraintNames(ArrayList tables)
{
for (int i = 0; i < tables.Count; i++)
{
GenerateConstraintNames((DataTable)tables[i]!, true);
}
}
private void GenerateConstraintNames(DataSet ds)
{
foreach (DataTable dt in ds.Tables)
{
GenerateConstraintNames(dt, false);
}
}
//Does the DS or ANY object in it have ExtendedProperties?
private static bool _PropsNotEmpty(PropertyCollection? props)
{
return props != null && props.Count != 0;
}
private bool HaveExtendedProperties(DataSet ds)
{
if (_PropsNotEmpty(ds._extendedProperties))
{
return true;
}
for (int t = 0; t < ds.Tables.Count; t++)
{
DataTable table = ds.Tables[t];
if (_PropsNotEmpty(table._extendedProperties))
{
return true;
}
for (int c = 0; c < table.Columns.Count; c++)
{
if (_PropsNotEmpty(table.Columns[c]._extendedProperties))
{
return true;
}
}
}
// What is the best way to enumerate relations? from DataSet of from DataTable?
for (int r = 0; r < ds.Relations.Count; r++)
{
if (_PropsNotEmpty(ds.Relations[r]._extendedProperties))
{
return true;
}
}
// What about constraints?
return false;
}// HaveExtendedProperties
internal void WriteSchemaRoot(XmlDocument xd, XmlElement rootSchema, string targetNamespace)
{
/*
if (_ds != null)
rootSchema.SetAttribute(Keywords.XSDID, XmlConvert.EncodeLocalName(_ds.DataSetName));
else
rootSchema.SetAttribute(Keywords.XSDID, XmlConvert.EncodeLocalName("NewDataSet"));
*/
if (!string.IsNullOrEmpty(targetNamespace))
{
rootSchema.SetAttribute(Keywords.TARGETNAMESPACE, targetNamespace);
rootSchema.SetAttribute(Keywords.XMLNS_MSTNS, targetNamespace);
}
// Add the namespaces
// rootSchema.SetAttribute(Keywords.XMLNS, Keywords.XSD_ATOM.String));
rootSchema.SetAttribute(Keywords.XMLNS, targetNamespace);
rootSchema.SetAttribute(Keywords.XMLNS_XSD, Keywords.XSDNS);
rootSchema.SetAttribute(Keywords.XMLNS_MSDATA, Keywords.MSDNS);
if ((_ds != null) && (HaveExtendedProperties(_ds)))
{
rootSchema.SetAttribute(Keywords.XMLNS_MSPROP, Keywords.MSPROPNS);
}
if (!string.IsNullOrEmpty(targetNamespace))
{
rootSchema.SetAttribute(Keywords.XSD_ATTRIBUTEFORMDEFAULT, Keywords.QUALIFIED);
rootSchema.SetAttribute(Keywords.XSD_ELEMENTFORMDEFAULT, Keywords.QUALIFIED);
}
}
internal static void ValidateColumnMapping(Type columnType)
{
if (DataStorage.IsTypeCustomType(columnType))
{
throw ExceptionBuilder.InvalidDataColumnMapping(columnType);
}
}
internal void SetupAutoGenerated(DataSet ds)
{
foreach (DataTable dt in ds.Tables)
SetupAutoGenerated(dt);
}
internal void SetupAutoGenerated(ArrayList dt)
{
for (int i = 0; i < dt.Count; i++)
{
SetupAutoGenerated((DataTable)dt[i]!);
}
}
internal void SetupAutoGenerated(DataTable dt)
{
foreach (DataColumn col in dt.Columns)
{
if (AutoGenerated(col))
_autogenerated[col] = col;
}
foreach (Constraint cs in dt.Constraints)
{
ForeignKeyConstraint? fk = (cs as ForeignKeyConstraint);
if (null != fk)
{
if (AutoGenerated(fk))
_autogenerated[fk] = fk;
else
{
if (_autogenerated[fk.Columns[0]] != null)
_autogenerated[fk.Columns[0]] = null;
if (_autogenerated[fk.RelatedColumnsReference[0]] != null)
_autogenerated[fk.RelatedColumnsReference[0]] = null;
// special case of the ghosted constraints:
UniqueConstraint? _constraint = (UniqueConstraint?)fk.RelatedTable.Constraints.FindConstraint(new UniqueConstraint("TEMP", fk.RelatedColumnsReference));
if (_constraint == null)
continue;
if (_autogenerated[_constraint] != null)
_autogenerated[_constraint] = null;
if (_autogenerated[_constraint.Key.ColumnsReference[0]] != null)
_autogenerated[_constraint.Key.ColumnsReference[0]] = null;
}
}
else
{
UniqueConstraint unique = (UniqueConstraint)cs;
if (AutoGenerated(unique))
_autogenerated[unique] = unique;
else
{
if (_autogenerated[unique.Key.ColumnsReference[0]] != null)
_autogenerated[unique.Key.ColumnsReference[0]] = null;
}
}
}
}
private void CreateTablesHierarchy(DataTable dt)
{
// if (!dt.SerializeHierarchy)
// return;
foreach (DataRelation r in dt.ChildRelations)
{
if (!_tables.Contains(r.ChildTable))
{
_tables.Add(r.ChildTable);
CreateTablesHierarchy(r.ChildTable);
}
}
}
private void CreateRelations(DataTable dt)
{
foreach (DataRelation r in dt.ChildRelations)
{
if (!_relations.Contains(r))
{
_relations.Add(r);
// if (dt.SerializeHierarchy)
CreateRelations(r.ChildTable);
}
}
}
private DataTable[] CreateToplevelTables()
{
ArrayList topTables = new ArrayList();
for (int i = 0; i < _tables.Count; i++)
{
DataTable table = (DataTable)_tables[i]!;
if (table.ParentRelations.Count == 0)
topTables.Add(table);
else
{
bool fNestedButNotSelfNested = false;
for (int j = 0; j < table.ParentRelations.Count; j++)
{
if (table.ParentRelations[j].Nested)
{
if (table.ParentRelations[j].ParentTable == table)
{
fNestedButNotSelfNested = false;
break;
}
fNestedButNotSelfNested = true;
}
}
if (!fNestedButNotSelfNested)
topTables.Add(table);
}
}
if (topTables.Count == 0)
{
return Array.Empty<DataTable>();
}
var temp = new DataTable[topTables.Count];
topTables.CopyTo(temp, 0);
return temp;
}
// SxS: this method can generate XSD files if the input xmlWriter is XmlTextWriter or DataTextWriter and its underlying stream is FileStream
// These XSDs are located in the same folder as the underlying stream's file path (see SetPath method).
[RequiresUnreferencedCode(DataSet.RequiresUnreferencedCodeMessage)]
internal void SchemaTree(XmlDocument xd, XmlWriter xmlWriter, DataSet? ds, DataTable? dt, bool writeHierarchy)
{
_constraintNames = new ArrayList();
_autogenerated = new Hashtable();
bool genSecondary = _filePath != null; //null non-file based streams.
_dsElement = xd.CreateElement(Keywords.XSD_PREFIX, Keywords.XSD_ELEMENT, Keywords.XSDNS);
DataTable[] top;
bool fFlat = false;
DataTable _dt = dt!;
if (ds != null)
{
_ds = ds;
foreach (DataTable table in ds.Tables)
{
_tables.Add(table);
}
}
else
{
if (dt!.DataSet != null)
{
// preserve datatable's dataset to use for xml
// if null it would write out document element instead of dt.DataSet.DataSetName
_ds = dt.DataSet;
}
_tables.Add(dt);
if (writeHierarchy)
{
CreateTablesHierarchy(dt);
}
}
_dc = xd;
_namespaces = new Hashtable();
_prefixes = new Hashtable();
XmlElement rootSchema = xd.CreateElement(Keywords.XSD_PREFIX, Keywords.XSD_SCHEMA, Keywords.XSDNS);
_sRoot = rootSchema;
// Need to writeid attribute on schema, as webservice relys on it for typeddataset deserialization
// to get class name
if (_ds != null)
{
rootSchema.SetAttribute(Keywords.XSDID, XmlConvert.EncodeLocalName(_ds.DataSetName));
}
else
{
rootSchema.SetAttribute(Keywords.XSDID, XmlConvert.EncodeLocalName("NewDataSet"));
}
if (_ds != null)
{
WriteSchemaRoot(xd, rootSchema, _ds.Namespace);
}
else
{
WriteSchemaRoot(xd, rootSchema, _dt.Namespace);
}
// register the root element and associated NS
if (_schFormat == SchemaFormat.Remoting)
{
if (_ds != null)
{
_namespaces[_ds.Namespace] = rootSchema;
}
else
{
_namespaces[_dt.Namespace] = rootSchema;
}
}
if (_schFormat != SchemaFormat.Remoting)
{
if (_ds != null)
{
_namespaces[_ds.Namespace] = rootSchema;
if (_ds.Namespace.Length == 0)
_prefixes[_ds.Namespace] = null;
else
{
// generate a prefix for the dataset schema itself.
rootSchema.SetAttribute(Keywords.XMLNS_MSTNS, _ds.Namespace);
_prefixes[_ds.Namespace] = "mstns";
}
}
}
// Generate all the constraint names
if (ds != null)
GenerateConstraintNames(ds);
else
GenerateConstraintNames(_tables);
// Setup AutoGenerated table
if (_schFormat != SchemaFormat.Remoting)
{
if (ds != null)
{
SetupAutoGenerated(ds);
}
else
{
SetupAutoGenerated(_tables);
}
}
//
// Output all top level elements, which will recursively invoke to other tables.
//
top = ((ds != null) ? ds.TopLevelTables(true) : CreateToplevelTables());
if (top.Length == 0 || _schFormat == SchemaFormat.WebServiceSkipSchema || _schFormat == SchemaFormat.RemotingSkipSchema)
{
// return an empty schema for now.
// probably we need to throw an exception
FillDataSetElement(xd, ds, dt);
rootSchema.AppendChild(_dsElement);
AddXdoProperties(_ds, _dsElement, xd);
AddExtendedProperties(ds!._extendedProperties, _dsElement);
xd.AppendChild(rootSchema);
xd.Save(xmlWriter);
xmlWriter.Flush();
return; // rootSchema content has already been pushed to xmlWriter
}
// if (schFormat != SchemaFormat.WebService && namespaces.Count > 1 && !genSecondary) {
// rootSchema.SetAttribute(Keywords.MSD_FRAGMENTCOUNT, Keywords.MSDNS, namespaces.Count.ToString());
// }
// Fill out dataset element
XmlElement dsCompositor = FillDataSetElement(xd, ds, dt);
_constraintSeparator = xd.CreateElement(Keywords.XSD_PREFIX, "SHOULDNOTBEHERE", Keywords.XSDNS);
_dsElement.AppendChild(_constraintSeparator);
// DataSet properties
if (_ds != null)
{
AddXdoProperties(_ds, _dsElement, xd);
AddExtendedProperties(_ds._extendedProperties, _dsElement);
}
for (int i = 0; i < top.Length; i++)
{
XmlElement el = HandleTable(top[i], xd, rootSchema);
if (((_ds != null) && (_ds.Namespace == top[i].Namespace)) || string.IsNullOrEmpty(top[i].Namespace) || (_schFormat == SchemaFormat.Remoting))
{
bool fNestedInDataset = top[i]._fNestedInDataset;
if (((_ds != null) && (_ds.Namespace.Length != 0)) && string.IsNullOrEmpty(top[i].Namespace))
{
fNestedInDataset = true;
}
// what if dt has two nested relation , one self nested , the other with dtParent
if (top[i].SelfNested)
{ // regarding above check : is it selfnested!
fNestedInDataset = false;
}
if (top[i].NestedParentsCount > 1)
{ // if it has multiple parents, it should be global
fNestedInDataset = false;
}
if (fNestedInDataset)
{ //deal with maxOccurs properly
if (top[i].MinOccurs != 1)
{
el.SetAttribute(Keywords.MINOCCURS, top[i].MinOccurs.ToString(CultureInfo.InvariantCulture));
}
if (top[i].MaxOccurs == -1)
{
el.SetAttribute(Keywords.MAXOCCURS, Keywords.ZERO_OR_MORE);
}
else if (top[i].MaxOccurs != 1)
{
el.SetAttribute(Keywords.MAXOCCURS, top[i].MaxOccurs.ToString(CultureInfo.InvariantCulture));
}
}
if (!fNestedInDataset)
{
rootSchema.AppendChild(el);
XmlElement node = xd.CreateElement(Keywords.XSD_PREFIX, Keywords.XSD_ELEMENT, Keywords.XSDNS);
if ((_ds != null && _ds.Namespace == top[i].Namespace) || string.IsNullOrEmpty(top[i].Namespace) || (_schFormat == SchemaFormat.Remoting))
node.SetAttribute(Keywords.REF, top[i].EncodedTableName);
else
node.SetAttribute(Keywords.REF, ((string)_prefixes[top[i].Namespace]!) + ':' + top[i].EncodedTableName);
dsCompositor.AppendChild(node);
}
else
dsCompositor.AppendChild(el);
}
else
{
AppendChildWithoutRef(rootSchema, top[i].Namespace, el, Keywords.XSD_ELEMENT);
XmlElement node = xd.CreateElement(Keywords.XSD_PREFIX, Keywords.XSD_ELEMENT, Keywords.XSDNS);
node.SetAttribute(Keywords.REF, ((string)_prefixes[top[i].Namespace]!) + ':' + top[i].EncodedTableName);
dsCompositor.AppendChild(node);
}
}
_dsElement.RemoveChild(_constraintSeparator);
rootSchema.AppendChild(_dsElement);
// Output all non-heirarchical relations without constraints
DataRelation[] rels = Array.Empty<DataRelation>();
if (ds != null && _tables.Count > 0)
{ // we need to make sure we want to write relation just for tables in list
rels = new DataRelation[ds.Relations.Count];
for (int i = 0; i < ds.Relations.Count; i++)
{
rels[i] = ds.Relations[i];
}
}
else if (writeHierarchy && _tables.Count > 0)
{
CreateRelations((DataTable)_tables[0]!);
rels = new DataRelation[_relations.Count];
_relations.CopyTo(rels, 0);
}
XmlElement? nodeAnn = null;
XmlElement? nodeApp = null;
for (int i = 0; i < rels.Length; ++i)
{
DataRelation rel = rels[i];
if (!rel.Nested || fFlat)
{
if (rel.ChildKeyConstraint == null)
{
if (nodeAnn == null)
{
nodeAnn = xd.CreateElement(Keywords.XSD_PREFIX, Keywords.XSD_ANNOTATION, Keywords.XSDNS);
rootSchema.AppendChild(nodeAnn);
nodeApp = xd.CreateElement(Keywords.XSD_PREFIX, Keywords.XSD_APPINFO, Keywords.XSDNS);
nodeAnn.AppendChild(nodeApp);
}
Debug.Assert(nodeApp != null, "Need to create <application..> node first.");
nodeApp.AppendChild(HandleRelation(rel, xd));
}
}
}
XmlComment? comment = null;
bool isMultipleNamespaceAndStreamingWriter = (_namespaces.Count > 1 && !genSecondary);
if (_schFormat != SchemaFormat.Remoting && _schFormat != SchemaFormat.RemotingSkipSchema)
{
// complete processing of rootSchema
foreach (string ns in _namespaces.Keys)
{
if (ns == ((_ds != null) ? _ds.Namespace : _dt.Namespace) || string.IsNullOrEmpty(ns))
{
continue;
}
XmlElement _import = xd.CreateElement(Keywords.XSD_PREFIX, Keywords.XSD_IMPORT, Keywords.XSDNS);
_import.SetAttribute(Keywords.XSD_NAMESPACE, ns);
if (_schFormat != SchemaFormat.WebService && !isMultipleNamespaceAndStreamingWriter)
{
_import.SetAttribute(Keywords.XSD_SCHEMALOCATION, _fileName + "_" + _prefixes[ns] + ".xsd");
}
rootSchema.PrependChild(_import);
}
if (_schFormat != SchemaFormat.WebService && isMultipleNamespaceAndStreamingWriter)
{
rootSchema.SetAttribute(Keywords.MSD_FRAGMENTCOUNT, Keywords.MSDNS, _namespaces.Count.ToString(CultureInfo.InvariantCulture));
}
// Post rootSchema content to xmlWriter.
xd.AppendChild(rootSchema); // KB
if (_schFormat != SchemaFormat.WebService && isMultipleNamespaceAndStreamingWriter)
{
xd.WriteTo(xmlWriter);
}
else
{
xd.Save(xmlWriter);
}
xd.RemoveChild(rootSchema); //KB
foreach (string ns in _namespaces.Keys)
{
if (ns == ((_ds != null) ? _ds.Namespace : _dt.Namespace) || string.IsNullOrEmpty(ns))
{
continue;
}
XmlWriter? xw = null;
if (!genSecondary)
{
xw = xmlWriter;
}
else
{
xw = new XmlTextWriter(_filePath + _fileName + "_" + _prefixes[ns] + ".xsd", null);
}
try
{
if (genSecondary)
{
if (xw is XmlTextWriter)
{
((XmlTextWriter)xw).Formatting = Formatting.Indented;
}
xw.WriteStartDocument(true);
}
XmlElement tNode = (XmlElement)_namespaces[ns]!;
_dc.AppendChild(tNode);
foreach (string imp_ns in _namespaces.Keys)
{
if (ns == imp_ns)
{
continue; // don't write out yourself
}
string? prefix = (string?)_prefixes[imp_ns];
if (prefix == null)
{ // only for dataset.Namespace == empty
continue; // do nothing
}
tNode.SetAttribute("xmlns:" + prefix, imp_ns);
XmlElement _import2 = _dc.CreateElement(Keywords.XSD_PREFIX, Keywords.XSD_IMPORT, Keywords.XSDNS);
_import2.SetAttribute(Keywords.XSD_NAMESPACE, imp_ns);
if (_schFormat != SchemaFormat.WebService && !isMultipleNamespaceAndStreamingWriter)
{
if (imp_ns == ((_ds != null) ? _ds.Namespace : _dt.Namespace))
_import2.SetAttribute(Keywords.XSD_SCHEMALOCATION, _fileName + _fileExt); // for the dataset namespace don't append anything
else
_import2.SetAttribute(Keywords.XSD_SCHEMALOCATION, _fileName + "_" + prefix + ".xsd");
}
tNode.PrependChild(_import2);
}
if (_schFormat != SchemaFormat.WebService && isMultipleNamespaceAndStreamingWriter)
{
_dc.WriteTo(xw);
}
else
{
_dc.Save(xw);
}
_dc.RemoveChild(tNode);
if (genSecondary)
{
xw.WriteEndDocument();
}
}
finally
{
if (genSecondary)
{
xw.Close();
}
}
}
}
else
{
xd.AppendChild(rootSchema);
xd.Save(xmlWriter);
}
if (comment != null)
{
rootSchema.PrependChild(comment);
}
if (!genSecondary)
{
xmlWriter.Flush();
}
return; // rootSchema;
}
[RequiresUnreferencedCode(DataSet.RequiresUnreferencedCodeMessage)]
internal XmlElement SchemaTree(XmlDocument xd, DataTable dt)
{
_dsElement = xd.CreateElement(Keywords.XSD_PREFIX, Keywords.XSD_ELEMENT, Keywords.XSDNS);
_constraintNames = new ArrayList();
_ds = dt.DataSet;
_dc = xd;
_namespaces = new Hashtable();
_prefixes = new Hashtable();
if (_schFormat != SchemaFormat.Remoting)
{
_autogenerated = new Hashtable();
}
XmlElement rootSchema = xd.CreateElement(Keywords.XSD_PREFIX, Keywords.XSD_SCHEMA, Keywords.XSDNS);
_sRoot = rootSchema;
WriteSchemaRoot(xd, rootSchema, dt.Namespace);
_ = FillDataSetElement(xd, null, dt);
_constraintSeparator = xd.CreateElement(Keywords.XSD_PREFIX, "SHOULDNOTBEHERE", Keywords.XSDNS);
_dsElement.AppendChild(_constraintSeparator);
if (_schFormat != SchemaFormat.Remoting)
{
if (_ds != null)
{
_namespaces[_ds.Namespace] = rootSchema;
if (_ds.Namespace.Length == 0)
{
_prefixes[_ds.Namespace] = null;
}
else
{
// generate a prefix for the dataset schema itself.
rootSchema.SetAttribute(Keywords.XMLNS_MSTNS, _ds.Namespace);
_prefixes[_ds.Namespace] = "mstns";
}
}
else
{
_namespaces[dt.Namespace] = rootSchema;
if (dt.Namespace.Length == 0)
{
_prefixes[dt.Namespace] = null;
}
else
{
// generate a prefix for the dataset schema itself.
rootSchema.SetAttribute(Keywords.XMLNS_MSTNS, dt.Namespace);
_prefixes[dt.Namespace] = "mstns";
}
}
}
// Generate all the constraint names
GenerateConstraintNames(dt, true);
//
// Output all top level elements, which will recursively invoke to other tables.
//
XmlElement el = HandleTable(dt, xd, rootSchema, false);
rootSchema.AppendChild(el);
_dsElement.RemoveChild(_constraintSeparator);
rootSchema.AppendChild(_dsElement);
return rootSchema;
}
internal XmlElement FillDataSetElement(XmlDocument xd, DataSet? ds, DataTable? dt)
{
Debug.Assert(ds == null || dt == null);
Debug.Assert(_dsElement != null);
DataSet? dataSet = (ds != null) ? ds : dt!.DataSet;
if (dataSet != null)
{
_dsElement.SetAttribute(Keywords.NAME, XmlConvert.EncodeLocalName(dataSet.DataSetName));
_dsElement.SetAttribute(Keywords.MSD_ISDATASET, Keywords.MSDNS, Keywords.TRUE);
if (ds == null)
_dsElement.SetAttribute(Keywords.MSD_MAINDATATABLE, Keywords.MSDNS, XmlConvert.EncodeLocalName(((dt!.Namespace.Length == 0) ? dt.TableName : (dt.Namespace + ":" + dt.TableName))));
// Add CaseSensitive and locale properties
if (dataSet.CaseSensitive)
{
_dsElement.SetAttribute(Keywords.MSD_CASESENSITIVE, Keywords.MSDNS, Keywords.TRUE);
}
if (dataSet.ShouldSerializeLocale() || !dataSet.Locale.Equals(CultureInfo.CurrentCulture))
{
_dsElement.SetAttribute(Keywords.MSD_LOCALE, Keywords.MSDNS, dataSet.Locale.ToString());
}
else
{
_dsElement.SetAttribute(Keywords.MSD_USECURRENTLOCALE, Keywords.MSDNS, Keywords.TRUE);
}
}
else
{ // No DataSet
if (dt != null)
{
_dsElement.SetAttribute(Keywords.NAME, XmlConvert.EncodeLocalName("NewDataSet"));
_dsElement.SetAttribute(Keywords.MSD_ISDATASET, Keywords.MSDNS, Keywords.TRUE);
_dsElement.SetAttribute(Keywords.MSD_MAINDATATABLE, Keywords.MSDNS, XmlConvert.EncodeLocalName(((dt.Namespace.Length == 0) ? dt.TableName : (dt.Namespace + ":" + dt.TableName))));
if (dt.CaseSensitive)
{
// it is a bug to go and write casesensitive attrib as 'true', by default
_dsElement.SetAttribute(Keywords.MSD_CASESENSITIVE, Keywords.MSDNS, Keywords.TRUE);
}
if (dt.ShouldSerializeLocale() || !dt.Locale.Equals(CultureInfo.CurrentCulture))
{
_dsElement.SetAttribute(Keywords.MSD_LOCALE, Keywords.MSDNS, dt.Locale.ToString());
}
else
{
_dsElement.SetAttribute(Keywords.MSD_USECURRENTLOCALE, Keywords.MSDNS, Keywords.TRUE);
}
}
}
XmlElement type = xd.CreateElement(Keywords.XSD_PREFIX, Keywords.XSD_COMPLEXTYPE, Keywords.XSDNS);
_dsElement.AppendChild(type);
XmlElement compositor = xd.CreateElement(Keywords.XSD_PREFIX, Keywords.XSD_CHOICE, Keywords.XSDNS);
compositor.SetAttribute(Keywords.MINOCCURS, Keywords.ZERO_DIGIT);
compositor.SetAttribute(Keywords.MAXOCCURS, Keywords.ZERO_OR_MORE);
type.AppendChild(compositor);
return compositor;
}
internal void SetPath(XmlWriter xw)
{
FileStream? fs = null;
DataTextWriter? sw = xw as DataTextWriter;
fs = (sw != null) ? sw.BaseStream as FileStream : null;
if (fs == null)
{
XmlTextWriter? textw = xw as XmlTextWriter;
if (textw == null)
return;
fs = textw.BaseStream as FileStream;
if (fs == null)
return;
}
_filePath = Path.GetDirectoryName(fs.Name);
_fileName = Path.GetFileNameWithoutExtension(fs.Name);
_fileExt = Path.GetExtension(fs.Name);
if (!string.IsNullOrEmpty(_filePath))
_filePath = _filePath + "\\";
}
[RequiresUnreferencedCode(DataSet.RequiresUnreferencedCodeMessage)]
internal void Save(DataSet ds, XmlWriter xw)
{
Save(ds, null, xw);
}
[RequiresUnreferencedCode(DataSet.RequiresUnreferencedCodeMessage)]
internal void Save(DataTable dt, XmlWriter xw)
{
XmlDocument doc = new XmlDocument();
if (_schFormat == SchemaFormat.Public)
{
SetPath(xw);
}
XmlElement rootSchema = SchemaTree(doc, dt);
doc.AppendChild(rootSchema);
doc.Save(xw);
}
[RequiresUnreferencedCode(DataSet.RequiresUnreferencedCodeMessage)]
internal void Save(DataSet ds, DataTable? dt, XmlWriter xw)
{
Save(ds, dt, xw, false);
}
[RequiresUnreferencedCode(DataSet.RequiresUnreferencedCodeMessage)]
internal void Save(DataSet? ds, DataTable? dt, XmlWriter xw, bool writeHierarchy)
{
Save(ds, dt, xw, writeHierarchy, null);
}
[RequiresUnreferencedCode(DataSet.RequiresUnreferencedCodeMessage)]
internal void Save(DataSet? ds, DataTable? dt, XmlWriter xw, bool writeHierarchy, Converter<Type, string>? multipleTargetConverter)
{
_targetConverter = multipleTargetConverter;
XmlDocument doc = new XmlDocument();
if (_schFormat == SchemaFormat.Public)
{
SetPath(xw);
}
if (_schFormat == SchemaFormat.WebServiceSkipSchema && xw.WriteState == WriteState.Element)
{
xw.WriteAttributeString(Keywords.MSD, Keywords.MSD_SCHEMASERIALIZATIONMODE, Keywords.MSDNS, Keywords.MSD_EXCLUDESCHEMA);
}
SchemaTree(doc, xw, ds, dt, writeHierarchy);
}
internal XmlElement HandleRelation(DataRelation rel, XmlDocument dc)
{
XmlElement root = dc.CreateElement(Keywords.MSD, Keywords.MSD_RELATION, Keywords.MSDNS);
// convert relation name to valid xml name
root.SetAttribute(Keywords.NAME, XmlConvert.EncodeLocalName(rel.RelationName));
root.SetAttribute(Keywords.MSD_PARENT, Keywords.MSDNS, rel.ParentKey.Table.EncodedTableName);
root.SetAttribute(Keywords.MSD_CHILD, Keywords.MSDNS, rel.ChildKey.Table.EncodedTableName);
if ((_ds == null) || (_ds.Tables.InternalIndexOf(rel.ParentKey.Table.TableName) == -3))
root.SetAttribute(Keywords.MSD_PARENTTABLENS, Keywords.MSDNS, rel.ParentKey.Table.Namespace);
if ((_ds == null) || (_ds.Tables.InternalIndexOf(rel.ChildKey.Table.TableName) == -3))
root.SetAttribute(Keywords.MSD_CHILDTABLENS, Keywords.MSDNS, rel.ChildKey.Table.Namespace);
DataColumn[] key = rel.ParentKey.ColumnsReference;
string text = key[0].EncodedColumnName;
StringBuilder? builder = null;
if (1 < key.Length)
{
builder = new StringBuilder();
builder.Append(text);
for (int i = 1; i < key.Length; i++)
{
builder.Append(Keywords.MSD_KEYFIELDSEP).Append(key[i].EncodedColumnName);
}
text = builder.ToString();
}
root.SetAttribute(Keywords.MSD_PARENTKEY, Keywords.MSDNS, text);
key = rel.ChildKey.ColumnsReference;
text = key[0].EncodedColumnName;
if (1 < key.Length)
{
if (null != builder)
{
builder.Length = 0;
}
else
{
builder = new StringBuilder();
}
builder.Append(text);
for (int i = 1; i < key.Length; i++)
{
builder.Append(Keywords.MSD_KEYFIELDSEP).Append(key[i].EncodedColumnName);
}
text = builder.ToString();
}
root.SetAttribute(Keywords.MSD_CHILDKEY, Keywords.MSDNS, text);
AddExtendedProperties(rel._extendedProperties, root);
return root;
}
private static XmlElement? FindSimpleType(XmlElement schema, string name)
{
for (XmlNode? n = schema.FirstChild; n != null; n = n.NextSibling)
{
if (n is XmlElement)
{
XmlElement e = (XmlElement)n;
if (e.GetAttribute(Keywords.NAME) == name)
{
return e;
}
}
}
return null;
}// FindSimpleType
internal XmlElement GetSchema(string NamespaceURI)
{
XmlElement? schemaEl = (XmlElement?)_namespaces![NamespaceURI];
if (schemaEl == null)
{
schemaEl = _dc!.CreateElement(Keywords.XSD_PREFIX, Keywords.XSD_SCHEMA, Keywords.XSDNS);
WriteSchemaRoot(_dc, schemaEl, NamespaceURI);
if (!string.IsNullOrEmpty(NamespaceURI))
{
string prefix = Keywords.APP + Convert.ToString(++_prefixCount, CultureInfo.InvariantCulture);
_sRoot!.SetAttribute("xmlns:" + prefix, NamespaceURI);
schemaEl.SetAttribute("xmlns:" + prefix, NamespaceURI);
_prefixes![NamespaceURI] = prefix;
}
_namespaces[NamespaceURI] = schemaEl;
}
return schemaEl;
}
internal void HandleColumnType(DataColumn col, XmlDocument dc, XmlElement root, XmlElement schema)
{
Debug.Assert(_prefixes != null);
string keyword = Keywords.TYPE;
if (col.ColumnMapping == MappingType.SimpleContent)
keyword = Keywords.BASE;
if (col.SimpleType != null)
{
// generate simpleType node
SimpleType? stNode = col.SimpleType;
while (stNode != null)
{
// for remoting, set the msdata:targetNamespace for the simpleType.
XmlNode type;
string? name = stNode.Name;
if (name != null && name.Length != 0)
{
// For remoting, always need to work with root schema's namespace
string nSpace = (_schFormat != SchemaFormat.Remoting) ? stNode.Namespace :
(col.Table!.DataSet != null ? col.Table.DataSet.Namespace : col.Table.Namespace);
// for remoting we need to use columns NS, for other cases it is wrong to get Columns NS, we need to take type's namespace
XmlElement schNode = GetSchema(nSpace);
//SchNode To Ensure BaseSimpleType Prefix is Generated
if (stNode.BaseSimpleType != null && stNode.BaseSimpleType.Namespace != null && stNode.BaseSimpleType.Namespace.Length > 0)
GetSchema(stNode.BaseSimpleType.Namespace); //it will ensure a prefix has been created for this namespace
type = stNode.ToNode(dc, _prefixes, (_schFormat == SchemaFormat.Remoting));
if (stNode == col.SimpleType)
{
string? prefix = (string?)_prefixes[nSpace];
// set the columns's type
if (prefix != null && prefix.Length > 0)
{
if (_schFormat != SchemaFormat.Remoting)
root.SetAttribute(keyword, (prefix + ":" + name)); // look at below,this loop assumes we would be here just oen time: Its Wrong
else // As all types (in remoting) belong to the same namespace, just write type name
root.SetAttribute(keyword, name);
}
else
root.SetAttribute(keyword, name);
// set the root to the actual type, do not overwrite it in the iteration.
}
XmlElement? elmSimpeType = FindSimpleType(schNode, name);
if (elmSimpeType == null)
{
// if we don't have the defenition for this simpleType yet. Add it
schNode.AppendChild(type);
}
else
{
#if DEBUG
// enzol: TO DO: replace the constructor with IsEqual(XmlElement)
// Debug.Assert(col.SimpleType.IsEqual(new SimpleType(elmSimpeType)), $"simpleTypes with the same name have to be the same: {name}");
#endif
}
}
else
{
//SchNode To Ensure BaseSimpleType Prefix is Generated
if (stNode.BaseSimpleType != null && stNode.BaseSimpleType.Namespace != null && stNode.BaseSimpleType.Namespace.Length > 0)
GetSchema(stNode.BaseSimpleType.Namespace); //it will ensure a prefix has been created for this namespace
type = stNode.ToNode(dc, _prefixes, _schFormat == SchemaFormat.Remoting);
root.AppendChild(type);
}
stNode = stNode.BaseSimpleType;
}
}
else if (col.XmlDataType != null && col.XmlDataType.Length != 0 && XSDSchema.IsXsdType(col.XmlDataType))
{
root.SetAttribute(keyword, XSDSchema.QualifiedName(col.XmlDataType));
}
else
{
string typeName = XmlDataTypeName(col.DataType); // do not update the hashtable, as it will not write msdata:DataType
if (typeName == null || typeName.Length == 0)
{
if (col.DataType == typeof(Guid) || col.DataType == typeof(Type))
{
typeName = "string";
}
else
{
if (col.ColumnMapping == MappingType.Attribute)
{
XmlTreeGen.ValidateColumnMapping(col.DataType);
}
typeName = Keywords.XSD_ANYTYPE;
}
}
root.SetAttribute(keyword, XSDSchema.QualifiedName(typeName));
}
}
internal void AddColumnProperties(DataColumn col, XmlElement root)
{
if (col.DataType != typeof(string))
{
string dt = XmlDataTypeName(col.DataType);
if ((col.IsSqlType && ((dt.Length == 0) || col.ImplementsINullable)) || (typeof(SqlXml) == col.DataType) || col.DataType == typeof(DateTimeOffset) || col.DataType == typeof(System.Numerics.BigInteger))
{ // no need to check if it is Sql typee if it already implements INullable,
root.SetAttribute(Keywords.MSD_DATATYPE, Keywords.MSDNS, col.DataType.FullName);
}
else if ((dt.Length == 0) || col.ImplementsINullable || ((dt == Keywords.XSD_ANYTYPE) && (col.XmlDataType != Keywords.XSD_ANYTYPE)))
{
// in Whidbey, XmlDataTypeName function changed to return "anyType" for typeof(Object)
// should still always hit this code path for all non-built in types
// to handle version qualified typeof(Object) and other CDT objects correctly
// we must write the output exactly the same way as we read it
SetMSDataAttribute(root, col.DataType);
}
}
if (col.ReadOnly)
root.SetAttribute("ReadOnly", Keywords.MSDNS, Keywords.TRUE);
if (col.Expression.Length != 0)
root.SetAttribute("Expression", Keywords.MSDNS, col.Expression);
if (col.AutoIncrement)
{
root.SetAttribute("AutoIncrement", Keywords.MSDNS, Keywords.TRUE);
}
if (col.AutoIncrementSeed != 0)
root.SetAttribute("AutoIncrementSeed", Keywords.MSDNS, col.AutoIncrementSeed.ToString(CultureInfo.InvariantCulture));
if (col.AutoIncrementStep != 1)
root.SetAttribute("AutoIncrementStep", Keywords.MSDNS, col.AutoIncrementStep.ToString(CultureInfo.InvariantCulture));
if (col.Caption != col.ColumnName)
root.SetAttribute("Caption", Keywords.MSDNS, col.Caption);
if (col.Prefix.Length != 0)
root.SetAttribute("Prefix", Keywords.MSDNS, col.Prefix);
if (col.DataType == typeof(DateTime) && col.DateTimeMode != DataSetDateTime.UnspecifiedLocal)
{
root.SetAttribute("DateTimeMode", Keywords.MSDNS, col.DateTimeMode.ToString());
}
}
private string FindTargetNamespace(DataTable table)
{
string tgNamespace = table.TypeName.IsEmpty ? table.Namespace : table.TypeName.Namespace;
if (string.IsNullOrEmpty(tgNamespace))
{
DataRelation[] nestedParentRelations = table.NestedParentRelations;
if (nestedParentRelations.Length != 0)
{
for (int i = 0; i < nestedParentRelations.Length; i++)
{
DataTable parentTable = nestedParentRelations[i].ParentTable;
if (table != parentTable)
{// table can be self nested so it may go to infinite loop!
tgNamespace = FindTargetNamespace(parentTable);
if (!string.IsNullOrEmpty(tgNamespace))
{
break;
}
}
}
}
else
{ // if it does not have any parent table , then it should inherit NS from DataSet
tgNamespace = _ds!.Namespace;
}
}
return tgNamespace;
}
[RequiresUnreferencedCode(DataSet.RequiresUnreferencedCodeMessage)]
internal XmlElement HandleColumn(DataColumn col, XmlDocument dc, XmlElement schema, bool fWriteOrdinal)
{
Debug.Assert(_prefixes != null);
Debug.Assert(_dc != null);
XmlElement root;
int minOccurs;
Debug.Assert(col.ColumnMapping != MappingType.SimpleContent, "Illegal state");
string refString = (col.ColumnMapping != MappingType.Element) ? Keywords.XSD_ATTRIBUTE : Keywords.XSD_ELEMENT;
root = dc.CreateElement(Keywords.XSD_PREFIX, refString, Keywords.XSDNS);
// First add any attributes.
root.SetAttribute(Keywords.NAME, col.EncodedColumnName);
if (col.Namespace.Length == 0)
{
DataTable _table = col.Table!;
// We need to travese the hirerarchy to find the targetnamepace
string tgNamespace = FindTargetNamespace(_table);
if (col.Namespace != tgNamespace)
{
root.SetAttribute(Keywords.FORM, Keywords.UNQUALIFIED);
}
}
if (col.GetType() != typeof(DataColumn))
AddXdoProperties(col, root, dc);
else
AddColumnProperties(col, root);
AddExtendedProperties(col._extendedProperties, root);
HandleColumnType(col, dc, root, schema);
if (col.ColumnMapping == MappingType.Hidden)
{ // CDT / UDT can not be mapped to Hidden column
if (!col.AllowDBNull)
root.SetAttribute(Keywords.MSD_ALLOWDBNULL, Keywords.MSDNS, Keywords.FALSE);
if (!col.DefaultValueIsNull)
if (col.DataType == typeof(bool))
root.SetAttribute(Keywords.MSD_DEFAULTVALUE, Keywords.MSDNS, (bool)(col.DefaultValue) ? Keywords.TRUE : Keywords.FALSE);
else
{
XmlTreeGen.ValidateColumnMapping(col.DataType);
root.SetAttribute(Keywords.MSD_DEFAULTVALUE, Keywords.MSDNS, col.ConvertObjectToXml(col.DefaultValue));
}
}
if ((!col.DefaultValueIsNull) && (col.ColumnMapping != MappingType.Hidden))
{
XmlTreeGen.ValidateColumnMapping(col.DataType);
if (col.ColumnMapping == MappingType.Attribute && !col.AllowDBNull)
{
if (col.DataType == typeof(bool))
{
root.SetAttribute(Keywords.MSD_DEFAULTVALUE, Keywords.MSDNS, (bool)(col.DefaultValue) ? Keywords.TRUE : Keywords.FALSE);
}
else
{ // CDT / UDT columns cn not be mapped to Attribute also
root.SetAttribute(Keywords.MSD_DEFAULTVALUE, Keywords.MSDNS, col.ConvertObjectToXml(col.DefaultValue));
}
}
else
{ // Element Column : need to handle CDT
if (col.DataType == typeof(bool))
{
root.SetAttribute(Keywords.DEFAULT, (bool)(col.DefaultValue) ? Keywords.TRUE : Keywords.FALSE);
}
else
{
if (!col.IsCustomType)
{ // built in type
root.SetAttribute(Keywords.DEFAULT, col.ConvertObjectToXml(col.DefaultValue));
}
else
{ // UDT column
}
}
}
}
if (_schFormat == SchemaFormat.Remoting)
root.SetAttribute(Keywords.TARGETNAMESPACE, Keywords.MSDNS, col.Namespace);
else
{
if ((col.Namespace != (col.Table!.TypeName.IsEmpty ? col.Table.Namespace : col.Table.TypeName.Namespace)) && (col.Namespace.Length != 0))
{
XmlElement schNode = GetSchema(col.Namespace);
if (FindTypeNode(schNode, col.EncodedColumnName) == null)
schNode.AppendChild(root);
root = _dc.CreateElement(Keywords.XSD_PREFIX, refString, Keywords.XSDNS);
root.SetAttribute(Keywords.REF, _prefixes[col.Namespace] + ":" + col.EncodedColumnName);
if (col.Table.Namespace != _ds!.Namespace)
{
_ = GetSchema(col.Table.Namespace);
}
}
}
minOccurs = (col.AllowDBNull) ? 0 : 1;
// March 2001 change
if (col.ColumnMapping == MappingType.Attribute && minOccurs != 0)
root.SetAttribute(Keywords.USE, Keywords.REQUIRED);
if (col.ColumnMapping == MappingType.Hidden)
{
root.SetAttribute(Keywords.USE, Keywords.PROHIBITED);
}
else
if (col.ColumnMapping != MappingType.Attribute && minOccurs != 1)
root.SetAttribute(Keywords.MINOCCURS, minOccurs.ToString(CultureInfo.InvariantCulture));
if ((col.ColumnMapping == MappingType.Element) && fWriteOrdinal)
root.SetAttribute(Keywords.MSD_ORDINAL, Keywords.MSDNS, col.Ordinal.ToString(CultureInfo.InvariantCulture));
return root;
}
internal static string TranslateAcceptRejectRule(AcceptRejectRule rule) =>
rule switch
{
AcceptRejectRule.Cascade => "Cascade",
AcceptRejectRule.None => "None",
_ => null!,
};
internal static string TranslateRule(Rule rule) =>
rule switch
{
Rule.Cascade => "Cascade",
Rule.None => "None",
Rule.SetNull => "SetNull",
Rule.SetDefault => "SetDefault",
_ => null!,
};
internal void AppendChildWithoutRef(XmlElement node, string Namespace, XmlElement el, string refString)
{
XmlElement schNode = GetSchema(Namespace);
if (FindTypeNode(schNode, el.GetAttribute(Keywords.NAME)) == null)
schNode.AppendChild(el);
}
internal XmlElement? FindTypeNode(XmlElement node, string strType)
{
if (node == null)
return null;
for (XmlNode? n = node.FirstChild; n != null; n = n.NextSibling)
{
if (!(n is XmlElement))
continue;
XmlElement child = (XmlElement)n;
if (XSDSchema.FEqualIdentity(child, Keywords.XSD_ELEMENT, Keywords.XSDNS) ||
XSDSchema.FEqualIdentity(child, Keywords.XSD_ATTRIBUTE, Keywords.XSDNS) ||
XSDSchema.FEqualIdentity(child, Keywords.XSD_COMPLEXTYPE, Keywords.XSDNS) ||
XSDSchema.FEqualIdentity(child, Keywords.XSD_SIMPLETYPE, Keywords.XSDNS))
{
if (child.GetAttribute(Keywords.NAME) == strType)
return child;
}
}
return null;
}
[RequiresUnreferencedCode(DataSet.RequiresUnreferencedCodeMessage)]
internal XmlElement HandleTable(DataTable table, XmlDocument dc, XmlElement schema)
{
return HandleTable(table, dc, schema, true);
}
// we write out column Ordinals only if the table contains columns
// that map both to Attributes and Elements
private bool HasMixedColumns(DataTable table)
{
bool hasAttributes = false;
bool hasElements = false;
foreach (DataColumn col in table.Columns)
{
if (!hasElements && col.ColumnMapping == MappingType.Element)
hasElements = true;
if (!hasAttributes && (col.ColumnMapping == MappingType.Attribute || col.ColumnMapping == MappingType.Hidden))
hasAttributes = !AutoGenerated(col);
if (hasAttributes && hasElements)
return true;
}
return false;
}
internal static bool AutoGenerated(DataColumn col)
{
// for now we use just this simple logic for the columns.
if (col.ColumnMapping != MappingType.Hidden)
return false;
if (col.DataType != typeof(int))
return false;
string generatedname = col.Table!.TableName + "_Id";
if ((col.ColumnName == generatedname) || (col.ColumnName == generatedname + "_0"))
return true;
generatedname = string.Empty;
foreach (DataRelation rel in col.Table.ParentRelations)
{
if (!rel.Nested)
continue;
if (rel.ChildColumnsReference.Length != 1)
continue;
if (rel.ChildColumnsReference[0] != col)
continue;
if (rel.ParentColumnsReference.Length != 1)
continue;
//ok if we are here it means that we have a 1column-1column relation
generatedname = rel.ParentColumnsReference[0].Table!.TableName + "_Id";
}
if ((col.ColumnName == generatedname) || (col.ColumnName == generatedname + "_0"))
return true;
return false;
}
internal static bool AutoGenerated(DataRelation rel)
{
string rName = rel.ParentTable.TableName + "_" + rel.ChildTable.TableName;
if (!rel.RelationName.StartsWith(rName, StringComparison.Ordinal))
return false;
if (rel.ExtendedProperties.Count > 0)
return false;
return true;
}
internal static bool AutoGenerated(UniqueConstraint unique)
{
// for now we use just this simple logic for the columns.
if (!unique.ConstraintName.StartsWith("Constraint", StringComparison.Ordinal))
return false;
if (unique.Key.ColumnsReference.Length != 1)
return false;
if (unique.ExtendedProperties.Count > 0)
return false;
return AutoGenerated(unique.Key.ColumnsReference[0]);
}
private bool AutoGenerated(ForeignKeyConstraint fk)
{
return AutoGenerated(fk, true);
}
internal static bool AutoGenerated(ForeignKeyConstraint fk, bool checkRelation)
{
// for now we use just this simple logic for the columns.
DataRelation? rel = fk.FindParentRelation();
if (checkRelation)
{
if (rel == null)
return false; // otherwise roundtrip will create column
if (!AutoGenerated(rel))
return false;
if (rel.RelationName != fk.ConstraintName)
return false;
}
if (fk.ExtendedProperties.Count > 0)
return false;
if (fk.AcceptRejectRule != AcceptRejectRule.None)
return false;
if (fk.DeleteRule != Rule.Cascade)
return false;
if (fk.RelatedColumnsReference.Length != 1)
return false;
return AutoGenerated(fk.RelatedColumnsReference[0]);
}
private bool IsAutoGenerated(object o)
{
if (_schFormat != SchemaFormat.Remoting)
return _autogenerated[o] != null;
return false;
}
[RequiresUnreferencedCode(DataSet.RequiresUnreferencedCodeMessage)]
internal XmlElement HandleTable(DataTable table, XmlDocument dc, XmlElement schema, bool genNested)
{
Debug.Assert(_prefixes != null);
Debug.Assert(_dc != null);
Debug.Assert(_dsElement != null);
XmlElement root = dc.CreateElement(Keywords.XSD_PREFIX, Keywords.XSD_ELEMENT, Keywords.XSDNS);
bool fWriteOrdinals = false;
bool fUnqualified = false;
if (((table.DataSet == null) || (_ds != null && table.Namespace != _ds.Namespace)) && (_schFormat == SchemaFormat.Remoting))
root.SetAttribute(Keywords.TARGETNAMESPACE, Keywords.MSDNS, table.Namespace);
// First add any attributes.
root.SetAttribute(Keywords.NAME, table.EncodedTableName);
if (table.Namespace.Length == 0)
{
DataTable _table = table;
string tgNamespace = _table.Namespace;
while (string.IsNullOrEmpty(tgNamespace))
{
DataRelation[] nestedParentRelations = _table.NestedParentRelations;
if (nestedParentRelations.Length == 0)
{
tgNamespace = (_ds != null) ? _ds.Namespace : "";
break;
}
int nestedparentPosition = -1; // it is find non-self-nested-parent
for (int i = 0; i < nestedParentRelations.Length; i++)
{
if (nestedParentRelations[i].ParentTable != _table)
{
nestedparentPosition = i;
break;
}
}
if (nestedparentPosition == -1)
{
break;
}
else
{
_table = nestedParentRelations[nestedparentPosition].ParentTable;
}
tgNamespace = _table.Namespace;
}
if (table.Namespace != tgNamespace)
{
root.SetAttribute(Keywords.FORM, Keywords.UNQUALIFIED);
fUnqualified = true;
}
}
if (table.ShouldSerializeCaseSensitive())
{
root.SetAttribute(Keywords.MSD_CASESENSITIVE, Keywords.MSDNS, table.CaseSensitive.ToString());
}
if (table.ShouldSerializeLocale())
{
root.SetAttribute(Keywords.MSD_LOCALE, Keywords.MSDNS, table.Locale.ToString());
}
AddXdoProperties(table, root, dc);
DataColumnCollection columns = table.Columns;
int cCount = columns.Count;
int realCount = 0;
if (cCount == 1 || cCount == 2)
for (int i = 0; i < cCount; i++)
{
DataColumn col = columns[i];
if (col.ColumnMapping == MappingType.Hidden)
{
DataRelationCollection childRelations = table.ChildRelations;
for (int j = 0; j < childRelations.Count; j++)
{
if (childRelations[j].Nested && childRelations[j].ParentKey.ColumnsReference.Length == 1 && childRelations[j].ParentKey.ColumnsReference[0] == col)
realCount++;
}
}
if (col.ColumnMapping == MappingType.Element)
realCount++;
}
if ((table._repeatableElement) && (realCount == 1))
{
// I only have 1 column and that gives me
// the type for this element
DataColumn col = table.Columns[0];
string _typeName = XmlDataTypeName(col.DataType);
if (_typeName == null || _typeName.Length == 0)
{
_typeName = Keywords.XSD_ANYTYPE;
}
root.SetAttribute(Keywords.TYPE, XSDSchema.QualifiedName(_typeName));
return root;
}
// Now add the type information nested inside the element or global.
XmlElement type = dc.CreateElement(Keywords.XSD_PREFIX, Keywords.XSD_COMPLEXTYPE, Keywords.XSDNS);
if (!table.TypeName.IsEmpty && _schFormat != SchemaFormat.Remoting)
{
XmlElement typeSchema = GetSchema(table.TypeName.Namespace);
if (string.IsNullOrEmpty(table.TypeName.Namespace))
{
if (_ds == null)
typeSchema = GetSchema(table.Namespace);
else
typeSchema = fUnqualified ? GetSchema(_ds.Namespace) : GetSchema(table.Namespace);
}
if (FindTypeNode(typeSchema, table.TypeName.Name) == null)
typeSchema.AppendChild(type);
type.SetAttribute(Keywords.NAME, table.TypeName.Name);
}
else
{
root.AppendChild(type);
}
if (!table.TypeName.IsEmpty)
{
if (_schFormat != SchemaFormat.Remoting)
root.SetAttribute(Keywords.TYPE, NewDiffgramGen.QualifiedName((string)_prefixes[table.TypeName.Namespace]!, table.TypeName.Name));
}
XmlElement? compositor = null;
DataColumn? colTxt = table.XmlText;
if (colTxt != null)
{
XmlElement sc = dc.CreateElement(Keywords.XSD_PREFIX, Keywords.XSD_SIMPLECONTENT, Keywords.XSDNS);
if (colTxt.GetType() != typeof(DataColumn))
AddXdoProperties(colTxt, sc, dc);
else
AddColumnProperties(colTxt, sc);
AddExtendedProperties(colTxt._extendedProperties, sc);
if (colTxt.AllowDBNull)
root.SetAttribute(Keywords.XSD_NILLABLE, string.Empty, Keywords.TRUE);
if (!colTxt.DefaultValueIsNull)
{
XmlTreeGen.ValidateColumnMapping(colTxt.DataType);
sc.SetAttribute(Keywords.MSD_DEFAULTVALUE, Keywords.MSDNS, colTxt.ConvertObjectToXml(colTxt.DefaultValue));
}
sc.SetAttribute(Keywords.MSD_COLUMNNAME, Keywords.MSDNS, colTxt.ColumnName);
sc.SetAttribute(Keywords.MSD_ORDINAL, Keywords.MSDNS, colTxt.Ordinal.ToString(CultureInfo.InvariantCulture));
type.AppendChild(sc);
XmlElement ext = dc.CreateElement(Keywords.XSD_PREFIX, Keywords.XSD_EXTENSION, Keywords.XSDNS);
sc.AppendChild(ext);
HandleColumnType(colTxt, dc, ext, schema);
type = ext;
}
compositor = dc.CreateElement(Keywords.XSD_PREFIX, Keywords.XSD_SEQUENCE, Keywords.XSDNS);
type.AppendChild(compositor);
fWriteOrdinals = HasMixedColumns(table);
for (int i = 0; i < cCount; i++)
{
DataColumn col = columns[i];
if (col.ColumnMapping == MappingType.SimpleContent)
continue;
if (col.ColumnMapping == MappingType.Attribute || col.ColumnMapping == MappingType.Element || col.ColumnMapping == MappingType.Hidden)
{
if (IsAutoGenerated(col)) // skip automanifactured columns
continue;
bool isAttribute = col.ColumnMapping != MappingType.Element;
XmlElement el = HandleColumn(col, dc, schema, fWriteOrdinals);
XmlElement node = isAttribute ? type : compositor;
//bool flag = isAttribute ? col.Namespace == "" : col.Namespace == table.Namespace;
node.AppendChild(el);
}
}
if ((table.XmlText == null) && (genNested))
{
DataRelationCollection childRelations = table.ChildRelations;
for (int j = 0; j < childRelations.Count; j++)
{
XmlElement NestedTable;
if (!childRelations[j].Nested)
continue;
DataTable childTable = childRelations[j].ChildTable;
if (childTable == table)
{ // self join
NestedTable = dc.CreateElement(Keywords.XSD_PREFIX, Keywords.XSD_ELEMENT, Keywords.XSDNS);
NestedTable.SetAttribute(Keywords.REF, table.EncodedTableName);
}
else if (childTable.NestedParentsCount > 1)
{ // skip relations with multiple parents
NestedTable = dc.CreateElement(Keywords.XSD_PREFIX, Keywords.XSD_ELEMENT, Keywords.XSDNS);
NestedTable.SetAttribute(Keywords.REF, childTable.EncodedTableName);
}
else
NestedTable = HandleTable(childTable, dc, schema);
if (childTable.Namespace == table.Namespace)
{
NestedTable.SetAttribute(Keywords.MINOCCURS, "0");
NestedTable.SetAttribute(Keywords.MAXOCCURS, Keywords.ZERO_OR_MORE);
}
if ((childTable.Namespace == table.Namespace) || (childTable.Namespace.Length == 0) || _schFormat == SchemaFormat.Remoting)
{
compositor.AppendChild(NestedTable);
}
else
{
if (childTable.NestedParentsCount <= 1)
GetSchema(childTable.Namespace).AppendChild(NestedTable);
NestedTable = dc.CreateElement(Keywords.XSD_PREFIX, Keywords.XSD_ELEMENT, Keywords.XSDNS);
NestedTable.SetAttribute(Keywords.REF, ((string)_prefixes[childTable.Namespace]!) + ':' + childTable.EncodedTableName);
compositor.AppendChild(NestedTable);
}
if (childRelations[j].ChildKeyConstraint != null)
continue; // we write the relation using the constraint
XmlElement nodeAnn = _dc.CreateElement(Keywords.XSD_PREFIX, Keywords.XSD_ANNOTATION, Keywords.XSDNS);
NestedTable.PrependChild(nodeAnn);
XmlElement nodeApp = _dc.CreateElement(Keywords.XSD_PREFIX, Keywords.XSD_APPINFO, Keywords.XSDNS);
nodeAnn.AppendChild(nodeApp);
nodeApp.AppendChild(HandleRelation(childRelations[j], dc));
}
}
if (compositor != null)
if (!compositor.HasChildNodes)
type.RemoveChild(compositor);
// Output all constraints.
ConstraintCollection constraints = table.Constraints;
XmlElement selector, field;
string xpathprefix = (_ds != null) ? (_ds.Namespace.Length != 0 ? Keywords.MSTNS_PREFIX : string.Empty) : string.Empty;
if (_schFormat != SchemaFormat.Remoting)
{
GetSchema(table.Namespace); // to ensure prefix handling
xpathprefix = table.Namespace.Length != 0 ? (string)_prefixes[table.Namespace]! + ':' : string.Empty;
}
for (int i = 0; i < constraints.Count; i++)
{
XmlElement? constraint = null;
DataColumn[] fields;
if (constraints[i] is UniqueConstraint)
{
UniqueConstraint unique = (UniqueConstraint)constraints[i];
if (IsAutoGenerated(unique))
continue;
// special case of the ghosted constraints:
fields = unique.Key.ColumnsReference;
constraint = dc.CreateElement(Keywords.XSD_PREFIX, Keywords.XSD_UNIQUE, Keywords.XSDNS);
if ((_ds == null) || (_ds.Tables.InternalIndexOf(table.TableName) == -3))
constraint.SetAttribute(Keywords.MSD_TABLENS, Keywords.MSDNS, table.Namespace);
// convert constraint name to valid xml name
constraint.SetAttribute(Keywords.NAME, XmlConvert.EncodeLocalName(unique.SchemaName));
if (unique.ConstraintName != unique.SchemaName)
constraint.SetAttribute(Keywords.MSD_CONSTRAINTNAME, Keywords.MSDNS, unique.ConstraintName);
AddExtendedProperties(unique._extendedProperties, constraint);
selector = dc.CreateElement(Keywords.XSD_PREFIX, Keywords.XSD_SELECTOR, Keywords.XSDNS);
selector.SetAttribute(Keywords.XSD_XPATH, ".//" + xpathprefix + table.EncodedTableName);
constraint.AppendChild(selector);
if (unique.IsPrimaryKey)
{
constraint.SetAttribute(Keywords.MSD_PRIMARYKEY, Keywords.MSDNS, Keywords.TRUE);
}
if (0 < fields.Length)
{
StringBuilder encodedName = new StringBuilder();
for (int k = 0; k < fields.Length; k++)
{
encodedName.Length = 0;
if (_schFormat != SchemaFormat.Remoting)
{
GetSchema(fields[k].Namespace);
if (!string.IsNullOrEmpty(fields[k].Namespace))
{
encodedName.Append(_prefixes[fields[k].Namespace]).Append(':');
}
encodedName.Append(fields[k].EncodedColumnName);
}
else
{
encodedName.Append(xpathprefix).Append(fields[k].EncodedColumnName);
}
if ((fields[k].ColumnMapping == MappingType.Attribute) || (fields[k].ColumnMapping == MappingType.Hidden))
{
encodedName.Insert(0, '@');
}
field = dc.CreateElement(Keywords.XSD_PREFIX, Keywords.XSD_FIELD, Keywords.XSDNS);
field.SetAttribute(Keywords.XSD_XPATH, encodedName.ToString());
constraint.AppendChild(field);
}
}
_dsElement.InsertBefore(constraint, _constraintSeparator);
}
else if (constraints[i] is ForeignKeyConstraint && genNested)
{
ForeignKeyConstraint foreign = (ForeignKeyConstraint)constraints[i];
if (_tables.Count > 0)
{
if (!_tables.Contains(foreign.RelatedTable) || !_tables.Contains(foreign.Table))
continue;
}
if (IsAutoGenerated(foreign))
continue;
DataRelation? rel = foreign.FindParentRelation();
// special case of the ghosted constraints:
fields = foreign.RelatedColumnsReference;
UniqueConstraint? _constraint = (UniqueConstraint?)foreign.RelatedTable.Constraints.FindConstraint(new UniqueConstraint("TEMP", fields));
if (_constraint == null)
{
constraint = dc.CreateElement(Keywords.XSD_PREFIX, Keywords.XSD_KEY, Keywords.XSDNS);
constraint.SetAttribute(Keywords.NAME, XmlConvert.EncodeLocalName(foreign.SchemaName));
if ((_ds == null) || (_ds.Tables.InternalIndexOf(table.TableName) == -3))
constraint.SetAttribute(Keywords.MSD_TABLENS, Keywords.MSDNS, table.Namespace);
selector = dc.CreateElement(Keywords.XSD_PREFIX, Keywords.XSD_SELECTOR, Keywords.XSDNS);
selector.SetAttribute(Keywords.XSD_XPATH, ".//" + xpathprefix + foreign.RelatedTable.EncodedTableName);
constraint.AppendChild(selector);
if (0 < fields.Length)
{
StringBuilder encodedName = new StringBuilder();
for (int k = 0; k < fields.Length; k++)
{
encodedName.Length = 0;
if (_schFormat != SchemaFormat.Remoting)
{
GetSchema(fields[k].Namespace);
if (!string.IsNullOrEmpty(fields[k].Namespace))
{
encodedName.Append(_prefixes[fields[k].Namespace]).Append(':');
}
encodedName.Append(fields[k].EncodedColumnName);
}
else
{
encodedName.Append(xpathprefix).Append(fields[k].EncodedColumnName);
}
if ((fields[k].ColumnMapping == MappingType.Attribute) || (fields[k].ColumnMapping == MappingType.Hidden))
{
encodedName.Insert(0, '@');
}
field = dc.CreateElement(Keywords.XSD_PREFIX, Keywords.XSD_FIELD, Keywords.XSDNS);
field.SetAttribute(Keywords.XSD_XPATH, encodedName.ToString());
constraint.AppendChild(field);
}
}
_dsElement.InsertBefore(constraint, _constraintSeparator);
}
constraint = dc.CreateElement(Keywords.XSD_PREFIX, Keywords.XSD_KEYREF, Keywords.XSDNS);
// convert constraint name to valid xml name
constraint.SetAttribute(Keywords.NAME, XmlConvert.EncodeLocalName(foreign.SchemaName));
if ((_ds == null) || (_ds.Tables.InternalIndexOf(foreign.RelatedTable.TableName) == -3)) // if there is a conflicting name/namespace only
constraint.SetAttribute(Keywords.MSD_TABLENS, Keywords.MSDNS, foreign.Table!.Namespace);
if (_constraint == null)
constraint.SetAttribute(Keywords.REFER, XmlConvert.EncodeLocalName(foreign.SchemaName));
else
constraint.SetAttribute(Keywords.REFER, XmlConvert.EncodeLocalName(_constraint.SchemaName));
AddExtendedProperties(foreign._extendedProperties, constraint, typeof(ForeignKeyConstraint));
if (foreign.ConstraintName != foreign.SchemaName)
constraint.SetAttribute(Keywords.MSD_CONSTRAINTNAME, Keywords.MSDNS, foreign.ConstraintName);
if (null == rel)
{
constraint.SetAttribute(Keywords.MSD_CONSTRAINTONLY, Keywords.MSDNS, Keywords.TRUE);
}
else
{
if (rel.Nested)
constraint.SetAttribute(Keywords.MSD_ISNESTED, Keywords.MSDNS, Keywords.TRUE);
AddExtendedProperties(rel._extendedProperties, constraint, typeof(DataRelation));
if (foreign.ConstraintName != rel.RelationName)
{
constraint.SetAttribute(Keywords.MSD_RELATIONNAME, Keywords.MSDNS, XmlConvert.EncodeLocalName(rel.RelationName));
}
}
selector = dc.CreateElement(Keywords.XSD_PREFIX, Keywords.XSD_SELECTOR, Keywords.XSDNS);
selector.SetAttribute(Keywords.XSD_XPATH, ".//" + xpathprefix + table.EncodedTableName);
constraint.AppendChild(selector);
if (foreign.AcceptRejectRule != ForeignKeyConstraint.AcceptRejectRule_Default)
constraint.SetAttribute(Keywords.MSD_ACCEPTREJECTRULE, Keywords.MSDNS,
TranslateAcceptRejectRule(foreign.AcceptRejectRule));
if (foreign.UpdateRule != ForeignKeyConstraint.Rule_Default)
constraint.SetAttribute(Keywords.MSD_UPDATERULE, Keywords.MSDNS, TranslateRule(foreign.UpdateRule));
if (foreign.DeleteRule != ForeignKeyConstraint.Rule_Default)
constraint.SetAttribute(Keywords.MSD_DELETERULE, Keywords.MSDNS, TranslateRule(foreign.DeleteRule));
fields = foreign.Columns;
if (0 < fields.Length)
{
StringBuilder encodedName = new StringBuilder();
for (int k = 0; k < fields.Length; k++)
{
encodedName.Length = 0;
if (_schFormat != SchemaFormat.Remoting)
{
GetSchema(fields[k].Namespace);
if (!string.IsNullOrEmpty(fields[k].Namespace))
{
encodedName.Append(_prefixes[fields[k].Namespace]).Append(':');
}
encodedName.Append(fields[k].EncodedColumnName);
}
else
{
encodedName.Append(xpathprefix).Append(fields[k].EncodedColumnName);
}
if ((fields[k].ColumnMapping == MappingType.Attribute) || (fields[k].ColumnMapping == MappingType.Hidden))
{
encodedName.Insert(0, '@');
}
field = dc.CreateElement(Keywords.XSD_PREFIX, Keywords.XSD_FIELD, Keywords.XSDNS);
field.SetAttribute(Keywords.XSD_XPATH, encodedName.ToString());
constraint.AppendChild(field);
}
}
_dsElement.InsertAfter(constraint, _constraintSeparator);
}
}
AddExtendedProperties(table._extendedProperties, root);
return root;
}
/// <summary>
/// resolve the name from the type for schema output and set the msdata:Data attribute
/// </summary>
/// <param name="root"></param>
/// <param name="type">non-special type to resolve</param>
/// <exception cref="DataException">if multipleTargetConverter throws or returns an empty result</exception>
private void SetMSDataAttribute(XmlElement root, Type type)
{
string result = DataStorage.GetQualifiedName(type);
try
{
if (null != _targetConverter)
{
result = _targetConverter(type);
}
if (!string.IsNullOrEmpty(result))
{
// SetAttribute doesn't fail with invalid data, but the final XmlDocument.Save will fail later
// with the ArgumentException when calling the actual XmlWriter.SetAttribute
root.SetAttribute(Keywords.MSD_DATATYPE, Keywords.MSDNS, result);
}
}
catch (Exception ex) when (ADP.IsCatchableExceptionType(ex))
{
ExceptionBuilder.ThrowMultipleTargetConverter(ex);
}
if (string.IsNullOrEmpty(result))
{
ExceptionBuilder.ThrowMultipleTargetConverter(null);
}
}
}
internal sealed class NewDiffgramGen
{
internal XmlDocument _doc;
internal DataSet? _ds;
internal DataTable? _dt;
internal XmlWriter _xmlw = default!; // Late-initialized
private bool _fBefore;
private bool _fErrors;
internal Hashtable _rowsOrder;
private readonly ArrayList _tables = new ArrayList();
private readonly bool _writeHierarchy;
internal NewDiffgramGen(DataSet ds)
{
_ds = ds;
_dt = null;
_doc = new XmlDocument();
for (int i = 0; i < ds.Tables.Count; i++)
{
_tables.Add(ds.Tables[i]);
}
DoAssignments(_tables);
}
internal NewDiffgramGen(DataTable dt, bool writeHierarchy)
{
_ds = null;
_dt = dt;
_doc = new XmlDocument();
_tables.Add(dt);
if (writeHierarchy)
{
_writeHierarchy = true;
CreateTableHierarchy(dt);
}
DoAssignments(_tables);
}
private void CreateTableHierarchy(DataTable dt)
{
// if (!dt.SerializeHierarchy)
// return;
foreach (DataRelation r in dt.ChildRelations)
{
if (!_tables.Contains(r.ChildTable))
{
_tables.Add(r.ChildTable);
CreateTableHierarchy(r.ChildTable);
}
}
}
[MemberNotNull(nameof(_rowsOrder))]
private void DoAssignments(ArrayList tables)
{
int rows = 0;
for (int i = 0; i < tables.Count; i++)
{
rows += ((DataTable)tables[i]!).Rows.Count;
}
_rowsOrder = new Hashtable(rows);
for (int i = 0; i < tables.Count; i++)
{
DataTable dt = (DataTable)tables[i]!;
DataRowCollection rc = dt.Rows;
rows = rc.Count;
for (int j = 0; j < rows; j++)
_rowsOrder[rc[j]] = j;
}
}
private bool EmptyData()
{
for (int i = 0; i < _tables.Count; i++)
{
if (((DataTable)_tables[i]!).Rows.Count > 0)
return false;
}
return true;
}
[RequiresUnreferencedCode(DataSet.RequiresUnreferencedCodeMessage)]
internal void Save(XmlWriter xmlw)
{
Save(xmlw, null);
}
[RequiresUnreferencedCode(DataSet.RequiresUnreferencedCodeMessage)]
internal void Save(XmlWriter xmlw, DataTable? table)
{
_xmlw = DataTextWriter.CreateWriter(xmlw);
_xmlw.WriteStartElement(Keywords.DFF, Keywords.DIFFGRAM, Keywords.DFFNS);
_xmlw.WriteAttributeString(Keywords.XMLNS, Keywords.MSD, null, Keywords.MSDNS);
// _xmlw.WriteAttributeString(Keywords.XMLNS, Keywords.UPDG, null, Keywords.UPDGNS);
if (!EmptyData())
{
// write the datapart
if (table != null)
new XmlDataTreeWriter(table, _writeHierarchy).SaveDiffgramData(_xmlw, _rowsOrder);
else
new XmlDataTreeWriter(_ds!).SaveDiffgramData(_xmlw, _rowsOrder);
// Walk the xd using relational apis and create nodes in nodeRoot appropriately.
if (table == null)
{
for (int i = 0; i < _ds!.Tables.Count; ++i)
{
GenerateTable(_ds.Tables[i]);
}
}
else
{
for (int i = 0; i < _tables.Count; i++)
{
GenerateTable((DataTable)_tables[i]!);
}
}
if (_fBefore)
_xmlw.WriteEndElement(); //SQL_BEFORE
if (table == null)
{
for (int i = 0; i < _ds!.Tables.Count; ++i)
{
GenerateTableErrors(_ds.Tables[i]);
}
}
else
{
for (int i = 0; i < _tables.Count; i++)
{
GenerateTableErrors((DataTable)_tables[i]!);
}
}
if (_fErrors)
_xmlw.WriteEndElement(); //ERRORS
}
_xmlw.WriteEndElement();
_xmlw.Flush();
}
[RequiresUnreferencedCode(DataSet.RequiresUnreferencedCodeMessage)]
private void GenerateTable(DataTable table)
{
int rowCount = table.Rows.Count;
if (rowCount <= 0)
return;
for (int rowNum = 0; rowNum < rowCount; ++rowNum)
GenerateRow(table.Rows[rowNum]);
}
private void GenerateTableErrors(DataTable table)
{
int rowCount = table.Rows.Count;
int colCount = table.Columns.Count;
if (rowCount <= 0)
return;
for (int rowNum = 0; rowNum < rowCount; ++rowNum)
{
bool tableName = false;
DataRow row = table.Rows[rowNum];
string prefix = (table.Namespace.Length != 0) ? table.Prefix : string.Empty;
if ((row.HasErrors) && (row.RowError.Length > 0))
{
if (!_fErrors)
{
_xmlw.WriteStartElement(Keywords.DFF, Keywords.MSD_ERRORS, Keywords.DFFNS);
_fErrors = true;
}
_xmlw.WriteStartElement(prefix, row.Table.EncodedTableName, row.Table.Namespace);
_xmlw.WriteAttributeString(Keywords.DFF, Keywords.DIFFID, Keywords.DFFNS, row.Table.TableName + row.rowID.ToString(CultureInfo.InvariantCulture));
_xmlw.WriteAttributeString(Keywords.DFF, Keywords.MSD_ERROR, Keywords.DFFNS, row.RowError);
tableName = true;
}
if (colCount <= 0)
continue;
for (int colNum = 0; colNum < colCount; ++colNum)
{
DataColumn column = table.Columns[colNum];
string error = row.GetColumnError(column);
string columnPrefix = (column.Namespace.Length != 0) ? column.Prefix : string.Empty;
if (error == null || error.Length == 0)
{
continue;
}
if (!tableName)
{
if (!_fErrors)
{
_xmlw.WriteStartElement(Keywords.DFF, Keywords.MSD_ERRORS, Keywords.DFFNS);
_fErrors = true;
}
_xmlw.WriteStartElement(prefix, row.Table.EncodedTableName, row.Table.Namespace);
_xmlw.WriteAttributeString(Keywords.DFF, Keywords.DIFFID, Keywords.DFFNS, row.Table.TableName + row.rowID.ToString(CultureInfo.InvariantCulture));
tableName = true;
}
_xmlw.WriteStartElement(columnPrefix, column.EncodedColumnName, column.Namespace);
_xmlw.WriteAttributeString(Keywords.DFF, Keywords.MSD_ERROR, Keywords.DFFNS, error);
_xmlw.WriteEndElement();
}
if (tableName)
_xmlw.WriteEndElement();
}
}
[RequiresUnreferencedCode(DataSet.RequiresUnreferencedCodeMessage)]
private void GenerateRow(DataRow row)
{
DataRowState state = row.RowState;
if ((state == DataRowState.Unchanged) || (state == DataRowState.Added))
{
return;
}
if (!_fBefore)
{
_xmlw.WriteStartElement(Keywords.DFF, Keywords.SQL_BEFORE, Keywords.DFFNS);
_fBefore = true;
}
DataTable table = row.Table;
int colCount = table.Columns.Count;
string rowIDString = table.TableName + row.rowID.ToString(CultureInfo.InvariantCulture);
string? parentId = null;
if ((state == DataRowState.Deleted) && (row.Table.NestedParentRelations.Length != 0))
{
DataRow? parentRow = row.GetNestedParentRow(DataRowVersion.Original);
if (parentRow != null)
{
parentId = parentRow.Table.TableName + parentRow.rowID.ToString(CultureInfo.InvariantCulture);
}
}
string tablePrefix = (table.Namespace.Length != 0) ? table.Prefix : string.Empty;
//old row
_xmlw.WriteStartElement(tablePrefix, row.Table.EncodedTableName, row.Table.Namespace);
_xmlw.WriteAttributeString(Keywords.DFF, Keywords.DIFFID, Keywords.DFFNS, rowIDString);
if ((state == DataRowState.Deleted) && XmlDataTreeWriter.RowHasErrors(row))
_xmlw.WriteAttributeString(Keywords.DFF, Keywords.HASERRORS, Keywords.DFFNS, Keywords.TRUE);
if (parentId != null)
_xmlw.WriteAttributeString(Keywords.DFF, Keywords.DIFFPID, Keywords.DFFNS, parentId);
_xmlw.WriteAttributeString(Keywords.MSD, Keywords.ROWORDER, Keywords.MSDNS, _rowsOrder[row]!.ToString());
for (int colNum = 0; colNum < colCount; ++colNum)
{
if ((row.Table.Columns[colNum].ColumnMapping == MappingType.Attribute) ||
(row.Table.Columns[colNum].ColumnMapping == MappingType.Hidden))
GenerateColumn(row, row.Table.Columns[colNum], DataRowVersion.Original);
}
for (int colNum = 0; colNum < colCount; ++colNum)
{
if ((row.Table.Columns[colNum].ColumnMapping == MappingType.Element) ||
(row.Table.Columns[colNum].ColumnMapping == MappingType.SimpleContent))
GenerateColumn(row, row.Table.Columns[colNum], DataRowVersion.Original);
}
_xmlw.WriteEndElement(); //old row
}
[RequiresUnreferencedCode(DataSet.RequiresUnreferencedCodeMessage)]
private void GenerateColumn(DataRow row, DataColumn col, DataRowVersion version)
{
string? value = null;
value = col.GetColumnValueAsString(row, version); // this is useless for CTD
if (value == null)
{
if (col.ColumnMapping == MappingType.SimpleContent)
_xmlw.WriteAttributeString(Keywords.XSI, Keywords.XSI_NIL, Keywords.XSINS, Keywords.TRUE);
return;
}
string colPrefix = (col.Namespace.Length != 0) ? col.Prefix : string.Empty;
switch (col.ColumnMapping)
{
case MappingType.Attribute:
_xmlw.WriteAttributeString(colPrefix, col.EncodedColumnName, col.Namespace, value);
break;
case MappingType.Hidden:
_xmlw.WriteAttributeString(Keywords.MSD, "hidden" + col.EncodedColumnName, Keywords.MSDNS, value);
break;
case MappingType.SimpleContent:
_xmlw.WriteString(value);
break;
case MappingType.Element:
bool startElementSkipped = true;
object columnValue = row[col, version];
// if the object is built in type or if it implements IXMLSerializable, write the start Element, otherwise
//(if CDT and does not implement IXmlSerializable) skip it
if (!col.IsCustomType || !col.IsValueCustomTypeInstance(columnValue) || (typeof(IXmlSerializable).IsAssignableFrom(columnValue.GetType())))
{
_xmlw.WriteStartElement(colPrefix, col.EncodedColumnName, col.Namespace);
startElementSkipped = false;
}
Type valuesType = columnValue.GetType();
if (!col.IsCustomType)
{ // if column's type is built in type CLR or SQLType
if (valuesType == typeof(char) || valuesType == typeof(string))
{
if (XmlDataTreeWriter.PreserveSpace(value))
{
_xmlw.WriteAttributeString(Keywords.XML, Keywords.SPACE, Keywords.XML_XMLNS, Keywords.PRESERVE);
}
}
_xmlw.WriteString(value);
}
else
{ // Columns type is CDT
if ((columnValue != DBNull.Value) && (!col.ImplementsINullable || !DataStorage.IsObjectSqlNull(columnValue)))
{
if (col.IsValueCustomTypeInstance(columnValue)/* && valuesType != typeof(Type)*/)
{// value is also CDT
// if SkippedElement, ie does not implement IXMLSerializable: so No Polymorphysm Support.
if (!startElementSkipped && columnValue.GetType() != col.DataType)
{
_xmlw.WriteAttributeString(Keywords.MSD, Keywords.MSD_INSTANCETYPE, Keywords.MSDNS, DataStorage.GetQualifiedName(valuesType));
}
if (!startElementSkipped)
{
col.ConvertObjectToXml(columnValue, _xmlw, null); // XmlRootAttribute MUST be passed null
}
else
{
// this column's type does not implement IXmlSerializable, so we need to handle serialization via XmlSerializer
if (columnValue.GetType() != col.DataType)
{ // throw if polymorphism; not supported
throw ExceptionBuilder.PolymorphismNotSupported(valuesType.AssemblyQualifiedName!);
}
// therefore we are skipping the start element, but by passing XmlRootAttribute with the same name as
// we open the start element (column's name), XmlSerializer will open and close it for us
XmlRootAttribute xmlAttrib = new XmlRootAttribute(col.EncodedColumnName);
xmlAttrib.Namespace = col.Namespace;
col.ConvertObjectToXml(columnValue, _xmlw, xmlAttrib);
}
}
else
{ // value is built in CLR type (eg: string, int etc.)
// these basic clr types do not have direct xsd type mappings
if (valuesType == typeof(Type) || valuesType == typeof(Guid) || valuesType == typeof(char) ||
DataStorage.IsSqlType(valuesType))
{ // if unmapped type or SQL type write msdata:Datatype=typeofinstance
_xmlw.WriteAttributeString(Keywords.MSD, Keywords.MSD_INSTANCETYPE, Keywords.MSDNS, valuesType.FullName);
}
else if (columnValue is Type)
{
_xmlw.WriteAttributeString(Keywords.MSD, Keywords.MSD_INSTANCETYPE, Keywords.MSDNS, Keywords.TYPEINSTANCE);
}
else
{
string xsdTypeName = Keywords.XSD_PREFIXCOLON + XmlTreeGen.XmlDataTypeName(valuesType);
_xmlw.WriteAttributeString(Keywords.XSI, Keywords.TYPE, Keywords.XSINS, xsdTypeName);
_xmlw.WriteAttributeString(Keywords.XSD_PREFIX, Keywords.XMLNS, Keywords.XSDNS, xsdTypeName);
}
if (!DataStorage.IsSqlType(valuesType))
{
_xmlw.WriteString(col.ConvertObjectToXml(columnValue));
}
else
{
col.ConvertObjectToXml(columnValue, _xmlw, null);
}
}
}
}
if (!startElementSkipped)
{
_xmlw.WriteEndElement();
}
break;
}
}
internal static string QualifiedName(string prefix, string name)
{
if (prefix != null)
return prefix + ":" + name;
return name;
}
}
// DataTreeWriter
internal sealed class XmlDataTreeWriter
{
private XmlWriter? _xmlw;
private readonly DataSet? _ds;
private readonly DataTable? _dt;
private readonly ArrayList _dTables = new ArrayList();
private readonly DataTable[] _topLevelTables;
private readonly bool _fFromTable; // also means no hierarchy
private bool _isDiffgram;
private Hashtable? _rowsOrder;
private readonly bool _writeHierarchy;
internal XmlDataTreeWriter(DataSet ds)
{
_ds = ds;
_topLevelTables = ds.TopLevelTables();
foreach (DataTable table in ds.Tables)
{
_dTables.Add(table);
}
}
internal XmlDataTreeWriter(DataTable dt, bool writeHierarchy)
{
_dt = dt;
_fFromTable = true;
if (dt.DataSet == null)
{
_dTables.Add(dt);
_topLevelTables = new DataTable[] { dt };
}
else
{
_ds = dt.DataSet;
_dTables.Add(dt);
if (writeHierarchy)
{
_writeHierarchy = true;
CreateTablesHierarchy(dt);
_topLevelTables = CreateToplevelTables();
}
else // if no hierarchy , top level table should be dt
_topLevelTables = new DataTable[] { dt };
}
}
private DataTable[] CreateToplevelTables()
{
ArrayList topTables = new ArrayList();
for (int i = 0; i < _dTables.Count; i++)
{
DataTable table = (DataTable)_dTables[i]!;
if (table.ParentRelations.Count == 0)
topTables.Add(table);
else
{
bool fNestedButNotSelfNested = false;
for (int j = 0; j < table.ParentRelations.Count; j++)
{
if (table.ParentRelations[j].Nested)
{
if (table.ParentRelations[j].ParentTable == table)
{
fNestedButNotSelfNested = false;
break;
}
fNestedButNotSelfNested = true;
}
}
if (!fNestedButNotSelfNested)
topTables.Add(table);
}
}
if (topTables.Count == 0)
{
return Array.Empty<DataTable>();
}
var temp = new DataTable[topTables.Count];
topTables.CopyTo(temp, 0);
return temp;
}
private void CreateTablesHierarchy(DataTable dt)
{
// if (!dt.SerializeHierarchy)
// return;
foreach (DataRelation r in dt.ChildRelations)
{
if (!_dTables.Contains(r.ChildTable))
{
_dTables.Add(r.ChildTable);
CreateTablesHierarchy(r.ChildTable);
}
}
}
internal static bool RowHasErrors(DataRow row)
{
int colCount = row.Table.Columns.Count;
if ((row.HasErrors) && (row.RowError.Length > 0))
return true;
for (int colNum = 0; colNum < colCount; ++colNum)
{
DataColumn column = row.Table.Columns[colNum];
string error = row.GetColumnError(column);
if (error == null || error.Length == 0)
{
continue;
}
return true;
}
return false;
}
// the following line writes the data part
// for the new diffgram format
[RequiresUnreferencedCode(DataSet.RequiresUnreferencedCodeMessage)]
internal void SaveDiffgramData(XmlWriter xw, Hashtable rowsOrder)
{
Debug.Assert(_ds != null || _dt != null);
_xmlw = DataTextWriter.CreateWriter(xw);
_isDiffgram = true;
_rowsOrder = rowsOrder;
string prefix = (_ds != null) ? ((_ds.Namespace.Length == 0) ? "" : _ds.Prefix) : ((_dt!.Namespace.Length == 0) ? "" : _dt.Prefix);
if (_ds == null || _ds.DataSetName == null || _ds.DataSetName.Length == 0)
_xmlw.WriteStartElement(prefix, Keywords.DOCUMENTELEMENT, (_dt!.Namespace == null) ? "" : _dt.Namespace);
else
_xmlw.WriteStartElement(prefix, XmlConvert.EncodeLocalName(_ds.DataSetName), _ds.Namespace);
// new XmlTreeGen(true).Save(_ds,_xmlw, false /* we don't care since we specified it's serialized */);
for (int i = 0; i < _dTables.Count; i++)
{
DataTable tempTable = ((DataTable)_dTables[i]!);
foreach (DataRow row in tempTable.Rows)
{
if (row.RowState == DataRowState.Deleted)
continue;
int nestedParentRowCount = row.GetNestedParentCount();
if (nestedParentRowCount == 0)
{
DataTable tempDT = ((DataTable)_dTables[i]!);
XmlDataRowWriter(row, tempDT.EncodedTableName);
}
else if (nestedParentRowCount > 1)
{
throw ExceptionBuilder.MultipleParentRows(tempTable.Namespace.Length == 0 ? tempTable.TableName : tempTable.Namespace + tempTable.TableName);
// At all times a nested row can only have 0 or 1 parents, never more than 1
}
}
}
_xmlw.WriteEndElement();
_xmlw.Flush();
}
[RequiresUnreferencedCode(DataSet.RequiresUnreferencedCodeMessage)]
internal void Save(XmlWriter xw, bool writeSchema)
{
Debug.Assert(_ds != null || _dt != null);
_xmlw = DataTextWriter.CreateWriter(xw);
int countTopTable = _topLevelTables.Length;
bool fWriteDSElement = true;
string prefix = (_ds != null) ? ((_ds.Namespace.Length == 0) ? "" : _ds.Prefix) : ((_dt!.Namespace.Length == 0) ? "" : _dt.Prefix);
if (!writeSchema && _ds != null && _ds._fTopLevelTable && countTopTable == 1)
{
if (_ds.TopLevelTables()[0].Rows.Count == 1)
fWriteDSElement = false;
}
if (fWriteDSElement)
{
if (_ds == null)
{
_xmlw.WriteStartElement(prefix, Keywords.DOCUMENTELEMENT, _dt!.Namespace);
}
else
{
if (_ds.DataSetName == null || _ds.DataSetName.Length == 0)
_xmlw.WriteStartElement(prefix, Keywords.DOCUMENTELEMENT, _ds.Namespace);
else
_xmlw.WriteStartElement(prefix, XmlConvert.EncodeLocalName(_ds.DataSetName), _ds.Namespace);
}
for (int i = 0; i < _dTables.Count; i++)
{
if (((DataTable)_dTables[i]!)._xmlText != null)
{
_xmlw.WriteAttributeString(Keywords.XMLNS, Keywords.XSI, Keywords.XSD_XMLNS_NS, Keywords.XSINS);
break;
}
}
if (writeSchema)
{
if (!_fFromTable)
{
new XmlTreeGen(SchemaFormat.Public).Save(_ds!, _xmlw);
}
else
{
new XmlTreeGen(SchemaFormat.Public).Save(null, _dt!, _xmlw, _writeHierarchy);
}
}
}
for (int i = 0; i < _dTables.Count; i++)
{
foreach (DataRow row in ((DataTable)_dTables[i]!).Rows)
{
if (row.RowState == DataRowState.Deleted)
continue;
int parentRowCount = row.GetNestedParentCount();
if (parentRowCount == 0)
{
XmlDataRowWriter(row, ((DataTable)_dTables[i]!).EncodedTableName);
}
else if (parentRowCount > 1)
{
DataTable dt = (DataTable)_dTables[i]!;
throw ExceptionBuilder.MultipleParentRows(dt.Namespace.Length == 0 ? dt.TableName : (dt.Namespace + dt.TableName));
// At all times a nested row can only have 0 or 1 parents, never more than 1
}
}
}
if (fWriteDSElement)
_xmlw.WriteEndElement();
_xmlw.Flush();
}
private ArrayList GetNestedChildRelations(DataRow row)
{
ArrayList list = new ArrayList();
foreach (DataRelation r in row.Table.ChildRelations)
{
if (r.Nested)
list.Add(r);
}
return list;
}
[RequiresUnreferencedCode(DataSet.RequiresUnreferencedCodeMessage)]
internal void XmlDataRowWriter(DataRow row, string encodedTableName)
{
Debug.Assert(_xmlw != null);
object value;
string prefix = (row.Table.Namespace.Length == 0) ? "" : row.Table.Prefix;
_xmlw.WriteStartElement(prefix, encodedTableName, row.Table.Namespace);
if (_isDiffgram)
{
_xmlw.WriteAttributeString(Keywords.DFF, Keywords.DIFFID, Keywords.DFFNS, row.Table.TableName + row.rowID.ToString(CultureInfo.InvariantCulture));
_xmlw.WriteAttributeString(Keywords.MSD, Keywords.ROWORDER, Keywords.MSDNS, _rowsOrder![row]!.ToString());
if (row.RowState == DataRowState.Added)
{
_xmlw.WriteAttributeString(Keywords.DFF, Keywords.HASCHANGES, Keywords.DFFNS, Keywords.INSERTED);
}
if (row.RowState == DataRowState.Modified)
{
_xmlw.WriteAttributeString(Keywords.DFF, Keywords.HASCHANGES, Keywords.DFFNS, Keywords.MODIFIED);
}
if (RowHasErrors(row))
{
_xmlw.WriteAttributeString(Keywords.DFF, Keywords.HASERRORS, Keywords.DFFNS, Keywords.TRUE);
}
}
//write the attribute columns first, if any
foreach (DataColumn col in row.Table.Columns)
{
if (col._columnMapping == MappingType.Attribute)
{
value = row[col];
string colPrefix = (col.Namespace.Length == 0) ? "" : col.Prefix;
if ((value != DBNull.Value) && (!col.ImplementsINullable || !DataStorage.IsObjectSqlNull(value)))
{
XmlTreeGen.ValidateColumnMapping(col.DataType);
_xmlw.WriteAttributeString(colPrefix, col.EncodedColumnName, col.Namespace, col.ConvertObjectToXml(value));
}
}
if (!_isDiffgram)
continue;
if (col._columnMapping == MappingType.Hidden)
{
value = row[col];
if ((value != DBNull.Value) && (!col.ImplementsINullable || !DataStorage.IsObjectSqlNull(value)))
{
XmlTreeGen.ValidateColumnMapping(col.DataType);
_xmlw.WriteAttributeString(Keywords.MSD, "hidden" + col.EncodedColumnName, Keywords.MSDNS, col.ConvertObjectToXml(value));
}
}
} //end foreach
foreach (DataColumn col in row.Table.Columns)
{
if (col._columnMapping != MappingType.Hidden)
{
value = row[col];
string colPrefix = (col.Namespace.Length == 0) ? "" : col.Prefix;
bool startElementSkipped = true;
if (((value == DBNull.Value) || (col.ImplementsINullable && DataStorage.IsObjectSqlNull(value))) && (col.ColumnMapping == MappingType.SimpleContent))
_xmlw.WriteAttributeString(Keywords.XSI, Keywords.XSI_NIL, Keywords.XSINS, Keywords.TRUE);
// basically this is a continue; if it is null we write xsi:nil='true'
// below, the check is if it is not null
if (((value != DBNull.Value) && (!col.ImplementsINullable || !DataStorage.IsObjectSqlNull(value))) && (col._columnMapping != MappingType.Attribute))
{
if (col._columnMapping != MappingType.SimpleContent)
{
// again, if we need to use XmlSerializer, do not write start Element (see above for more info)
if (!col.IsCustomType || !col.IsValueCustomTypeInstance(value) || (typeof(IXmlSerializable).IsAssignableFrom(value.GetType())))
{
_xmlw.WriteStartElement(colPrefix, col.EncodedColumnName, col.Namespace);
startElementSkipped = false;
}
}
Type valuesType = value.GetType();
if (!col.IsCustomType)
{ // if column's type is built in type: CLR and SQLTypes : ie storage supported types
if (valuesType == typeof(char) || valuesType == typeof(string))
{
if (PreserveSpace(value))
{
_xmlw.WriteAttributeString(Keywords.XML, Keywords.SPACE, Keywords.XML_XMLNS, Keywords.PRESERVE);
}
}
_xmlw.WriteString(col.ConvertObjectToXml(value));
}
else
{ // Columns type is CDT
if (col.IsValueCustomTypeInstance(value) /*&& !(value is Type) && valuesType != typeof(Type)*/)
{// value is also CDT
// if SkippedElement, ie does not implement IXMLSerializable: so No Polymorphism Support.
if (!startElementSkipped && valuesType != col.DataType)
{ // for polymorphism.
_xmlw.WriteAttributeString(Keywords.MSD, Keywords.MSD_INSTANCETYPE, Keywords.MSDNS, DataStorage.GetQualifiedName(valuesType));
}
if (!startElementSkipped)
{ // make sure XmlRootAttribute is passed null as this type implement IXmlSerializable
col.ConvertObjectToXml(value, _xmlw, null); // pass XmlRootAttribute as null, it also means: No XmlSerializer
}
else
{ // startElement is skipped: this column's type does not implement IXmlSerializable, need to go via XmlSerializer
if (value.GetType() != col.DataType)
{ // throw if polymorphism; not supported
throw ExceptionBuilder.PolymorphismNotSupported(valuesType.AssemblyQualifiedName!);
}
// therefore we are skipping the start element, but by passing XmlRootAttribute with the same name as
// we open the start element (column's name), XmlSerializer will open and close it for us
XmlRootAttribute xmlAttrib = new XmlRootAttribute(col.EncodedColumnName);
xmlAttrib.Namespace = col.Namespace;
col.ConvertObjectToXml(value, _xmlw, xmlAttrib);
}
}
else
{ // this is case that column type is object and value is CLR or SQLTypes
if (valuesType == typeof(Type) || valuesType == typeof(Guid) || valuesType == typeof(char) ||
DataStorage.IsSqlType(valuesType))
{ // if unmapped type or SQL type write msdata:Datatype=typeofinstance
_xmlw.WriteAttributeString(Keywords.MSD, Keywords.MSD_INSTANCETYPE, Keywords.MSDNS, valuesType.FullName);
}
else if (value is Type)
{
_xmlw.WriteAttributeString(Keywords.MSD, Keywords.MSD_INSTANCETYPE, Keywords.MSDNS, Keywords.TYPEINSTANCE);
}
else
{
string xsdTypeName = Keywords.XSD_PREFIXCOLON + XmlTreeGen.XmlDataTypeName(valuesType);
_xmlw.WriteAttributeString(Keywords.XSI, Keywords.TYPE, Keywords.XSINS, xsdTypeName);
_xmlw.WriteAttributeString(Keywords.XSD_PREFIX, Keywords.XMLNS, Keywords.XSDNS, xsdTypeName);
}
if (!DataStorage.IsSqlType(valuesType))
{
_xmlw.WriteString(col.ConvertObjectToXml(value));
}
else
{
col.ConvertObjectToXml(value, _xmlw, null);
}
}
}
if (col._columnMapping != MappingType.SimpleContent && !startElementSkipped)
_xmlw.WriteEndElement();
}
}
} //end foreach
if (_ds != null)
foreach (DataRelation dr in GetNestedChildRelations(row))
{
foreach (DataRow r in row.GetChildRows(dr))
{
XmlDataRowWriter(r, dr.ChildTable.EncodedTableName);
}
}
_xmlw.WriteEndElement();
}
internal static bool PreserveSpace(object value)
{
Debug.Assert(value != null, "Value can not be null");
string tempValue = value.ToString()!;
if (tempValue.Length == 0)
{
return false;
}
for (int i = 0; i < tempValue.Length; i++)
{
if (!char.IsWhiteSpace(tempValue, i))
{
return false;
}
}
return true;
}
}
internal sealed class DataTextWriter : XmlWriter
{
private readonly XmlWriter _xmltextWriter;
internal static XmlWriter CreateWriter(XmlWriter xw)
{
return new DataTextWriter(xw);
}
private DataTextWriter(XmlWriter w)
{
_xmltextWriter = w;
}
internal Stream? BaseStream
{
get
{
XmlTextWriter? textWriter = _xmltextWriter as XmlTextWriter;
if (null != textWriter)
{
return textWriter.BaseStream;
}
return null;
}
}
public override void WriteStartDocument()
{
_xmltextWriter.WriteStartDocument();
}
public override void WriteStartDocument(bool standalone)
{
_xmltextWriter.WriteStartDocument(standalone);
}
public override void WriteEndDocument()
{
_xmltextWriter.WriteEndDocument();
}
public override void WriteDocType(string name, string? pubid, string? sysid, string? subset)
{
_xmltextWriter.WriteDocType(name, pubid, sysid, subset);
}
public override void WriteStartElement(string? prefix, string localName, string? ns)
{
_xmltextWriter.WriteStartElement(prefix, localName, ns);
}
public override void WriteEndElement()
{
_xmltextWriter.WriteEndElement();
}
public override void WriteFullEndElement()
{
_xmltextWriter.WriteFullEndElement();
}
public override void WriteStartAttribute(string? prefix, string localName, string? ns)
{
_xmltextWriter.WriteStartAttribute(prefix, localName, ns);
}
public override void WriteEndAttribute()
{
_xmltextWriter.WriteEndAttribute();
}
public override void WriteCData(string? text)
{
_xmltextWriter.WriteCData(text);
}
public override void WriteComment(string? text)
{
_xmltextWriter.WriteComment(text);
}
public override void WriteProcessingInstruction(string name, string? text)
{
_xmltextWriter.WriteProcessingInstruction(name, text);
}
public override void WriteEntityRef(string name)
{
_xmltextWriter.WriteEntityRef(name);
}
public override void WriteCharEntity(char ch)
{
_xmltextWriter.WriteCharEntity(ch);
}
public override void WriteWhitespace(string? ws)
{
_xmltextWriter.WriteWhitespace(ws);
}
public override void WriteString(string? text)
{
_xmltextWriter.WriteString(text);
}
public override void WriteSurrogateCharEntity(char lowChar, char highChar)
{
_xmltextWriter.WriteSurrogateCharEntity(lowChar, highChar);
}
public override void WriteChars(char[] buffer, int index, int count)
{
_xmltextWriter.WriteChars(buffer, index, count);
}
public override void WriteRaw(char[] buffer, int index, int count)
{
_xmltextWriter.WriteRaw(buffer, index, count);
}
public override void WriteRaw(string data)
{
_xmltextWriter.WriteRaw(data);
}
public override void WriteBase64(byte[] buffer, int index, int count)
{
_xmltextWriter.WriteBase64(buffer, index, count);
}
public override void WriteBinHex(byte[] buffer, int index, int count)
{
_xmltextWriter.WriteBinHex(buffer, index, count);
}
public override WriteState WriteState
{
get
{
return _xmltextWriter.WriteState;
}
}
public override void Close()
{
_xmltextWriter.Close();
}
public override void Flush()
{
_xmltextWriter.Flush();
}
public override void WriteName(string name)
{
_xmltextWriter.WriteName(name);
}
public override void WriteQualifiedName(string localName, string? ns)
{
_xmltextWriter.WriteQualifiedName(localName, ns);
}
public override string? LookupPrefix(string ns)
{
return _xmltextWriter.LookupPrefix(ns);
}
public override XmlSpace XmlSpace
{
get
{
return _xmltextWriter.XmlSpace;
}
}
public override string? XmlLang
{
get
{
return _xmltextWriter.XmlLang;
}
}
public override void WriteNmToken(string name)
{
_xmltextWriter.WriteNmToken(name);
}
}
internal sealed class DataTextReader : XmlReader
{
private readonly XmlReader _xmlreader;
internal static XmlReader CreateReader(XmlReader xr)
{
Debug.Assert(!(xr is DataTextReader), "XmlReader is DataTextReader");
return new DataTextReader(xr);
}
private DataTextReader(XmlReader input)
{
_xmlreader = input;
}
public override XmlReaderSettings? Settings
{
get
{
return _xmlreader.Settings;
}
}
public override XmlNodeType NodeType
{
get
{
return _xmlreader.NodeType;
}
}
public override string Name
{
get
{
return _xmlreader.Name;
}
}
public override string LocalName
{
get
{
return _xmlreader.LocalName;
}
}
public override string NamespaceURI
{
get
{
return _xmlreader.NamespaceURI;
}
}
public override string Prefix
{
get { return _xmlreader.Prefix; }
}
public override bool HasValue
{
get { return _xmlreader.HasValue; }
}
public override string Value
{
get { return _xmlreader.Value; }
}
public override int Depth
{
get { return _xmlreader.Depth; }
}
public override string BaseURI
{
get { return _xmlreader.BaseURI; }
}
public override bool IsEmptyElement
{
get { return _xmlreader.IsEmptyElement; }
}
public override bool IsDefault
{
get { return _xmlreader.IsDefault; }
}
public override char QuoteChar
{
get { return _xmlreader.QuoteChar; }
}
public override XmlSpace XmlSpace
{
get { return _xmlreader.XmlSpace; }
}
public override string XmlLang
{
get { return _xmlreader.XmlLang; }
}
public override int AttributeCount { get { return _xmlreader.AttributeCount; } }
public override string? GetAttribute(string name)
{
return _xmlreader.GetAttribute(name);
}
public override string? GetAttribute(string localName, string? namespaceURI)
{
return _xmlreader.GetAttribute(localName, namespaceURI);
}
public override string GetAttribute(int i)
{
return _xmlreader.GetAttribute(i);
}
public override bool MoveToAttribute(string name)
{
return _xmlreader.MoveToAttribute(name);
}
public override bool MoveToAttribute(string localName, string? namespaceURI)
{
return _xmlreader.MoveToAttribute(localName, namespaceURI);
}
public override void MoveToAttribute(int i)
{
_xmlreader.MoveToAttribute(i);
}
public override bool MoveToFirstAttribute()
{
return _xmlreader.MoveToFirstAttribute();
}
public override bool MoveToNextAttribute()
{
return _xmlreader.MoveToNextAttribute();
}
public override bool MoveToElement()
{
return _xmlreader.MoveToElement();
}
public override bool ReadAttributeValue()
{
return _xmlreader.ReadAttributeValue();
}
public override bool Read()
{
return _xmlreader.Read();
}
public override bool EOF
{
get { return _xmlreader.EOF; }
}
public override void Close()
{
_xmlreader.Close();
}
public override ReadState ReadState
{
get { return _xmlreader.ReadState; }
}
public override void Skip()
{
_xmlreader.Skip();
}
public override XmlNameTable NameTable
{
get { return _xmlreader.NameTable; }
}
public override string? LookupNamespace(string prefix)
{
return _xmlreader.LookupNamespace(prefix);
}
public override bool CanResolveEntity
{
get { return _xmlreader.CanResolveEntity; }
}
public override void ResolveEntity()
{
_xmlreader.ResolveEntity();
}
public override bool CanReadBinaryContent
{
get { return _xmlreader.CanReadBinaryContent; }
}
public override int ReadContentAsBase64(byte[] buffer, int index, int count)
{
return _xmlreader.ReadContentAsBase64(buffer, index, count);
}
public override int ReadElementContentAsBase64(byte[] buffer, int index, int count)
{
return _xmlreader.ReadElementContentAsBase64(buffer, index, count);
}
public override int ReadContentAsBinHex(byte[] buffer, int index, int count)
{
return _xmlreader.ReadContentAsBinHex(buffer, index, count);
}
public override int ReadElementContentAsBinHex(byte[] buffer, int index, int count)
{
return _xmlreader.ReadElementContentAsBinHex(buffer, index, count);
}
public override bool CanReadValueChunk
{
get { return _xmlreader.CanReadValueChunk; }
}
public override string ReadString()
{
return _xmlreader.ReadString();
}
}
}
| 40.532449 | 217 | 0.501904 | [
"MIT"
] | Maximys/runtime | src/libraries/System.Data.Common/src/System/Data/xmlsaver.cs | 143,647 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace LiveSplitX.WPF.Host
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
root.Content = new global::Uno.UI.Skia.Platform.WpfHost(Dispatcher, () => new LiveSplitX.App());
}
}
}
| 24.225806 | 108 | 0.703063 | [
"MIT"
] | jtrinklein/LiveSplitX | LiveSplitX/LiveSplitX.Skia.Wpf.Host/MainWindow.xaml.cs | 753 | 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("ProjectEulerLib")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("ProjectEulerLib")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("6eae5dc5-ede4-4135-b02c-fa363969a794")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 37.918919 | 84 | 0.746258 | [
"MIT"
] | rhubinak/ProjectEuler | ProjectEulerLib/Properties/AssemblyInfo.cs | 1,406 | C# |
// <auto-generated />
namespace Reverb.Data.Migrations
{
using System.CodeDom.Compiler;
using System.Data.Entity.Migrations;
using System.Data.Entity.Migrations.Infrastructure;
using System.Resources;
[GeneratedCode("EntityFramework.Migrations", "6.1.0-30225")]
public sealed partial class AddUserCollectionInSongs : IMigrationMetadata
{
private readonly ResourceManager Resources = new ResourceManager(typeof(AddUserCollectionInSongs));
string IMigrationMetadata.Id
{
get { return "201710142015305_AddUserCollectionInSongs"; }
}
string IMigrationMetadata.Source
{
get { return null; }
}
string IMigrationMetadata.Target
{
get { return Resources.GetString("Target"); }
}
}
}
| 28.5 | 107 | 0.636257 | [
"MIT"
] | Xenoleth/Reverb-MVC | Reverb/Reverb.Data/Migrations/201710142015305_AddUserCollectionInSongs.Designer.cs | 855 | C# |
using System;
namespace ShareThings.Domain
{
public sealed class BorrowScore
{
private BorrowScore()
{
}
public BorrowScore(Score score, User owner, Borrow borrow) : this()
{
this.Punctuation = score ?? throw new ArgumentNullException(nameof(owner));
this.Owner = owner ?? throw new ArgumentNullException(nameof(owner));
this.Borrow = borrow ?? throw new ArgumentNullException(nameof(borrow));
}
public int ScoreId { get; private set; }
public Score Punctuation { get; private set; }
public int OwnerId { get; private set; }
public User Owner { get; private set; }
public int BorrowId { get; private set; }
public Borrow Borrow { get; private set; }
public int GetScore()
{
return this.Punctuation.Punctuation;
}
}
} | 30.033333 | 87 | 0.596004 | [
"Apache-2.0"
] | MasterCloudApps-Projects/RUP-Arquitecturas-Agiles | src/ShareThings.Domain/BorrowScore.cs | 903 | C# |
using System;
using System.ComponentModel.DataAnnotations;
namespace WebApplication.Models
{
public class IntegrationRuntime
{
public int IntegrationRuntimeId { get; set; }
[Required(AllowEmptyStrings = false, ErrorMessage = "Please input valid Name")]
public string IntegrationRuntimeName { get; set; }
public long DataFactoryId { get; set; }
[Display(Name = "Is Active")]
public bool ActiveYn { get; set; }
public virtual DataFactory DataFactory { get; set; }
}
}
| 29.833333 | 87 | 0.668529 | [
"MIT"
] | G-arj/azure-data-services-go-fast-codebase | solution/WebApplication/WebApplication.DataAccess/Models/IntegrationRuntime.cs | 539 | C# |
// Copyright 1998-2018 Epic Games, Inc. All Rights Reserved.
using UnrealBuildTool;
public class ATCSVLogger : ModuleRules
{
public ATCSVLogger(ReadOnlyTargetRules Target) : base(Target)
{
PCHUsage = ModuleRules.PCHUsageMode.UseExplicitOrSharedPCHs;
PublicIncludePaths.AddRange(
new string[] {
// ... add public include paths required here ...
}
);
PrivateIncludePaths.AddRange(
new string[] {
// ... add other private include paths required here ...
}
);
PublicDependencyModuleNames.AddRange(
new string[]
{
"Core",
// ... add other public dependencies that you statically link with here ...
}
);
PrivateDependencyModuleNames.AddRange(
new string[]
{
"CoreUObject",
"Engine",
"Slate",
"SlateCore",
// ... add private dependencies that you statically link with here ...
}
);
DynamicallyLoadedModuleNames.AddRange(
new string[]
{
// ... add any modules that your module loads dynamically here ...
}
);
}
}
| 19.407407 | 79 | 0.639313 | [
"MIT"
] | AlekseiTepljakov/csv-ue4-plugin | ATCSVLogger/Source/ATCSVLogger/ATCSVLogger.Build.cs | 1,048 | C# |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Text;
namespace PartialityLauncher {
public static class DebugLogger {
private static StringBuilder sb = new StringBuilder();
public static void Log(object obj) {
Debug.WriteLine( obj.ToString() );
sb.AppendLine( obj.ToString() );
}
public static void WriteToFile() {
string executablePath = Assembly.GetEntryAssembly().Location;
string executableDirectory = Directory.GetParent( executablePath ).FullName;
string aboveDirectory = Directory.GetParent( executableDirectory ).FullName;
string filePath = aboveDirectory + "\\LOG.txt";
File.WriteAllText( filePath, sb.ToString() );
}
}
} | 31.481481 | 88 | 0.662353 | [
"MIT"
] | EFLFE/PartialityLauncher | PartialityLauncher/PartialityLauncher/Debugging/DebugLogger.cs | 852 | C# |
//------------------------------------------------------------------------------
// <copyright file="PrologCompiler.cs" company="Axiom">
//
// Copyright (c) 2006 Axiom, Inc. All rights reserved.
//
// The use and distribution terms for this source code are contained in the file
// named license.txt, which can be found in the root of this distribution.
// By using this software in any fashion, you are agreeing to be bound by the
// terms of this license.
//
// You must not remove this notice, or any other, from this software.
//
// </copyright>
//------------------------------------------------------------------------------
using System;
using System.IO;
using System.Reflection;
using System.Collections;
using System.CodeDom;
using System.CodeDom.Compiler;
using Axiom.Runtime;
using Axiom.Runtime.Instructions;
using Axiom.Compiler.CodeObjectModel;
namespace Axiom.Compiler.Framework
{
public abstract class PrologCompiler : PrologCodeGenerator, IPrologCompiler
{
PrologCompilerResults IPrologCompiler.CompileAbstractCodeFromUnit(PrologCompilerParameters p, PrologCodeUnit unit)
{
PrologCompilerResults results = new PrologCompilerResults();
results.AbstractInstructions = new ArrayList();
GenerateCodeFromUnit(unit, results.AbstractInstructions);
/* patch predicates */
//PatchPredicates(results.AbstractInstructions, GetPredicateAddresses(results.AbstractInstructions));
/* save foreign methods */
//results.ForeignMethods = GetForeignMethods(unit.Methods);
/* save namespaces */
results.Namespaces = unit.Namespaces;
/* save assembly files */
results.AssemblyFiles = unit.AssemblyFiles;
/* return results */
return results;
}
PrologCompilerResults IPrologCompiler.CompileAbstractCodeFromFile(PrologCompilerParameters p, string fileName)
{
PrologCompilerResults results = new PrologCompilerResults();
PrologCodeParser parser = new PrologCodeParser();
PrologCodeUnit unit = new PrologCodeUnit();
try
{
StreamReader reader = new StreamReader(fileName);
unit = parser.Parse(reader);
/* Get errors after parsing */
results.Errors = parser.Errors;
}
catch (FileNotFoundException)
{
results.Errors.Add(new PrologCompilerError("P0008", "Input file not found.", fileName, false, 0, 0));
return results;
}
results.AbstractInstructions = new ArrayList();
GenerateCodeFromUnit(unit, results.AbstractInstructions);
/* patch predicates */
//PatchPredicates(results.AbstractInstructions, GetPredicateAddresses(results.AbstractInstructions));
/* Save foreign methods */
//results.ForeignMethods = GetForeignMethods(unit.Methods);
/* save namespaces */
results.Namespaces = unit.Namespaces;
/* save assembly files */
results.AssemblyFiles = unit.AssemblyFiles;
/* return results */
return results;
}
PrologCompilerResults IPrologCompiler.CompileAssemblyFromUnit (PrologCompilerParameters options, PrologCodeUnit e)
{
return FromUnit(options, e);
}
PrologCompilerResults IPrologCompiler.CompileAssemblyFromFile (PrologCompilerParameters options, string fileName)
{
return FromFile(options, fileName);
}
protected virtual PrologCompilerResults FromUnit (PrologCompilerParameters options, PrologCodeUnit e)
{
ArrayList instructions = new ArrayList();
PrologCompilerResults results = new PrologCompilerResults();
/* Generate abstract machine instructions */
GenerateCodeFromUnit(e, instructions);
/* Determine assembly name and type to generate */
if (options.GenerateExecutable)
{
results.CompiledAssembly = GenerateExecutableAssembly(options, instructions);
}
else
{
results.CompiledAssembly = GenerateDllAssembly(options, instructions, e);
}
return results;
}
private Assembly GenerateDllAssembly(PrologCompilerParameters compilerParameters, ArrayList instructions, PrologCodeUnit unit)
{
CodeCompileUnit compileUnit = new CodeCompileUnit();
// Declare namespace, default is Prolog.Assembly
CodeNamespace plNamespace = new CodeNamespace("Prolog.Assembly");
plNamespace.Imports.Add(new CodeNamespaceImport("System"));
plNamespace.Imports.Add(new CodeNamespaceImport("System.Collections"));
plNamespace.Imports.Add(new CodeNamespaceImport("Axiom.Runtime"));
compileUnit.Namespaces.Add(plNamespace);
// Declare class type
CodeTypeDeclaration classType = new CodeTypeDeclaration(unit.Class);
plNamespace.Types.Add(classType);
classType.TypeAttributes = TypeAttributes.Public;
// Declare private members
CodeMemberField machineField = new CodeMemberField(new CodeTypeReference("AbstractMachineState"), "machine");
CodeMemberField moreField = new CodeMemberField(new CodeTypeReference("System.Boolean"), "_more");
classType.Members.Add(machineField);
classType.Members.Add(moreField);
// Generate constructor method
CodeConstructor cons = new CodeConstructor();
cons.Attributes = MemberAttributes.Public;
cons.Statements.Add(new CodeSnippetExpression("Init()"));
classType.Members.Add(cons);
// Generate the 'More' property
CodeMemberProperty moreProperty = new CodeMemberProperty();
moreProperty.Attributes = MemberAttributes.Public;
moreProperty.Name = "More";
moreProperty.HasGet = true;
moreProperty.HasSet = false;
moreProperty.Type = new CodeTypeReference("System.Boolean");
string getStmt1 = "if (machine.Program.CurrentInstruction() == null || machine.Program.CurrentInstruction().Name().Equals(\"stop\")) { _more = false; } ";
string getStmt2 = "return !(machine.Program.CurrentInstruction() == null || machine.Program.CurrentInstruction().Name().Equals(\"stop\"));";
moreProperty.GetStatements.Add(new CodeSnippetStatement(getStmt1));
moreProperty.GetStatements.Add(new CodeSnippetStatement(getStmt2));
classType.Members.Add(moreProperty);
// Generate Redo() method
CodeMemberMethod redoMethod = new CodeMemberMethod();
redoMethod.Name = "Redo";
redoMethod.Statements.Add(new CodeSnippetStatement("machine.Backtrack();"));
redoMethod.Statements.Add(new CodeSnippetStatement("_more = true;"));
redoMethod.Attributes = MemberAttributes.Public;
classType.Members.Add(redoMethod);
// Generate Init() method
GenerateInitMethod(classType, instructions);
// Generate method signatures
GenerateMethodSignatures(classType, instructions);
// Compile the file into a DLL
CompilerParameters compparams = new CompilerParameters(new string[] { "mscorlib.dll", "Axiom.Runtime.dll" });
compparams.GenerateInMemory = false;
compparams.OutputAssembly = compilerParameters.OutputAssembly;
compparams.TempFiles.KeepFiles = true;
Microsoft.CSharp.CSharpCodeProvider csharp = new Microsoft.CSharp.CSharpCodeProvider();
ICodeCompiler cscompiler = csharp.CreateCompiler();
CompilerResults compresult = cscompiler.CompileAssemblyFromDom(compparams, compileUnit);
if (compresult.Errors.Count > 0)
{
foreach(CompilerError err in compresult.Errors)
{
Console.WriteLine(err);
}
return null;
}
return compresult.CompiledAssembly;
}
private void GenerateMethodSignatures(CodeTypeDeclaration classType, ArrayList instructions)
{
Hashtable procedures = new Hashtable();
// Get all predicate names
foreach (AbstractInstruction i in instructions)
{
if (i.Name() == "procedure")
{
ProcedureInstruction pi = (ProcedureInstruction)i;
if (!procedures.ContainsKey(pi.ProcedureName))
{
procedures.Add(pi.ProcedureName, pi);
}
}
}
foreach (DictionaryEntry entry in procedures)
{
ProcedureInstruction pi = (ProcedureInstruction)entry.Value;
GenerateMethod(classType, pi);
}
}
private void GenerateMethod(CodeTypeDeclaration classType, ProcedureInstruction pi)
{
CodeMemberMethod method = new CodeMemberMethod();
method.Name = pi.ProcedureName;
method.ReturnType = new CodeTypeReference("System.Boolean");
method.Attributes = MemberAttributes.Public;
string objectStatement = "new object [] { ";
for (int i = 0; i < pi.Arity; i++)
{
method.Parameters.Add(new CodeParameterDeclarationExpression("System.Object", "arg" + (i + 1)));
objectStatement += "arg" + (i + 1);
if (i == pi.Arity - 1)
{
objectStatement += " }";
}
else
{
objectStatement += ", ";
}
}
method.Statements.Add(new CodeSnippetStatement("return machine.Call(\"" + pi.ProcedureName + "\", " + pi.Arity + ", " + objectStatement + ", _more);"));
classType.Members.Add(method);
}
private void GenerateInitMethod(CodeTypeDeclaration classType, ArrayList instructions)
{
CodeMemberMethod initMethod = new CodeMemberMethod();
initMethod.Attributes = MemberAttributes.Private;
initMethod.Name = "Init";
initMethod.Statements.Add(new CodeSnippetStatement("ArrayList program = new ArrayList();"));
initMethod.Statements.Add(new CodeSnippetStatement("machine = new AbstractMachineState(new AMFactory());"));
initMethod.Statements.Add(new CodeSnippetStatement("AMInstructionSet iset = new AMInstructionSet();"));
initMethod.Statements.Add(new CodeSnippetStatement("_more = false;"));
// generate instructions here...
foreach (AbstractInstruction inst in instructions)
{
string statement = GetInstructionStatement(inst);
initMethod.Statements.Add(new CodeSnippetStatement(statement));
}
initMethod.Statements.Add(new CodeSnippetStatement("machine.Initialize(program);"));
classType.Members.Add(initMethod);
}
private string GetInstructionStatement(AbstractInstruction inst)
{
string statement = "program.Add(iset.CreateInstruction(";
if (inst.Name() == "procedure")
{
ProcedureInstruction pi = (ProcedureInstruction)inst;
statement += "\"procedure\", \"" + pi.ProcedureName + "\", \"" + pi.Arity + "\"";
}
else
{
if (inst._arguments == null || inst._arguments.Length == 0)
{
statement += "\"" + inst.Name() + "\"";
}
else
{
statement += "\"" + inst.Name() + "\", ";
for (int i = 0; i < inst._arguments.Length; i++)
{
statement += "\"" + inst._arguments[i] + "\"";
if (i != (inst._arguments.Length - 1))
{
statement += ", ";
}
}
}
}
statement += "));";
return statement;
}
private Assembly GenerateExecutableAssembly(PrologCompilerParameters compilerParameters, ArrayList instructions)
{
CodeCompileUnit compileUnit = new CodeCompileUnit();
// Declare namespace, default is Prolog.Assembly
CodeNamespace plNamespace = new CodeNamespace("Prolog.Assembly");
plNamespace.Imports.Add(new CodeNamespaceImport("System"));
plNamespace.Imports.Add(new CodeNamespaceImport("System.Collections"));
plNamespace.Imports.Add(new CodeNamespaceImport("Axiom.Runtime"));
compileUnit.Namespaces.Add(plNamespace);
// Declare class type
CodeTypeDeclaration classType = new CodeTypeDeclaration("PrologApp");
plNamespace.Types.Add(classType);
classType.TypeAttributes = TypeAttributes.Public;
// Declare private members
CodeMemberField machineField = new CodeMemberField(new CodeTypeReference("AbstractMachineState"), "machine");
CodeMemberField moreField = new CodeMemberField(new CodeTypeReference("System.Boolean"), "_more");
classType.Members.Add(machineField);
classType.Members.Add(moreField);
// Generate constructor method
CodeConstructor cons = new CodeConstructor();
cons.Attributes = MemberAttributes.Public;
cons.Statements.Add(new CodeSnippetExpression("Init()"));
classType.Members.Add(cons);
// Generate Init() method
GenerateInitMethod(classType, instructions);
// Generate main method
CodeEntryPointMethod mainMethod = new CodeEntryPointMethod();
mainMethod.Name = "Main";
mainMethod.Attributes = MemberAttributes.Static | MemberAttributes.Public;
mainMethod.Statements.Add(new CodeSnippetStatement("PrologApp app = new PrologApp();"));
mainMethod.Statements.Add(new CodeSnippetStatement("app.Run();"));
classType.Members.Add(mainMethod);
CodeMemberMethod runMethod = new CodeMemberMethod();
runMethod.Name = "Run";
runMethod.Attributes = MemberAttributes.Public;
runMethod.Statements.Add(new CodeSnippetStatement("machine.Call(\"main\");"));
classType.Members.Add(runMethod);
// Compile the file into a DLL
CompilerParameters compparams = new CompilerParameters(new string[] { "mscorlib.dll", "Axiom.Runtime.dll" });
compparams.GenerateInMemory = false;
compparams.GenerateExecutable = true;
compparams.OutputAssembly = compilerParameters.OutputAssembly;
compparams.TempFiles.KeepFiles = true;
Microsoft.CSharp.CSharpCodeProvider csharp = new Microsoft.CSharp.CSharpCodeProvider();
ICodeCompiler cscompiler = csharp.CreateCompiler();
CompilerResults compresult = cscompiler.CompileAssemblyFromDom(compparams, compileUnit);
if (compresult.Errors.Count > 0)
{
foreach (CompilerError err in compresult.Errors)
{
Console.WriteLine(err);
}
return null;
}
return compresult.CompiledAssembly;
}
protected virtual PrologCompilerResults FromFile (PrologCompilerParameters options, string fileName)
{
PrologCompilerResults results = new PrologCompilerResults();
PrologCodeParser parser = new PrologCodeParser();
PrologCodeUnit unit = new PrologCodeUnit();
try
{
StreamReader reader = new StreamReader(fileName);
unit = parser.Parse(reader);
}
catch (FileNotFoundException)
{
results.Errors.Add(new PrologCompilerError("P0008", "Input file not found.", fileName, false, 0, 0));
return results;
}
return FromUnit(options, unit);
}
}
} | 40.829684 | 167 | 0.592694 | [
"MIT"
] | FacticiusVir/prologdotnet | Prolog.Compiler/Framework/PrologCompiler.cs | 16,781 | C# |
using System.IO;
using System.Runtime.Serialization;
using WolvenKit.CR2W.Reflection;
using FastMember;
using static WolvenKit.CR2W.Types.Enums;
namespace WolvenKit.CR2W.Types
{
[DataContract(Namespace = "")]
[REDMeta]
public class BTTaskRotateOnRotateEvent : IBehTreeTask
{
public BTTaskRotateOnRotateEvent(CR2WFile cr2w, CVariable parent, string name) : base(cr2w, parent, name){ }
public static new CVariable Create(CR2WFile cr2w, CVariable parent, string name) => new BTTaskRotateOnRotateEvent(cr2w, parent, name);
public override void Read(BinaryReader file, uint size) => base.Read(file, size);
public override void Write(BinaryWriter file) => base.Write(file);
}
} | 30.956522 | 137 | 0.748596 | [
"MIT"
] | DerinHalil/CP77Tools | CP77.CR2W/Types/W3/RTTIConvert/BTTaskRotateOnRotateEvent.cs | 690 | C# |
/* ****************************************************************************
*
* Copyright (c) Microsoft Corporation.
*
* This source code is subject to terms and conditions of the Apache License, Version 2.0. A
* copy of the license can be found in the License.html file at the root of this distribution. If
* you cannot locate the Apache License, Version 2.0, please send an email to
* [email protected]. By using this source code in any fashion, you are agreeing to be bound
* by the terms of the Apache License, Version 2.0.
*
* You must not remove this notice, or any other, from this software.
*
*
* ***************************************************************************/
#if !CLR2
#else
using Microsoft.Scripting.Ast;
#endif
namespace System.Management.Automation.Interpreter
{
internal interface ILightCallSiteBinder
{
bool AcceptsArgumentArray { get; }
}
}
| 32.464286 | 97 | 0.60066 | [
"MIT"
] | 202006233011/PowerShell | src/System.Management.Automation/engine/interpreter/ILightCallSiteBinder.cs | 909 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.
namespace Microsoft.Azure.PowerShell.Cmdlets.Compute.Models.Api20210701
{
using Microsoft.Azure.PowerShell.Cmdlets.Compute.Runtime.PowerShell;
/// <summary>Describes the properties of a run command parameter.</summary>
[System.ComponentModel.TypeConverter(typeof(RunCommandInputParameterTypeConverter))]
public partial class RunCommandInputParameter
{
/// <summary>
/// <c>AfterDeserializeDictionary</c> will be called after the deserialization has finished, allowing customization of the
/// object before it is returned. Implement this method in a partial class to enable this behavior
/// </summary>
/// <param name="content">The global::System.Collections.IDictionary content that should be used.</param>
partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content);
/// <summary>
/// <c>AfterDeserializePSObject</c> will be called after the deserialization has finished, allowing customization of the object
/// before it is returned. Implement this method in a partial class to enable this behavior
/// </summary>
/// <param name="content">The global::System.Management.Automation.PSObject content that should be used.</param>
partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content);
/// <summary>
/// <c>BeforeDeserializeDictionary</c> will be called before the deserialization has commenced, allowing complete customization
/// of the object before it is deserialized.
/// If you wish to disable the default deserialization entirely, return <c>true</c> in the <see "returnNow" /> output parameter.
/// Implement this method in a partial class to enable this behavior.
/// </summary>
/// <param name="content">The global::System.Collections.IDictionary content that should be used.</param>
/// <param name="returnNow">Determines if the rest of the serialization should be processed, or if the method should return
/// instantly.</param>
partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow);
/// <summary>
/// <c>BeforeDeserializePSObject</c> will be called before the deserialization has commenced, allowing complete customization
/// of the object before it is deserialized.
/// If you wish to disable the default deserialization entirely, return <c>true</c> in the <see "returnNow" /> output parameter.
/// Implement this method in a partial class to enable this behavior.
/// </summary>
/// <param name="content">The global::System.Management.Automation.PSObject content that should be used.</param>
/// <param name="returnNow">Determines if the rest of the serialization should be processed, or if the method should return
/// instantly.</param>
partial void BeforeDeserializePSObject(global::System.Management.Automation.PSObject content, ref bool returnNow);
/// <summary>
/// Deserializes a <see cref="global::System.Collections.IDictionary" /> into an instance of <see cref="Microsoft.Azure.PowerShell.Cmdlets.Compute.Models.Api20210701.RunCommandInputParameter"
/// />.
/// </summary>
/// <param name="content">The global::System.Collections.IDictionary content that should be used.</param>
/// <returns>
/// an instance of <see cref="Microsoft.Azure.PowerShell.Cmdlets.Compute.Models.Api20210701.IRunCommandInputParameter" />.
/// </returns>
public static Microsoft.Azure.PowerShell.Cmdlets.Compute.Models.Api20210701.IRunCommandInputParameter DeserializeFromDictionary(global::System.Collections.IDictionary content)
{
return new RunCommandInputParameter(content);
}
/// <summary>
/// Deserializes a <see cref="global::System.Management.Automation.PSObject" /> into an instance of <see cref="Microsoft.Azure.PowerShell.Cmdlets.Compute.Models.Api20210701.RunCommandInputParameter"
/// />.
/// </summary>
/// <param name="content">The global::System.Management.Automation.PSObject content that should be used.</param>
/// <returns>
/// an instance of <see cref="Microsoft.Azure.PowerShell.Cmdlets.Compute.Models.Api20210701.IRunCommandInputParameter" />.
/// </returns>
public static Microsoft.Azure.PowerShell.Cmdlets.Compute.Models.Api20210701.IRunCommandInputParameter DeserializeFromPSObject(global::System.Management.Automation.PSObject content)
{
return new RunCommandInputParameter(content);
}
/// <summary>
/// Creates a new instance of <see cref="RunCommandInputParameter" />, deserializing the content from a json string.
/// </summary>
/// <param name="jsonText">a string containing a JSON serialized instance of this model.</param>
/// <returns>an instance of the <see cref="className" /> model class.</returns>
public static Microsoft.Azure.PowerShell.Cmdlets.Compute.Models.Api20210701.IRunCommandInputParameter FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.Compute.Runtime.Json.JsonNode.Parse(jsonText));
/// <summary>
/// Deserializes a <see cref="global::System.Collections.IDictionary" /> into a new instance of <see cref="Microsoft.Azure.PowerShell.Cmdlets.Compute.Models.Api20210701.RunCommandInputParameter"
/// />.
/// </summary>
/// <param name="content">The global::System.Collections.IDictionary content that should be used.</param>
internal RunCommandInputParameter(global::System.Collections.IDictionary content)
{
bool returnNow = false;
BeforeDeserializeDictionary(content, ref returnNow);
if (returnNow)
{
return;
}
// actually deserialize
((Microsoft.Azure.PowerShell.Cmdlets.Compute.Models.Api20210701.IRunCommandInputParameterInternal)this).Name = (string) content.GetValueForProperty("Name",((Microsoft.Azure.PowerShell.Cmdlets.Compute.Models.Api20210701.IRunCommandInputParameterInternal)this).Name, global::System.Convert.ToString);
((Microsoft.Azure.PowerShell.Cmdlets.Compute.Models.Api20210701.IRunCommandInputParameterInternal)this).Value = (string) content.GetValueForProperty("Value",((Microsoft.Azure.PowerShell.Cmdlets.Compute.Models.Api20210701.IRunCommandInputParameterInternal)this).Value, global::System.Convert.ToString);
AfterDeserializeDictionary(content);
}
/// <summary>
/// Deserializes a <see cref="global::System.Management.Automation.PSObject" /> into a new instance of <see cref="Microsoft.Azure.PowerShell.Cmdlets.Compute.Models.Api20210701.RunCommandInputParameter"
/// />.
/// </summary>
/// <param name="content">The global::System.Management.Automation.PSObject content that should be used.</param>
internal RunCommandInputParameter(global::System.Management.Automation.PSObject content)
{
bool returnNow = false;
BeforeDeserializePSObject(content, ref returnNow);
if (returnNow)
{
return;
}
// actually deserialize
((Microsoft.Azure.PowerShell.Cmdlets.Compute.Models.Api20210701.IRunCommandInputParameterInternal)this).Name = (string) content.GetValueForProperty("Name",((Microsoft.Azure.PowerShell.Cmdlets.Compute.Models.Api20210701.IRunCommandInputParameterInternal)this).Name, global::System.Convert.ToString);
((Microsoft.Azure.PowerShell.Cmdlets.Compute.Models.Api20210701.IRunCommandInputParameterInternal)this).Value = (string) content.GetValueForProperty("Value",((Microsoft.Azure.PowerShell.Cmdlets.Compute.Models.Api20210701.IRunCommandInputParameterInternal)this).Value, global::System.Convert.ToString);
AfterDeserializePSObject(content);
}
/// <summary>Serializes this instance to a json string.</summary>
/// <returns>a <see cref="System.String" /> containing this model serialized to JSON text.</returns>
public string ToJsonString() => ToJson(null, Microsoft.Azure.PowerShell.Cmdlets.Compute.Runtime.SerializationMode.IncludeAll)?.ToString();
}
/// Describes the properties of a run command parameter.
[System.ComponentModel.TypeConverter(typeof(RunCommandInputParameterTypeConverter))]
public partial interface IRunCommandInputParameter
{
}
} | 65.927536 | 314 | 0.699384 | [
"MIT"
] | Agazoth/azure-powershell | src/Compute/Compute.Autorest/generated/api/Models/Api20210701/RunCommandInputParameter.PowerShell.cs | 8,961 | C# |
using SS14.Client.Graphics.Drawing;
using SS14.Client.Graphics.Overlays;
using SS14.Client.Graphics.Shaders;
using SS14.Client.Interfaces.Graphics.ClientEye;
using SS14.Client.Interfaces.Graphics.Overlays;
using SS14.Shared.IoC;
using SS14.Shared.Maths;
using SS14.Shared.Prototypes;
namespace Content.Client.Graphics.Overlays
{
public class CircleMaskOverlay : Overlay
{
#pragma warning disable 649
[Dependency] private readonly IPrototypeManager _prototypeManager;
[Dependency] private readonly IEyeManager _eyeManager;
#pragma warning restore 649
public override OverlaySpace Space => OverlaySpace.WorldSpace;
public CircleMaskOverlay() : base(nameof(CircleMaskOverlay))
{
IoCManager.InjectDependencies(this);
Shader = _prototypeManager.Index<ShaderPrototype>("circlemask").Instance();
}
protected override void Draw(DrawingHandle handle)
{
var worldHandle = (DrawingHandleWorld)handle;
var viewport = _eyeManager.GetWorldViewport();
worldHandle.DrawRect(viewport, Color.White);
}
}
}
| 32.485714 | 87 | 0.716799 | [
"MIT"
] | praisenarsie/space-station-14-content | Content.Client/Graphics/Overlays/CircleMaskOverlay.cs | 1,139 | C# |
using System.Net.Http;
using System.Net.Http.Formatting;
using System.Threading.Tasks;
using Umbraco.Core.Models;
namespace Umbraco.Core.Persistence.Repositories.Implement
{
internal class InstallationRepository : IInstallationRepository
{
private static HttpClient _httpClient;
private const string RestApiInstallUrl = "https://our.umbraco.com/umbraco/api/Installation/Install";
public async Task SaveInstallLogAsync(InstallLog installLog)
{
try
{
if (_httpClient == null)
_httpClient = new HttpClient();
await _httpClient.PostAsync(RestApiInstallUrl, installLog, new JsonMediaTypeFormatter());
}
// this occurs if the server for Our is down or cannot be reached
catch (HttpRequestException)
{ }
}
}
}
| 30.482759 | 108 | 0.643665 | [
"MIT"
] | AaronSadlerUK/Umbraco-CMS | src/Umbraco.Core/Persistence/Repositories/Implement/InstallationRepository.cs | 886 | C# |
using System.Reflection;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("ReferenceEvaluationAddon")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Swiss Academic Software")]
[assembly: AssemblyProduct("ReferenceEvaluationAddon")]
[assembly: AssemblyCopyright("Copyright © Swiss Academic Software 2017")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("6db1ffe3-cde6-459e-9a60-27acd7ee462b")]
// 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.1.0.0")]
[assembly: AssemblyFileVersion("1.1.0.0")]
| 39.666667 | 84 | 0.751401 | [
"MIT"
] | Citavi/C6-Add-Ons-and-Online-Sources | src/ReferenceEvaluation/Properties/AssemblyInfo.cs | 1,431 | C# |
using System;
using System.Windows.Forms;
namespace Main_RBS
{
internal static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
private static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new frmHome());
}
}
} | 24.210526 | 66 | 0.558696 | [
"MIT"
] | Avinch/RoomBookingSystem | RBS/Main-RBS/Program.cs | 462 | C# |
using System;
using System.Collections.Generic;
using System.Web.Mvc;
using YNDIY.API.Models;
namespace YNDIY.Admin.Controllers
{
/// <summary>
/// 管理员管理商家,面料商,衣服加工厂商
/// </summary>
public class AdminController : ParentController
{
/// <summary>
/// 工厂店铺关系
/// </summary>
/// <returns></returns>
public ActionResult FactoryShopRelation()
{
if (!checkSession())
{
return loginRerirect();
}
//判断是否是管理员账号
int type = Convert.ToInt32(Session["Type"]);
if (type != API.Controllers.ShopUserController.type_0)
{
return View();
}
return View();
}
public ActionResult GetFactoryShopRelation()
{
if (!checkSession())
{
return loginRerirect();
}
//判断是否是管理员账号
int type = Convert.ToInt32(Session["Type"]);
if (type != API.Controllers.ShopUserController.type_0)
{
return View();
}
string searchKey = Request.QueryString["searchKey"];
int searchType = Convert.ToInt32(Request.QueryString["searchType"]);
int pageIndex = 1;
int pageSize = 10;
if (!string.IsNullOrEmpty(Request.QueryString["pageSize"]))
{
pageSize = Convert.ToInt32(Request.QueryString["pageSize"]);
}
if (!string.IsNullOrEmpty(Request.QueryString["pageIndex"]))
{
pageIndex = Convert.ToInt32(Request.QueryString["pageIndex"]);
}
API.Controllers.FactoryShopRelationController factoryShopRelationController = new API.Controllers.FactoryShopRelationController();
List<YNFactoryShopRelation> relationList = factoryShopRelationController.getRelationListByAdmin(searchKey, searchType, pageIndex, pageSize);
int count = factoryShopRelationController.getRelationListByAdminCount(searchKey, searchType);
API.Controllers.PagesController page = new API.Controllers.PagesController();
page.GetPage(pageIndex, count, pageSize);
ViewBag.page = page;
ViewBag.relationList = relationList;
return View();
}
//删除关联
public JsonResult deleteRelation()
{
if (!checkSession())
{
return getLoginJsonMessage(0, "请登陆");
}
//判断是否是管理员账号
int type = Convert.ToInt32(Session["Type"]);
if (type != API.Controllers.ShopUserController.type_0)
{
return getLoginJsonMessage(0, "权限不够");
}
int id = Convert.ToInt32(Request.QueryString["id"]);
API.Controllers.FactoryShopRelationController factoryShopRelationController = new API.Controllers.FactoryShopRelationController();
factoryShopRelationController.Detete(id);
return getLoginJsonMessage(1, "删除成功");
}
//添加关联
public JsonResult addRelation()
{
if (!checkSession())
{
return getLoginJsonMessage(0, "请登陆");
}
//判断是否是管理员账号
int type = Convert.ToInt32(Session["Type"]);
if (type != API.Controllers.ShopUserController.type_0)
{
return getLoginJsonMessage(0, "权限不够");
}
string shopAccount = Request.Form["shopAccount"];
string factoryAccount = Request.Form["factoryAccount"];
API.Controllers.ShopUserController shopUserController = new API.Controllers.ShopUserController();
YNShopUser shopUser = shopUserController.GetUserByAccount(shopAccount);
if (shopUser == null)
{
return getLoginJsonMessage(0, "商家账号不正确");
}
if (shopUser.parent_shop_id != 0)
{
return getLoginJsonMessage(0, "商家账号不是主帐号");
}
API.Controllers.ShopInfoController shopInfoController = new API.Controllers.ShopInfoController();
YNShopInfo yNShopInfo = shopInfoController.GetShopInfoByID(shopUser.shop_id);
if (yNShopInfo == null)
{
return getLoginJsonMessage(0, "商家信息不存在");
}
YNShopUser factoryUser = shopUserController.GetUserByAccount(factoryAccount);
if (factoryUser == null)
{
return getLoginJsonMessage(0, "工厂账号不正确");
}
if (factoryUser.role_type != API.Controllers.ShopUserController.role_type0)
{
return getLoginJsonMessage(0, "工厂账号不是主帐号");
}
API.Controllers.ClothFactoryInfoController clothFactoryInfoController = new API.Controllers.ClothFactoryInfoController();
YNClothFactoryInfo yNClothFactoryInfo = clothFactoryInfoController.GetClothFactoryInfoByID(factoryUser.cloth_factory_id);
if (yNClothFactoryInfo == null)
{
return getLoginJsonMessage(0, "工厂信息不存在");
}
API.Controllers.FactoryShopRelationController factoryShopRelationController = new API.Controllers.FactoryShopRelationController();
if (factoryShopRelationController.checkExist(yNShopInfo.id, yNClothFactoryInfo.id))
{
return getLoginJsonMessage(0, "关联信息已经存在,不能重复添加");
}
YNFactoryShopRelation yNFactoryShopRelation = new YNFactoryShopRelation();
yNFactoryShopRelation.factory_id = yNClothFactoryInfo.id;
yNFactoryShopRelation.factory_user_id = factoryUser.id;
yNFactoryShopRelation.factory_user_account = factoryUser.account;
yNFactoryShopRelation.factory_name = yNClothFactoryInfo.cloth_factory_name;
yNFactoryShopRelation.factory_link_man = yNClothFactoryInfo.link_man;
yNFactoryShopRelation.factory_link_phone = yNClothFactoryInfo.phone;
yNFactoryShopRelation.factory_link_address = yNClothFactoryInfo.address_detail;
yNFactoryShopRelation.shop_id = yNShopInfo.id;
yNFactoryShopRelation.shop_user_id = shopUser.id;
yNFactoryShopRelation.shop_user_account = shopUser.account;
yNFactoryShopRelation.shop_name = yNShopInfo.shop_name;
yNFactoryShopRelation.shop_link_man = yNShopInfo.link_man;
yNFactoryShopRelation.shop_link_phone = yNShopInfo.phone;
yNFactoryShopRelation.shop_link_address = yNShopInfo.address_detail;
yNFactoryShopRelation.create_time = DateTime.Now;
yNFactoryShopRelation.modify_time = DateTime.Now;
factoryShopRelationController.Create(yNFactoryShopRelation);
return getLoginJsonMessage(1, "添加成功");
}
/// <summary>
/// 商家列表
/// </summary>
/// <returns></returns>
public ActionResult shopInfoList()
{
if (!checkSession())
{
return loginRerirect();
}
//判断是否是管理员账号
int type = Convert.ToInt32(Session["Type"]);
if (type != API.Controllers.ShopUserController.type_0)
{
return View();
}
return View();
}
public ActionResult shopInfoListItems()
{
if (!checkSession())
{
return loginRerirect();
}
//判断是否是管理员账号
int type = Convert.ToInt32(Session["Type"]);
if (type != API.Controllers.ShopUserController.type_0)
{
return View();
}
int pageIndex = 1;
int pageSize = 20;
if (!string.IsNullOrEmpty(Request.QueryString["pageIndex"]))
{
pageIndex = Convert.ToInt32(Request.QueryString["pageIndex"]);
}
if (!string.IsNullOrEmpty(Request.QueryString["pageSize"]))
{
pageSize = Convert.ToInt32(Request.QueryString["pageSize"]);
}
string searchKey = Request.QueryString["searchKey"];
API.Controllers.ShopUserController shopUserController = new API.Controllers.ShopUserController();
List<YNShopUser> shopUserList = shopUserController.getShopUserListAdmin(searchKey, API.Controllers.ShopUserController.type_1, pageIndex, pageSize);
int count = shopUserController.getShopUserListAdminCount(searchKey, API.Controllers.ShopUserController.type_1);
API.Controllers.PagesController page = new API.Controllers.PagesController();
page.GetPage(pageIndex, count, pageSize);
ViewBag.shopUserList = shopUserList;
ViewBag.page = page;
return View();
}
/// <summary>
/// 衣服加工厂列表
/// </summary>
/// <returns></returns>
public ActionResult clothFactoryList()
{
if (!checkSession())
{
return loginRerirect();
}
//判断是否是管理员账号
int type = Convert.ToInt32(Session["Type"]);
if (type != API.Controllers.ShopUserController.type_0)
{
return View();
}
return View();
}
public ActionResult clothFactoryListItems()
{
if (!checkSession())
{
return loginRerirect();
}
API.Controllers.PagesController page = new API.Controllers.PagesController();
//判断是否是管理员账号
int type = Convert.ToInt32(Session["Type"]);
if (type != API.Controllers.ShopUserController.type_0)
{
page.GetPage(1, 0, 20);
ViewBag.shopUserList = new List<YNShopUser> ();
ViewBag.page = page;
return View();
}
int pageIndex = 1;
int pageSize = 20;
if (!string.IsNullOrEmpty(Request.QueryString["pageIndex"]))
{
pageIndex = Convert.ToInt32(Request.QueryString["pageIndex"]);
}
if (!string.IsNullOrEmpty(Request.QueryString["pageSize"]))
{
pageSize = Convert.ToInt32(Request.QueryString["pageSize"]);
}
string searchKey = Request.QueryString["searchKey"];
API.Controllers.ShopUserController shopUserController = new API.Controllers.ShopUserController();
List<YNShopUser> shopUserList = shopUserController.getShopUserListAdmin(searchKey, API.Controllers.ShopUserController.type_3, pageIndex, pageSize);
int count = shopUserController.getShopUserListAdminCount(searchKey, API.Controllers.ShopUserController.type_3);
//API.Controllers.PagesController page = new API.Controllers.PagesController();
page.GetPage(pageIndex, count, pageSize);
ViewBag.shopUserList = shopUserList;
ViewBag.page = page;
return View();
}
/// <summary>
/// 面料厂商列表
/// </summary>
/// <returns></returns>
public ActionResult fabricFactoryList()
{
if (!checkSession())
{
return loginRerirect();
}
//判断是否是管理员账号
int type = Convert.ToInt32(Session["Type"]);
if (type != API.Controllers.ShopUserController.type_0)
{
return View();
}
return View();
}
public ActionResult fabricFactoryListItems()
{
if (!checkSession())
{
return loginRerirect();
}
//判断是否是管理员账号
int type = Convert.ToInt32(Session["Type"]);
if (type != API.Controllers.ShopUserController.type_0)
{
return View();
}
int pageIndex = 1;
int pageSize = 20;
if (!string.IsNullOrEmpty(Request.QueryString["pageIndex"]))
{
pageIndex = Convert.ToInt32(Request.QueryString["pageIndex"]);
}
if (!string.IsNullOrEmpty(Request.QueryString["pageSize"]))
{
pageSize = Convert.ToInt32(Request.QueryString["pageSize"]);
}
string searchKey = Request.QueryString["searchKey"];
API.Controllers.ShopUserController shopUserController = new API.Controllers.ShopUserController();
List<YNShopUser> shopUserList = shopUserController.getShopUserListAdmin(searchKey, API.Controllers.ShopUserController.type_2, pageIndex, pageSize);
int count = shopUserController.getShopUserListAdminCount(searchKey, API.Controllers.ShopUserController.type_2);
API.Controllers.PagesController page = new API.Controllers.PagesController();
page.GetPage(pageIndex, count, pageSize);
ViewBag.shopUserList = shopUserList;
ViewBag.page = page;
return View();
}
/// <summary>
/// 根据id获取商家或者工厂信息
/// </summary>
/// <returns></returns>
public JsonResult getShopUserById()
{
if (!checkSession())
{
return getLoginJsonMessage(0,"请登陆");
}
//判断是否是管理员账号
int type = Convert.ToInt32(Session["Type"]);
if (type != API.Controllers.ShopUserController.type_0)
{
return getLoginJsonMessage(0, "不是管理员账号,不能操作");
}
int userId = Convert.ToInt32(Request.QueryString["userId"]);
API.Controllers.ShopUserController shopUserController = new API.Controllers.ShopUserController();
YNShopUser yNShopUser = shopUserController.GetUserByID(userId);
if (yNShopUser == null)
{
return getLoginJsonMessage(0, "参数错误");
}
if (!string.IsNullOrEmpty(yNShopUser.r_p_d))
{
yNShopUser.password = API.Controllers.EncryptionController.DESPWDecrypt(yNShopUser.r_p_d);
}
else
{
yNShopUser.password = "";
}
return getDataJsonMessage(1, "成功", yNShopUser);
}
/// <summary>
/// 根据id删除工厂或者面料商的信息
/// </summary>
/// <returns></returns>
public JsonResult deleteShopUser()
{
if (!checkSession())
{
return getLoginJsonMessage(0, "请登陆");
}
//判断是否是管理员账号
int type = Convert.ToInt32(Session["Type"]);
if (type != API.Controllers.ShopUserController.type_0)
{
return getLoginJsonMessage(0, "不是管理员账号,不能操作");
}
int userId = Convert.ToInt32(Request.QueryString["userId"]);
API.Controllers.ShopUserController shopUserController = new API.Controllers.ShopUserController();
YNShopUser yNShopUser = shopUserController.GetUserByID(userId);
if (yNShopUser == null)
{
return getLoginJsonMessage(0, "参数错误");
}
//商家
if (yNShopUser.type == API.Controllers.ShopUserController.type_1)
{
API.Controllers.ShopInfoController shopInfoController = new API.Controllers.ShopInfoController();
shopInfoController.Delete(yNShopUser.shop_id);
shopUserController.Delete(yNShopUser);
}
//面料商
else if (yNShopUser.type == API.Controllers.ShopUserController.type_2)
{
//API.Controllers.FabricFactoryInfoController fabricFactoryInfoController = new API.Controllers.FabricFactoryInfoController();
//fabricFactoryInfoController.Delete(yNShopUser.fabric_factory_id);
//shopUserController.Delete(yNShopUser);
}
//衣服加工厂
else if (yNShopUser.type == API.Controllers.ShopUserController.type_3)
{
API.Controllers.ClothFactoryInfoController clothFactoryInfoController = new API.Controllers.ClothFactoryInfoController();
clothFactoryInfoController.Delete(yNShopUser.cloth_factory_id);
shopUserController.Delete(yNShopUser);
}
return getLoginJsonMessage(1, "删除成功");
}
/// <summary>
/// 保存或者新增商家和厂家信息
/// </summary>
/// <returns></returns>
public JsonResult saveShopUser()
{
if (!checkSession())
{
return getLoginJsonMessage(0, "请登陆");
}
//判断是否是管理员账号
int type = Convert.ToInt32(Session["Type"]);
if (type != API.Controllers.ShopUserController.type_0)
{
return getLoginJsonMessage(0, "不是管理员账号,不能操作");
}
string userIdStr = Request.Form["userId"];
int userId = 0;
if(!string.IsNullOrEmpty(userIdStr)){
userId = Convert.ToInt32(userIdStr);
}
API.Controllers.ShopUserController shopUserController = new API.Controllers.ShopUserController();
API.Controllers.ShopInfoController shopInfoController = new API.Controllers.ShopInfoController();
//API.Controllers.FabricFactoryInfoController fabricFactoryInfoController = new API.Controllers.FabricFactoryInfoController();
API.Controllers.ClothFactoryInfoController clothFactoryInfoController = new API.Controllers.ClothFactoryInfoController();
YNShopUser yNShopUser = new YNShopUser();
if (userId != 0)
{
yNShopUser = shopUserController.GetUserByID(userId);
if (yNShopUser == null)
{
return getLoginJsonMessage(0, "参数错误");
}
}
yNShopUser.account = Request.Form["account"];
yNShopUser.phone = Request.Form["phone"];
yNShopUser.password = Request.Form["password"];
if (string.IsNullOrEmpty(yNShopUser.account) || string.IsNullOrEmpty(yNShopUser.password))
{
return getLoginJsonMessage(0, "账号和密码不能为空");
}
if (userId != 0)
{
if (shopUserController.GetUserByAccountPhoneExists(yNShopUser.account, yNShopUser.phone,userId))
{
return getLoginJsonMessage(0, "账号和电话不能重复,请重新设置账号");
}
}
else
{
if (shopUserController.GetUserByAccountPhoneExists(yNShopUser.account, yNShopUser.phone))
{
return getLoginJsonMessage(0, "账号和电话不能重复,请重新设置账号");
}
}
yNShopUser.r_p_d = API.Controllers.EncryptionController.DESPWEncrypt(yNShopUser.password);
yNShopUser.password = API.Controllers.EncryptionController.MD5(yNShopUser.password + API.Controllers.TokenController.DIYToken);
yNShopUser.email = Request.Form["email"];
yNShopUser.link_man = Request.Form["link_man"];
//yNShopUser.pisition = Request.Form["pisition"];
//yNShopUser.nick_name = Request.Form["nick_name"];
//yNShopUser.job_number = Request.Form["job_number"];
yNShopUser.type = Convert.ToInt32(Request.Form["type"]);
yNShopUser.role_type = API.Controllers.ShopUserController.role_type0;
yNShopUser.status = API.Controllers.ShopUserController.status_0;
//商家
if (yNShopUser.type == API.Controllers.ShopUserController.type_1)
{
yNShopUser.shop_name = Request.Form["shop_name"];
}
//面料供应商
else if (yNShopUser.type == API.Controllers.ShopUserController.type_2)
{
yNShopUser.fabric_factory_name = Request.Form["fabric_factory_name"];
}
//衣服加工厂
else if (yNShopUser.type == API.Controllers.ShopUserController.type_3)
{
yNShopUser.cloth_factory_name = Request.Form["cloth_factory_name"];
}
if (userId != 0)
{
yNShopUser.modify_time = DateTime.Now;
shopUserController.SaveChanges();
return getLoginJsonMessage(1, "保存成功");
}
else
{
yNShopUser.create_time = DateTime.Now;
yNShopUser.modify_time = DateTime.Now;
//商家
if (yNShopUser.type == API.Controllers.ShopUserController.type_1)
{
YNShopInfo yNShopInfo = new YNShopInfo();
yNShopInfo.shop_name = yNShopUser.shop_name;
yNShopInfo.link_man = yNShopUser.link_man;
yNShopInfo.phone = yNShopUser.phone;
yNShopInfo.email = yNShopUser.email;
yNShopInfo.parent_shop_id = 0;
yNShopInfo.status = API.Controllers.ShopInfoController.status_0;
yNShopInfo.create_time = DateTime.Now;
yNShopInfo.modify_time = DateTime.Now;
//添加商家信息
shopInfoController.Create(yNShopInfo);
yNShopUser.shop_id = yNShopInfo.id;
shopUserController.Create(yNShopUser);
return getLoginJsonMessage(1, "添加商家信息成功");
}
//面料供应商
else if (yNShopUser.type == API.Controllers.ShopUserController.type_2)
{
//YNFabricFactoryInfo yNFabricFactoryInfo = new YNFabricFactoryInfo();
//yNFabricFactoryInfo.shop_id = 0;
//yNFabricFactoryInfo.fabric_factory_name = yNShopUser.fabric_factory_name;
//yNFabricFactoryInfo.link_man = yNShopUser.link_man;
//yNFabricFactoryInfo.phone = yNShopUser.phone;
//yNFabricFactoryInfo.email = yNShopUser.email;
//yNFabricFactoryInfo.status = API.Controllers.FabricFactoryInfoController.status_0;
//yNFabricFactoryInfo.type = API.Controllers.FabricFactoryInfoController.type_1;
//yNFabricFactoryInfo.show_state = API.Controllers.FabricFactoryInfoController.show_state0;
//yNFabricFactoryInfo.create_time = DateTime.Now;
//yNFabricFactoryInfo.modify_time = DateTime.Now;
////添加面料商信息
//fabricFactoryInfoController.Create(yNFabricFactoryInfo);
//yNShopUser.fabric_factory_id = yNFabricFactoryInfo.id;
//shopUserController.Create(yNShopUser);
return getLoginJsonMessage(1, "添加面料商信息成功");
}
//衣服加工厂
else if (yNShopUser.type == API.Controllers.ShopUserController.type_3)
{
YNClothFactoryInfo yNClothFactoryInfo = new YNClothFactoryInfo();
yNClothFactoryInfo.shop_id = 0;
yNClothFactoryInfo.cloth_factory_name = yNShopUser.cloth_factory_name;
yNClothFactoryInfo.link_man = yNShopUser.link_man;
yNClothFactoryInfo.phone = yNShopUser.phone;
yNClothFactoryInfo.email = yNShopUser.email;
yNClothFactoryInfo.status = API.Controllers.ClothFactoryInfoController.status_0;
yNClothFactoryInfo.type = API.Controllers.ClothFactoryInfoController.type_1;
yNClothFactoryInfo.show_state = API.Controllers.ClothFactoryInfoController.show_state0;
yNClothFactoryInfo.create_time = DateTime.Now;
yNClothFactoryInfo.modify_time = DateTime.Now;
//添加工厂信息
clothFactoryInfoController.Create(yNClothFactoryInfo);
yNShopUser.cloth_factory_id = yNClothFactoryInfo.id;
shopUserController.Create(yNShopUser);
//新建自己为系统客户
YNShopInfo yNShopInfo = new YNShopInfo();
yNShopInfo.cloth_factory_id = yNClothFactoryInfo.id;
yNShopInfo.shop_name = yNShopUser.cloth_factory_name;
yNShopInfo.link_man = yNShopUser.link_man;
yNShopInfo.phone = yNShopUser.phone;
yNShopInfo.email = yNShopUser.email;
yNShopInfo.parent_shop_id = 0;
yNShopInfo.status = API.Controllers.ShopInfoController.status_0;
yNShopInfo.type = API.Controllers.ShopInfoController.type_1;
yNShopInfo.create_time = DateTime.Now;
yNShopInfo.modify_time = DateTime.Now;
//添加商家信息
shopInfoController.Create(yNShopInfo);
return getLoginJsonMessage(1, "添加衣服加工厂信息成功");
}
else
{
return getLoginJsonMessage(0, "参数错误");
}
}
}
}
}
| 45.229947 | 159 | 0.57417 | [
"MIT"
] | hqqshe/JIAJU | YNDIY.Admin/Controllers/AdminController.cs | 26,398 | C# |
using System;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;
using NSubstitute;
using Sentry.Extensibility;
using Sentry.Protocol;
using Sentry.Testing;
using Xunit;
using static Sentry.Internal.Constants;
using static Sentry.Protocol.Constants;
using static Sentry.DsnSamples;
namespace Sentry.Tests
{
[Collection(nameof(SentrySdkCollection))]
public class SentrySdkTests : SentrySdkTestFixture
{
[Fact]
public void IsEnabled_StartsOfFalse()
{
Assert.False(SentrySdk.IsEnabled);
}
[Fact]
public void LastEventId_StartsOfFalse()
{
Assert.Equal(default, SentrySdk.LastEventId);
}
[Fact]
public void LastEventId_SetToEventId()
{
EnvironmentVariableGuard.WithVariable(
DsnEnvironmentVariable,
ValidDsnWithSecret,
() =>
{
using (SentrySdk.Init())
{
var id = SentrySdk.CaptureMessage("test");
Assert.Equal(id, SentrySdk.LastEventId);
}
});
}
[Fact]
public void Init_BrokenDsn_Throws()
{
_ = Assert.Throws<UriFormatException>(() => SentrySdk.Init("invalid stuff"));
}
[Fact]
public void Init_ValidDsnWithSecret_EnablesSdk()
{
using (SentrySdk.Init(ValidDsnWithSecret))
Assert.True(SentrySdk.IsEnabled);
}
[Fact]
public void Init_ValidDsnWithoutSecret_EnablesSdk()
{
using (SentrySdk.Init(ValidDsnWithoutSecret))
Assert.True(SentrySdk.IsEnabled);
}
[Fact]
public void Init_DsnInstance_EnablesSdk()
{
var dsn = new Dsn(ValidDsnWithoutSecret);
using (SentrySdk.Init(dsn))
Assert.True(SentrySdk.IsEnabled);
}
[Fact]
public void Init_CallbackWithoutDsn_ValidDsnEnvironmentVariable_LocatesDsnEnvironmentVariable()
{
EnvironmentVariableGuard.WithVariable(
DsnEnvironmentVariable,
ValidDsnWithSecret,
() =>
{
using (SentrySdk.Init(c => { }))
Assert.True(SentrySdk.IsEnabled);
});
}
[Fact]
public void Init_CallbackWithoutDsn_InvalidDsnEnvironmentVariable_DisabledSdk()
{
EnvironmentVariableGuard.WithVariable(
DsnEnvironmentVariable,
InvalidDsn,
() =>
{
using (SentrySdk.Init(c => { }))
Assert.False(SentrySdk.IsEnabled);
});
}
[Fact]
public void Init_ValidDsnEnvironmentVariable_EnablesSdk()
{
EnvironmentVariableGuard.WithVariable(
DsnEnvironmentVariable,
ValidDsnWithSecret,
() =>
{
using (SentrySdk.Init())
Assert.True(SentrySdk.IsEnabled);
});
}
[Fact]
public void Init_InvalidDsnEnvironmentVariable_Throws()
{
EnvironmentVariableGuard.WithVariable(
DsnEnvironmentVariable,
// If the variable was set, to non empty string but value is broken, better crash than silently disable
InvalidDsn,
() =>
{
var ex = Assert.Throws<ArgumentException>(() => SentrySdk.Init());
Assert.Equal("Invalid DSN: A Project Id is required.", ex.Message);
});
}
[Fact]
public void Init_DisableDsnEnvironmentVariable_DisablesSdk()
{
EnvironmentVariableGuard.WithVariable(
DsnEnvironmentVariable,
DisableSdkDsnValue,
() =>
{
using (SentrySdk.Init())
Assert.False(SentrySdk.IsEnabled);
});
}
[Fact]
public void Init_EmptyDsn_DisabledSdk()
{
using (SentrySdk.Init(string.Empty))
Assert.False(SentrySdk.IsEnabled);
}
[Fact]
public void Init_EmptyDsn_LogsWarning()
{
var logger = Substitute.For<IDiagnosticLogger>();
_ = logger.IsEnabled(SentryLevel.Warning).Returns(true);
var options = new SentryOptions
{
DiagnosticLogger = logger,
Debug = true
};
using (SentrySdk.Init(options))
{
logger.Received(1).Log(SentryLevel.Warning, "Init was called but no DSN was provided nor located. Sentry SDK will be disabled.");
}
}
[Fact]
public void Init_EmptyDsnDisabledDiagnostics_DoesNotLogWarning()
{
var logger = Substitute.For<IDiagnosticLogger>();
_ = logger.IsEnabled(SentryLevel.Warning).Returns(true);
var options = new SentryOptions
{
DiagnosticLogger = logger,
Debug = false,
};
using (SentrySdk.Init(options))
{
logger.DidNotReceive().Log(Arg.Any<SentryLevel>(), Arg.Any<string>());
}
}
[Fact]
public void Init_MultipleCalls_ReplacesHubWithLatest()
{
var first = SentrySdk.Init(ValidDsnWithSecret);
SentrySdk.AddBreadcrumb("test", "category");
var called = false;
SentrySdk.ConfigureScope(p =>
{
called = true;
_ = Assert.Single(p.Breadcrumbs);
});
Assert.True(called);
called = false;
var second = SentrySdk.Init(ValidDsnWithSecret);
SentrySdk.ConfigureScope(p =>
{
called = true;
Assert.Empty(p.Breadcrumbs);
});
Assert.True(called);
first.Dispose();
second.Dispose();
}
[Fact]
public void Disposable_MultipleCalls_NoOp()
{
var disposable = SentrySdk.Init();
disposable.Dispose();
disposable.Dispose();
Assert.False(SentrySdk.IsEnabled);
}
[Fact]
public void Dispose_DisposingFirst_DoesntAffectSecond()
{
var first = SentrySdk.Init(ValidDsnWithSecret);
var second = SentrySdk.Init(ValidDsnWithSecret);
SentrySdk.AddBreadcrumb("test", "category");
first.Dispose();
var called = false;
SentrySdk.ConfigureScope(p =>
{
called = true;
_ = Assert.Single(p.Breadcrumbs);
});
Assert.True(called);
second.Dispose();
}
[Fact]
public Task FlushAsync_NotInit_NoOp() => SentrySdk.FlushAsync(TimeSpan.FromDays(1));
[Fact]
public void PushScope_InstanceOf_DisabledClient()
{
Assert.Same(DisabledHub.Instance, SentrySdk.PushScope());
}
[Fact]
public void PushScope_NullArgument_NoOp()
{
var scopeGuard = SentrySdk.PushScope(null as object);
Assert.False(SentrySdk.IsEnabled);
scopeGuard.Dispose();
}
[Fact]
public void PushScope_Parameterless_NoOp()
{
var scopeGuard = SentrySdk.PushScope();
Assert.False(SentrySdk.IsEnabled);
scopeGuard.Dispose();
}
[Fact]
public void PushScope_MultiCallState_SameDisposableInstance()
{
var state = new object();
Assert.Same(SentrySdk.PushScope(state), SentrySdk.PushScope(state));
}
[Fact]
public void PushScope_MultiCallParameterless_SameDisposableInstance() => Assert.Same(SentrySdk.PushScope(), SentrySdk.PushScope());
[Fact]
public void AddBreadcrumb_NoClock_NoOp() => SentrySdk.AddBreadcrumb(message: null);
[Fact]
public void AddBreadcrumb_WithClock_NoOp() => SentrySdk.AddBreadcrumb(clock: null, null);
[Fact]
public void ConfigureScope_Sync_CallbackNeverInvoked()
{
var invoked = false;
SentrySdk.ConfigureScope(_ => invoked = true);
Assert.False(invoked);
}
[Fact]
public async Task ConfigureScope_OnTask_PropagatedToCaller()
{
const string expected = "test";
using (SentrySdk.Init(ValidDsnWithoutSecret))
{
await ModifyScope();
string actual = null;
SentrySdk.ConfigureScope(s => actual = s.Breadcrumbs.First().Message);
Assert.Equal(expected, actual);
async Task ModifyScope()
{
await Task.Yield();
SentrySdk.AddBreadcrumb(expected);
}
}
}
[Fact]
public void WithScope_DisabledSdk_CallbackNeverInvoked()
{
var invoked = false;
SentrySdk.WithScope(_ => invoked = true);
Assert.False(invoked);
}
[Fact]
public void WithScope_InvokedWithNewScope()
{
using (SentrySdk.Init(ValidDsnWithoutSecret))
{
Scope expected = null;
SentrySdk.ConfigureScope(s => expected = s);
Scope actual = null;
SentrySdk.WithScope(s => actual = s);
Assert.NotNull(actual);
Assert.NotSame(expected, actual);
SentrySdk.ConfigureScope(s => Assert.Same(expected, s));
}
}
[Fact]
public async Task ConfigureScope_Async_CallbackNeverInvoked()
{
var invoked = false;
await SentrySdk.ConfigureScopeAsync(_ =>
{
invoked = true;
return Task.CompletedTask;
});
Assert.False(invoked);
}
[Fact]
public void CaptureEvent_Instance_NoOp() => SentrySdk.CaptureEvent(new SentryEvent());
[Fact]
public void CaptureException_Instance_NoOp() => SentrySdk.CaptureException(new Exception());
[Fact]
public void CaptureMessage_Message_NoOp() => SentrySdk.CaptureMessage("message");
[Fact]
public void CaptureMessage_MessageLevel_NoOp() => SentrySdk.CaptureMessage("message", SentryLevel.Debug);
[Fact]
public void CaptureMessage_SdkInitialized_IncludesScope()
{
var worker = Substitute.For<IBackgroundWorker>();
const string expected = "test";
using (SentrySdk.Init(o =>
{
o.Dsn = Valid;
o.BackgroundWorker = worker;
}))
{
SentrySdk.AddBreadcrumb(expected);
_ = SentrySdk.CaptureMessage("message");
_ = worker.EnqueueEvent(Arg.Is<SentryEvent>(e => e.Breadcrumbs.Single().Message == expected));
}
}
[Fact]
public void Implements_Client()
{
var clientMembers = typeof(ISentryClient).GetMembers(BindingFlags.Public | BindingFlags.Instance);
var sentrySdk = typeof(SentrySdk).GetMembers(BindingFlags.Public | BindingFlags.Static);
Assert.Empty(clientMembers.Select(m => m.ToString()).Except(sentrySdk.Select(m => m.ToString())));
}
[Fact]
public void Implements_ClientExtensions()
{
var clientExtensions = typeof(SentryClientExtensions).GetMembers(BindingFlags.Public | BindingFlags.Static)
// Remove the extension argument: Method(this ISentryClient client, ...
.Select(m => m.ToString().Replace($"({typeof(ISentryClient).FullName}, ", "("));
var sentrySdk = typeof(SentrySdk).GetMembers(BindingFlags.Public | BindingFlags.Static);
Assert.Empty(clientExtensions.Except(sentrySdk.Select(m => m.ToString())));
}
[Fact]
public void Implements_ScopeManagement()
{
var scopeManagement = typeof(ISentryScopeManager).GetMembers(BindingFlags.Public | BindingFlags.Instance);
var sentrySdk = typeof(SentrySdk).GetMembers(BindingFlags.Public | BindingFlags.Static);
Assert.Empty(scopeManagement.Select(m => m.ToString()).Except(sentrySdk.Select(m => m.ToString())));
}
}
}
| 31.762376 | 145 | 0.543875 | [
"MIT"
] | lucas-zimerman/sentry-dotnet-xamsample | test/Sentry.Tests/SentrySdkTests.cs | 12,832 | C# |
#if NETFX_CORE
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Documents;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Media.Imaging;
using Windows.UI.Xaml.Shapes;
#else
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
#endif
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NeuroSpeech.UIAtoms.Core;
using NeuroSpeech.UIAtoms.Expressions;
namespace NeuroSpeech.UIAtoms.Controls
{
/// <summary>
///
/// </summary>
public partial class AtomCalculator : Control
{
private AtomLogicContext valueContext = new AtomLogicContext();
#region partial void OnAfterValueChanged(DependencyPropertyChangedEventArgs e)
partial void OnAfterValueChanged(DependencyPropertyChangedEventArgs e)
{
valueContext.PreventRecursive(() =>
{
// clear everything..
Clear();
if (PART_Value != null)
{
PART_Value.Text = Value.ToString();
}
});
if (ValueChanged != null)
{
ValueChanged(this, e);
}
}
#endregion
/// <summary>
///
/// </summary>
public void Clear()
{
// resets...
if (PART_Value != null)
{
PART_Value.Text = "";
}
AppendMode = true;
CurrentExpression = null;
LastEntry = null;
LastAction = null;
LastValue = null;
ExpressionHistory = "";
}
#region Buttons and Value
private TextBox PART_Value;
private Button PART_BKSP;
private Button PART_Clear;
private Button PART_ClearEntry;
private Button PART_PosNeg;
private Button PART_Root;
private Button PART_Seven;
private Button PART_Eight;
private Button PART_Nine;
private Button PART_Division;
private Button PART_Modulo;
private Button PART_Four;
private Button PART_Five;
private Button PART_Six;
private Button PART_Mul;
private Button PART_OnebyX;
private Button PART_One;
private Button PART_Two;
private Button PART_Three;
private Button PART_Minus;
private Button PART_Zero;
private Button PART_Zero2;
private Button PART_Dot;
private Button PART_Plus;
private Button PART_Equal;
#endregion
#region partial void OnAfterTemplateApplied()
partial void OnAfterTemplateApplied()
{
PART_BKSP = (Button)GetTemplateChild("PART_BackSpace");
PART_Clear = (Button)GetTemplateChild("PART_Clear");
PART_ClearEntry = (Button)GetTemplateChild("PART_ClearEntry");
PART_PosNeg = (Button)GetTemplateChild("PART_PosNeg");
PART_Root = (Button)GetTemplateChild("PART_Root");
PART_Seven = (Button)GetTemplateChild("PART_Seven");
PART_Eight = (Button)GetTemplateChild("PART_Eight");
PART_Nine = (Button)GetTemplateChild("PART_Nine");
PART_Division = (Button)GetTemplateChild("PART_Division");
PART_Modulo = (Button)GetTemplateChild("PART_Modulo");
PART_Four = (Button)GetTemplateChild("PART_Four");
PART_Five = (Button)GetTemplateChild("PART_Five");
PART_Six = (Button)GetTemplateChild("PART_Six");
PART_Mul = (Button)GetTemplateChild("PART_Mul");
PART_OnebyX = (Button)GetTemplateChild("PART_OnebyX");
PART_One = (Button)GetTemplateChild("PART_One");
PART_Two = (Button)GetTemplateChild("PART_Two");
PART_Three = (Button)GetTemplateChild("PART_Three");
PART_Minus = (Button)GetTemplateChild("PART_Minus");
PART_Zero = (Button)GetTemplateChild("PART_Zero");
PART_Zero2 = (Button)GetTemplateChild("PART_Zero2");
PART_Dot = (Button)GetTemplateChild("PART_Dot");
PART_Plus = (Button)GetTemplateChild("PART_Plus");
PART_Equal = (Button)GetTemplateChild("PART_Equal");
PART_Value = (TextBox)GetTemplateChild("PART_Value");
if (Value != 0)
{
PART_Value.Text = Value.ToString();
}
SetupEvents();
}
#endregion
/// <summary>
///
/// </summary>
#region SetupEvents
private void SetupEvents()
{
PART_Zero.Click += new RoutedEventHandler(ContentButton_Click);
PART_Zero2.Click += new RoutedEventHandler(ContentButton_Click);
PART_One.Click += new RoutedEventHandler(ContentButton_Click);
PART_Two.Click += new RoutedEventHandler(ContentButton_Click);
PART_Three.Click += new RoutedEventHandler(ContentButton_Click);
PART_Four.Click += new RoutedEventHandler(ContentButton_Click);
PART_Five.Click += new RoutedEventHandler(ContentButton_Click);
PART_Six.Click += new RoutedEventHandler(ContentButton_Click);
PART_Seven.Click += new RoutedEventHandler(ContentButton_Click);
PART_Eight.Click += new RoutedEventHandler(ContentButton_Click);
PART_Nine.Click += new RoutedEventHandler(ContentButton_Click);
PART_Dot.Click += new RoutedEventHandler(ContentButton_Click);
PART_Minus.Click += new RoutedEventHandler(PART_Minus_Click);
PART_Plus.Click += new RoutedEventHandler(PART_Plus_Click);
PART_Division.Click += new RoutedEventHandler(PART_Division_Click);
PART_Modulo.Click += new RoutedEventHandler(PART_Modulo_Click);
PART_Mul.Click += new RoutedEventHandler(PART_Mul_Click);
PART_Root.Click += new RoutedEventHandler(PART_Root_Click);
PART_OnebyX.Click += new RoutedEventHandler(PART_OnebyX_Click);
PART_PosNeg.Click += new RoutedEventHandler(PART_PosNeg_Click);
PART_Equal.Click += new RoutedEventHandler(PART_Equal_Click);
PART_BKSP.Click += new RoutedEventHandler(PART_BKSP_Click);
PART_Clear.Click += new RoutedEventHandler(PART_Clear_Click);
PART_ClearEntry.Click += new RoutedEventHandler(PART_ClearEntry_Click);
PART_Value.TextChanged += new TextChangedEventHandler(PART_Value_TextChanged);
}
#endregion
void PART_Value_TextChanged(object sender, TextChangedEventArgs e)
{
//SaveValue();
}
void PART_ClearEntry_Click(object sender, RoutedEventArgs e)
{
PART_Value.Text = "";
AppendMode = true;
}
void PART_Clear_Click(object sender, RoutedEventArgs e)
{
Clear();
}
void PART_BKSP_Click(object sender, RoutedEventArgs e)
{
if (AppendMode)
{
string txt = PART_Value.Text;
if (txt.Length > 0)
{
PART_Value.Text = txt.Substring(0, txt.Length - 1);
}
else
{
AtomUtils.Beep();
}
}
}
void PART_Equal_Click(object sender, RoutedEventArgs e)
{
SaveValue();
}
private void SaveValue()
{
PerformOperation(false, null);
valueContext.PreventRecursive(() =>
{
this.Value = decimal.Parse(PART_Value.Text);
});
}
void PART_PosNeg_Click(object sender, RoutedEventArgs e)
{
PerformOperation(true, (x, y) => MathDecimalExpression.Neg(x));
}
void PART_OnebyX_Click(object sender, RoutedEventArgs e)
{
PerformOperation(true, (x, y) => MathDecimalExpression.Reciproc(x));
}
void PART_Root_Click(object sender, RoutedEventArgs e)
{
PerformOperation(true, (x, y) => MathDecimalExpression.Sqrt(x));
}
void PART_Mul_Click(object sender, RoutedEventArgs e)
{
PerformOperation(false, (x, y) => MathDecimalExpression.Mul(x, y));
}
void PART_Modulo_Click(object sender, RoutedEventArgs e)
{
BeforePerform();
if (CurrentExpression != null) {
BinaryMathExpression<decimal> be = CurrentExpression as BinaryMathExpression<decimal>;
if (be != null)
{
decimal right = LastEntry.Invoke();
decimal left = be.Left.Invoke();
right = (left * right) / (decimal)100;
PART_Value.Text = right.ToString();
}
}
}
void PART_Division_Click(object sender, RoutedEventArgs e)
{
PerformOperation(false, (x, y) => MathDecimalExpression.Div(x, y));
}
void PART_Plus_Click(object sender, RoutedEventArgs e)
{
PerformOperation(false, (x, y) => MathDecimalExpression.Add(x, y));
}
void PART_Minus_Click(object sender, RoutedEventArgs e)
{
PerformOperation(false, (x,y) => MathDecimalExpression.Sub(x,y));
}
private BaseMathExpression<decimal> CurrentExpression = null;
private BaseMathExpression<decimal> LastEntry = null;
private BaseMathExpression<decimal> LastValue = null;
private InvokeOperationDelegate LastAction = null;
private void PerformOperation(bool unary, InvokeOperationDelegate action)
{
try
{
BeforePerform();
if (action == null)
{
if (!unary)
{
PerformCalculation(action);
ExpressionHistory = "";
}
}
else
{
if (unary)
{
PerformUnary(action);
}
else
{
PerformBinary(action);
}
// update expression history
ExpressionHistory = CurrentExpression.ToString();
}
}
catch (Exception ex) {
MessageBox.Show(ex.Message, "Invalid Input", MessageBoxButton.OK);
}
// enable editing...
AppendMode = false;
}
/// <summary>
/// Executed when "=" sign is pressed
/// </summary>
/// <param name="action"></param>
private void PerformCalculation(InvokeOperationDelegate action)
{
BinaryMathExpression<decimal> be = CurrentExpression as BinaryMathExpression<decimal>;
if (be == null)
{
if (LastValue == null)
return;
BaseMathExpression<decimal> value = LastAction(LastValue, LastEntry);
LastValue = value.ValueExpression;
}
else
{
be.Right = LastEntry;
// calculate
LastValue = be.ValueExpression;
}
CurrentExpression = LastValue;
PART_Value.Text = LastValue.Invoke().ToString();
}
/// <summary>
///
/// </summary>
/// <param name="action"></param>
private void PerformBinary(InvokeOperationDelegate action)
{
BinaryMathExpression<decimal> be = CurrentExpression as BinaryMathExpression<decimal>;
LastAction = action;
// nothing was entered, just change the sign..
if (!AppendMode)
{
if (be != null)
{
CurrentExpression = (BinaryMathExpression<decimal>)action(be.Left, null);
return;
}
}
if (be == null)
{
CurrentExpression = (BinaryMathExpression<decimal>)LastAction(LastValue ?? LastEntry, null);
}
else
{
be.Right = LastValue ?? LastEntry;
CurrentExpression = (BinaryMathExpression<decimal>)LastAction(CurrentExpression, null);
PART_Value.Text = be.Invoke().ToString();
}
}
private void PerformUnary(InvokeOperationDelegate action)
{
if (LastValue != null)
{
LastValue = action(LastValue, null);
PART_Value.Text = LastValue.Invoke().ToString();
CurrentExpression = LastValue;
}
else
{
LastEntry = action(LastEntry, null);
PART_Value.Text = LastEntry.Invoke().ToString();
}
}
private void BeforePerform()
{
if (AppendMode) {
// something was edited...
LastEntry = new ConstantMathExpression<decimal>(decimal.Parse(PART_Value.Text));
if (CurrentExpression == null) {
CurrentExpression = LastEntry;
}
LastValue = null;
}
}
private delegate BaseMathExpression<decimal> InvokeOperationDelegate(BaseMathExpression<decimal> lastExp , BaseMathExpression<decimal> curOp);
private void ContentButton_Click(object sender, RoutedEventArgs e)
{
Button b = (Button)sender;
string txt = b.Content as string;
AppendContent(txt);
}
private bool AppendMode = true;
private void AppendContent(string txt)
{
string txtValue = "";
if (AppendMode)
{
txtValue = PART_Value.Text;
}
AppendMode = true;
txtValue += txt;
decimal val = 0;
if (decimal.TryParse(txtValue, out val))
{
PART_Value.Text = txtValue;
}
else
{
AtomUtils.Beep();
}
}
/// <summary>
///
/// </summary>
/// <param name="e"></param>
#region Keyboard Bindings
protected override void OnKeyUp(KeyEventArgs e)
{
base.OnKeyUp(e);
switch (e.Key)
{
case Key.D0:
case Key.NumPad0:
AppendContent("0");
break;
case Key.D1:
case Key.NumPad1:
AppendContent("1");
break;
case Key.D2:
case Key.NumPad2:
AppendContent("2");
break;
case Key.D3:
case Key.NumPad3:
AppendContent("3");
break;
case Key.D4:
case Key.NumPad4:
AppendContent("4");
break;
case Key.D5:
case Key.NumPad5:
AppendContent("5");
break;
case Key.D6:
case Key.NumPad6:
AppendContent("6");
break;
case Key.D7:
case Key.NumPad7:
AppendContent("7");
break;
case Key.D8:
case Key.NumPad8:
AppendContent("8");
break;
case Key.D9:
case Key.NumPad9:
AppendContent("9");
break;
case Key.Delete:
PART_ClearEntry_Click(null, null);
break;
case Key.Escape:
PART_Clear_Click(null, null);
break;
case Key.Back:
PART_BKSP_Click(null, null);
break;
case Key.Multiply:
PART_Mul_Click(null, null);
break;
case Key.Enter:
PART_Equal_Click(null, null);
break;
case Key.F9:
PART_PosNeg_Click(null, null);
break;
case Key.R:
PART_OnebyX_Click(null, null);
break;
case Key.D:
PART_Modulo_Click(null, null);
break;
case Key.Divide:
PART_Division_Click(null, null);
break;
case Key.Add:
PART_Plus_Click(null, null);
break;
case Key.Subtract:
PART_Minus_Click(null, null);
break;
}
}
#endregion
}
}
| 28.714286 | 150 | 0.532807 | [
"MIT"
] | neurospeech/ui-atoms-wpf-silverlight | MAIN/Source/WPF/Controls/Calculator/AtomCalculator.cs | 17,085 | C# |
using System.Collections.Generic;
using System.Linq;
using Denik.DQEmulation.Repository;
using UniRx;
using UnityEngine;
namespace Denik.DQEmulation.Service
{
[RequireComponent(typeof(AudioSource))]
public class BGMPlayer : MonoBehaviour, IBGMPlayer
{
private AudioSource _audioSource;
private readonly Dictionary<string, int> _NameToIndex = new Dictionary<string, int>();
private int _CurrentAudioIndex = -1;
private IBGMRepository _bgmRepository;
public IReadOnlyReactiveProperty<float> Volume => _volume;
private IReadOnlyReactiveProperty<float> _volume;
[Zenject.Inject]
[VContainer.Inject]
public void Construct(IBGMRepository bgmRepository)
{
_bgmRepository = bgmRepository;
TryGetComponent(out _audioSource);
_audioSource.Stop();
(_audioSource.mute, _audioSource.playOnAwake, _audioSource.loop, _audioSource.volume)
= (false, false, true, _bgmRepository.Volume);
for (var i = 0; i < _bgmRepository.BGMEntities.Count; i++)
{
var audioName = _bgmRepository.BGMEntities[i].Name;
_NameToIndex.Add(audioName, i);
}
_volume = _audioSource.ObserveEveryValueChanged(x => x.volume).ToReactiveProperty();
}
public void Play(string audioName)
{
if (!_NameToIndex.ContainsKey(audioName))
{
Debug.LogError("Unable to play because a non-existent audio name was specified.", this);
}
Play(_NameToIndex[audioName]);
}
public void Play(int audioIndex = 0)
{
PlayInternal(audioIndex);
}
public void Stop()
{
_audioSource.Stop();
}
public void AdjustVolume(float volumeRate)
{
_audioSource.volume = volumeRate;
}
private void PlayInternal(int audioIndex = 0)
{
if (!_bgmRepository.BGMEntities.Any())
{
Debug.LogError("Unable to play because no audio entity is set.", this);
return;
}
if (audioIndex < 0 || _bgmRepository.BGMEntities.Count <= audioIndex)
{
Debug.LogError("Unable to play because a non-existent index number was specified.", this);
}
if (audioIndex == _CurrentAudioIndex)
{
if (!_audioSource.isPlaying)
{
_audioSource.Play();
}
}
else
{
var clip = _bgmRepository.BGMEntities[audioIndex].Clip;
if(_audioSource.isPlaying) _audioSource.Stop();
_audioSource.clip = clip;
_audioSource.Play();
_CurrentAudioIndex = audioIndex;
}
}
}
} | 30.770833 | 106 | 0.565335 | [
"MIT"
] | shiena/Three-Sacred-Treasures-Hands-on | Assets/DQEmulation/Scripts/00_Domain/Service/BGMPlayer.cs | 2,954 | C# |
namespace Remact.Net.Bms1Serializer.Internal
{
using System;
using System.IO;
using System.Collections.Generic;
internal class InternalReader : IBms1InternalReader, IMessageReader
{
internal BinaryReader Stream; // set by TestSerializer for testing purpose.
private TagReader _tagReader;
public InternalReader()
{
_tagReader = new TagReader();
}
// returns false, when EndOfBlock or EndOfMessage == true after reading next tag
public bool ReadNextTag()
{
_tagReader.ClearAttributes();
while (_tagReader.TagEnum == Bms1Tag.Attribute)
{
_tagReader.ReadTag(Stream);
}
if (_tagReader.TagSetNumber != 0)
{
_tagReader.TagEnum = Bms1Tag.UnknownValue;
}
// block or value tag and its attributes are read, data is available for read
if (_tagReader.TagEnum == Bms1Tag.MessageFooter || _tagReader.TagEnum == Bms1Tag.MessageEnd)
{
EndOfMessage = true;
if (BlockNestingLevel != 0)
{
EndOfBlock = true;
BlockNestingLevel = 0;
throw new Bms1Exception("wrong block nesting at end of message: " + BlockNestingLevel);
}
}
if (EndOfMessage)
{
EndOfBlock = true;
}
else
{
if (_tagReader.TagEnum == Bms1Tag.BlockEnd)
{
BlockNestingLevel--;
EndOfBlock = true;
}
else
{
if (_tagReader.TagEnum == Bms1Tag.BlockStart)
{
BlockNestingLevel++;
}
EndOfBlock = false;
}
}
return !EndOfBlock;
}
#region IBms1MessageReader Members
// returns attributes of next message block
public IBms1InternalReader ReadMessageStart(BinaryReader binaryReader)
{
Stream = binaryReader;
while (true)
{
EndOfMessage = false;
EndOfBlock = false;
BlockNestingLevel = 0;
if (_tagReader.TagEnum != Bms1Tag.MessageStart)
{
_tagReader.SkipData(Stream);
ReadNextTag();
}
if (_tagReader.TagEnum == Bms1Tag.MessageStart)
{
if (ReadNextTag() && _tagReader.TagEnum == Bms1Tag.BlockStart)
{
return this; // valid message- and block start
}
}
}// while
}
// returns null (default(T)), when not read because: readMessageDto==null (message is skipped)
public T ReadMessage<T>(IBms1Reader reader, Func<IBms1Reader, T> readMessageDto) where T : new()
{
if (EndOfBlock || _tagReader.TagEnum != Bms1Tag.BlockStart || BlockNestingLevel != 1)
{
throw new Bms1Exception("stream is not at start of message");
}
T dto = readMessageDto(reader);
while (_tagReader.TagEnum != Bms1Tag.MessageEnd && _tagReader.TagEnum != Bms1Tag.MessageStart)
{
// unknown blocks or values at end of message or resynchronization
_tagReader.SkipData(Stream);
ReadNextTag();
}
return dto;
}
// returns null (default(T)), when not read because: EndOfBlock, EndOfMessage, readDto==null (block is skipped)
public T ReadBlock<T>(Func<T> readDto)
{
T dto = default(T);
if (EndOfBlock)
{
return dto; // null, when object
}
var thisBlockLevel = BlockNestingLevel;
Bms1Exception exception = null;
try
{
if (_tagReader.TagEnum == Bms1Tag.Null)
{
ReadNextTag(); // get attributes of next value
return dto; // null, when object
}
if (_tagReader.TagEnum != Bms1Tag.BlockStart)
{
throw new Bms1Exception("stream is not at start of block");
}
ReadNextTag(); // get attributes of first value
if (readDto != null)
{
dto = readDto(); // call the user code to create and deserialize the data transfer object
}
}
finally
{
while (!BlockFinished(thisBlockLevel))
{
// skip unknown blocks or values at end of block or resynchronize
_tagReader.SkipData(Stream);
ReadNextTag();
}
if (!EndOfMessage)
{
var endOfBlockLevel = BlockNestingLevel + 1;
if (endOfBlockLevel != thisBlockLevel)
{
BlockNestingLevel = 0;
throw new Bms1Exception(
"wrong block nesting = " + endOfBlockLevel + " at end of block level: " + thisBlockLevel,
exception);
}
if (_tagReader.TagEnum != Bms1Tag.BlockEnd)
{
throw new Bms1Exception("no correct block end after block level: " + thisBlockLevel, exception);
}
ReadNextTag(); // get attributes of next value
}
}
return dto;
}
private bool BlockFinished(int blockLevel)
{
if (_tagReader.TagEnum == Bms1Tag.MessageEnd || _tagReader.TagEnum == Bms1Tag.MessageStart)
{
EndOfMessage = true;
return true;
}
return BlockNestingLevel < blockLevel && (_tagReader.TagEnum == Bms1Tag.BlockEnd || _tagReader.TagEnum == Bms1Tag.BlockStart);
}
#endregion
#region IBms1InternalReader Members
public void ReadAttributes()
{
if (!EndOfBlock)
{
ReadNextTag();
}
}
public bool IsCollection
{
get { return _tagReader.CollectionElementCount != Bms1Length.None; }
}
// -1 = no collection, -2 = collection until end of block (not a predefined length)
public int CollectionElementCount
{
get { return _tagReader.CollectionElementCount; }
}
public Bms1Tag TagEnum
{
get { return _tagReader.TagEnum; }
}
public bool IsSingleValueOfType(Bms1Tag tag)
{
return !EndOfBlock && _tagReader.TagEnum == tag && !_tagReader.IsArrayData;
}
public bool IsCharacterType
{
get { return _tagReader.IsCharacterType; }
}
public int BlockTypeId
{
get { return _tagReader.BlockTypeId; }
}
public int BlockNestingLevel
{
get; private set;
}
public string ObjectType
{
get { return _tagReader.ObjectType; }
}
public string ObjectName
{
get { return _tagReader.ObjectName; }
}
public List<string> NameValueAttributes
{
get { return _tagReader.NameValues; }
}
public List<string> NamespaceAttributes
{
get { return _tagReader.Namespaces; }
}
public bool EndOfMessage
{
get; private set;
}
public bool EndOfBlock
{
get; private set;
}
public bool IsArrayData
{
get { return _tagReader.IsArrayData; }
}
public int DataLength
{
get { return _tagReader.DataLength; }
}
public void SkipData()
{
_tagReader.SkipData(Stream);
}
public string ReadDataString()
{
return _tagReader.ReadDataString(Stream);
}
public uint ReadDataUInt()
{
return _tagReader.ReadDataUInt(Stream);
}
public Bms1Exception Bms1Exception(string message)
{
var attr = string.Empty;
if (EndOfBlock)
{
attr += "EndOfBlock";
}
if (IsCollection)
{
attr += " Collection["+ _tagReader.CollectionElementCount+"]";
}
if (IsArrayData) // attribute coded in the LengthSpecifier
{
attr += " Array";
}
if (IsCharacterType)
{
attr += " Char";
}
return new Bms1Exception(string.Format("{0} @ Type={1}, Tag={2}({3}.{4}), Len={5}, Attr='{6}'", message, _tagReader.BlockTypeId, _tagReader.TagEnum, _tagReader.TagByte, _tagReader.TagSetNumber, _tagReader.DataLength, attr));
}
#endregion
}
}
| 30.695925 | 237 | 0.468852 | [
"MIT"
] | steforster/Remact.Net.Bms1Serializer | src/Remact.Net.Bms1Serializer/Internal/InternalReader.cs | 9,476 | C# |
namespace Lucene.Net.Benchmarks.ByTask.Stats
{
/*
* 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.
*/
/// <summary>
/// Textual report of current statistics.
/// </summary>
public class Report
{
private string text;
private int size;
private int outOf;
private int reported;
public Report(string text, int size, int reported, int outOf)
{
this.text = text;
this.size = size;
this.reported = reported;
this.outOf = outOf;
}
/// <summary>
/// Gets total number of stats points when this report was created.
/// </summary>
public virtual int OutOf => outOf;
/// <summary>
/// Gets number of lines in the report.
/// </summary>
public virtual int Count => size;
/// <summary>
/// Gets the report text.
/// </summary>
public virtual string Text => text;
/// <summary>
/// Gets number of stats points represented in this report.
/// </summary>
public virtual int Reported => reported;
}
}
| 33.169492 | 79 | 0.607052 | [
"Apache-2.0"
] | Ref12/lucenenet | src/Lucene.Net.Benchmark/ByTask/Stats/Report.cs | 1,959 | C# |
using System;
using System.Linq;
using System.Security.Claims;
using System.Security.Principal;
using KinaUna.Data.Models;
namespace KinaUnaWeb.Services
{
public class IdentityParser : IIdentityParser<ApplicationUser>
{
public ApplicationUser Parse(IPrincipal principal)
{
// Pattern matching 'is' expression
// assigns "claims" if "principal" is a "ClaimsPrincipal"
if (principal is ClaimsPrincipal claims)
{
var joinDateParse =
DateTime.TryParse(claims.Claims.FirstOrDefault(x => x.Type == "joindate")?.Value ?? "",
out var joinDateValue);
if (!joinDateParse)
{
joinDateValue = DateTime.Now;
}
return new ApplicationUser
{
FirstName = claims.Claims.FirstOrDefault(x => x.Type == "firstname")?.Value ?? "",
MiddleName = claims.Claims.FirstOrDefault(x => x.Type == "middlename")?.Value ?? "",
LastName = claims.Claims.FirstOrDefault(x => x.Type == "lastname")?.Value ?? "",
ViewChild = int.Parse(claims.Claims.FirstOrDefault(x => x.Type == "viewchild")?.Value ?? "0"),
TimeZone = claims.Claims.FirstOrDefault(x => x.Type == "timezone")?.Value ?? "",
JoinDate = joinDateValue,
Email = claims.Claims.FirstOrDefault(x => x.Type == "email")?.Value ?? "",
Id = claims.Claims.FirstOrDefault(x => x.Type == "sub")?.Value ?? "",
UserName = claims.Claims.FirstOrDefault(x => x.Type == "preferred_username")?.Value ?? "",
PhoneNumber = claims.Claims.FirstOrDefault(x => x.Type == "phone_number")?.Value ?? "",
};
}
throw new ArgumentException(message: "The principal must be a ClaimsPrincipal", paramName: nameof(principal));
}
}
}
| 46.136364 | 122 | 0.539409 | [
"MIT"
] | KinaUna/KinaUnaCom | KinaUnaWeb/Services/IdentityParser.cs | 2,032 | C# |
#if UNITY_EDITOR || UNITY_ANDROID
using System;
using System.Runtime.InteropServices;
using UnityEngine.Experimental.Input.Plugins.Android.LowLevel;
using UnityEngine.Experimental.Input.Utilities;
using UnityEngine.Experimental.Input.Controls;
using UnityEngine.Experimental.Input.Layouts;
using UnityEngine.Experimental.Input.Processors;
namespace UnityEngine.Experimental.Input.Plugins.Android.LowLevel
{
public enum AndroidSensorType
{
Accelerometer = 1,
MagneticField = 2,
Orientation = 3, // Was deprecated in API 8 https://developer.android.com/reference/android/hardware/Sensor#TYPE_ORIENTATION
Gyroscope = 4,
Light = 5,
Pressure = 6,
Temperature = 7, // Was deprecated in API 14 https://developer.android.com/reference/android/hardware/Sensor#TYPE_TEMPERATURE
Proximity = 8,
Gravity = 9,
LinearAcceleration = 10,
RotationVector = 11,
RelativeHumidity = 12,
AmbientTemperature = 13,
MagneticFieldUncalibrated = 14,
GameRotationVector = 15,
GyroscopeUncalibrated = 16,
SignificantMotion = 17,
StepDetector = 18,
StepCounter = 19,
GeomagneticRotationVector = 20,
HeartRate = 21,
Pose6DOF = 28,
StationaryDetect = 29,
MotionDetect = 30,
HeartBeat = 31,
LowLatencyOffBodyDetect = 34,
AccelerometerUncalibrated = 35,
}
[Serializable]
public struct AndroidSensorCapabilities
{
public AndroidSensorType sensorType;
public string ToJson()
{
return JsonUtility.ToJson(this);
}
public static AndroidSensorCapabilities FromJson(string json)
{
if (json == null)
throw new ArgumentNullException("json");
return JsonUtility.FromJson<AndroidSensorCapabilities>(json);
}
public override string ToString()
{
return string.Format("type = {0}", sensorType.ToString());
}
}
[StructLayout(LayoutKind.Sequential)]
public unsafe struct AndroidSensorState : IInputStateTypeInfo
{
public static FourCC kFormat = new FourCC('A', 'S', 'S', ' ');
////FIXME: Sensors to check if values matches old system
// Accelerometer - OK
// MagneticField - no alternative in old system
// Gyroscope - OK
// Light - no alternative in old system
// Pressure - no alternative in old system
// Proximity - no alternative in old system
// Gravity - OK
// LinearAcceleration - need to check
// RotationVector - OK
// RelativeHumidity - no alternative in old system
// AmbientTemperature - no alternative in old system
// StepCounter - no alternative in old system
// GeomagneticRotationVector - no alternative in old system
// HeartRate - no alternative in old system
[InputControl(name = "acceleration", layout = "Vector3", processors = "AndroidCompensateDirection", variants = "Accelerometer")]
[InputControl(name = "magneticField", layout = "Vector3", variants = "MagneticField")]
// Note: Using CompensateDirection instead of AndroidCompensateDirection, because we don't need to normalize velocity
[InputControl(name = "angularVelocity", layout = "Vector3", processors = "CompensateDirection", variants = "Gyroscope")]
[InputControl(name = "lightLevel", layout = "Axis", variants = "Light")]
[InputControl(name = "atmosphericPressure", layout = "Axis", variants = "Pressure")]
[InputControl(name = "distance", layout = "Axis", variants = "Proximity")]
[InputControl(name = "gravity", layout = "Vector3", processors = "AndroidCompensateDirection", variants = "Gravity")]
[InputControl(name = "acceleration", layout = "Vector3", processors = "AndroidCompensateDirection", variants = "LinearAcceleration")]
[InputControl(name = "attitude", layout = "Quaternion", processors = "AndroidCompensateRotation", variants = "RotationVector")]
[InputControl(name = "relativeHumidity", layout = "Axis", variants = "RelativeHumidity")]
[InputControl(name = "ambientTemperature", layout = "Axis", variants = "AmbientTemperature")]
[InputControl(name = "stepCounter", layout = "Integer", variants = "StepCounter")]
[InputControl(name = "rotation", layout = "Quaternion", processors = "AndroidCompensateRotation", variants = "GeomagneticRotationVector")]
[InputControl(name = "rate", layout = "Axis", variants = "HeartRate")]
public fixed float data[16];
public AndroidSensorState WithData(params float[] data)
{
fixed(float* dataPtr = this.data)
{
for (var i = 0; i < data.Length && i < 16; i++)
dataPtr[i] = data[i];
// Fill the rest with zeroes
for (var i = data.Length; i < 16; i++)
dataPtr[i] = 0.0f;
}
return this;
}
public FourCC GetFormat()
{
return kFormat;
}
}
public class AndroidCompensateDirectionProcessor : CompensateDirectionProcessor
{
// Taken from platforms\android-<API>\arch-arm\usr\include\android\sensor.h
private const float kSensorStandardGravity = 9.80665f;
private const float kAccelerationMultiplier = -1.0f / kSensorStandardGravity;
public override Vector3 Process(Vector3 vector, InputControl<Vector3> control)
{
return base.Process(vector * kAccelerationMultiplier, control);
}
}
public class AndroidCompensateRotationProcessor : CompensateRotationProcessor
{
public override Quaternion Process(Quaternion value, InputControl<Quaternion> control)
{
// https://developer.android.com/reference/android/hardware/SensorEvent#values
// "...The rotation vector represents the orientation of the device as a combination of an angle and an axis, in which the device has rotated through an angle theta around an axis <x, y, z>."
// "...The three elements of the rotation vector are < x * sin(theta / 2), y* sin(theta / 2), z* sin(theta / 2)>, such that the magnitude of the rotation vector is equal to sin(theta / 2), and the direction of the rotation vector is equal to the direction of the axis of rotation."
// "...The three elements of the rotation vector are equal to the last three components of a unit quaternion < cos(theta / 2), x* sin(theta/ 2), y* sin(theta / 2), z* sin(theta/ 2)>."
//
// In other words, axis + rotation is combined into Vector3, to recover the quaternion from it, we must compute 4th component as 1 - sqrt(x*x + y*y + z*z)
var sinRho2 = value.x * value.x + value.y * value.y + value.z * value.z;
value.w = (sinRho2 < 1.0f) ? Mathf.Sqrt(1.0f - sinRho2) : 0.0f;
return base.Process(value, control);
}
}
}
namespace UnityEngine.Experimental.Input.Plugins.Android
{
[InputControlLayout(stateType = typeof(AndroidSensorState), variants = "Accelerometer")]
public class AndroidAccelerometer : Accelerometer
{
}
[InputControlLayout(stateType = typeof(AndroidSensorState), variants = "MagneticField")]
public class AndroidMagneticField : Sensor
{
/// <summary>
/// All values are in micro-Tesla (uT) and measure the ambient magnetic field in the X, Y and Z axis.
/// </summary>
public Vector3Control magneticField { get; private set; }
protected override void FinishSetup(InputDeviceBuilder builder)
{
magneticField = builder.GetControl<Vector3Control>("magneticField");
base.FinishSetup(builder);
}
}
[InputControlLayout(stateType = typeof(AndroidSensorState), variants = "Gyroscope")]
public class AndroidGyroscope : Gyroscope
{
}
[InputControlLayout(stateType = typeof(AndroidSensorState), variants = "Light")]
public class AndroidLight : Sensor
{
/// <summary>
/// Light level in SI lux units
/// </summary>
public AxisControl lightLevel { get; private set; }
protected override void FinishSetup(InputDeviceBuilder builder)
{
lightLevel = builder.GetControl<AxisControl>("lightLevel");
base.FinishSetup(builder);
}
}
[InputControlLayout(stateType = typeof(AndroidSensorState), variants = "Pressure")]
public class AndroidPressure : Sensor
{
/// <summary>
/// Atmospheric pressure in hPa (millibar)
/// </summary>
public AxisControl atmosphericPressure { get; private set; }
protected override void FinishSetup(InputDeviceBuilder builder)
{
atmosphericPressure = builder.GetControl<AxisControl>("atmosphericPressure");
base.FinishSetup(builder);
}
}
[InputControlLayout(stateType = typeof(AndroidSensorState), variants = "Proximity")]
public class AndroidProximity : Sensor
{
/// <summary>
/// Proximity sensor distance measured in centimeters
/// </summary>
public AxisControl distance { get; private set; }
protected override void FinishSetup(InputDeviceBuilder builder)
{
distance = builder.GetControl<AxisControl>("distance");
base.FinishSetup(builder);
}
}
[InputControlLayout(stateType = typeof(AndroidSensorState), variants = "Gravity")]
public class AndroidGravity : Gravity
{
}
[InputControlLayout(stateType = typeof(AndroidSensorState), variants = "LinearAcceleration")]
public class AndroidLinearAcceleration : LinearAcceleration
{
}
[InputControlLayout(stateType = typeof(AndroidSensorState), variants = "RotationVector")]
public class AndroidRotationVector : Attitude
{
}
[InputControlLayout(stateType = typeof(AndroidSensorState), variants = "RelativeHumidity")]
public class AndroidRelativeHumidity : Sensor
{
/// <summary>
/// Relative ambient air humidity in percent
/// </summary>
public AxisControl relativeHumidity { get; private set; }
protected override void FinishSetup(InputDeviceBuilder builder)
{
relativeHumidity = builder.GetControl<AxisControl>("relativeHumidity");
base.FinishSetup(builder);
}
}
[InputControlLayout(stateType = typeof(AndroidSensorState), variants = "AmbientTemperature")]
public class AndroidAmbientTemperature : Sensor
{
/// <summary>
/// Ambient (room) temperature in degree Celsius.
/// </summary>
public AxisControl ambientTemperature { get; private set; }
protected override void FinishSetup(InputDeviceBuilder builder)
{
ambientTemperature = builder.GetControl<AxisControl>("ambientTemperature");
base.FinishSetup(builder);
}
}
[InputControlLayout(stateType = typeof(AndroidSensorState), variants = "StepCounter")]
public class AndroidStepCounter : Sensor
{
/// <summary>
/// The number of steps taken by the user since the last reboot while activated.
/// </summary>
public IntegerControl stepCounter { get; private set; }
protected override void FinishSetup(InputDeviceBuilder builder)
{
stepCounter = builder.GetControl<IntegerControl>("stepCounter");
base.FinishSetup(builder);
}
}
}
#endif
| 40.437931 | 293 | 0.645519 | [
"MIT"
] | ToadsworthLP/Millenium | Library/PackageCache/[email protected]/InputSystem/Plugins/Android/AndroidSensors.cs | 11,727 | C# |
/*
* Copyright 2007 ZXing authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
namespace ZXing.Common
{
/// <summary> Implementations of this class can, given locations of finder patterns for a QR code in an
/// image, sample the right points in the image to reconstruct the QR code, accounting for
/// perspective distortion. It is abstracted since it is relatively expensive and should be allowed
/// to take advantage of platform-specific optimized implementations, like Sun's Java Advanced
/// Imaging library, but which may not be available in other environments such as J2ME, and vice
/// versa.
///
/// The implementation used can be controlled by calling {@link #setGridSampler(GridSampler)}
/// with an instance of a class which implements this interface.
/// </summary>
/// <author> Sean Owen</author>
public abstract class GridSampler
{
/// <returns> the current implementation of <see cref="GridSampler"/>
/// </returns>
public static GridSampler Instance
{
get
{
return gridSampler;
}
}
private static GridSampler gridSampler = new DefaultGridSampler();
/// <summary> Sets the implementation of <see cref="GridSampler"/> used by the library. One global
/// instance is stored, which may sound problematic. But, the implementation provided
/// ought to be appropriate for the entire platform, and all uses of this library
/// in the whole lifetime of the JVM. For instance, an Android activity can swap in
/// an implementation that takes advantage of native platform libraries.
/// </summary>
/// <param name="newGridSampler">The platform-specific object to install.</param>
public static void setGridSampler(GridSampler newGridSampler)
{
if (newGridSampler == null)
{
throw new System.ArgumentException();
}
gridSampler = newGridSampler;
}
/// <summary>
/// <p>Samples an image for a square matrix of bits of the given dimension. This is used to extract
/// the black/white modules of a 2D barcode like a QR Code found in an image. Because this barcode
/// may be rotated or perspective-distorted, the caller supplies four points in the source image
/// that define known points in the barcode, so that the image may be sampled appropriately.</p>
/// <p>The last eight "from" parameters are four X/Y coordinate pairs of locations of points in
/// the image that define some significant points in the image to be sample. For example,
/// these may be the location of finder pattern in a QR Code.</p>
/// <p>The first eight "to" parameters are four X/Y coordinate pairs measured in the destination
/// <see cref="BitMatrix"/>, from the top left, where the known points in the image given by the "from"
/// parameters map to.</p>
/// <p>These 16 parameters define the transformation needed to sample the image.</p>
/// </summary>
/// <param name="image">image to sample</param>
/// <param name="dimensionX">The dimension X.</param>
/// <param name="dimensionY">The dimension Y.</param>
/// <param name="p1ToX">The p1 preimage X.</param>
/// <param name="p1ToY">The p1 preimage Y.</param>
/// <param name="p2ToX">The p2 preimage X.</param>
/// <param name="p2ToY">The p2 preimage Y.</param>
/// <param name="p3ToX">The p3 preimage X.</param>
/// <param name="p3ToY">The p3 preimage Y.</param>
/// <param name="p4ToX">The p4 preimage X.</param>
/// <param name="p4ToY">The p4 preimage Y.</param>
/// <param name="p1FromX">The p1 image X.</param>
/// <param name="p1FromY">The p1 image Y.</param>
/// <param name="p2FromX">The p2 image X.</param>
/// <param name="p2FromY">The p2 image Y.</param>
/// <param name="p3FromX">The p3 image X.</param>
/// <param name="p3FromY">The p3 image Y.</param>
/// <param name="p4FromX">The p4 image X.</param>
/// <param name="p4FromY">The p4 image Y.</param>
/// <returns>
/// <see cref="BitMatrix"/> representing a grid of points sampled from the image within a region
/// defined by the "from" parameters
/// </returns>
/// <throws> ReaderException if image can't be sampled, for example, if the transformation defined </throws>
public abstract BitMatrix sampleGrid(BitMatrix image, int dimensionX, int dimensionY, float p1ToX, float p1ToY, float p2ToX, float p2ToY, float p3ToX, float p3ToY, float p4ToX, float p4ToY, float p1FromX, float p1FromY, float p2FromX, float p2FromY, float p3FromX, float p3FromY, float p4FromX, float p4FromY);
/// <summary>
///
/// </summary>
/// <param name="image"></param>
/// <param name="dimensionX"></param>
/// <param name="dimensionY"></param>
/// <param name="transform"></param>
/// <returns></returns>
public virtual BitMatrix sampleGrid(BitMatrix image, int dimensionX, int dimensionY, PerspectiveTransform transform)
{
throw new System.NotSupportedException();
}
/// <summary> <p>Checks a set of points that have been transformed to sample points on an image against
/// the image's dimensions to see if the point are even within the image.</p>
///
/// <p>This method will actually "nudge" the endpoints back onto the image if they are found to be
/// barely (less than 1 pixel) off the image. This accounts for imperfect detection of finder
/// patterns in an image where the QR Code runs all the way to the image border.</p>
///
/// <p>For efficiency, the method will check points from either end of the line until one is found
/// to be within the image. Because the set of points are assumed to be linear, this is valid.</p>
///
/// </summary>
/// <param name="image">image into which the points should map
/// </param>
/// <param name="points">actual points in x1,y1,...,xn,yn form
/// </param>
protected internal static bool checkAndNudgePoints(BitMatrix image, float[] points)
{
int width = image.Width;
int height = image.Height;
// Check and nudge points from start until we see some that are OK:
bool nudged = true;
int maxOffset = points.Length - 1; // points.length must be even
for (int offset = 0; offset < maxOffset && nudged; offset += 2)
{
int x = (int)points[offset];
int y = (int)points[offset + 1];
if (x < -1 || x > width || y < -1 || y > height)
{
return false;
}
nudged = false;
if (x == -1)
{
points[offset] = 0.0f;
nudged = true;
}
else if (x == width)
{
points[offset] = width - 1;
nudged = true;
}
if (y == -1)
{
points[offset + 1] = 0.0f;
nudged = true;
}
else if (y == height)
{
points[offset + 1] = height - 1;
nudged = true;
}
}
// Check and nudge points from end:
nudged = true;
for (int offset = points.Length - 2; offset >= 0 && nudged; offset -= 2)
{
//UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'"
int x = (int)points[offset];
//UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'"
int y = (int)points[offset + 1];
if (x < -1 || x > width || y < -1 || y > height)
{
return false;
}
nudged = false;
if (x == -1)
{
points[offset] = 0.0f;
nudged = true;
}
else if (x == width)
{
points[offset] = width - 1;
nudged = true;
}
if (y == -1)
{
points[offset + 1] = 0.0f;
nudged = true;
}
else if (y == height)
{
points[offset + 1] = height - 1;
nudged = true;
}
}
return true;
}
}
}
| 47.590244 | 318 | 0.565088 | [
"MIT"
] | SpacePassport/unity-algorand-sdk | Runtime/zxing.unity/Source/lib/common/GridSampler.cs | 9,756 | C# |
using System;
using Autofac;
using GitTrends.Shared;
using Shiny.Notifications;
namespace GitTrends
{
public static class ContainerService
{
readonly static Lazy<IContainer> _containerHolder = new Lazy<IContainer>(CreateContainer);
public static IContainer Container => _containerHolder.Value;
static IContainer CreateContainer()
{
var builder = new ContainerBuilder();
//Register Services
builder.RegisterType<AnalyticsService>().AsSelf().SingleInstance();
builder.RegisterType<AzureFunctionsApiService>().AsSelf().SingleInstance();
builder.RegisterType<BackgroundFetchService>().AsSelf().SingleInstance();
builder.RegisterType<DeepLinkingService>().AsSelf().SingleInstance();
builder.RegisterType<GitHubApiV3Service>().AsSelf().SingleInstance();
builder.RegisterType<GitHubAuthenticationService>().AsSelf().SingleInstance();
builder.RegisterType<GitHubGraphQLApiService>().AsSelf().SingleInstance();
builder.RegisterType<NotificationService>().AsSelf().SingleInstance();
builder.RegisterType<RepositoryDatabase>().AsSelf().SingleInstance();
builder.RegisterType<ReviewService>().AsSelf().SingleInstance();
builder.RegisterType<SortingService>().AsSelf().SingleInstance();
builder.RegisterType<SyncFusionService>().AsSelf().SingleInstance();
builder.RegisterType<TrendsChartSettingsService>().AsSelf().SingleInstance();
#if !AppStore
builder.RegisterType<UITestBackdoorService>().AsSelf().SingleInstance();
#endif
//Register ViewModels
builder.RegisterType<ReferringSitesViewModel>().AsSelf();
builder.RegisterType<RepositoryViewModel>().AsSelf();
builder.RegisterType<SettingsViewModel>().AsSelf();
builder.RegisterType<SplashScreenViewModel>().AsSelf();
builder.RegisterType<TrendsViewModel>().AsSelf();
//Register Pages
builder.RegisterType<ReferringSitesPage>().AsSelf().WithParameter(new TypedParameter(typeof(Repository), nameof(Repository).ToLower()));
builder.RegisterType<RepositoryPage>().AsSelf();
builder.RegisterType<SettingsPage>().AsSelf();
builder.RegisterType<SplashScreenPage>().AsSelf();
builder.RegisterType<TrendsPage>().AsSelf().WithParameter(new TypedParameter(typeof(Repository), nameof(Repository).ToLower()));
return builder.Build();
}
}
}
| 47.703704 | 148 | 0.68323 | [
"MIT"
] | GillCleeren/GitTrends | GitTrends/Services/ContainerService.cs | 2,578 | C# |
singleton Material(TerrainFX_ter_sand_bumpy_01)
{
mapTo = "ter_sand_bumpy_01_B";
footstepSoundId = "1";
terrainMaterials = "1";
ShowDust = "1";
showFootprints = "1";
materialTag0 = "Terrain_Sand";
specularPower[0] = "1";
effectColor[0] = "0.803922 0.780392 0.635294 1";
effectColor[1] = "0.843137 0.780392 0.454902 0.349";
impactSoundId = "0";
};
new TerrainMaterial()
{
diffuseMap = "art/terrains/sand/ter_sand_bumpy_01_B";
diffuseSize = "250";
detailMap = "art/terrains/sand/ter_sand_bumpy_01_D";
detailSize = "4";
detailDistance = "100";
internalName = "ter_sand_bumpy_01";
macroSize = "20";
macroStrength = "1.2";
macroMap = "art/terrains/sand/ter_sand_bumpy_01_M";
normalMap = "art/terrains/sand/ter_sand_bumpy_01_N";
parallaxScale = "0.05";
};
singleton Material(TerrainFX_ter_sand_dirty_01)
{
mapTo = "ter_sand_dirty_01_B";
footstepSoundId = "1";
terrainMaterials = "1";
ShowDust = "1";
showFootprints = "1";
materialTag0 = "Terrain_Sand";
specularPower[0] = "1";
effectColor[0] = "0.803922 0.780392 0.635294 1";
effectColor[1] = "0.843137 0.780392 0.454902 0.349";
impactSoundId = "0";
};
new TerrainMaterial()
{
diffuseMap = "art/terrains/sand/ter_sand_dirty_01_B";
diffuseSize = "250";
detailMap = "art/terrains/sand/ter_sand_dirty_01_D";
detailDistance = "100";
macroSize = "75";
internalName = "ter_sand_dirty_01";
macroStrength = "0.5";
detailSize = "4";
macroMap = "art/terrains/sand/ter_sand_dirty_01_D";
normalMap = "art/terrains/sand/ter_sand_dirty_01_N";
parallaxScale = "0.1";
};
singleton Material(TerrainFX_ter_sand_dirty_02)
{
mapTo = "ter_sand_dirty_02_B";
footstepSoundId = "1";
terrainMaterials = "1";
ShowDust = "1";
showFootprints = "1";
materialTag0 = "Terrain_Sand";
specularPower[0] = "1";
effectColor[0] = "0.803922 0.780392 0.635294 1";
effectColor[1] = "0.843137 0.780392 0.454902 0.349";
impactSoundId = "0";
};
new TerrainMaterial()
{
diffuseMap = "art/terrains/sand/ter_sand_dirty_02_B";
diffuseSize = "250";
detailMap = "art/terrains/sand/ter_sand_dirty_02_D";
detailDistance = "100";
macroMap = "art/terrains/sand/ter_sand_dirty_02_D";
macroSize = "75";
internalName = "ter_sand_dirty_02";
detailSize = "4";
macroStrength = "0.5";
normalMap = "art/terrains/sand/ter_sand_dirty_02_N";
parallaxScale = "0.1";
};
singleton Material(TerrainFX_ter_sand_dirty_03)
{
mapTo = "ter_sand_dirty_03_B";
footstepSoundId = "1";
terrainMaterials = "1";
ShowDust = "1";
showFootprints = "1";
materialTag0 = "Terrain_Sand";
specularPower[0] = "1";
effectColor[0] = "0.803922 0.780392 0.635294 1";
effectColor[1] = "0.843137 0.780392 0.454902 0.349";
impactSoundId = "0";
};
new TerrainMaterial(ter_sand_dirty_03)
{
diffuseMap = "art/terrains/sand/ter_sand_dirty_03_B";
diffuseSize = "250";
detailMap = "art/terrains/sand/ter_sand_dirty_03_D";
detailDistance = "100";
macroSize = "75";
internalName = "ter_sand_dirty_03";
macroMap = "art/terrains/sand/ter_sand_dirty_03_D";
macroStrength = "0.5";
normalMap = "art/terrains/sand/ter_sand_dirty_03_N";
parallaxScale = "0.05";
};
singleton Material(TerrainFX_ter_sand_rough_01)
{
mapTo = "ter_sand_rough_01_B";
footstepSoundId = "1";
terrainMaterials = "1";
ShowDust = "1";
showFootprints = "1";
materialTag0 = "Terrain_Sand";
specularPower[0] = "1";
effectColor[0] = "0.803922 0.780392 0.635294 1";
effectColor[1] = "0.843137 0.780392 0.454902 0.349";
impactSoundId = "0";
};
new TerrainMaterial()
{
diffuseMap = "art/terrains/sand/ter_sand_rough_01_B";
diffuseSize = "250";
detailMap = "art/terrains/sand/ter_sand_rough_01_D";
detailDistance = "100";
macroSize = "50";
internalName = "ter_sand_rough_01";
macroStrength = "1";
macroMap = "art/terrains/sand/ter_sand_rough_01_M";
normalMap = "art/terrains/sand/ter_sand_rough_01_N";
parallaxScale = "0.05";
};
| 29.58042 | 57 | 0.650591 | [
"Unlicense"
] | fossabot/Uebergame | art/terrains/sand/materials.cs | 4,230 | C# |
namespace DAL.Models
{
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity.Spatial;
[Table("AdminClaim")]
public partial class AdminClaim
{
public int Id { get; set; }
[Required]
[StringLength(128)]
public string UserId { get; set; }
public string ClaimType { get; set; }
public string ClaimValue { get; set; }
public virtual Admin Admin { get; set; }
}
}
| 22 | 55 | 0.634615 | [
"Apache-2.0"
] | eletol/Goo-App-Architecture | DAL/Models/AdminClaim.cs | 572 | C# |
using Models.DB;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace API.Controllers
{
[Route("api/[controller]")]
//[Authorize]
[ApiController]
public class TrunTimessController : Controller
{
private RailML_3_1Context db = new RailML_3_1Context();
// GET api/values/5
[HttpGet("{id}")]
public async Task<string> Get(int id)
{
//IList<TrunTimes> lTrunTimess = await db.TrunTimes.GetAllCompanyTrunTimess(id);
//return JsonConvert.SerializeObject(lTrunTimess.ToArray());
return "";
}
// POST api/values
[HttpPost]
public async Task<string> Post([FromBody]TrunTimes truntimes)
{
//Create
db.TrunTimes.Add(truntimes);
await db.SaveChangesAsync();
return JsonConvert.SerializeObject(truntimes);
}
// PUT api/values/5
[HttpPut("{id}")]
public async Task Put(int id, [FromBody]TrunTimes truntimes)
{
//Update
db.TrunTimes.Update(truntimes);
await db.SaveChangesAsync();
}
// DELETE api/values/5
[HttpDelete("{id}")]
public async Task<string> DeleteAsync([FromBody]TrunTimes truntimes)
{
db.TrunTimes.Remove(truntimes);
await db.SaveChangesAsync();
return JsonConvert.SerializeObject("Ok");
}
}
}
| 24.944444 | 85 | 0.69265 | [
"Apache-2.0"
] | LightosLimited/RailML | v3.1/API/Controllers/TrunTimesController.cs | 1,347 | C# |
using FluentValidation.Attributes;
using Newtonsoft.Json;
using Nop.Plugin.Api.Validators;
namespace Nop.Plugin.Api.DTOs.ProductAttributes
{
[JsonObject(Title = "product_attribute")]
[Validator(typeof(ProductAttributeDtoValidator))]
public class ProductAttributeDto
{
/// <summary>
/// Gets or sets the product attribute id
/// </summary>
[JsonProperty("id")]
public string Id { get; set; }
/// <summary>
/// Gets or sets the name
/// </summary>
[JsonProperty("name")]
public string Name { get; set; }
///// <summary>
///// Gets or sets the localized names
///// </summary>
//[JsonProperty("localized_names")]
//public List<LocalizedNameDto> LocalizedNames
//{
// get
// {
// return _localizedNames;
// }
// set
// {
// _localizedNames = value;
// }
//}
/// <summary>
/// Gets or sets the description
/// </summary>
[JsonProperty("description")]
public string Description { get; set; }
}
} | 26.355556 | 54 | 0.520236 | [
"MIT"
] | DiogenesPolanco/api-plugin-for-nopcommerce | Nop.Plugin.Api/DTOs/ProductAttributes/ProductAttributeDto.cs | 1,188 | C# |
// *****************************************************************************
//
// © Component Factory Pty Ltd 2012. All rights reserved.
// The software and associated documentation supplied hereunder are the
// proprietary information of Component Factory Pty Ltd, 17/267 Nepean Hwy,
// Seaford, Vic 3198, Australia and are supplied subject to licence terms.
//
// Version 4.4.0.0 www.ComponentFactory.com
// *****************************************************************************
using System;
using System.Text;
using System.Drawing;
using System.Drawing.Design;
using System.Windows.Forms;
using System.ComponentModel;
using System.ComponentModel.Design;
using System.Collections.Generic;
using System.Diagnostics;
namespace ComponentFactory.Krypton.Toolkit
{
/// <summary>
/// Implementation for internal calendar buttons.
/// </summary>
public class ButtonSpecCalendar : ButtonSpec
{
#region Instance Fields
private ViewDrawMonth _month;
private RelativeEdgeAlign _edge;
private bool _visible;
private bool _enabled;
#endregion
#region Identity
/// <summary>
/// Initialize a new instance of the ButtonSpecCalendar class.
/// </summary>
/// <param name="month">Reference to owning view.</param>
/// <param name="fixedStyle">Fixed style to use.</param>
/// <param name="edge">Alignment edge.</param>
public ButtonSpecCalendar(ViewDrawMonth month,
PaletteButtonSpecStyle fixedStyle,
RelativeEdgeAlign edge)
{
Debug.Assert(month != null);
// Remember back reference to owning navigator.
_month = month;
_edge = edge;
_enabled = true;
_visible = true;
// Fix the type
ProtectedType = fixedStyle;
}
#endregion
#region Public
/// <summary>
/// Gets and sets the visible state.
/// </summary>
public bool Visible
{
get { return _visible; }
set { _visible = value; }
}
/// <summary>
/// Gets and sets the enabled state.
/// </summary>
public bool Enabled
{
get { return _enabled; }
set { _enabled = value; }
}
/// <summary>
/// Can a component be associated with the view.
/// </summary>
public override bool AllowComponent
{
get { return false; }
}
/// <summary>
/// Gets the button visible value.
/// </summary>
/// <param name="palette">Palette to use for inheriting values.</param>
/// <returns>Button visibiliy.</returns>
public override bool GetVisible(IPalette palette)
{
return Visible;
}
/// <summary>
/// Gets the button enabled state.
/// </summary>
/// <param name="palette">Palette to use for inheriting values.</param>
/// <returns>Button enabled state.</returns>
public override ButtonEnabled GetEnabled(IPalette palette)
{
return (Enabled ? ButtonEnabled.Container : ButtonEnabled.False);
}
/// <summary>
/// Gets the button checked state.
/// </summary>
/// <param name="palette">Palette to use for inheriting values.</param>
/// <returns>Button checked state.</returns>
public override ButtonCheckState GetChecked(IPalette palette)
{
return ButtonCheckState.Unchecked;
}
/// <summary>
/// Gets the button edge to position against.
/// </summary>
/// <param name="palette">Palette to use for inheriting values.</param>
/// <returns>Edge position.</returns>
public override RelativeEdgeAlign GetEdge(IPalette palette)
{
return _edge;
}
#endregion
}
}
| 31.65625 | 81 | 0.551086 | [
"BSD-3-Clause"
] | ElektroStudios/Krypton | Source/Krypton Components/ComponentFactory.Krypton.Toolkit/ButtonSpec/ButtonSpecCalendar.cs | 4,055 | C# |
using Microsoft.EntityFrameworkCore.Migrations;
namespace Faksistent.Migrations
{
public partial class Upgraded_To_ABP_6_0 : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.AddColumn<string>(
name: "NewValueHash",
table: "AbpEntityPropertyChanges",
type: "nvarchar(max)",
nullable: true);
migrationBuilder.AddColumn<string>(
name: "OriginalValueHash",
table: "AbpEntityPropertyChanges",
type: "nvarchar(max)",
nullable: true);
migrationBuilder.AddColumn<string>(
name: "DisplayName",
table: "AbpDynamicProperties",
type: "nvarchar(max)",
nullable: true);
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropColumn(
name: "NewValueHash",
table: "AbpEntityPropertyChanges");
migrationBuilder.DropColumn(
name: "OriginalValueHash",
table: "AbpEntityPropertyChanges");
migrationBuilder.DropColumn(
name: "DisplayName",
table: "AbpDynamicProperties");
}
}
}
| 30.954545 | 71 | 0.552129 | [
"MIT"
] | bayo04/Faksistent | aspnet-core/src/Faksistent.EntityFrameworkCore/Migrations/20201112121732_Upgraded_To_ABP_6_0.cs | 1,364 | C# |
using System;
using System.Windows.Forms;
namespace Media_Sorter
{
public partial class FDateTimePicker : Form
{
bool dtpChecked = true;
public FDateTimePicker()
{
InitializeComponent();
}
private void FDateTimePicker_Load(object sender, EventArgs e)
{
tb_Name.Enabled = false;
}
private void FDateTimePicker_Shown(object sender, EventArgs e)
{
Cursor.Current = Cursors.Default;
}
private void dtp_Main_ValueChanged(object sender, EventArgs e)
{
if (dtp_Main.Checked != dtpChecked)
{
dtpChecked = dtp_Main.Checked;
b_OK.Enabled = dtpChecked;
tb_Name.Enabled = !dtpChecked;
label2.Enabled = !dtpChecked;
if (!dtpChecked)
{
tb_Name_TextChanged(tb_Name, new EventArgs());
tb_Name.Focus();
}
}
}
private void tb_Name_TextChanged(object sender, EventArgs e)
{
if (!dtpChecked)
b_OK.Enabled = tb_Name.Text.Length > 0;
}
private void b_OK_Click(object sender, EventArgs e)
{
this.Tag = dtpChecked ? string.Format("{0}.{1}.{2}", dtp_Main.Value.Year, GetValue(dtp_Main.Value.Month), GetValue(dtp_Main.Value.Day)) : tb_Name.Text;
this.Close();
}
private void b_Cancel_Click(object sender, EventArgs e)
{
this.Close();
}
private string GetValue(int value)
{
string result = value.ToString();
return result.Length > 1 ? result : "0" + result;
}
}
}
| 27.447761 | 164 | 0.508972 | [
"MIT"
] | stroev-ao/MediaSorter | Media Sorter/FDateTimePicker.cs | 1,841 | 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 iotevents-data-2018-10-23.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;
using System.Net;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
namespace Amazon.IoTEventsData.Model
{
/// <summary>
/// The current state of the variable.
/// </summary>
public partial class Variable
{
private string _name;
private string _value;
/// <summary>
/// Gets and sets the property Name.
/// <para>
/// The name of the variable.
/// </para>
/// </summary>
[AWSProperty(Required=true, Min=1, Max=128)]
public string Name
{
get { return this._name; }
set { this._name = value; }
}
// Check to see if Name property is set
internal bool IsSetName()
{
return this._name != null;
}
/// <summary>
/// Gets and sets the property Value.
/// <para>
/// The current value of the variable.
/// </para>
/// </summary>
[AWSProperty(Required=true, Min=1, Max=1024)]
public string Value
{
get { return this._value; }
set { this._value = value; }
}
// Check to see if Value property is set
internal bool IsSetValue()
{
return this._value != null;
}
}
} | 27.089744 | 112 | 0.595362 | [
"Apache-2.0"
] | ChristopherButtars/aws-sdk-net | sdk/src/Services/IoTEventsData/Generated/Model/Variable.cs | 2,113 | C# |
using Amazon.JSII.Runtime.Deputy;
#pragma warning disable CS0672,CS0809,CS1591
namespace AlibabaCloud.SDK.ROS.CDK.Waf
{
/// <summary>A ROS resource type: `ALIYUN::WAF::DomainConfig`.</summary>
[JsiiClass(nativeType: typeof(AlibabaCloud.SDK.ROS.CDK.Waf.DomainConfig), fullyQualifiedName: "@alicloud/ros-cdk-waf.DomainConfig", parametersJson: "[{\"name\":\"scope\",\"type\":{\"fqn\":\"@alicloud/ros-cdk-core.Construct\"}},{\"name\":\"id\",\"type\":{\"primitive\":\"string\"}},{\"name\":\"props\",\"type\":{\"fqn\":\"@alicloud/ros-cdk-waf.DomainConfigProps\"}},{\"name\":\"enableResourcePropertyConstraint\",\"optional\":true,\"type\":{\"primitive\":\"boolean\"}}]")]
public class DomainConfig : AlibabaCloud.SDK.ROS.CDK.Core.Resource_
{
/// <summary>Create a new `ALIYUN::WAF::DomainConfig`.</summary>
/// <remarks>
/// Param scope - scope in which this resource is defined
/// Param id - scoped id of the resource
/// Param props - resource properties
/// </remarks>
public DomainConfig(AlibabaCloud.SDK.ROS.CDK.Core.Construct scope, string id, AlibabaCloud.SDK.ROS.CDK.Waf.IDomainConfigProps props, bool? enableResourcePropertyConstraint = null): base(new DeputyProps(new object?[]{scope, id, props, enableResourcePropertyConstraint}))
{
}
/// <summary>Used by jsii to construct an instance of this class from a Javascript-owned object reference</summary>
/// <param name="reference">The Javascript-owned object reference</param>
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
protected DomainConfig(ByRefValue reference): base(reference)
{
}
/// <summary>Used by jsii to construct an instance of this class from DeputyProps</summary>
/// <param name="props">The deputy props</param>
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
protected DomainConfig(DeputyProps props): base(props)
{
}
/// <summary>Attribute Cname: CNAME assigned by WAF instance.</summary>
[JsiiProperty(name: "attrCname", typeJson: "{\"fqn\":\"@alicloud/ros-cdk-core.IResolvable\"}")]
public virtual AlibabaCloud.SDK.ROS.CDK.Core.IResolvable AttrCname
{
get => GetInstanceProperty<AlibabaCloud.SDK.ROS.CDK.Core.IResolvable>()!;
}
/// <summary>Attribute ProtocolType: agreement type:0: indicates that the HTTP protocol is supported.1: indicates that the HTTPS protocol is supported.2: indicates that both HTTP and HTTPS protocols are supported.</summary>
[JsiiProperty(name: "attrProtocolType", typeJson: "{\"fqn\":\"@alicloud/ros-cdk-core.IResolvable\"}")]
public virtual AlibabaCloud.SDK.ROS.CDK.Core.IResolvable AttrProtocolType
{
get => GetInstanceProperty<AlibabaCloud.SDK.ROS.CDK.Core.IResolvable>()!;
}
}
}
| 59.48 | 475 | 0.677875 | [
"Apache-2.0"
] | aliyun/Resource-Orchestration-Service-Cloud-Development-K | multiple-languages/dotnet/AlibabaCloud.SDK.ROS.CDK.Waf/AlibabaCloud/SDK/ROS/CDK/Waf/DomainConfig.cs | 2,974 | C# |
using Microsoft.Win32;
using Playnite.SDK;
using Playnite.SDK.Models;
using Playnite.SDK.Plugins;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Controls;
namespace UplayLibrary
{
public class UplayLibrary : LibraryPlugin
{
private ILogger logger = LogManager.GetLogger();
private const string dbImportMessageId = "uplaylibImportError";
internal UplayLibrarySettings LibrarySettings { get; private set; }
public UplayLibrary(IPlayniteAPI api) : base(api)
{
LibrarySettings = new UplayLibrarySettings(this);
}
public GameAction GetGamePlayTask(string id)
{
return new GameAction()
{
Type = GameActionType.URL,
Path = Uplay.GetLaunchString(id),
IsHandledByPlugin = true
};
}
public List<GameInfo> GetLibraryGames()
{
var games = new List<GameInfo>();
var dlcsToIgnore = new List<uint>();
foreach (var item in Uplay.GetLocalProductCache())
{
if (item.root.addons.HasItems())
{
foreach (var dlc in item.root.addons.Select(a => a.id))
{
dlcsToIgnore.AddMissing(dlc);
}
}
if (item.root.third_party_platform != null)
{
continue;
}
if (item.root.is_ulc)
{
dlcsToIgnore.AddMissing(item.uplay_id);
continue;
}
if (dlcsToIgnore.Contains(item.uplay_id))
{
continue;
}
if (item.root.start_game == null)
{
continue;
}
var newGame = new GameInfo
{
Name = item.root.name.RemoveTrademarks(),
GameId = item.uplay_id.ToString(),
BackgroundImage = item.root.background_image,
Icon = item.root.icon_image,
CoverImage = item.root.thumb_image,
Source = "Ubisoft Connect",
Platform = "PC"
};
games.Add(newGame);
}
return games;
}
public List<GameInfo> GetInstalledGames()
{
var games = new List<GameInfo>();
var root = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry32);
var installsKey = root.OpenSubKey(@"SOFTWARE\ubisoft\Launcher\Installs\");
if (installsKey == null)
{
root = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry64);
installsKey = root.OpenSubKey(@"SOFTWARE\ubisoft\Launcher\Installs\");
}
if (installsKey != null)
{
foreach (var install in installsKey.GetSubKeyNames())
{
var gameData = installsKey.OpenSubKey(install);
var installDir = (gameData.GetValue("InstallDir") as string)?.Replace('/', Path.DirectorySeparatorChar);
if (!installDir.IsNullOrEmpty() && Directory.Exists(installDir))
{
var newGame = new GameInfo()
{
GameId = install,
Source = "Ubisoft Connect",
InstallDirectory = installDir,
PlayAction = GetGamePlayTask(install),
Name = Path.GetFileName(installDir.TrimEnd(Path.DirectorySeparatorChar)),
IsInstalled = true,
Platform = "PC"
};
games.Add(newGame);
}
}
}
return games;
}
#region ILibraryPlugin
public override LibraryClient Client => new UplayClient();
public override string LibraryIcon => Uplay.Icon;
public override string Name => "Ubisoft Connect";
public override Guid Id => Guid.Parse("C2F038E5-8B92-4877-91F1-DA9094155FC5");
public override LibraryPluginCapabilities Capabilities { get; } = new LibraryPluginCapabilities
{
CanShutdownClient = true
};
public override ISettings GetSettings(bool firstRunSettings)
{
return LibrarySettings;
}
public override UserControl GetSettingsView(bool firstRunView)
{
return new UplayLibrarySettingsView();
}
public override IGameController GetGameController(Game game)
{
return new UplayGameController(this, game);
}
public override IEnumerable<GameInfo> GetGames()
{
var allGames = new List<GameInfo>();
var installedGames = new List<GameInfo>();
Exception importError = null;
if (LibrarySettings.ImportInstalledGames)
{
try
{
installedGames = GetInstalledGames();
logger.Debug($"Found {installedGames.Count} installed Uplay games.");
allGames.AddRange(installedGames);
}
catch (Exception e)
{
logger.Error(e, "Failed to import installed Uplay games.");
importError = e;
}
}
if (LibrarySettings.ImportUninstalledGames)
{
try
{
var libraryGames = GetLibraryGames();
logger.Debug($"Found {libraryGames.Count} library Uplay games.");
foreach (var libGame in libraryGames)
{
var installed = installedGames.FirstOrDefault(a => a.GameId == libGame.GameId);
if (installed != null)
{
installed.Icon = libGame.Icon;
installed.BackgroundImage = libGame.BackgroundImage;
installed.CoverImage = libGame.CoverImage;
}
else
{
allGames.Add(libGame);
}
}
}
catch (Exception e)
{
logger.Error(e, "Failed to import uninstalled Uplay games.");
importError = e;
}
}
if (importError != null)
{
PlayniteApi.Notifications.Add(new NotificationMessage(
dbImportMessageId,
string.Format(PlayniteApi.Resources.GetString("LOCLibraryImportError"), Name) +
System.Environment.NewLine + importError.Message,
NotificationType.Error,
() => OpenSettingsView()));
}
else
{
PlayniteApi.Notifications.Remove(dbImportMessageId);
}
return allGames;
}
public override LibraryMetadataProvider GetMetadataDownloader()
{
return new UplayMetadataProvider();
}
#endregion ILibraryPlugin
}
}
| 34.175966 | 125 | 0.477082 | [
"MIT"
] | 1gjunior/Playnite | source/Plugins/UplayLibrary/UplayLibrary.cs | 7,965 | C# |
#if SQLServer
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.Entity;
using System.Linq.Expressions;
using System.Reflection;
namespace SecureUserAccess
{
static class Ext
{
public static IQueryable<TSource> Search<TSource, TValue>(this IQueryable<TSource> source, Expression<Func<TSource, TValue>> selector, TValue value)
{
var predicate = Expression.Lambda<Func<TSource, bool>>(
Expression.Equal(
selector.Body,
Expression.Constant(value, typeof(TValue))
), selector.Parameters);
return source.Where(predicate);
}
static PropertyInfo GetPropertyInfo<TSource, TValue>(this Expression<Func<TSource, TValue>> @propSelector)
{
Type type = typeof(TSource);
MemberExpression member = @propSelector.Body as MemberExpression;
if (member == null)
throw new ArgumentException(string.Format(
"Expression '{0}' refers to a method, not a property.",
@propSelector.ToString()));
PropertyInfo propInfo = member.Member as PropertyInfo;
if (propInfo == null)
throw new ArgumentException(string.Format(
"Expression '{0}' refers to a field, not a property.",
@propSelector.ToString()));
if (type != propInfo.ReflectedType &&
!type.IsSubclassOf(propInfo.ReflectedType))
throw new ArgumentException(string.Format(
"Expression '{0}' refers to a property that is not from type {1}.",
@propSelector.ToString(),
type));
return propInfo;
}
public static void SetValue<TSource, TValue>(this Expression<Func<TSource, TValue>> @propSelector, TSource @object, TValue value)
{
var prop = propSelector.GetPropertyInfo();
prop.SetValue(@object, value);
}
public static TValue GetValue<TSource, TValue>(this Expression<Func<TSource, TValue>> @propSelector, TSource @object)
{
var prop = propSelector.GetPropertyInfo();
TValue value = (TValue)prop.GetValue(@object);
return value;
}
}
public class SqlServerUserEnctyptionStore<TUser> where TUser : class, new()
{
private readonly Expression<Func<TUser, string>> passwordSelector;
private readonly Expression<Func<TUser, string>> usernameSelector;
public SqlServerUserEnctyptionStore(Expression<Func<TUser, string>> usernameSelector, Expression<Func<TUser, string>> passwordSelector)
{
this.usernameSelector = usernameSelector;
this.passwordSelector = passwordSelector;
}
public TUser ValidateUser(DbContext context, string username, string password)
{
var user = context.Set<TUser>().Search<TUser, string>(usernameSelector, username).FirstOrDefault();
if (user == null) return null;
if (!PasswordHash.Validate(password, passwordSelector.GetValue(user))) return null;
return user;
}
public void SetPassword(TUser user, string password)
{
passwordSelector.SetValue(user, password);
}
}
}
#endif | 37.857143 | 156 | 0.615385 | [
"MIT"
] | AmirOfir/SecureUserAccess | SqlServerUserEnctyptionStore.cs | 3,447 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
using System.Data.SqlClient;
using System.Text.RegularExpressions;
namespace InventoryManagementSystem
{
class mainclass
{
private static string path = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments); // take a path where folder is available
private static string s = File.ReadAllText(path+"\\connect");
public static Regex rg = new Regex(@"^[0-9]*(?:\.[0-9]*)?$");
public static SqlConnection con = new SqlConnection(s);
public static DialogResult showMessage(string msg, string heading, string type)
{
if(type=="Success")
{
return MessageBox.Show(msg, heading, MessageBoxButtons.OK, MessageBoxIcon.Information);
}else
{
return MessageBox.Show(msg, heading, MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
public static void showWindow(Form openWin, Form closeWin, Form mdiWin )
{
closeWin.Close();
openWin.MdiParent = mdiWin;
openWin.WindowState = FormWindowState.Maximized;
openWin.Show();
}
public static void showWindow(Form openWin, Form mdiWin)
{
openWin.MdiParent = mdiWin;
openWin.WindowState = FormWindowState.Maximized;
openWin.Show();
}
public static void disable_reset(Panel p)
{
foreach(Control c in p.Controls)
{
if(c is TextBox)
{
TextBox t = (TextBox)c;
t.Enabled = false;
t.Text = "";
}
if(c is ComboBox)
{
ComboBox cb = (ComboBox)c;
cb.Enabled = false;
cb.SelectedIndex = -1;
}
if (c is RadioButton)
{
RadioButton rb = (RadioButton)c;
rb.Enabled = false;
rb.Checked = false;
}
if (c is CheckBox)
{
CheckBox cb = (CheckBox)c;
cb.Enabled = false;
cb.Checked = false;
}
if (c is DateTimePicker)
{
DateTimePicker dtp = (DateTimePicker)c;
dtp.Enabled = false;
dtp.Value = DateTime.Now;
}
}
}
public static void disable(Panel p)
{
foreach (Control c in p.Controls)
{
if (c is TextBox)
{
TextBox t = (TextBox)c;
t.Enabled = false;
}
if (c is ComboBox)
{
ComboBox cb = (ComboBox)c;
cb.Enabled = false;
}
if (c is RadioButton)
{
RadioButton rb = (RadioButton)c;
rb.Enabled = false;
}
if (c is CheckBox)
{
CheckBox cb = (CheckBox)c;
cb.Enabled = false;
}
if (c is DateTimePicker)
{
DateTimePicker cb = (DateTimePicker)c;
cb.Enabled = false;
}
if (c is DateTimePicker)
{
DateTimePicker dtp = (DateTimePicker)c;
dtp.Enabled = false;
}
}
}
public static void enable_reset(Panel p)
{
foreach (Control c in p.Controls)
{
if (c is TextBox)
{
TextBox t = (TextBox)c;
t.Enabled = true;
t.Text = "";
}
if (c is ComboBox)
{
ComboBox cb = (ComboBox)c;
cb.Enabled = true;
cb.SelectedIndex = -1;
}
if (c is RadioButton)
{
RadioButton rb = (RadioButton)c;
rb.Enabled = true;
rb.Checked = false;
}
if (c is CheckBox)
{
CheckBox cb = (CheckBox)c;
cb.Enabled = true;
cb.Checked = false;
}
if (c is DateTimePicker)
{
DateTimePicker dtp = (DateTimePicker)c;
dtp.Enabled = true;
dtp.Value = DateTime.Now;
}
}
}
public static void enable(Panel p)
{
foreach (Control c in p.Controls)
{
if (c is TextBox)
{
TextBox t = (TextBox)c;
t.Enabled = true;
}
if (c is ComboBox)
{
ComboBox cb = (ComboBox)c;
cb.Enabled = true;
}
if (c is RadioButton)
{
RadioButton rb = (RadioButton)c;
rb.Enabled = true;
}
if (c is CheckBox)
{
CheckBox cb = (CheckBox)c;
cb.Enabled = true;
}
if (c is DateTimePicker)
{
DateTimePicker dtp = (DateTimePicker)c;
dtp.Enabled = true;
}
}
}
public static void enable_reset(GroupBox gb)
{
foreach (Control c in gb.Controls)
{
if (c is TextBox)
{
TextBox t = (TextBox)c;
t.Enabled = true;
t.Text = "";
}
if (c is ComboBox)
{
ComboBox cb = (ComboBox)c;
cb.Enabled = true;
cb.SelectedIndex = -1;
}
if (c is RadioButton)
{
RadioButton rb = (RadioButton)c;
rb.Enabled = true;
rb.Checked = false;
}
if (c is CheckBox)
{
CheckBox cb = (CheckBox)c;
cb.Enabled = true;
cb.Checked = false;
}
if (c is DateTimePicker)
{
DateTimePicker dtp = (DateTimePicker)c;
dtp.Enabled = true;
dtp.Value = DateTime.Now;
}
}
}
}
}
| 32.575893 | 144 | 0.381527 | [
"MIT"
] | Pro-procrastinator/CheckOut | InventoryManagementSystem/mainclass.cs | 7,299 | C# |
namespace BlazorBoilerplate.Shared.Extensions
{
public static class DateTimeExtensions
{
/// <summary>
/// Gets the 12:00:00 instance of a DateTime
/// </summary>
public static DateTime AbsoluteStart(this DateTime dateTime)
{
return dateTime.Date;
}
/// <summary>
/// Gets the 11:59:59 instance of a DateTime
/// </summary>
public static DateTime AbsoluteEnd(this DateTime dateTime)
{
return AbsoluteStart(dateTime).AddDays(1).AddTicks(-1);
}
public static int GetQuarter(this DateTime date)
{
if (date.Month >= 4 && date.Month <= 6)
return 1;
else if (date.Month >= 7 && date.Month <= 9)
return 2;
else if (date.Month >= 10 && date.Month <= 12)
return 3;
else
return 4;
}
public static DateTime GetLastDayOfQuarter(this DateTime date)
{
if (date.Month >= 4 && date.Month <= 6)
return new DateTime(date.Year, 6, 30).AbsoluteEnd();
else if (date.Month >= 7 && date.Month <= 9)
return new DateTime(date.Year, 9, 30).AbsoluteEnd();
else if (date.Month >= 10 && date.Month <= 12)
return new DateTime(date.Year, 12, 31).AbsoluteEnd();
else
return new DateTime(date.Year, 3, 31).AbsoluteEnd();
}
public static DateTime GetFirstDayOfQuarter(this DateTime date)
{
if (date.Month >= 4 && date.Month <= 6)
return new DateTime(date.Year, 4, 1);
else if (date.Month >= 7 && date.Month <= 9)
return new DateTime(date.Year, 7, 1);
else if (date.Month >= 10 && date.Month <= 12)
return new DateTime(date.Year, 10, 1);
else
return new DateTime(date.Year, 1, 1);
}
}
}
| 35.017544 | 71 | 0.511523 | [
"MIT"
] | IamFlashUser/blazorboilerplate | src/Shared/BlazorBoilerplate.Shared/Extensions/DateTimeExtensions.cs | 1,998 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
namespace Winforms._4._0.Full
{
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
}
}
| 22.181818 | 65 | 0.598361 | [
"MIT"
] | AndrewK2/html-agility-pack | src/Tests/NugetReferenceTests/Winforms.4.0.Full/Program.cs | 490 | C# |
namespace Tagger
{
partial class FrmUpload
{
/// <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.pictureBox1 = new System.Windows.Forms.PictureBox();
this.progressBar1 = new System.Windows.Forms.ProgressBar();
this.button1 = new System.Windows.Forms.Button();
this.textBox1 = new System.Windows.Forms.TextBox();
this.label1 = new System.Windows.Forms.Label();
this.backgroundWorker1 = new System.ComponentModel.BackgroundWorker();
((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).BeginInit();
this.SuspendLayout();
//
// pictureBox1
//
this.pictureBox1.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)));
this.pictureBox1.Location = new System.Drawing.Point(12, 12);
this.pictureBox1.Name = "pictureBox1";
this.pictureBox1.Size = new System.Drawing.Size(150, 149);
this.pictureBox1.SizeMode = System.Windows.Forms.PictureBoxSizeMode.CenterImage;
this.pictureBox1.TabIndex = 0;
this.pictureBox1.TabStop = false;
//
// progressBar1
//
this.progressBar1.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.progressBar1.Location = new System.Drawing.Point(177, 110);
this.progressBar1.Name = "progressBar1";
this.progressBar1.Size = new System.Drawing.Size(253, 22);
this.progressBar1.TabIndex = 1;
//
// button1
//
this.button1.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.button1.Location = new System.Drawing.Point(355, 138);
this.button1.Name = "button1";
this.button1.Size = new System.Drawing.Size(75, 23);
this.button1.TabIndex = 3;
this.button1.Text = "Cancel";
this.button1.UseVisualStyleBackColor = true;
this.button1.Click += new System.EventHandler(this.button1_Click);
//
// textBox1
//
this.textBox1.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.textBox1.BackColor = System.Drawing.SystemColors.Window;
this.textBox1.Location = new System.Drawing.Point(177, 12);
this.textBox1.Multiline = true;
this.textBox1.Name = "textBox1";
this.textBox1.ReadOnly = true;
this.textBox1.Size = new System.Drawing.Size(253, 92);
this.textBox1.TabIndex = 2;
//
// label1
//
this.label1.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)));
this.label1.AutoSize = true;
this.label1.Location = new System.Drawing.Point(174, 143);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(72, 13);
this.label1.TabIndex = 4;
this.label1.Text = "? of ? loaded.";
//
// backgroundWorker1
//
this.backgroundWorker1.WorkerReportsProgress = true;
this.backgroundWorker1.WorkerSupportsCancellation = true;
this.backgroundWorker1.DoWork += new System.ComponentModel.DoWorkEventHandler(this.backgroundWorker1_DoWork);
this.backgroundWorker1.RunWorkerCompleted += new System.ComponentModel.RunWorkerCompletedEventHandler(this.backgroundWorker1_RunWorkerCompleted);
this.backgroundWorker1.ProgressChanged += new System.ComponentModel.ProgressChangedEventHandler(this.backgroundWorker1_ProgressChanged);
//
// FrmUpload
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(442, 173);
this.Controls.Add(this.label1);
this.Controls.Add(this.button1);
this.Controls.Add(this.textBox1);
this.Controls.Add(this.progressBar1);
this.Controls.Add(this.pictureBox1);
this.MaximizeBox = false;
this.MinimumSize = new System.Drawing.Size(450, 200);
this.Name = "FrmUpload";
this.ShowInTaskbar = false;
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent;
this.Text = "Uploading Images...";
this.Shown += new System.EventHandler(this.FrmUpload_Shown);
((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).EndInit();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.PictureBox pictureBox1;
private System.Windows.Forms.ProgressBar progressBar1;
private System.Windows.Forms.Button button1;
private System.Windows.Forms.TextBox textBox1;
private System.Windows.Forms.Label label1;
private System.ComponentModel.BackgroundWorker backgroundWorker1;
}
} | 49.149254 | 160 | 0.61236 | [
"MIT"
] | graphnode/imgtagger | Tagger/FrmUpload.Designer.cs | 6,588 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Identity.UI;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.EntityFrameworkCore;
using Winterwood.Inventory.Web.Data;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Winterwood.Inventory.Service.Interfaces;
using Winterwood.Inventory.Service;
namespace Winterwood.Inventory.Web
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(
Configuration.GetConnectionString("DefaultConnection")));
services.AddDefaultIdentity<IdentityUser>(options => options.SignIn.RequireConfirmedAccount = false)
.AddEntityFrameworkStores<ApplicationDbContext>();
services.AddControllersWithViews();
services.AddRazorPages();
#region Adding dependencies
services.AddTransient<IBatchService, BatchService>();
services.AddTransient<IStockService, StockService>();
services.AddTransient<ICommonService, CommonService>();
#endregion
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseDatabaseErrorPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
endpoints.MapRazorPages();
});
}
}
}
| 35.56962 | 143 | 0.63879 | [
"MIT"
] | abhilashpullelil/winterwood | Winterwood.Inventory/Winterwood.Inventory.Web/Startup.cs | 2,810 | C# |
using ETLBox.Connection;
using ETLBox.Helper;
namespace ETLBox.ControlFlow.Tasks
{
/// <summary>
/// Creates or alters a view.
/// </summary>
/// <example>
/// <code>
/// CreateViewTask.CreateOrAlter("viewname","SELECT value FROM table");
/// </code>
/// </example>
public class CreateViewTask : ControlFlowTask
{
/// <inheritdoc/>
public override string TaskName => $"Create or alter view {ViewName ?? string.Empty}";
/// <summary>
/// Executes the creation/altering of the view.
/// </summary>
public void Execute()
{
IsExisting = new IfTableOrViewExistsTask(ViewName) { ConnectionManager = this.ConnectionManager, DisableLogging = true }.Exists();
if (
(ConnectionType == ConnectionManagerType.SQLite || ConnectionType == ConnectionManagerType.Access)
&& IsExisting
)
new DropViewTask(ViewName) { ConnectionManager = this.ConnectionManager, DisableLogging = true }.Drop();
new SqlTask(this, Sql).ExecuteNonQuery();
}
/// <summary>
/// The name of the view
/// </summary>
public string ViewName { get; set; }
/// <summary>
/// The formatted name of the view
/// </summary>
public ObjectNameDescriptor VN => new ObjectNameDescriptor(ViewName, QB, QE);
/// <summary>
/// The view definition.
/// </summary>
public string Definition { get; set; }
/// <summary>
/// The sql that is generated to create the view
/// </summary>
public string Sql
{
get
{
return $@"{CreateOrAlterSql} VIEW {CreateViewName}
AS
{Definition}
";
}
}
public CreateViewTask()
{
}
public CreateViewTask(string viewName, string definition) : this()
{
this.ViewName = viewName;
this.Definition = definition;
}
/// <summary>
/// Creates or alter a view.
/// </summary>
/// <param name="viewName">The name of the view</param>
/// <param name="definition">The view definition</param>
public static void CreateOrAlter(string viewName, string definition) => new CreateViewTask(viewName, definition).Execute();
/// <summary>
/// Creates or alter a view.
/// </summary>
/// <param name="connectionManager">The connection manager of the database you want to connect</param>
/// <param name="viewName">The name of the view</param>
/// <param name="definition">The view definition</param>
public static void CreateOrAlter(IConnectionManager connectionManager, string viewName, string definition) => new CreateViewTask(viewName, definition) { ConnectionManager = connectionManager }.Execute();
string CreateViewName => ConnectionType == ConnectionManagerType.Access ? VN.UnquotatedFullName : VN.QuotatedFullName;
bool IsExisting { get; set; }
string CreateOrAlterSql {
get {
if (!IsExisting) {
return "CREATE";
}
else {
if (ConnectionType == ConnectionManagerType.SQLite || ConnectionType == ConnectionManagerType.Access)
return "CREATE";
else if (ConnectionType == ConnectionManagerType.Postgres || ConnectionType == ConnectionManagerType.Oracle)
return "CREATE OR REPLACE";
else
return "ALTER";
}
}
}
}
}
| 34.859813 | 211 | 0.563003 | [
"MIT"
] | gjvanvuuren/etlbox | ETLBox/src/Toolbox/Database/CreateViewTask.cs | 3,732 | C# |
using System;
namespace Solitons
{
/// <summary>
/// Represents a point in time, typically expressed as a date and time of day, relative to Coordinated Universal Time (UTC).
/// </summary>
public partial interface IClock
{
/// <summary>
///
/// </summary>
DateTimeOffset Now { get; }
/// <summary>
///
/// </summary>
DateTimeOffset UtcNow { get; }
}
public partial interface IClock
{
/// <summary>
/// System clock
/// </summary>
public static readonly IClock System = new SystemClock();
/// <summary>
/// System clock implementation
/// </summary>
sealed class SystemClock : IClock
{
/// <summary>
///
/// </summary>
public DateTimeOffset Now => DateTimeOffset.Now;
/// <summary>
///
/// </summary>
public DateTimeOffset UtcNow => DateTimeOffset.UtcNow;
}
}
}
| 23.266667 | 128 | 0.493792 | [
"MIT"
] | AlexeyEvlampiev/Solitons.Core | src/Solitons.Core/IClock.cs | 1,049 | C# |
//------------------------------------------------------------------------------
// <copyright file="ErrorEventHandler.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
namespace System.IO {
using System.Diagnostics;
using System;
using System.ComponentModel;
/// <include file='doc\ErrorEventHandler.uex' path='docs/doc[@for="ErrorEventHandler"]/*' />
/// <devdoc>
/// <para>Represents the method that will
/// handle the <see cref='E:System.IO.FileSystemWatcher.Error'/>
/// event of
/// a <see cref='T:System.IO.FileSystemWatcher'/>.</para>
/// </devdoc>
public delegate void ErrorEventHandler(object sender, ErrorEventArgs e);
}
| 42 | 97 | 0.477273 | [
"Unlicense"
] | bestbat/Windows-Server | com/netfx/src/framework/services/io/system/io/erroreventhandler.cs | 924 | C# |
/*
* Copyright (c) 2018 THL A29 Limited, a Tencent company. 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.
*/
namespace TencentCloud.Vod.V20180717.Models
{
using Newtonsoft.Json;
using System.Collections.Generic;
using TencentCloud.Common;
public class HeadTailConfigureInfoForUpdate : AbstractModel
{
/// <summary>
/// 视频片头片尾识别任务开关,可选值:
/// <li>ON:开启智能视频片头片尾识别任务;</li>
/// <li>OFF:关闭智能视频片头片尾识别任务。</li>
/// </summary>
[JsonProperty("Switch")]
public string Switch{ get; set; }
/// <summary>
/// For internal usage only. DO NOT USE IT.
/// </summary>
public override void ToMap(Dictionary<string, string> map, string prefix)
{
this.SetParamSimple(map, prefix + "Switch", this.Switch);
}
}
}
| 30.043478 | 81 | 0.649783 | [
"Apache-2.0"
] | TencentCloud/tencentcloud-sdk-dotnet | TencentCloud/Vod/V20180717/Models/HeadTailConfigureInfoForUpdate.cs | 1,480 | 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 P01_HospitalDatabase.Data;
namespace P01_HospitalDatabase.Data.Migrations
{
[DbContext(typeof(HospitalContext))]
[Migration("20191101115813_DoctorTable")]
partial class DoctorTable
{
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "2.2.0-rtm-35687")
.HasAnnotation("Relational:MaxIdentifierLength", 128)
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
modelBuilder.Entity("P01_HospitalDatabase.Data.Models.Diagnose", b =>
{
b.Property<int>("DiagnoseId")
.ValueGeneratedOnAdd()
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<string>("Comments")
.HasMaxLength(250)
.IsUnicode(true);
b.Property<string>("Name")
.HasMaxLength(50)
.IsUnicode(true);
b.Property<int>("PatientId");
b.HasKey("DiagnoseId");
b.HasIndex("PatientId");
b.ToTable("Diagnoses");
});
modelBuilder.Entity("P01_HospitalDatabase.Data.Models.Doctor", b =>
{
b.Property<int>("DoctorId")
.ValueGeneratedOnAdd()
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<string>("Name")
.IsRequired()
.HasMaxLength(100)
.IsUnicode(true);
b.Property<string>("Specialty")
.IsRequired()
.HasMaxLength(100)
.IsUnicode(true);
b.HasKey("DoctorId");
b.ToTable("Doctor");
});
modelBuilder.Entity("P01_HospitalDatabase.Data.Models.Medicament", b =>
{
b.Property<int>("MedicamentId")
.ValueGeneratedOnAdd()
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<string>("Name")
.HasMaxLength(50)
.IsUnicode(true);
b.HasKey("MedicamentId");
b.ToTable("Medicaments");
});
modelBuilder.Entity("P01_HospitalDatabase.Data.Models.Patient", b =>
{
b.Property<int>("PatientId")
.ValueGeneratedOnAdd()
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<string>("Address")
.HasMaxLength(250)
.IsUnicode(true);
b.Property<string>("Email")
.HasMaxLength(250)
.IsUnicode(false);
b.Property<string>("FirstName")
.HasMaxLength(50)
.IsUnicode(true);
b.Property<bool>("HasInsurance");
b.Property<string>("LastName")
.HasMaxLength(50)
.IsUnicode(true);
b.HasKey("PatientId");
b.ToTable("Patients");
});
modelBuilder.Entity("P01_HospitalDatabase.Data.Models.PatientMedicament", b =>
{
b.Property<int>("PatientId");
b.Property<int>("MedicamentId");
b.HasKey("PatientId", "MedicamentId");
b.HasIndex("MedicamentId");
b.ToTable("PatientsMedicaments");
});
modelBuilder.Entity("P01_HospitalDatabase.Data.Models.Visitation", b =>
{
b.Property<int>("VisitationId")
.ValueGeneratedOnAdd()
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<string>("Comments")
.HasMaxLength(250)
.IsUnicode(true);
b.Property<DateTime>("Date");
b.Property<int>("DoctorId");
b.Property<int>("PatientId");
b.HasKey("VisitationId");
b.HasIndex("DoctorId");
b.HasIndex("PatientId");
b.ToTable("Visitations");
});
modelBuilder.Entity("P01_HospitalDatabase.Data.Models.Diagnose", b =>
{
b.HasOne("P01_HospitalDatabase.Data.Models.Patient", "Patient")
.WithMany("Diagnoses")
.HasForeignKey("PatientId")
.OnDelete(DeleteBehavior.Cascade);
});
modelBuilder.Entity("P01_HospitalDatabase.Data.Models.PatientMedicament", b =>
{
b.HasOne("P01_HospitalDatabase.Data.Models.Medicament", "Medicament")
.WithMany("Prescriptions")
.HasForeignKey("MedicamentId")
.OnDelete(DeleteBehavior.Cascade);
b.HasOne("P01_HospitalDatabase.Data.Models.Patient", "Patient")
.WithMany("Prescriptions")
.HasForeignKey("PatientId")
.OnDelete(DeleteBehavior.Cascade);
});
modelBuilder.Entity("P01_HospitalDatabase.Data.Models.Visitation", b =>
{
b.HasOne("P01_HospitalDatabase.Data.Models.Doctor", "Doctor")
.WithMany("Visitations")
.HasForeignKey("DoctorId")
.OnDelete(DeleteBehavior.Cascade);
b.HasOne("P01_HospitalDatabase.Data.Models.Patient", "Patient")
.WithMany("Visitations")
.HasForeignKey("PatientId")
.OnDelete(DeleteBehavior.Cascade);
});
#pragma warning restore 612, 618
}
}
}
| 37.096257 | 125 | 0.501081 | [
"MIT"
] | kalintsenkov/SoftUni-Software-Engineering | CSharp-DB/Databases-Advanced/Homeworks/04Code-First/P01_HospitalDatabase/Data/Migrations/20191101115813_DoctorTable.Designer.cs | 6,939 | C# |
using CharacterGen.Domain.Generators.Randomizers.CharacterClasses.ClassNames;
using CharacterGen.Domain.Tables;
using NUnit.Framework;
namespace CharacterGen.Tests.Unit.Generators.Randomizers.CharacterClasses.ClassNames
{
[TestFixture]
public class NonSpellcasterClassNameRandomizerTests : ClassNameRandomizerTests
{
protected override string classNameGroup
{
get { return GroupConstants.Spellcasters; }
}
[SetUp]
public void Setup()
{
randomizer = new NonSpellcasterClassNameRandomizer(mockPercentileResultSelector.Object, mockCollectionsSelector.Object, generator);
}
[Test]
public void ClassIsAllowed()
{
alignmentClasses.Add(ClassName);
var classNames = randomizer.GetAllPossibleResults(alignment);
Assert.That(classNames, Contains.Item(ClassName));
}
[Test]
public void ClassIsNotInAlignment()
{
var classNames = randomizer.GetAllPossibleResults(alignment);
Assert.That(classNames, Is.All.Not.EqualTo(ClassName));
}
[Test]
public void ClassIsInGroup()
{
alignmentClasses.Add(ClassName);
groupClasses.Add(ClassName);
var classNames = randomizer.GetAllPossibleResults(alignment);
Assert.That(classNames, Is.All.Not.EqualTo(ClassName));
}
}
} | 32.222222 | 143 | 0.653793 | [
"MIT"
] | DnDGen/CharacterGen | CharacterGen.Tests.Unit/Generators/Randomizers/CharacterClasses/ClassNames/NonSpellcasterClassNameRandomizerTests.cs | 1,452 | C# |
//------------------------------------------------------------------------------
//-------1---------2---------3---------4---------5---------6---------7---------8
// 01234567890123456789012345678901234567890123456789012345678901234567890
//-------+---------+---------+---------+---------+---------+---------+---------+
// copyright: 2014 WiM - USGS
// authors: Jeremy K. Newson USGS Wisconsin Internet Mapping
// Tonia Roddick USGS Wisconsin Internet Mapping
//
// purpose: Handles Site resources through the HTTP uniform interface.
// Equivalent to the controller in MVC.
//
//discussion: Handlers are objects which handle all interaction with resources.
// https://github.com/openrasta/openrasta/wiki/Handlers
//
//
#region Comments
// 03.28.16 - JKN - Created
#endregion
using OpenRasta.Web;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using STNServices2.Utilities.ServiceAgent;
using STNServices2.Security;
using STNDB;
using WiM.Exceptions;
using WiM.Resources;
using WiM.Security;
namespace STNServices2.Handlers
{
public class Site_HousingHandler : STNHandlerBase
{
#region GetMethods
[HttpOperation(HttpMethod.GET)]
public OperationResult Get()
{
List<site_housing> entities = null;
try
{
using (STNAgent sa = new STNAgent())
{
entities = sa.Select<site_housing>().OrderBy(e => e.site_housing_id).ToList();
sm(MessageType.info, "Count: " + entities.Count());
sm(sa.Messages);
}
return new OperationResult.OK { ResponseResource = entities, Description = this.MessageString };
}
catch (Exception ex)
{
return HandleException(ex);
}
}//end HttpMethod.GET
[HttpOperation(HttpMethod.GET)]
public OperationResult Get(Int32 entityId)
{
site_housing anEntity = null;
try
{
if (entityId <= 0) throw new BadRequestException("Invalid input parameters");
using (STNAgent sa = new STNAgent())
{
anEntity = sa.Select<site_housing>().FirstOrDefault(e => e.site_housing_id == entityId);
if (anEntity == null) throw new NotFoundRequestException();
sm(sa.Messages);
}//end using
return new OperationResult.OK { ResponseResource = anEntity, Description = this.MessageString };
}
catch (Exception ex)
{
return HandleException(ex);
}
}//end HttpMethod.GET
[HttpOperation(HttpMethod.GET, ForUriName = "GetSiteSiteHousing")]
public OperationResult SiteHousings(Int32 siteId)
{
List<site_housing> entities = null;
try
{
if (siteId <= 0) throw new BadRequestException("Invalid input parameters");
using (STNAgent sa = new STNAgent())
{
entities = sa.Select<site_housing>().Where(m => m.site_id == siteId).ToList();
sm(MessageType.info, "Count: " + entities.Count());
sm(sa.Messages);
}//end using
return new OperationResult.OK { ResponseResource = entities, Description = this.MessageString };
}
catch (Exception ex)
{
return HandleException(ex);
}
}//end HttpMethod.GET
#endregion
#region PostMethods
[STNRequiresRole(new string[] { AdminRole, ManagerRole, FieldRole })]
[HttpOperation(HttpMethod.POST)]
public OperationResult POST(site_housing anEntity)
{
//this is changed from previous version.. passed in siteId and site_housing object , then before adding, put the site_id prop on it.
try
{
if (anEntity.site_id <= 0 || anEntity.housing_type_id <= 0 || anEntity.amount <= 0)
throw new BadRequestException("Invalid input parameters");
using (EasySecureString securedPassword = GetSecuredPassword())
{
using (STNAgent sa = new STNAgent(username, securedPassword))
{
// last updated parts
List<member> MemberList = sa.Select<member>().Where(m => m.username.ToUpper() == username.ToUpper()).ToList();
Int32 loggedInUserId = MemberList.First<member>().member_id;
anEntity.last_updated = DateTime.Now;
anEntity.last_updated_by = loggedInUserId;
anEntity = sa.Add<site_housing>(anEntity);
sm(sa.Messages);
}//end using
}//end using
return new OperationResult.Created { ResponseResource = anEntity, Description = this.MessageString };
}
catch (Exception ex)
{ return HandleException(ex); }
}//end HttpMethod.GET
#endregion
#region PutMethods
///
/// Force the user to provide authentication and authorization
///
[STNRequiresRole(new string[] { AdminRole, ManagerRole, FieldRole })]
[HttpOperation(HttpMethod.PUT)]
public OperationResult Put(Int32 entityId, site_housing anEntity)
{
try
{
if (anEntity.site_id <= 0 || anEntity.housing_type_id <= 0 || anEntity.amount <= 0)
throw new BadRequestException("Invalid input parameters");
using (EasySecureString securedPassword = GetSecuredPassword())
{
using (STNAgent sa = new STNAgent(username, securedPassword))
{
// last updated parts
List<member> MemberList = sa.Select<member>().Where(m => m.username.ToUpper() == username.ToUpper()).ToList();
Int32 loggedInUserId = MemberList.First<member>().member_id;
anEntity.last_updated = DateTime.Now;
anEntity.last_updated_by = loggedInUserId;
anEntity = sa.Update<site_housing>(entityId, anEntity);
sm(sa.Messages);
}//end using
}//end using
return new OperationResult.Modified { ResponseResource = anEntity, Description = this.MessageString };
}
catch (Exception ex)
{ return HandleException(ex); }
}//end HttpMethod.PUT
#endregion
#region DeleteMethods
///
/// Force the user to provide authentication and authorization
///
[STNRequiresRole(new string[] { AdminRole, ManagerRole, FieldRole })]
[HttpOperation(HttpMethod.DELETE)]
public OperationResult Delete(Int32 entityId)
{
site_housing anEntity = null;
try
{
if (entityId <= 0) throw new BadRequestException("Invalid input parameters");
using (EasySecureString securedPassword = GetSecuredPassword())
{
using (STNAgent sa = new STNAgent(username, securedPassword))
{
anEntity = sa.Select<site_housing>().FirstOrDefault(i => i.site_housing_id == entityId);
if (anEntity == null) throw new WiM.Exceptions.NotFoundRequestException();
sa.Delete<site_housing>(anEntity);
sm(sa.Messages);
}//end using
}//end using
return new OperationResult.OK { Description = this.MessageString };
}
catch (Exception ex)
{ return HandleException(ex); }
}//end HttpMethod.PUT
#endregion
}//end horizontal_datumsHandler
}
| 38.864486 | 144 | 0.531682 | [
"CC0-1.0"
] | USGS-WiM/STNServices2 | STNServices2/Handlers/Site_HousingHandler.cs | 8,319 | C# |
namespace Twitch.Net.Api.Client
{
public class ApiClientFactory
{
public IApiClient CreateClient()
=> new ApiClient();
}
} | 19.375 | 40 | 0.606452 | [
"MIT"
] | Twitch-Net/Twitch.Net | Twitch.Net.Api/Client/ApiClientFactory.cs | 157 | C# |
using Entity.Tools;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace Entity.DBEntities
{
[Index(propertyNames: "Email", IsUnique = true, Name = "IX_EntUser_Email")]
[Index(propertyNames: "Username", IsUnique = true, Name = "IX_EntUser_Username")]
public class EntUser
{
[Key]
[Display(Name = "کد")]
public long ID { set; get; }
[Display(Name = "نام")]
[MinLength(length: 3, ErrorMessage = "حداقل طول رشته ورودی بایستی 3 نویسه باشد")]
[RegularExpression(pattern: ValidationTools.StandardFaName_Regx, ErrorMessage = ValidationTools.StandardFaName_Msg)]
public string Name { set; get; }
[Display(Name = "نام خانوادگی")]
[MinLength(length: 3, ErrorMessage = "حداقل طول رشته ورودی بایستی 3 نویسه باشد")]
[RegularExpression(pattern: ValidationTools.StandardFaName_Regx, ErrorMessage = ValidationTools.StandardFaName_Msg)]
public string LastName { set; get; }
[Display(Name = "نام کاربری")]
[MinLength(length: 8, ErrorMessage = "حداقل طول رشته ورودی بایستی 8 نویسه باشد")]
[RegularExpression(pattern: ValidationTools.StandardEngName_Regx, ErrorMessage = ValidationTools.StandardEngName_Msg)]
public string Username { set; get; }
[Display(Name = "گذرواژه")]
[DataType(DataType.Password)]
[MinLength(length: 8, ErrorMessage = ValidationTools.Pass_Msg)]
[RegularExpression(pattern: ValidationTools.Pass_Regx, ErrorMessage = ValidationTools.Pass_Msg)]
public string Password { set; get; }
[Display(Name = "پست الکترونیک")]
[DataType(DataType.EmailAddress)]
[MinLength(length: 8, ErrorMessage = ValidationTools.Mail_Msg)]
[MaxLength(length: 35, ErrorMessage = ValidationTools.Mail_Msg)]
[RegularExpression(pattern: ValidationTools.Mail_Regx, ErrorMessage = ValidationTools.Mail_Msg)]
public string Email { set; get; }
[Display(Name = "تاریخ تولد")]
[DataType(DataType.Date)]
[Required(ErrorMessage = ValidationTools.RequiredField_Msg)]
public DateTime BirthDate { set; get; }
[Display(Name = "آدرس پستی")]
public string Address { set; get; }
[Display(Name = "شماره همراه")]
[DataType(DataType.PhoneNumber)]
[RegularExpression(pattern: ValidationTools.Tell_Regx, ErrorMessage = ValidationTools.Tell_Msg)]
[Required(ErrorMessage = ValidationTools.RequiredField_Msg)]
public string Tell { set; get; }
[Display(Name = "تاریخ عضویت")]
[DataType(DataType.Date)]
[Required(ErrorMessage = ValidationTools.RequiredField_Msg)]
public DateTime RegDate { set; get; } = DateTime.Now.Date;
[Display(Name = "فعال است ؟")]
public bool IsActive { set; get; } = false;
[Display(Name = "لیست ورودها")]
public virtual List<EntLogin> Logins { set; get; }
[Display(Name = "نوشته ها")]
public virtual List<EntPost> Posts { set; get; }
[Display(Name = "سطح دسترسی")]
[Required(ErrorMessage = ValidationTools.RequiredField_Msg)]
[ForeignKey("Role")]
public long RoleID { set; get; }
public EntRole Role { set; get; }
}
}
| 40.722892 | 126 | 0.665089 | [
"Unlicense"
] | rezaamooee/SimpleWebSite | Entity/DBEntities/EntUser.cs | 3,593 | C# |
// <auto-generated />
using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using MovieStoreWebApi.Data;
namespace MovieStoreWebApi.Migrations
{
[DbContext(typeof(MovieStoreDbContext))]
partial class MovieStoreDbContextModelSnapshot : ModelSnapshot
{
protected override void BuildModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("Relational:MaxIdentifierLength", 128)
.HasAnnotation("ProductVersion", "5.0.13")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
modelBuilder.Entity("CharacterMovie", b =>
{
b.Property<int>("CharacterId")
.HasColumnType("int");
b.Property<int>("MovieId")
.HasColumnType("int");
b.HasKey("CharacterId", "MovieId");
b.HasIndex("MovieId");
b.ToTable("CharacterMovie");
b.HasData(
new
{
CharacterId = 1,
MovieId = 4
},
new
{
CharacterId = 2,
MovieId = 5
},
new
{
CharacterId = 4,
MovieId = 7
},
new
{
CharacterId = 5,
MovieId = 2
},
new
{
CharacterId = 5,
MovieId = 3
},
new
{
CharacterId = 6,
MovieId = 2
},
new
{
CharacterId = 6,
MovieId = 3
},
new
{
CharacterId = 7,
MovieId = 8
},
new
{
CharacterId = 8,
MovieId = 8
});
});
modelBuilder.Entity("MovieStoreWebApi.Models.Domain.Character", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<string>("Alias")
.IsRequired()
.HasMaxLength(50)
.HasColumnType("nvarchar(50)");
b.Property<string>("FullName")
.IsRequired()
.HasMaxLength(50)
.HasColumnType("nvarchar(50)");
b.Property<string>("Gender")
.IsRequired()
.HasMaxLength(50)
.HasColumnType("nvarchar(50)");
b.Property<string>("ImageUrl")
.HasMaxLength(500)
.HasColumnType("nvarchar(500)");
b.HasKey("Id");
b.ToTable("Character");
b.HasData(
new
{
Id = 1,
Alias = "Spider-Man",
FullName = "Peter Parker",
Gender = "Male",
ImageUrl = "https://static.wikia.nocookie.net/marvelcinematicuniverse/images/4/48/Spider-Man_No_Way_Home_poster_011_Textless.jpg/revision/latest?cb=20220120195924"
},
new
{
Id = 2,
Alias = "Captain Marvel",
FullName = "Carol Susan Jane Danvers",
Gender = "Female",
ImageUrl = "https://static.wikia.nocookie.net/marvelcinematicuniverse/images/f/fe/CapMarvel-EndgameProfile.jpeg/revision/latest?cb=20190423175247"
},
new
{
Id = 3,
Alias = "Batman",
FullName = "Bruce Wayne",
Gender = "Male",
ImageUrl = "https://static.wikia.nocookie.net/marvel_dc/images/7/76/Batman_Urban_Legends_Vol_1_5_Textless.jpg/revision/latest?cb=20210717062920"
},
new
{
Id = 4,
Alias = "The Joker",
FullName = "Unknown",
Gender = "Male",
ImageUrl = "https://static.wikia.nocookie.net/marvel_dc/images/5/5d/Doomsday_Clock_Vol_1_5_Textless_Variant.jpg/revision/latest?cb=20180606215837"
},
new
{
Id = 5,
Alias = "The Chosen One",
FullName = "Harry James Potter",
Gender = "Male",
ImageUrl = "https://static.wikia.nocookie.net/harrypotter/images/9/97/Harry_Potter.jpg/revision/latest/scale-to-width-down/360?cb=20140603201724"
},
new
{
Id = 6,
Alias = "Harry Potter (under disguise of Polyjuice Potion)",
FullName = "Hermione Jean Granger",
Gender = "Female",
ImageUrl = "https://static.wikia.nocookie.net/harrypotter/images/3/34/Hermione_Granger.jpg/revision/latest/scale-to-width-down/1000?cb=20210522145306"
},
new
{
Id = 7,
Alias = "Thorongil",
FullName = "Aragorn II Elessar",
Gender = "Male",
ImageUrl = "https://static.wikia.nocookie.net/lotr/images/b/b6/Aragorn_profile.jpg/revision/latest?cb=20170121121423"
},
new
{
Id = 8,
Alias = "Old Greybeard",
FullName = "Gandalf",
Gender = "Male",
ImageUrl = "https://static.wikia.nocookie.net/lotr/images/e/e7/Gandalf_the_Grey.jpg/revision/latest/scale-to-width-down/952?cb=20121110131754"
});
});
modelBuilder.Entity("MovieStoreWebApi.Models.Domain.Franchise", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<string>("Description")
.IsRequired()
.HasMaxLength(500)
.HasColumnType("nvarchar(500)");
b.Property<string>("Name")
.IsRequired()
.HasMaxLength(50)
.HasColumnType("nvarchar(50)");
b.HasKey("Id");
b.ToTable("Franchise");
b.HasData(
new
{
Id = 1,
Description = "Harry Potter is a film series based on the eponymous novels by J. K. Rowling. The series is distributed by Warner Bros. and consists of eight fantasy films, beginning with Harry Potter and the Philosopher's Stone (2001) and culminating with Harry Potter and the Deathly Hallows – Part 2 (2011).",
Name = "Harry Potter"
},
new
{
Id = 2,
Description = "The Marvel Cinematic Universe (MCU) is an American media franchise and shared universe centered on a series of superhero films produced by Marvel Studios. The films are based on characters that appear in American comic books published by Marvel Comics. The franchise also includes television series, short films, digital series, and literature.",
Name = "Marvel Cinematic Universe"
},
new
{
Id = 3,
Description = "The DC Extended Universe is a collection of interconnected films and other media based on characters that appear in publications by DC Comics. The universe largely spans through films, though is touched on in many other mediums including comics, novels, guidebooks, short films, and video games.",
Name = "DC Extended Universe"
},
new
{
Id = 4,
Description = "The Lord of the Rings is an epic high fantasy novel written by J.R.R. Tolkien, which was later fitted as a trilogy. The story began as a sequel to Tolkien's earlier fantasy book The Hobbit, and soon developed into a much larger story.",
Name = "Lord of the Rings"
});
});
modelBuilder.Entity("MovieStoreWebApi.Models.Domain.Movie", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<string>("Director")
.IsRequired()
.HasMaxLength(50)
.HasColumnType("nvarchar(50)");
b.Property<int?>("FranchiseId")
.HasColumnType("int");
b.Property<string>("Genre")
.IsRequired()
.HasMaxLength(50)
.HasColumnType("nvarchar(50)");
b.Property<string>("ImageUrl")
.HasMaxLength(500)
.HasColumnType("nvarchar(500)");
b.Property<int>("ReleaseYear")
.HasMaxLength(4)
.HasColumnType("int");
b.Property<string>("Title")
.IsRequired()
.HasMaxLength(50)
.HasColumnType("nvarchar(50)");
b.Property<string>("TrailerUrl")
.HasMaxLength(500)
.HasColumnType("nvarchar(500)");
b.HasKey("Id");
b.HasIndex("FranchiseId");
b.ToTable("Movie");
b.HasData(
new
{
Id = 1,
Director = "Chris Columbus",
FranchiseId = 1,
Genre = "Adventure, Family, Fantasy",
ImageUrl = "https://upload.wikimedia.org/wikipedia/en/7/7a/Harry_Potter_and_the_Philosopher%27s_Stone_banner.jpg",
ReleaseYear = 2001,
Title = "Harry Potter and the Philosopher's Stone",
TrailerUrl = "https://www.youtube.com/watch?v=VyHV0BRtdxo"
},
new
{
Id = 2,
Director = "Alfonso Cuarón",
FranchiseId = 1,
Genre = "Adventure, Family, Fantasy",
ImageUrl = "https://upload.wikimedia.org/wikipedia/en/b/bc/Prisoner_of_azkaban_UK_poster.jpg",
ReleaseYear = 2004,
Title = "Harry Potter and the Prisoner of Azkaban",
TrailerUrl = "https://www.youtube.com/watch?v=1ZdlAg3j8nI"
},
new
{
Id = 3,
Director = "David Yates",
FranchiseId = 1,
Genre = "Adventure, Family, Fantasy",
ImageUrl = "https://upload.wikimedia.org/wikipedia/en/e/e7/Harry_Potter_and_the_Order_of_the_Phoenix_poster.jpg",
ReleaseYear = 2007,
Title = "Harry Potter and the Order of the Phoenix",
TrailerUrl = "https://www.youtube.com/watch?v=y6ZW7KXaXYk"
},
new
{
Id = 4,
Director = "Jon Watts",
FranchiseId = 2,
Genre = "Action, Superhero",
ImageUrl = "https://upload.wikimedia.org/wikipedia/en/b/bd/Spider-Man_Far_From_Home_poster.jpg",
ReleaseYear = 2019,
Title = "Spider-Man: Far From Home",
TrailerUrl = "https://www.youtube.com/watch?v=Nt9L1jCKGnE"
},
new
{
Id = 5,
Director = "Anna Boden",
FranchiseId = 2,
Genre = "Action, Superhero",
ImageUrl = "https://upload.wikimedia.org/wikipedia/en/4/4e/Captain_Marvel_%28film%29_poster.jpg",
ReleaseYear = 2019,
Title = "Captain Marvel",
TrailerUrl = "https://www.youtube.com/watch?v=Z1BCujX3pw8"
},
new
{
Id = 6,
Director = "Zack Snyder",
FranchiseId = 3,
Genre = "Adventure, Action, Superhero",
ImageUrl = "https://upload.wikimedia.org/wikipedia/en/5/50/Man_of_Steel_%28film%29_poster.jpg",
ReleaseYear = 2013,
Title = "Man of Steel",
TrailerUrl = "https://www.youtube.com/watch?v=T6DJcgm3wNY"
},
new
{
Id = 7,
Director = "James Gunn",
FranchiseId = 3,
Genre = "Adventure, Action, Superhero",
ImageUrl = "https://upload.wikimedia.org/wikipedia/en/0/06/The_Suicide_Squad_%28film%29_poster.jpg",
ReleaseYear = 2021,
Title = "The Suicide Squad",
TrailerUrl = "https://www.youtube.com/watch?v=JuDLepNa7hw"
},
new
{
Id = 8,
Director = "Peter Jackson",
FranchiseId = 4,
Genre = "Adventure, Fantasy",
ImageUrl = "https://upload.wikimedia.org/wikipedia/en/d/d0/Lord_of_the_Rings_-_The_Two_Towers_%282002%29.jpg",
ReleaseYear = 2002,
Title = "The Lord of the Rings: The Two Towers",
TrailerUrl = "https://www.youtube.com/watch?v=LbfMDwc4azU"
});
});
modelBuilder.Entity("CharacterMovie", b =>
{
b.HasOne("MovieStoreWebApi.Models.Domain.Character", null)
.WithMany()
.HasForeignKey("CharacterId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("MovieStoreWebApi.Models.Domain.Movie", null)
.WithMany()
.HasForeignKey("MovieId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("MovieStoreWebApi.Models.Domain.Movie", b =>
{
b.HasOne("MovieStoreWebApi.Models.Domain.Franchise", "Franchise")
.WithMany("Movies")
.HasForeignKey("FranchiseId");
b.Navigation("Franchise");
});
modelBuilder.Entity("MovieStoreWebApi.Models.Domain.Franchise", b =>
{
b.Navigation("Movies");
});
#pragma warning restore 612, 618
}
}
}
| 46.139241 | 389 | 0.408285 | [
"MIT"
] | konstapascal/MovieStoreWebApi | MovieStoreWebApi/Migrations/MovieStoreDbContextModelSnapshot.cs | 18,230 | C# |
/*
* Copyright 2017-2020 Wouter Huysentruit
*
* See LICENSE file.
*/
using System;
using System.Linq;
using System.Reflection;
using EntityFrameworkCoreMock.Shared.KeyFactoryBuilders;
namespace EntityFrameworkCoreMock
{
public sealed class ConventionBasedKeyFactoryBuilder : KeyFactoryBuilderBase
{
protected override PropertyInfo[] ResolveKeyProperties<T>()
{
var entityType = typeof(T);
var keyProperties = entityType.GetProperties(BindingFlags.Instance | BindingFlags.Public)
.Where(x => x.Name.Equals("Id") || x.Name.Equals($"{entityType.Name}Id"))
.ToArray();
if (!keyProperties.Any()) throw new InvalidOperationException($"Entity type {entityType.Name} does not contain any property named Id or {entityType.Name}Id");
if (keyProperties.Count() > 1) throw new InvalidOperationException($"Entity type {entityType.Name} contains multiple conventional id properties");
return keyProperties;
}
}
}
| 36.928571 | 170 | 0.687621 | [
"MIT"
] | alvarollmenezes/entity-framework-core-mock | src/EntityFrameworkCoreMock.Shared/KeyFactoryBuilders/ConventionBasedKeyFactoryBuilder.cs | 1,036 | C# |
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
namespace ContosoUniversity.Models
{
public class Student : Person
{
[Required(ErrorMessage = "Enrollment date is required.")]
[DisplayFormat(DataFormatString = "{0:d}", ApplyFormatInEditMode = true)]
[Display(Name = "Enrollment Date")]
public DateTime? EnrollmentDate { get; set; }
public virtual ICollection<Enrollment> Enrollments { get; set; }
}
} | 32.125 | 82 | 0.673152 | [
"MIT"
] | Kymeric/specbind | examples/FullDemo/ContosoUniversity/Models/Student.cs | 516 | C# |
// Copyright 2021 Maintainers of NUKE.
// Distributed under the MIT License.
// https://github.com/nuke-build/nuke/blob/master/LICENSE
#if ENTERPRISE
using System;
using Nuke.Common;
using Nuke.Common.CI.AppVeyor;
using Nuke.Common.CI.GitHubActions;
using Nuke.Common.Execution;
using Nuke.Common.Git;
using Nuke.Enterprise.Auditing;
using Nuke.Enterprise.Notifications;
[AuditBuildMembers(
DeclaringTypes = new[] { typeof(Build) },
Members = new[] { nameof(RootDirectory), nameof(Host), nameof(Verbosity) })]
[DeploymentSlackNotification]
[BuildStatusSlackNotification]
partial class Build : IHazSlackCredentials, IHazAzurePipelinesAccessToken, IHazGitHubAccessToken
{
string IHazGitHubAccessToken.AccessToken => GitHubToken;
public class DeploymentSlackNotificationAttribute : SlackNotificationAttribute
{
public override bool ReportBuildAlways => Host is AppVeyor { ProjectSlug: "nuke-deployment" };
public override string ReceiverId => Host switch
{
AppVeyor { ProjectSlug: "nuke-deployment", RepositoryBranch: "master" } => "C01SNUZL50V",
AppVeyor { ProjectSlug: "nuke-deployment" } => "G01HT7MCQ2D",
_ => null
};
}
public class BuildStatusSlackNotificationAttribute : SlackNotificationAttribute
{
public override bool ReportBuildAlways => true;
public override ExecutionStatus[] ReportTargets => new[] { ExecutionStatus.Running, ExecutionStatus.Failed };
public override string ReceiverId => Host is GitHubActions _ or AppVeyor _ ? "U9S0MU8A3" : null;
public override bool IncludeCommits => false;
public override string Timestamp => Host switch
{
AppVeyor { ProjectSlug: "nuke-continuous", JobName: "Image: Visual Studio 2019" } => "1617073137.006600",
AppVeyor { ProjectSlug: "nuke-continuous", JobName: "Image: Ubuntu1804" } => "1617073148.007000",
GitHubActions { GitHubJob: "windows-latest" } => "1617073157.007100",
GitHubActions { GitHubJob: "macOS-latest" } => "1617073163.007200",
GitHubActions { GitHubJob: "ubuntu-latest" } => "1617073169.007300",
_ => throw new NotSupportedException(Host.ToString())
};
public override bool ShouldNotify(NukeBuild build) => ((Build) build).GitRepository.IsOnDevelopBranch();
}
}
#endif
| 41.155172 | 117 | 0.699204 | [
"MIT"
] | chaquotay/nuke | build/Build.Enterprise.cs | 2,389 | C# |
namespace Frank.Libraries.Ubl;
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.8.3928.0")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(Namespace = "urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2")]
[System.Xml.Serialization.XmlRootAttribute("ParentDocumentLineReferenceID", Namespace = "urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2", IsNullable = false)]
public partial class ParentDocumentLineReferenceIDType : IdentifierType1
{
} | 53.75 | 180 | 0.823256 | [
"MIT"
] | frankhaugen/Frank.Extensions | src/Frank.Libraries.Ubl/UBL/ParentDocumentLineReferenceIDType.cs | 645 | C# |
#region Copyright and License
// Copyright (c) 2013-2014 The Khronos Group Inc.
// Copyright (c) of C# port 2014 by Shinta <[email protected]>
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and/or associated documentation files (the
// "Materials"), to deal in the Materials without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Materials, and to
// permit persons to whom the Materials are 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 Materials.
//
// THE MATERIALS ARE 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
// MATERIALS OR THE USE OR OTHER DEALINGS IN THE MATERIALS.
#endregion
namespace OpenGL.Core
{
/// <summary>
/// Enum for program parameter. Used by <see cref="gl.GetProgramiv"/> and <see cref="gl.ProgramParameteri"/>.
/// </summary>
public enum glProgramParameter : uint
{
/// <summary>
/// Returns the number of active atomic counter buffers used by the program.
/// </summary>
ACTIVE_ATOMIC_COUNTER_BUFFERS = 0x92D9,
/// <summary>
/// Returns the length of the longest active attribute name, including a null terminator.
/// </summary>
ACTIVE_ATTRIBUTE_MAX_LENGTH = 0x8B8A,
/// <summary>
/// Returns the number of active attributes in the program.
/// </summary>
ACTIVE_ATTRIBUTES = 0x8B89,
/// <summary>
/// Returns the length of the longest active uniform block name, including a null terminator.
/// </summary>
ACTIVE_UNIFORM_BLOCK_MAX_NAME_LENGTH = 0x8A35,
/// <summary>
/// Returns the number of uniform blocks for the program containing active uniforms.
/// </summary>
ACTIVE_UNIFORM_BLOCKS = 0x8A36,
/// <summary>
/// Returns the length of the longest active uniform name, including a null terminator.
/// </summary>
ACTIVE_UNIFORM_MAX_LENGTH = 0x8B87,
/// <summary>
/// Returns the number of active uniforms.
/// </summary>
ACTIVE_UNIFORMS = 0x8B86,
/// <summary>
/// Returns the number of attached objects.
/// </summary>
ATTACHED_SHADERS = 0x8B85,
/// <summary>
/// Returns an array of three <b>int</b>s containing the local work group size of the compute program,
/// as specified by its input layout qualifier(s).
/// </summary>
COMPUTE_WORK_GROUP_SIZE = 0x8267,
/// <summary>
/// Returns <see cref="gl.TRUE"/> if the program has been flagged for deletion.
/// </summary>
DELETE_STATUS = 0x8B80,
/// <summary>
/// Returns the geometry shader input type as <see cref="glGeometryInputType"/>.
/// </summary>
GEOMETRY_INPUT_TYPE = 0x8917,
/// <summary>
/// Returns the geometry shader output type as <see cref="glGeometryOutputType"/>.
/// </summary>
GEOMETRY_OUTPUT_TYPE = 0x8918,
/// <summary>
/// Returns the number of geometry shader invocations per primitive.
/// </summary>
GEOMETRY_SHADER_INVOCATIONS = 0x887F,
/// <summary>
/// Returns the maximum number of vertices the geometry shader will output.
/// </summary>
GEOMETRY_VERTICES_OUT = 0x8916,
/// <summary>
/// Returns the length of the info log, including a null terminator.
/// </summary>
INFO_LOG_LENGTH = 0x8B84,
/// <summary>
/// Returns <see cref="gl.TRUE"/> if the program was last compiled successfully.
/// </summary>
LINK_STATUS = 0x8B82,
/// <summary>
/// Returns the length of the binary program.
/// </summary>
PROGRAM_BINARY_LENGTH = 0x8741,
/// <summary>
/// <see cref="gl.GetProgramiv"/> returns <see cref="gl.TRUE"/> if the binary retrieval hint is enabled for program.
/// Use <see cref="gl.ProgramParameteri"/> to indicate whether a program binary is likely to be retrieved later.
/// </summary>
PROGRAM_BINARY_RETRIEVABLE_HINT = 0x8257,
/// <summary>
/// <see cref="gl.GetProgramiv"/> returns <see cref="gl.TRUE"/> if the program has been flagged for use as
/// a separable program object that canbe bound to individual shader stages with <see cref="gl.UseProgramStages"/>.
/// Use <see cref="gl.ProgramParameteri"/> to indicate whether program can be bound for individual pipeline stages
/// using <see cref="gl.UseProgramStages"/> after it is next linked.
/// </summary>
PROGRAM_SEPARABLE = 0x8258,
/// <summary>
/// Returns the number of vertices in the tessellation control shader output patch.
/// </summary>
TESS_CONTROL_OUTPUT_VERTICES = 0x8E75,
/// <summary>
/// Returns the tesselation evaluation shader primitive mode as <see cref="glTessGenMode"/>.
/// </summary>
TESS_GEN_MODE = 0x8E76,
/// <summary>
/// Returns <see cref="gl.TRUE"/> if point mode is enabled in a tessellation evaluation shader.
/// </summary>
TESS_GEN_POINT_MODE = 0x8E79,
/// <summary>
/// Returns the tesselation evaluation shader input spacing as <see cref="glTessGenSpacing"/>.
/// </summary>
TESS_GEN_SPACING = 0x8E77,
/// <summary>
/// Returns the tesselation evaluation shader vertex order as <see cref="glFrontFaceDirection"/>.
/// </summary>
TESS_GEN_VERTEX_ORDER = 0x8E78,
/// <summary>
/// Returns the buffer mode used when transform feedback is active as <see cref="glTransformFeedbackBufferMode"/>.
/// </summary>
TRANSFORM_FEEDBACK_BUFFER_MODE = 0x8C7F,
/// <summary>
/// Returns the length of the longest output variable name specified to be used for transform feedback,
/// including a null terminator.
/// </summary>
TRANSFORM_FEEDBACK_VARYING_MAX_LENGTH = 0x8C76,
/// <summary>
/// Returns the number of output variables to capture in transform feedback mode for the program.
/// </summary>
TRANSFORM_FEEDBACK_VARYINGS = 0x8C83,
/// <summary>
/// Returns <see cref="gl.TRUE"/> if the last call to <see cref="gl.ValidateProgram"/> with program was successful.
/// </summary>
VALIDATE_STATUS = 0x8B83,
}
}
| 35.47486 | 118 | 0.704882 | [
"MIT"
] | shintadono/OpenGL.Core | Defines/glProgramParameter.cs | 6,352 | C# |
using System;
using System.Runtime.Serialization;
namespace BcGov.Malt.Web
{
[Serializable]
public class UserNotFoundException : Exception
{
public string Username { get; }
public UserNotFoundException()
{
}
public UserNotFoundException(string username) : base("User not found")
{
Username = username;
}
public UserNotFoundException(string message, Exception inner) : base(message, inner)
{
}
protected UserNotFoundException(
SerializationInfo info,
StreamingContext context) : base(info, context)
{
}
}
}
| 22.483871 | 93 | 0.571019 | [
"Apache-2.0"
] | bcgov/maltd | api/src/BcGov.Malt.Web/UserNotFoundException.cs | 697 | C# |
#region license
// Copyright (c) 2007-2010 Mauricio Scheffer
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#endregion
using NUnit.Framework;
using System.Linq;
using SolrNet.Impl.FieldSerializers;
using SolrNet.Impl.QuerySerializers;
namespace SolrNet.Tests {
[TestFixture]
public class SolrQueryInListTests {
public string Serialize(object q) {
var serializer = new DefaultQuerySerializer(new DefaultFieldSerializer());
return serializer.Serialize(q);
}
[Test]
public void ListOfInt() {
var q = new SolrQueryInList("id", new[] {1, 2, 3, 4}.Select(i => i.ToString()));
Assert.AreEqual("(id:((1) OR (2) OR (3) OR (4)))", Serialize(q));
}
[Test]
public void ShouldQuoteValues() {
var q = new SolrQueryInList("id", new[] {"one", "two thousand"});
Assert.AreEqual("(id:((one) OR (\"two thousand\")))", Serialize(q));
}
[Test]
public void ShouldQuoteEmptyValues() {
var q = new SolrQueryInList("id", new[] { "", "two thousand" });
Assert.AreEqual("(id:((\"\") OR (\"two thousand\")))", Serialize(q));
}
[Test]
public void EmptyList_should_be_null_query() {
var q = new SolrQueryInList("id", new string[0]);
Assert.IsNull(Serialize(q));
}
[Test]
public void Fieldname_with_spaces()
{
var q = new SolrQueryInList("i have spaces", new[] { "one", "two thousand" });
Assert.AreEqual("(i\\ have\\ spaces:((one) OR (\"two thousand\")))", Serialize(q));
}
}
} | 34.904762 | 96 | 0.599818 | [
"Apache-2.0"
] | Denis-Vlassenko/SolrNet | SolrNet.Tests/SolrQueryInListTests.cs | 2,201 | C# |
using SvgXml.Svg.Attributes;
using SvgXml.Xml.Attributes;
namespace SvgXml.Svg.Text
{
[Element("glyph")]
public class SvgGlyph : SvgStylableElement,
ISvgCommonAttributes,
ISvgPresentationAttributes,
ISvgStylableAttributes
{
[Attribute("d", SvgNamespace)]
public string? PathData
{
get => this.GetAttribute("d", false, null);
set => this.SetAttribute("d", value);
}
[Attribute("horiz-adv-x", SvgNamespace)]
public string? HorizAdvX
{
get => this.GetAttribute("horiz-adv-x", false, null); // TODO
set => this.SetAttribute("horiz-adv-x", value);
}
[Attribute("vert-origin-x", SvgNamespace)]
public string? VertOriginX
{
get => this.GetAttribute("vert-origin-x", false, null); // TODO
set => this.SetAttribute("vert-origin-x", value);
}
[Attribute("vert-origin-y", SvgNamespace)]
public string? VertOriginY
{
get => this.GetAttribute("vert-origin-y", false, null); // TODO
set => this.SetAttribute("vert-origin-y", value);
}
[Attribute("vert-adv-y", SvgNamespace)]
public string? VertAdvY
{
get => this.GetAttribute("vert-adv-y", false, null); // TODO
set => this.SetAttribute("vert-adv-y", value);
}
[Attribute("unicode", SvgNamespace)]
public string? Unicode
{
get => this.GetAttribute("unicode", false, null);
set => this.SetAttribute("unicode", value);
}
[Attribute("glyph-name", SvgNamespace)]
public string? GlyphName
{
get => this.GetAttribute("glyph-name", false, null);
set => this.SetAttribute("glyph-name", value);
}
[Attribute("orientation", SvgNamespace)]
public string? Orientation
{
get => this.GetAttribute("orientation", false, null);
set => this.SetAttribute("orientation", value);
}
[Attribute("arabic-form", SvgNamespace)]
public string? ArabicForm
{
get => this.GetAttribute("arabic-form", false, null);
set => this.SetAttribute("arabic-form", value);
}
[Attribute("lang", SvgNamespace)]
public string? LanguageCodes
{
get => this.GetAttribute("lang", false, null);
set => this.SetAttribute("lang", value);
}
public override void SetPropertyValue(string key, string? value)
{
base.SetPropertyValue(key, value);
switch (key)
{
case "d":
PathData = value;
break;
case "horiz-adv-x":
HorizAdvX = value;
break;
case "vert-origin-x":
VertOriginX = value;
break;
case "vert-origin-y":
VertOriginY = value;
break;
case "vert-adv-y":
VertAdvY = value;
break;
case "unicode":
Unicode = value;
break;
case "glyph-name":
GlyphName = value;
break;
case "orientation":
Orientation = value;
break;
case "arabic-form":
ArabicForm = value;
break;
case "lang":
LanguageCodes = value;
break;
}
}
}
}
| 30.933884 | 75 | 0.481432 | [
"MIT"
] | benjaminZale/Svg.Skia | experimental/SvgXml.Svg/Text/SvgGlyph.cs | 3,745 | C# |
using System;
using System.Collections.Generic;
using System.Dynamic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using System.Web.Mvc;
using Zephyr.Core;
using ERP.Web.Models;
using ERP.Web;
namespace ERP.Web.Areas.Erp.Controllers
{
public class SupplierController : Controller
{
public ActionResult Index()
{
var model = new
{
dataSource = new
{
Items1 = new base_dataService().GetDynamicList(ParamQuery.Instance().Select("name as value,name as text").AndWhere("type", "客户等级").AndWhere("isenable", "1"))
},
urls = new
{
query = "/api/erp/Supplier",
edit = "/api/erp/Supplier/edit"
},
resx = new
{
noneSelect = "请先选择一条数据!",
editSuccess = "保存成功!",
},
form = new
{
name = "",
grade = ""
},
defaultRow = new
{
},
setting = new
{
postListFields = new string[] { "id", "jc_name", "name", "contacts", "contacts_phone", "email", "grade", "address", "isenable", "remark", "create_time", "create_username" }
}
};
return View(model);
}
}
public class SupplierApiController : ApiController
{
public dynamic Get(RequestWrapper query)
{
query.LoadSettingXmlString(@"
<settings defaultOrderBy='id'>
<select>*</select>
<from>base_Supplier</from>
<where defaultForAll='true' defaultCp='equal' defaultIgnoreEmpty='true' >
<field name='name' cp='like'></field>
<field name='grade' cp='equal' ></field>
</where>
</settings>");
var service = new base_supplierService();
var pQuery = query.ToParamQuery();
var result = service.GetDynamicListWithPaging(pQuery);
return result;
}
[System.Web.Http.HttpPost]
public void Edit(dynamic data)
{
var listWrapper = RequestWrapper.Instance().LoadSettingXmlString(@"
<settings>
<table>base_Supplier</table>
<where>
<field name='id' cp='equal'></field>
</where>
</settings>");
var service = new base_supplierService();
var result = service.Edit(null, listWrapper, data);
}
}
}
| 31.724138 | 192 | 0.479348 | [
"MIT"
] | zhupangithub/WEBERP | Code/ERP.Web/Areas/Erp/Controllers/SupplierController.cs | 2,798 | 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 clouddirectory-2016-05-10.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.CloudDirectory.Model
{
/// <summary>
/// This is the response object from the AttachObject operation.
/// </summary>
public partial class AttachObjectResponse : AmazonWebServiceResponse
{
private string _attachedObjectIdentifier;
/// <summary>
/// Gets and sets the property AttachedObjectIdentifier.
/// <para>
/// Attached <code>ObjectIdentifier</code>, which is the child <code>ObjectIdentifier</code>.
/// </para>
/// </summary>
public string AttachedObjectIdentifier
{
get { return this._attachedObjectIdentifier; }
set { this._attachedObjectIdentifier = value; }
}
// Check to see if AttachedObjectIdentifier property is set
internal bool IsSetAttachedObjectIdentifier()
{
return this._attachedObjectIdentifier != null;
}
}
} | 32.214286 | 112 | 0.68459 | [
"Apache-2.0"
] | Bynder/aws-sdk-net | sdk/src/Services/CloudDirectory/Generated/Model/AttachObjectResponse.cs | 1,804 | C# |
// Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using osu.Framework.Input.StateChanges;
using osu.Framework.Logging;
using osu.Framework.Utils;
using osu.Framework.Platform;
using osu.Framework.Statistics;
using osu.Framework.Threading;
using osuTK.Input;
using JoystickState = osu.Framework.Input.States.JoystickState;
namespace osu.Framework.Input.Handlers.Joystick
{
public class OsuTKJoystickHandler : InputHandler
{
private ScheduledDelegate scheduled;
private readonly List<JoystickDevice> devices = new List<JoystickDevice>();
private readonly List<osuTK.Input.JoystickState> rawStates = new List<osuTK.Input.JoystickState>();
public override bool Initialize(GameHost host)
{
Enabled.BindValueChanged(e =>
{
if (e.NewValue)
{
host.InputThread.Scheduler.Add(scheduled = new ScheduledDelegate(delegate
{
refreshDevices();
foreach (var device in devices)
{
if ((device.LastRawState.HasValue && device.RawState.Equals(device.LastRawState.Value))
|| !device.RawState.IsConnected)
continue;
handleState(device, new OsuTKJoystickState(device));
FrameStatistics.Increment(StatisticsCounterType.JoystickEvents);
}
}, 0, 0));
}
else
{
scheduled?.Cancel();
foreach (var device in devices)
{
if (device.LastState != null)
handleState(device, new JoystickState());
}
devices.Clear();
}
}, true);
return true;
}
private void handleState(JoystickDevice device, JoystickState newState)
{
PendingInputs.Enqueue(new JoystickButtonInput(newState.Buttons, device.LastState?.Buttons));
device.LastState = newState;
}
private void refreshDevices()
{
// update states and add newly connected devices
osuTK.Input.Joystick.GetStates(rawStates);
// it seems like OpenTK leaves all disconnected devices with IsConnceted == false
Debug.Assert(devices.Count <= rawStates.Count);
for (int index = 0; index < rawStates.Count; index++)
{
var rawState = rawStates[index];
if (index < devices.Count)
{
devices[index].UpdateRawState(rawState);
}
else
{
var guid = osuTK.Input.Joystick.GetGuid(index);
var newDevice = new JoystickDevice(guid, rawState);
devices.Add(newDevice);
Logger.Log($"Connected joystick device: {newDevice.Guid}");
}
}
}
public override bool IsActive => true;
public override int Priority => 0;
private class OsuTKJoystickState : JoystickState
{
public OsuTKJoystickState(JoystickDevice device)
{
// Populate axes
for (int i = 0; i < JoystickDevice.MAX_AXES; i++)
{
var value = device.RawState.GetAxis(i);
// do not allow a deadzone below float_epsilon
var deadzone = MathF.Max(device.DefaultDeadzones?[i] ?? 0, Precision.FLOAT_EPSILON);
if (!Precision.AlmostEquals(value, 0, deadzone))
{
Axes.Add(new JoystickAxis(i, value));
// We're off the center, activate negative / positive button
if (value > deadzone)
Buttons.SetPressed(JoystickButton.FirstAxisPositive + i, true);
else if (value < deadzone * -1)
Buttons.SetPressed(JoystickButton.FirstAxisNegative + i, true);
}
}
// Populate normal buttons
for (int i = 0; i < JoystickDevice.MAX_BUTTONS; i++)
{
if (device.RawState.GetButton(i) == ButtonState.Pressed)
Buttons.SetPressed(JoystickButton.FirstButton + i, true);
}
// Populate hat buttons
for (int i = 0; i < JoystickDevice.MAX_HATS; i++)
{
foreach (var hatButton in getHatButtons(device, i))
Buttons.SetPressed(hatButton, true);
}
}
private IEnumerable<JoystickButton> getHatButtons(JoystickDevice device, int hat)
{
var state = device.RawState.GetHat(JoystickHat.Hat0 + hat);
if (state.IsUp)
yield return JoystickButton.FirstHatUp + hat;
else if (state.IsDown)
yield return JoystickButton.FirstHatDown + hat;
if (state.IsLeft)
yield return JoystickButton.FirstHatLeft + hat;
else if (state.IsRight)
yield return JoystickButton.FirstHatRight + hat;
}
}
private class JoystickDevice
{
/// <summary>
/// Amount of axes supported by osuTK.
/// </summary>
public const int MAX_AXES = 64;
/// <summary>
/// Amount of buttons supported by osuTK.
/// </summary>
public const int MAX_BUTTONS = 128;
/// <summary>
/// Amount of hats supported by osuTK.
/// </summary>
public const int MAX_HATS = 4;
/// <summary>
/// Amount of movement around the "centre" of the axis that counts as moving within the deadzone.
/// </summary>
private const float deadzone_threshold = 0.05f;
/// <summary>
/// The last state of this <see cref="JoystickDevice"/>.
/// This is updated with ever invocation of <see cref="UpdateRawState"/>.
/// </summary>
public osuTK.Input.JoystickState? LastRawState { get; private set; }
public JoystickState LastState { get; set; }
/// <summary>
/// The current state of this <see cref="JoystickDevice"/>.
/// Use <see cref="UpdateRawState"/> to update the state.
/// </summary>
public osuTK.Input.JoystickState RawState { get; private set; }
private readonly Lazy<float[]> defaultDeadZones = new Lazy<float[]>(() => new float[MAX_AXES]);
/// <summary>
/// Default deadzones for each axis. Can be null if deadzones have not been found.
/// </summary>
public float[] DefaultDeadzones => defaultDeadZones.IsValueCreated ? defaultDeadZones.Value : null;
/// <summary>
/// The <see cref="Guid"/> for this <see cref="JoystickDevice"/>.
/// </summary>
public readonly Guid Guid;
public JoystickDevice(Guid guid, osuTK.Input.JoystickState rawState)
{
Guid = guid;
UpdateRawState(rawState);
}
public void UpdateRawState(osuTK.Input.JoystickState rawState)
{
LastRawState = RawState;
RawState = rawState;
if (!defaultDeadZones.IsValueCreated)
{
for (int i = 0; i < MAX_AXES; i++)
{
var axisValue = Math.Abs(RawState.GetAxis(i));
if (Precision.AlmostEquals(0, axisValue))
continue;
defaultDeadZones.Value[i] = axisValue + deadzone_threshold;
}
}
}
}
}
}
| 37.617391 | 116 | 0.500578 | [
"MIT"
] | Aergwyn/osu-framework | osu.Framework/Input/Handlers/Joystick/OsuTKJoystickHandler.cs | 8,425 | C# |
/*
* Change phone number token bridge.
*
* @author Michel Megens
* @email [email protected]
*/
using System;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace SensateIoT.API.Common.Data.Models
{
[Table("PhoneNumberTokens")]
public class ChangePhoneNumberToken
{
[Key]
public string IdentityToken { get; set; }
[Key]
public string PhoneNumber { get; set; }
public string UserToken { get; set; }
public string UserId { get; set; }
public DateTime Timestamp { get; set; }
}
} | 23.64 | 52 | 0.697124 | [
"Apache-2.0"
] | sensate-iot/platform-api | SensateIoT.API/SensateIoT.API.Common.Data/Models/ChangePhoneNumberToken.cs | 593 | 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.DirectoryService;
using Amazon.DirectoryService.Model;
namespace Amazon.PowerShell.Cmdlets.DS
{
/// <summary>
/// Creates an alias for a directory and assigns the alias to the directory. The alias
/// is used to construct the access URL for the directory, such as <code>http://<alias>.awsapps.com</code>.
///
/// <important><para>
/// After an alias has been created, it cannot be deleted or reused, so this operation
/// should only be used when absolutely necessary.
/// </para></important>
/// </summary>
[Cmdlet("New", "DSAlias", SupportsShouldProcess = true, ConfirmImpact = ConfirmImpact.Medium)]
[OutputType("Amazon.DirectoryService.Model.CreateAliasResponse")]
[AWSCmdlet("Calls the AWS Directory Service CreateAlias API operation.", Operation = new[] {"CreateAlias"}, SelectReturnType = typeof(Amazon.DirectoryService.Model.CreateAliasResponse))]
[AWSCmdletOutput("Amazon.DirectoryService.Model.CreateAliasResponse",
"This cmdlet returns an Amazon.DirectoryService.Model.CreateAliasResponse object containing multiple properties. The object can also be referenced from properties attached to the cmdlet entry in the $AWSHistory stack."
)]
public partial class NewDSAliasCmdlet : AmazonDirectoryServiceClientCmdlet, IExecutor
{
#region Parameter Alias
/// <summary>
/// <para>
/// <para>The requested alias.</para><para>The alias must be unique amongst all aliases in AWS. This operation throws an <code>EntityAlreadyExistsException</code>
/// error if the alias already exists.</para>
/// </para>
/// </summary>
#if !MODULAR
[System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)]
#else
[System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true, Mandatory = true)]
[System.Management.Automation.AllowEmptyString]
[System.Management.Automation.AllowNull]
#endif
[Amazon.PowerShell.Common.AWSRequiredParameter]
public System.String Alias { get; set; }
#endregion
#region Parameter DirectoryId
/// <summary>
/// <para>
/// <para>The identifier of the directory for which to create the alias.</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.AllowEmptyString]
[System.Management.Automation.AllowNull]
#endif
[Amazon.PowerShell.Common.AWSRequiredParameter]
public System.String DirectoryId { get; set; }
#endregion
#region Parameter Select
/// <summary>
/// Use the -Select parameter to control the cmdlet output. The default value is '*'.
/// Specifying -Select '*' will result in the cmdlet returning the whole service response (Amazon.DirectoryService.Model.CreateAliasResponse).
/// Specifying the name of a property of type Amazon.DirectoryService.Model.CreateAliasResponse 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; } = "*";
#endregion
#region Parameter PassThru
/// <summary>
/// Changes the cmdlet behavior to return the value passed to the DirectoryId parameter.
/// The -PassThru parameter is deprecated, use -Select '^DirectoryId' instead. This parameter will be removed in a future version.
/// </summary>
[System.Obsolete("The -PassThru parameter is deprecated, use -Select '^DirectoryId' instead. This parameter will be removed in a future version.")]
[System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)]
public SwitchParameter PassThru { get; set; }
#endregion
#region Parameter Force
/// <summary>
/// This parameter overrides confirmation prompts to force
/// the cmdlet to continue its operation. This parameter should always
/// be used with caution.
/// </summary>
[System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)]
public SwitchParameter Force { get; set; }
#endregion
protected override void ProcessRecord()
{
base.ProcessRecord();
var resourceIdentifiersText = FormatParameterValuesForConfirmationMsg(nameof(this.DirectoryId), MyInvocation.BoundParameters);
if (!ConfirmShouldProceed(this.Force.IsPresent, resourceIdentifiersText, "New-DSAlias (CreateAlias)"))
{
return;
}
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.DirectoryService.Model.CreateAliasResponse, NewDSAliasCmdlet>(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.DirectoryId;
}
#pragma warning restore CS0618, CS0612 //A class member was marked with the Obsolete attribute
context.Alias = this.Alias;
#if MODULAR
if (this.Alias == null && ParameterWasBound(nameof(this.Alias)))
{
WriteWarning("You are passing $null as a value for parameter Alias 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.DirectoryId = this.DirectoryId;
#if MODULAR
if (this.DirectoryId == null && ParameterWasBound(nameof(this.DirectoryId)))
{
WriteWarning("You are passing $null as a value for parameter DirectoryId 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
// allow further manipulation of loaded context prior to processing
PostExecutionContextLoad(context);
var output = Execute(context) as CmdletOutput;
ProcessOutput(output);
}
#region IExecutor Members
public object Execute(ExecutorContext context)
{
var cmdletContext = context as CmdletContext;
// create request
var request = new Amazon.DirectoryService.Model.CreateAliasRequest();
if (cmdletContext.Alias != null)
{
request.Alias = cmdletContext.Alias;
}
if (cmdletContext.DirectoryId != null)
{
request.DirectoryId = cmdletContext.DirectoryId;
}
CmdletOutput output;
// issue call
var client = Client ?? CreateClient(_CurrentCredentials, _RegionEndpoint);
try
{
var response = CallAWSServiceOperation(client, request);
object pipelineOutput = null;
pipelineOutput = cmdletContext.Select(response, this);
output = new CmdletOutput
{
PipelineOutput = pipelineOutput,
ServiceResponse = response
};
}
catch (Exception e)
{
output = new CmdletOutput { ErrorResponse = e };
}
return output;
}
public ExecutorContext CreateContext()
{
return new CmdletContext();
}
#endregion
#region AWS Service Operation Call
private Amazon.DirectoryService.Model.CreateAliasResponse CallAWSServiceOperation(IAmazonDirectoryService client, Amazon.DirectoryService.Model.CreateAliasRequest request)
{
Utils.Common.WriteVerboseEndpointMessage(this, client.Config, "AWS Directory Service", "CreateAlias");
try
{
#if DESKTOP
return client.CreateAlias(request);
#elif CORECLR
return client.CreateAliasAsync(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 System.String Alias { get; set; }
public System.String DirectoryId { get; set; }
public System.Func<Amazon.DirectoryService.Model.CreateAliasResponse, NewDSAliasCmdlet, object> Select { get; set; } =
(response, cmdlet) => response;
}
}
}
| 45.864542 | 282 | 0.615445 | [
"Apache-2.0"
] | 5u5hma/aws-tools-for-powershell | modules/AWSPowerShell/Cmdlets/DirectoryService/Basic/New-DSAlias-Cmdlet.cs | 11,512 | C# |
// c:\program files (x86)\windows kits\10\include\10.0.18362.0\um\d3dtypes.h(1547,9)
using System.Runtime.InteropServices;
namespace DirectN
{
[StructLayout(LayoutKind.Sequential, Pack = 4)]
public partial struct _D3DSTATE
{
public _D3DSTATE__union_0 __union_0;
public _D3DSTATE__union_1 __union_1;
}
}
| 25.923077 | 85 | 0.715134 | [
"MIT"
] | bbday/DirectN | DirectN/DirectN/Generated/_D3DSTATE.cs | 339 | C# |
Subsets and Splits