text stringlengths 13 6.01M |
|---|
using DChild.Gameplay.Combat;
using DChild.Gameplay.Objects;
using DChild.Gameplay.Systems.Subroutine;
using Sirenix.OdinInspector;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace DChild.Gameplay.Environment
{
public class Laser : MonoBehaviour
{
[System.Serializable]
private struct Beam
{
[SerializeField]
private ParticleFX m_decayfx;
[SerializeField]
private ParticleFX m_hitfx;
[SerializeField]
private LineRenderer m_renderer;
public void SetWidth(float width)
{
m_renderer.startWidth = width;
m_renderer.endWidth = width;
}
public void DrawBeam(Vector2 start, Vector2 direction, bool isHit)
{
m_renderer.enabled = true;
var end = start + direction;
m_renderer.SetPosition(0, start);
m_renderer.SetPosition(1, end);
if (isHit)
{
PlayerLaserEndFX(m_hitfx, m_decayfx, end);
}
else
{
PlayerLaserEndFX(m_decayfx, m_hitfx, end);
}
}
public void Stop()
{
m_hitfx.Stop(); ;
m_decayfx.Stop();
m_renderer.enabled = false;
}
private void PlayerLaserEndFX(ParticleFX enableFX, ParticleFX disableFX, Vector2 position)
{
if (enableFX.isEmmiting == false)
{
enableFX.Play();
}
disableFX.Stop();
enableFX.transform.position = position;
}
#if UNITY_EDITOR
public void Draw(Vector2 start, Vector2 direction)
{
m_renderer.enabled = true;
var end = start + direction;
m_renderer.SetPosition(0, start);
m_renderer.SetPosition(1, end);
}
#endif
}
[SerializeField]
[BoxGroup("Beam Config")]
[MinValue(0f)]
private float m_maxRange;
[SerializeField]
[BoxGroup("Beam Config")]
[MinValue(0f)]
private float m_hitboxWidth;
[SerializeField]
[BoxGroup("Beam Config")]
private float m_verticalOffSet;
[SerializeField]
private Beam m_beam;
public float maxRange => m_maxRange;
#if UNITY_EDITOR
private Vector3 m_fireDirection;
#endif
public IDamageable[] Fire(Vector2 fireDirection)
{
#if UNITY_EDITOR
m_fireDirection = fireDirection;
#endif
var source = transform.parent.position;
var visualHit = Physics2D.Raycast(source, fireDirection, m_maxRange, 1 << LayerMask.NameToLayer("Environment"));
DrawBeam(source, fireDirection, visualHit);
return GetAffectedDamageable(source, fireDirection, visualHit);
}
public void StopFire()
{
m_beam.Stop();
}
public IDamageable[] Cast(Vector2 source, Vector2 fireDirection)
{
#if UNITY_EDITOR
m_fireDirection = fireDirection;
#endif
var visualHit = Physics2D.Raycast(source, fireDirection, m_maxRange, 1 << LayerMask.NameToLayer("Environment"));
return GetAffectedDamageable(source, fireDirection, visualHit);
}
public IDamageable[] Cast(Vector2 fireDirection)
{
return Cast(transform.position, fireDirection);
}
private IDamageable[] GetAffectedDamageable(Vector3 source, Vector3 fireDirection, RaycastHit2D visualHit)
{
var distance = GetDistance(visualHit);
var damageHit = CastLaser(source, fireDirection, distance);
List<IDamageable> affectedList = new List<IDamageable>();
for (int i = 0; i < damageHit.Length; i++)
{
var hit = damageHit[i];
var hitbox = hit.collider.GetComponent<Hitbox>();
if (hitbox != null)
{
var damageable = hitbox.damageable;
if (affectedList.Contains(damageable) == false)
{
affectedList.Add(damageable);
}
}
}
return affectedList.ToArray();
}
private RaycastHit2D[] CastLaser(Vector3 source, Vector3 fireDirection, float distance)
{
source.y += m_verticalOffSet;
var size = new Vector2(1, m_hitboxWidth);
var angle = Vector2.Angle(Vector2.right, fireDirection);
return Physics2D.BoxCastAll(source, size, angle, fireDirection, distance, Physics2D.GetLayerCollisionMask(gameObject.layer));
}
private void DrawBeam(Vector3 source, Vector3 fireDirection, RaycastHit2D visualHit)
{
if (visualHit.collider != null)
{
m_beam.DrawBeam(source, fireDirection * visualHit.distance, true);
}
else
{
m_beam.DrawBeam(source, fireDirection * m_maxRange, false);
}
}
private float GetDistance(RaycastHit2D raycastHit2D) => raycastHit2D.collider ? raycastHit2D.distance : m_maxRange;
private void OnDrawGizmosSelected()
{
#if UNITY_EDITOR
var source = transform.position;
var visualHit = Physics2D.Raycast(source, m_fireDirection, m_maxRange, 1 << LayerMask.NameToLayer("Environment"));
var distance = GetDistance(visualHit);
if (Application.isPlaying)
{
Gizmos.DrawLine(source,m_fireDirection * distance);
}
else
{
m_beam.Draw(source, m_fireDirection * distance);
}
var center = source;
center.x += m_maxRange / 2f;
center.y += m_verticalOffSet;
var size = new Vector3(m_maxRange, m_hitboxWidth, 0f);
Gizmos.DrawWireCube(center, size);
#endif
}
private void OnValidate()
{
#if UNITY_EDITOR
m_fireDirection = transform.right;
m_beam.SetWidth(m_beamWidth);
#endif
}
#if UNITY_EDITOR
[SerializeField]
[BoxGroup("Beam Config")]
private float m_beamWidth;
#endif
}
}
|
using System;
using System.Collections.Generic;
namespace gView.Framework.Geometry
{
public class PointM : Point
{
private object _m;
public PointM() : base()
{ }
public PointM(double x, double y, object m)
: base(x, y)
{
_m = m;
}
public PointM(double x, double y, double z, object m)
: base(x, y, z)
{
_m = m;
}
public PointM(IPoint p, object m)
: this(p.X, p.Y, p.Z, m)
{
}
new public object M
{
get { return _m; }
set { _m = value; }
}
#region Classes
public class MComparer<T> : IComparer<PointM>
where T : IComparable
{
#region IComparer<PointM> Member
public int Compare(PointM x, PointM y)
{
return ((T)x.M).CompareTo(((T)y.M));
}
#endregion
}
#endregion
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.ServiceModel;
//Программа создана студентом 156н группы Мирненко Максимом Дмитриевиичем 30.04.20
namespace RemoteProcessesInformation
{
// контейнер для хранения информации о пользователе
class ServerUser
{
public int ID { get; set; }
public string Name { get; set; }
public OperationContext operationContext { get; set; }
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
/// <summary>
/// Spawn Coal as fuel for the engine
/// </summary>
/// <remarks>
/// The speed of spawning increases over time
/// </remarks>
public class CoalSpawner : Spawner
{
public float maxTimeLowerLimit = 0.31f;
public float minTimeLowerLimit = 0.51f;
// Unrefined audio files. Code implemented but audio is disabled due to grating audio negativly effecting experiance.
public AudioSource MachineRunning;
public AudioSource MachineBreaking;
/// <summary>
/// Initialise first random timer
/// </summary>
/// <remarks>
/// This should start playing audio for coal spawner, but the audio is so unrefined I have the audio files disabled in the editor. Enabling the audio files will cause the audio to work.
/// </remarks>
protected override void Start()
{
SetRandomTime();
MachineRunning.Play();
}
/// <summary>
/// Count the time until you need to spawn an object, at which point, set a new random time.
/// See if the coal machine should randomly break.
/// </summary>
protected override void FixedUpdate()
{
//Counts up
time += Time.deltaTime;
//Check if its the right time to spawn the object
if (time >= spawnTime)
{
SpawnObject();
SetRandomTime();
BreakMachine();
}
}
/// <summary>
/// Spawns the Object, and resets the time for the next spawn.
/// </summary>
/// <remarks>
/// There are 3 possible coal rocks that can be spawned, so we randomly select 1 of these each time.
/// </remarks>
protected override void SpawnObject()
{
//Reset time to start
time = 0;
//Reduce timers slightly to a minmum
if (minTime > minTimeLowerLimit)
{
minTime -= 0.1f;
}
if (maxTime > maxTimeLowerLimit)
{
maxTime -= 0.1f;
}
//Max int is exclusive
int rnd = Random.Range(0, Object.Length);
//The Object instantiation happens here.
GameObject TemporaryObjectHandler;
TemporaryObjectHandler = Instantiate(Object[rnd], ObjectEmitter.transform.position, ObjectEmitter.transform.rotation) as GameObject;
}
/// <summary>
/// Every time a piece of coal spawns, the spawner has a chance of "breaking". Once this happens, the user must hit the spawner 3 times to fix. Code seen in "FixCoalSpawner" file.
/// </summary>
/// <remarks>
/// The machine should break on average once every 20 pieces.
/// </remarks>
void BreakMachine()
{
int isBreak = Random.Range(0, 1000);
if (isBreak < 50)
{
//Disable spawning, enable script to allow object to be fixed.
(GetComponent("RandomCoalSpawning") as MonoBehaviour).enabled = false;
(GetComponent("FixCoalSpawner") as MonoBehaviour).enabled = true;
transform.Find("WhiteSmoke").gameObject.SetActive(true);
MachineRunning.Stop();
MachineBreaking.Play();
}
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
using System;
public class TerrainGenerator : MonoBehaviour {
Mesh mesh;
Renderer textureRenderer;
float[,] noiseMap;
public enum DrawMode { textureMode, colorMode, meshMode };
Vector3[] vertices;
int[] triangles;
Vector2[] uvs;
[Header("Terrain Dimensions")]
public int terrainWidth = 20; //x
public int terrainHeight = 20; //z
public bool useChunks = false;
[Range(0, 6)]
public int levelOfDetail = 0;
[Header("Terrain Control")]
public float noiseScale = 3;
public int octaves = 1;
[Range(0, 1)]
public float persistance = 0.5f;
public float lacunarity = 2;
public int seed = 0;
public Vector2 sampleOffset = new Vector2(0, 0);
public float elevation = 1;
public AnimationCurve elevationCurve;
[Header("Color Settings")]
public Material material;
public Gradient colorGradient;
public bool coloredMesh = true;
[Header("Other Settings")]
public DrawMode drawMode;
public bool enableVertexGizmos = false;
public bool autoUpdate = false;
void Start() {
CreateMesh();
UpdateMesh();
}
float[,] GenerateNoiseMap() {
float [,] noiseMap = new float[terrainWidth, terrainHeight];
System.Random rng = new System.Random(seed);
Vector2[] octaveOffsets = new Vector2[octaves];
for(int i = 0; i < octaves; i++) {
octaveOffsets[i] = new Vector2(rng.Next(-100000, 100000) + sampleOffset.x, rng.Next(-100000, 100000) + sampleOffset.y);
}
float tmpScale = noiseScale;
if(tmpScale <= 0) tmpScale = 0.001f;
float maxNoiseHeight = float.MinValue;
float minNoiseHeight = float.MaxValue;
for(int x = 0; x < terrainWidth; x++) {
for(int z = 0; z < terrainHeight; z++) {
float amplitude = 1;
float frequency = 1;
float noiseHeight = 0;
for(int i = 0; i < octaves; i++) {
float sampleX = (x - terrainWidth / 2) / tmpScale * frequency + octaveOffsets[i].x;
float sampleZ = (z - terrainHeight / 2) / tmpScale * frequency + octaveOffsets[i].y;
noiseHeight += Mathf.PerlinNoise(sampleX, sampleZ) * amplitude * 2 - 1;
amplitude *= persistance;
frequency *= lacunarity;
}
if(noiseHeight > maxNoiseHeight) maxNoiseHeight = noiseHeight;
else if(noiseHeight < minNoiseHeight) minNoiseHeight = noiseHeight;
noiseMap[x,z] = noiseHeight;
}
}
for(int x = 0; x < terrainWidth; x++) {
for(int z = 0; z < terrainHeight; z++) {
noiseMap[x,z] = Mathf.InverseLerp(minNoiseHeight, maxNoiseHeight, noiseMap[x, z]);
}
}
return noiseMap;
}
public void CreateMesh() {
GameObject go = new GameObject("Chunk", typeof(MeshFilter), typeof(MeshRenderer), typeof(MeshCollider));
go.transform.parent = transform;
go.GetComponent<Renderer>().material = material;
mesh = new Mesh();
go.GetComponent<MeshFilter>().mesh = mesh;
go.GetComponent<MeshCollider>().sharedMesh = mesh;
textureRenderer = go.GetComponent<MeshRenderer>();
textureRenderer.material = material;
int inc = (useChunks && levelOfDetail != 0) ? levelOfDetail * 2 : 1;
int xVerts = (terrainWidth - 1) / inc + 1;
int zVerts = (terrainHeight - 1) / inc + 1;
vertices = new Vector3[xVerts * zVerts];
triangles = new int[(xVerts - 1) * (zVerts - 1) * 6];
uvs = new Vector2[xVerts * zVerts];
noiseMap = GenerateNoiseMap();
for(int x = 0; x < terrainWidth; x += inc) {
for(int z = 0; z < terrainHeight; z += inc) {
int xNorm = x / inc;
int zNorm = z / inc;
vertices[xNorm * zVerts + zNorm] = new Vector3(x, (drawMode == DrawMode.meshMode) ? elevationCurve.Evaluate(noiseMap[x, z]) * elevation : 0, z);
uvs[xNorm * zVerts + zNorm] = new Vector2(x/(float)terrainWidth, z/(float)terrainHeight);
if(z != (terrainHeight - 1) && x != terrainWidth - 1) {
triangles[(xNorm * (zVerts - 1) + zNorm) * 6] = xNorm * zVerts + zNorm;
triangles[(xNorm * (zVerts - 1) + zNorm) * 6 + 1] = xNorm * zVerts + zNorm + 1;
triangles[(xNorm * (zVerts - 1) + zNorm) * 6 + 2] = (xNorm + 1) * zVerts + zNorm + 1;
triangles[(xNorm * (zVerts - 1) + zNorm) * 6 + 3] = xNorm * zVerts + zNorm;
triangles[(xNorm * (zVerts - 1) + zNorm) * 6 + 4] = (xNorm + 1) * zVerts + zNorm + 1;
triangles[(xNorm * (zVerts - 1) + zNorm) * 6 + 5] = (xNorm + 1) * zVerts + zNorm;
}
}
}
if(drawMode == DrawMode.textureMode) drawNoiseMap(noiseMap);
else if(drawMode == DrawMode.colorMode || (drawMode == DrawMode.meshMode && coloredMesh)) drawColorMap(noiseMap);
else textureRenderer.sharedMaterial.mainTexture = null;
}
public void UpdateMesh() {
mesh.Clear();
mesh.vertices = vertices;
mesh.triangles = triangles;
mesh.uv = uvs;
mesh.RecalculateNormals();
}
public void drawNoiseMap(float[,] noiseMap) {
Texture2D texture = new Texture2D(terrainWidth, terrainHeight);
Color[] colorMap = new Color[terrainWidth * terrainHeight];
for(int x = 0; x < terrainWidth; x++) {
for(int z = 0; z < terrainHeight; z++) {
colorMap[z + terrainHeight * x] = Color.Lerp(Color.black, Color.white, noiseMap[x, z]);
}
}
texture.SetPixels(colorMap);
texture.Apply();
textureRenderer.sharedMaterial.mainTexture = texture;
}
public void drawColorMap(float[,] noiseMap) {
Texture2D texture = new Texture2D(terrainWidth, terrainHeight);
Color[] colorMap = new Color[terrainWidth * terrainHeight];
for(int x = 0; x < terrainWidth; x++) {
for(int z = 0; z < terrainHeight; z++) {
colorMap[x + terrainWidth * z] = colorGradient.Evaluate(noiseMap[x, z]);
}
}
texture.filterMode = FilterMode.Point;
texture.SetPixels(colorMap);
texture.Apply();
textureRenderer.sharedMaterial.mainTexture = texture;
}
private void OnDrawGizmos() {
if(enableVertexGizmos) {
if(vertices == null) return;
for(int i = 0; i < vertices.Length; i++) {
Gizmos.DrawSphere(vertices[i], .1f);
}
}
}
private void OnValidate() {
if(!useChunks) {
if(terrainWidth < 1) terrainWidth = 1;
if(terrainWidth > 255) terrainWidth = 255;
if(terrainHeight < 1) terrainHeight = 1;
if(terrainHeight > 255) terrainHeight = 255;
} else {
terrainWidth = 241;
terrainHeight = 241;
}
if(noiseScale < 0) noiseScale = 0;
if(octaves < 0) octaves = 0;
if(lacunarity < 0) lacunarity = 0;
if(elevation < 0) elevation = 0;
}
private void Update() {
if(coloredMesh && textureRenderer.sharedMaterial.mainTexture == null) drawColorMap(noiseMap);
}
} |
using Microsoft.Extensions.Logging;
using SFA.DAS.CommitmentsV2.Shared.Interfaces;
using SFA.DAS.Encoding;
using SFA.DAS.ProviderCommitments.Interfaces;
using SFA.DAS.ProviderCommitments.Web.Models.Cohort;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Threading.Tasks;
using SFA.DAS.ProviderCommitments.Extensions;
using SFA.DAS.ProviderCommitments.Infrastructure.OuterApi.Responses;
namespace SFA.DAS.ProviderCommitments.Web.Mappers.Cohort
{
public class ReviewApprenticeRequestToReviewApprenticeViewModelMapper : IMapper<FileUploadReviewApprenticeRequest, FileUploadReviewApprenticeViewModel>
{
private readonly IOuterApiService _outerApiService;
private readonly ICacheService _cacheService;
private readonly IEncodingService _encodingService;
private readonly ILogger<ReviewApprenticeRequestToReviewApprenticeViewModelMapper> _logger;
public ReviewApprenticeRequestToReviewApprenticeViewModelMapper(ILogger<ReviewApprenticeRequestToReviewApprenticeViewModelMapper> logger,
IOuterApiService commitmentApiClient, ICacheService cacheService, IEncodingService encodingService)
{
_outerApiService = commitmentApiClient;
_cacheService = cacheService;
_encodingService = encodingService;
_logger = logger;
}
public async Task<FileUploadReviewApprenticeViewModel> Map(FileUploadReviewApprenticeRequest source)
{
//Get CsvRecord details
var csvRecords = await _cacheService.GetFromCache<List<CsvRecord>>(source.CacheRequestId.ToString());
var csvRecordsGroupedByCohort = csvRecords.Where(x => (!string.IsNullOrWhiteSpace(x.CohortRef) && x.CohortRef == source.CohortRef) ||
(string.IsNullOrWhiteSpace(source.CohortRef) && string.IsNullOrWhiteSpace(x.CohortRef) && source.AgreementId == x.AgreementId));
_logger.LogInformation("Total number of records from cache: " + csvRecords.Count);
//Get commitments from DB
var existingCohortDetails = new List<ReviewApprenticeDetailsForExistingCohort>();
var messageFromEmployer = string.Empty;
if (!string.IsNullOrWhiteSpace(source.CohortRef))
{
var cohortId = _encodingService.Decode(source.CohortRef, EncodingType.CohortReference);
messageFromEmployer = (await _outerApiService.GetCohort(cohortId)).LatestMessageCreatedByEmployer;
var existingDraftApprenticeshipsResponse = await _outerApiService.GetDraftApprenticeships(cohortId);
if (existingDraftApprenticeshipsResponse != null)
{
_logger.LogInformation("Total number of records from db: " + existingDraftApprenticeshipsResponse.DraftApprenticeships.Count);
existingCohortDetails = await MapExistingCohortDetails(existingDraftApprenticeshipsResponse);
}
}
var publicAccountLegalEntityIdNew = _encodingService.Decode(csvRecordsGroupedByCohort.FirstOrDefault().AgreementId, EncodingType.PublicAccountLegalEntityId);
var result = new FileUploadReviewApprenticeViewModel
{
ProviderId = source.ProviderId,
CohortRef = (!string.IsNullOrWhiteSpace(source.CohortRef)) ? source.CohortRef : string.Empty,
CacheRequestId = source.CacheRequestId,
ExistingCohortDetails = existingCohortDetails,
FileUploadCohortDetails = await MapFileUploadCohortDetails(csvRecordsGroupedByCohort),
LegalEntityName = (await _outerApiService.GetAccountLegalEntity(publicAccountLegalEntityIdNew)).LegalEntityName,
MessageFromEmployer = messageFromEmployer
};
return result;
}
private async Task<List<ReviewApprenticeDetailsForFileUploadCohort>> MapFileUploadCohortDetails(IEnumerable<CsvRecord> csvRecordsGroupedByCohort)
{
var reviewApprenticeDetailsForFileUploadCohort = new List<ReviewApprenticeDetailsForFileUploadCohort>();
foreach (var csvRecord in csvRecordsGroupedByCohort)
{
var courseDetails = await _outerApiService.GetStandardDetails(csvRecord.StdCode);
var dateOfBirth = GetValidDate(csvRecord.DateOfBirth, "yyyy-MM-dd");
var apprenticeStartDate = GetValidDate(csvRecord.StartDate, "yyyy-MM-dd");
var apprenticeEndDate = GetValidDate(csvRecord.EndDate, "yyyy-MM");
var fileUploadApprenticeDetail = new ReviewApprenticeDetailsForFileUploadCohort
{
Name = $"{csvRecord.GivenNames} {csvRecord.FamilyName}",
TrainingCourse = courseDetails.Title,
ULN = csvRecord.ULN,
DateOfBirth = dateOfBirth.Value.ToString("d MMM yyyy"),
Email = csvRecord.EmailAddress,
TrainingDates = $"{apprenticeStartDate.Value:MMM yyyy} to {apprenticeEndDate.Value:MMM yyyy} ",
Price = int.Parse(csvRecord.TotalPrice),
FundingBandCap = GetFundingBandCap(courseDetails, apprenticeStartDate.Value.Date)
};
reviewApprenticeDetailsForFileUploadCohort.Add(fileUploadApprenticeDetail);
}
return reviewApprenticeDetailsForFileUploadCohort;
}
private async Task<List<ReviewApprenticeDetailsForExistingCohort>> MapExistingCohortDetails(GetDraftApprenticeshipsResult response)
{
var reviewApprenticeDetailsForExistingCohort = new List<ReviewApprenticeDetailsForExistingCohort>();
foreach (var item in response.DraftApprenticeships)
{
var course = await _outerApiService.GetStandardDetails(item.CourseCode);
var apprenticeDetail = new ReviewApprenticeDetailsForExistingCohort
{
Name = $"{item.FirstName} {item.LastName}",
TrainingCourse = item.CourseName,
ULN = item.Uln,
DateOfBirth = item.DateOfBirth.Value.ToString("d MMM yyyy"),
Email = item.Email,
TrainingDates = $"{item.StartDate.Value:MMM yyyy} to {item.EndDate.Value:MMM yyyy} ",
Price = item.Cost ?? 0,
FundingBandCapForExistingCohort = GetFundingBandCap(course, item.StartDate.Value.Date)
};
reviewApprenticeDetailsForExistingCohort.Add(apprenticeDetail);
}
return reviewApprenticeDetailsForExistingCohort;
}
private DateTime? GetValidDate(string date, string format)
{
DateTime outDateTime;
if (DateTime.TryParseExact(date, format, CultureInfo.InvariantCulture, DateTimeStyles.None, out outDateTime))
return outDateTime;
return null;
}
private int? GetFundingBandCap(GetStandardResponse course, DateTime? startDate)
{
if (startDate == null)
{
return null;
}
if (course == null)
{
return null;
}
var cap = course.FundingCapOn(startDate.Value);
if (cap > 0)
{
return cap;
}
return null;
}
}
} |
namespace qbq.EPCIS.Repository.Custom.Entities
{
class EpcisEventValueStringValueString
{
//create table #EPCISEvent_Value_String_Value_String
//(
//EPCISEvent_ValueID bigint not null,
//Value_StringID bigint not null
//);
public long EpcisEventValueId { get; set; }
public long ValueStringId { get; set; }
}
}
|
using Profiling2.Domain.Prf;
namespace Profiling2.Web.Mvc.Areas.Profiling.Controllers.ViewModels
{
public class RegionViewModel
{
public int Id { get; set; }
public string RegionName { get; set; }
public string Notes { get; set; }
public bool Archive { get; set; }
public RegionViewModel() { }
public RegionViewModel(Region reg)
{
if (reg != null)
{
this.Id = reg.Id;
this.RegionName = reg.RegionName;
this.Notes = reg.Notes;
this.Archive = reg.Archive;
}
}
}
} |
using System;
using System.Collections.Generic;
using System.Collections;
using System.Collections.Specialized;
namespace LeetCodeTests
{
public abstract class Problem_0073
{
/*
Given a m x n matrix, if an element is 0, set its entire row and column to 0. Do it in place.
Follow up:
Did you use extra space?
A straight forward solution using O(mn) space is probably a bad idea.
A simple improvement uses O(m + n) space, but still not the best solution.
Could you devise a constant space solution?
*/
public static void Test()
{
Solution sol = new Solution();
/*
var input = new int[] { 2, 7, 11, 15 };
Console.WriteLine($"Input array: {string.Join(", ", input)}");
*/
var input = new int[4, 5]{
{1,2,0,4,3},
{0,3,2,1,5},
{1,2,3,4,5},
{1,2,3,4,0}};
Console.WriteLine($"For input matrix:\n{Utils.Print2DArray(input)}");
sol.SetZeroes(input);
Console.WriteLine($"Output matrix:\n{Utils.Print2DArray(input)}\n");
input = new int[4, 5]{
{1,2,3,4,3},
{1,3,2,1,5},
{1,2,3,4,5},
{1,2,3,4,0}};
Console.WriteLine($"For input matrix:\n{Utils.Print2DArray(input)}");
sol.SetZeroes(input);
Console.WriteLine($"Output matrix:\n{Utils.Print2DArray(input)}\n");
input = new int[4, 5]{
{0,2,3,4,3},
{1,3,2,1,5},
{1,2,3,4,5},
{1,2,3,4,0}};
Console.WriteLine($"For input matrix:\n{Utils.Print2DArray(input)}");
sol.SetZeroes(input);
Console.WriteLine($"Output matrix:\n{Utils.Print2DArray(input)}\n");
/*
Submission Result: Wrong Answer
Input:[[-4,-2147483648,6,-7,0],[-8,6,-8,-6,0],[2147483647,2,-9,-6,-10]]
Output: [[0,0,0,0,0],[0,0,0,0,0],[0,2,-9,-6,0]]
Expected: [[0,0,0,0,0],[0,0,0,0,0],[2147483647,2,-9,-6,0]]
*/
input = new int[3, 5]{
{-4,-2147483648,6,-7,0},
{-8,6,-8,-6,0},
{2147483647,2,-9,-6,-10}};
Console.WriteLine($"For input matrix:\n{Utils.Print2DArray(input)}");
sol.SetZeroes(input);
Console.WriteLine($"Output matrix:\n{Utils.Print2DArray(input)}\n");
}
public class Solution
{
public void SetZeroes(int[,] matrix)
{
int m = matrix.GetLength(0);
int n = matrix.GetLength(1);
bool Col0 = false;
// use first element in row to say - all row should be 0
// add variable Col0 to indicate that all First column should be 0
for (int i = 0; i < m; i++)
{
Col0 |= (matrix[i, 0] == 0);
for (int j = 1; j < n; j++)
if (matrix[i, j] == 0)
{
matrix[i, 0] = 0;
matrix[0, j] = 0;
}
}
// fill
for (int i = m - 1; i >= 0; i--)
for (int j = n - 1; j >= 0; j--)
if ((matrix[i, 0] == 0) || ((matrix[0, j] == 0) && (j != 0)) || ((j == 0) && Col0))
matrix[i, j] = 0;
}
}
/// <summary>
/// passed solution
/// </summary>
public class Solution_no_bad
{
public void SetZeroes(int[,] matrix)
{
int m = matrix.GetLength(0);
int n = matrix.GetLength(1);
// idea:
// if row contains 0, first element will be 0, so, use first element to indicate ROW should be 0
// if col contains 0, col element in first row will be 0, so use first row as indicator COL should be 0
// need only two flag ZeroRow and ZeroCol for check if Fist row or First col contains 0
bool ZeroRow = false;
bool ZeroCol = false;
for (int i = 0; i < m; i++)
{
for (int j = 0; j < n; j++)
{
if (matrix[i, j] == 0)
{
ZeroRow |= (i == 0);
ZeroCol |= (j == 0);
matrix[0, j] = 0;
matrix[i, 0] = 0;
}
}
}
for (int i = 1; i < m; i++)
{
if (matrix[i, 0] == 0)
for (int j = 1; j < n; j++)
matrix[i, j] = 0;
}
for (int j = 1; j < n; j++)
{
if (matrix[0, j] == 0)
for (int i = 1; i < m; i++)
matrix[i, j] = 0;
}
if (ZeroRow)
for (int j = 0; j<n; j++)
matrix[0, j] = 0;
if (ZeroCol)
for (int i = 0; i < m; i++)
matrix[i, 0] = 0;
}
}
}//public abstract class Problem_
} |
public class Minigun : Weapon
{
public override void Shoot()
{
Fire();
}
private void Fire()
{
if (hitScan)
FireWithHitScan();
else if (!hitScan)
FireProjectile();
OnShotFired();
}
}
|
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System;
public class Pusher : MonoBehaviour {
private static GameObject Host = new GameObject();
private static GameObject LockObj = new GameObject();
private static List<Action> actions = new List<Action>();
public static void Instantiate()
{
if (Host.GetComponent<Pusher>() == null)
{
Pusher pusher = Host.AddComponent<Pusher>();
Host.name = "Global_Pusher";
LockObj.name = "Lock";
LockObj.transform.parent = Host.transform;
DontDestroyOnLoad(Host);
DontDestroyOnLoad(LockObj);
}
}
void Start () {
}
void Update () {
this.push();
}
void Awake()
{
}
void push()
{
lock (LockObj)
{
try
{
foreach(Action act in actions)
{
act.Invoke();
}
actions.Clear();
}
catch
{
actions.Clear();
}
}
}
public static void Run(Action action)
{
lock(LockObj)
{
actions.Add(action);
}
}
}
|
using System.Collections.Generic;
using System.Linq;
using Dapper;
using System.Data;
using MySql.Data.MySqlClient;
using Demo.Models;
using Microsoft.Extensions.Options;
namespace Demo.Factories
{
public class UserFactory
{
private MySqlOptions _options;
public UserFactory(IOptions<MySqlOptions> config)
{
_options = config.Value;
}
internal IDbConnection Connection
{
get
{
return new MySqlConnection(_options.ConnectionString);
}
}
public void Add(User user)
{
using (IDbConnection dbConnection = Connection)
{
string query = "INSERT INTO users (name, email, password, created_at, updated_at) VALUES (@Name, @Email, @Password, NOW(), NOW())";
dbConnection.Open();
dbConnection.Execute(query, user);
}
}
public IEnumerable<User> FindAll()
{
using (IDbConnection dbConnection = Connection)
{
dbConnection.Open();
return dbConnection.Query<User>("SELECT * FROM users");
}
}
public User FindByID(int id)
{
using (IDbConnection dbConnection = Connection)
{
dbConnection.Open();
return dbConnection.Query<User>("SELECT * FROM users WHERE id = @Id", new { Id = id }).FirstOrDefault();
}
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace IdomOffice.Core.Config
{
public class ConfigDateInfo:ConfigInfo
{
public DateTime GetValue(string key)
{
DateTime data = DateTime.Now;
var item = LoadJson().Find(m => m.Key == key);
string itemtype = item.KeyType;
string itemvalue = item.Value;
data = DateTime.Parse(itemvalue);
return data;
}
}
}
|
using Cs_IssPrefeitura.Aplicacao.Interfaces;
using Cs_IssPrefeitura.Dominio.Entities;
using Cs_IssPrefeitura.Dominio.Interfaces.Servicos;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Cs_IssPrefeitura.Aplicacao.ServicosApp
{
public class AppServicoAtoIss: AppServicoBase<AtoIss>, IAppServicoAtoIss
{
private readonly IServicoAtoIss _servicoAtoIss;
public AppServicoAtoIss(IServicoAtoIss servicoAtoIss)
:base(servicoAtoIss)
{
_servicoAtoIss = servicoAtoIss;
}
public AtoIss CalcularValoresAtoIss(AtoIss atoCalcular)
{
return _servicoAtoIss.CalcularValoresAtoIss(atoCalcular);
}
public List<AtoIss> LerArquivoXml(string caminho)
{
return _servicoAtoIss.LerArquivoXml(caminho);
}
public List<string> CarregarListaAtribuicoes()
{
return _servicoAtoIss.CarregarListaAtribuicoes();
}
public List<string> CarregarListaTipoAtos()
{
return _servicoAtoIss.CarregarListaTipoAtos();
}
public List<AtoIss> ListarAtosPorPeriodo(DateTime inicio, DateTime fim)
{
return _servicoAtoIss.ListarAtosPorPeriodo(inicio, fim);
}
public List<AtoIss> VerificarRegistrosExistentesPorData(DateTime data)
{
return _servicoAtoIss.VerificarRegistrosExistentesPorData(data);
}
public List<AtoIss> ConsultaDetalhada(string tipoConsulta, string dados)
{
return _servicoAtoIss.ConsultaDetalhada(tipoConsulta, dados);
}
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace lab_009
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
comboBox1.Text = "Выбери опцию";
comboBox1.Items.AddRange(new string[]
{
"Прибавить",
"Отнять",
"Умножить",
"Разделить",
"Очистить"
});
comboBox1.TabIndex = 2;
textBox1.Clear();
textBox1.TabIndex = 0;
textBox2.Clear();
textBox2.TabIndex = 1;
this.Text = "Суперкалькулятор";
label1.Text = "Равно: ";
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
label1.Text = "Равно: ";
float X, Y, Z = 0;
bool isNumber1 = float.TryParse(textBox1.Text,
System.Globalization.NumberStyles.Number,
System.Globalization.NumberFormatInfo.CurrentInfo,
out X);
bool isNumber2 = float.TryParse(textBox2.Text,
System.Globalization.NumberStyles.Number,
System.Globalization.NumberFormatInfo.CurrentInfo,
out Y);
if (isNumber1 == false || isNumber2 == false)
{
MessageBox.Show("Следует вводить числа!", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
switch (comboBox1.SelectedIndex)
{
case 0:
Z = X + Y;
break;
case 1:
Z = X - Y;
break;
case 2:
Z = X * Y;
break;
case 3:
Z = X / Y;
break;
case 4:
textBox1.Clear();
textBox2.Clear();
label1.Text = "Равно: ";
return;
default:
break;
}
label1.Text = string.Format("Равно: {0:F5}", Z);
}
}
}
|
using FinalExamNew.Dal;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace FinalExamNew.Data.Configuration
{
public class OglasConfiguration : IEntityTypeConfiguration<Oglas>
{
public void Configure(EntityTypeBuilder<Oglas> builder)
{
builder.HasKey(o => o.OglasId);
builder.ToTable("Oglas");
//builder.Ignore(m => m.CenaView);
//builder.Ignore(m => m.DatumDoView);
//builder.Ignore(m => m.DatumOdView);
//builder.Ignore(m => m.KljucneReciView);
//builder.Ignore(m => m.NaslovView);
//builder.Ignore(m => m.TekstView);
//builder.Ignore(m => m.TipoviOglasaView);
//builder.Ignore(m => m.UploadFilesView);
builder.HasMany(o => o.KljucneReciOglasa).WithOne(kro => kro.Oglas);
builder.HasMany(o => o.Slike).WithOne(s => s.Oglas);
builder.HasMany(o => o.Oglasavanja).WithOne(obj => obj.Oglas);
builder.HasOne(o => o.User).WithMany(n => n.Oglasi).HasForeignKey(m=>m.UserId);
builder.HasOne(o => o.Cena).WithMany(m=>m.Oglasi);
}
}
}
|
using DFC.ServiceTaxonomy.GraphSync.GraphSyncers.Exceptions;
using DFC.ServiceTaxonomy.GraphSync.GraphSyncers.Helpers;
using DFC.ServiceTaxonomy.GraphSync.GraphSyncers.Interfaces.ContentItemVersions;
using DFC.ServiceTaxonomy.GraphSync.Models;
using DFC.ServiceTaxonomy.GraphSync.Settings;
using FakeItEasy;
using Newtonsoft.Json.Linq;
using OrchardCore.ContentManagement.Metadata;
using OrchardCore.ContentManagement.Metadata.Models;
using Xunit;
namespace DFC.ServiceTaxonomy.UnitTests.GraphSync.GraphSyncers.Helpers
{
public class SyncNameProviderHelperTests
{
public IContentDefinitionManager ContentDefinitionManager { get; set; }
public ISuperpositionContentItemVersion SuperpositionContentItemVersion { get; set; }
// using a real one is not ideal
public ContentTypeDefinition ContentTypeDefinition { get; set; }
public SyncNameProvider SyncNameProvider { get; set; }
private const string _contentType = "ContentType";
public SyncNameProviderHelperTests()
{
ContentDefinitionManager = A.Fake<IContentDefinitionManager>();
ContentTypeDefinition = new ContentTypeDefinition("name", "displayName",
new[]
{
new ContentTypePartDefinition(nameof(GraphSyncPart), new ContentPartDefinition(nameof(GraphSyncPart)), null)
},
new JObject());
A.CallTo(() => ContentDefinitionManager.GetTypeDefinition(_contentType)).Returns(ContentTypeDefinition);
SuperpositionContentItemVersion = A.Fake<ISuperpositionContentItemVersion>();
SyncNameProvider = new SyncNameProvider(
ContentDefinitionManager,
SuperpositionContentItemVersion);
}
[Fact]
public void SyncNameProvider_ContentTypeSetToNull_ArgumentNullExceptionThrown()
{
Assert.Throws<SetArgumentNullException>(() => SyncNameProvider.ContentType = null);
}
[Fact]
public void SyncNameProvider_ContentTypeSet_GraphSyncPartSettingsReturned()
{
SyncNameProvider.ContentType = _contentType;
GraphSyncPartSettings graphSyncPartSettings = SyncNameProvider.GraphSyncPartSettings;
Assert.NotNull(graphSyncPartSettings);
}
}
}
|
using Rexxar.Chat.Dtos;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
namespace Rexxar.Chat.Extensions
{
public static class UserExtension
{
public static UserDto GetUser(this ClaimsPrincipal claimsPrincipal)
{
return new UserDto
{
Id = new Guid(claimsPrincipal.Claims.FirstOrDefault(r => r.Type == "sub").Value),
EMail = claimsPrincipal.Claims.FirstOrDefault(r => r.Type == "email").Value,
UserName = claimsPrincipal.Claims.FirstOrDefault(r => r.Type == "username").Value,
Avatar = claimsPrincipal.Claims.FirstOrDefault(r => r.Type == "avatar").Value,
};
}
}
}
|
using System;
using System.Collections.Generic;
using System.Net;
using System.Text;
namespace GK.Core
{
/// <summary>
/// This exception is used to return an error message back to the caller. It should not be used for
/// exceptions which contain sensitive info such as stack traces, hostnames, etc.
/// </summary>
public class GKFriendlyException : GKException
{
public GKFriendlyException()
{ }
public GKFriendlyException(string message)
: base(message)
{ }
public GKFriendlyException(HttpStatusCode statusCode, string message)
: base(statusCode, message)
{ }
public GKFriendlyException(string message, Exception inner)
: base(message, inner)
{ }
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void BulletedList1_Click(object sender, BulletedListEventArgs e)
{
Response.Write("your selected:" + BulletedList1.Items[e.Index].Text);
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using CreamBell_DMS_WebApps.App_Code;
using System.IO;
using Elmah;
namespace CreamBell_DMS_WebApps
{
public partial class frmFOCPurchaseInvoice : System.Web.UI.Page
{
public DataTable dtLineItems;
SqlConnection conn = null;
SqlCommand cmd, cmd1;
SqlTransaction transaction;
SqlDataAdapter adp2, adp1;
DataSet ds2 = new DataSet();
DataSet ds1 = new DataSet();
public static decimal ProductWeight;
public static decimal ProductLitre;
SqlDataAdapter da = new SqlDataAdapter();
protected void Page_Load(object sender, EventArgs e)
{
if (Session["USERID"] == null || Session["USERID"].ToString() == string.Empty)
{
Response.Redirect("Login.aspx");
return;
}
if (!Page.IsPostBack)
{
string datestring = DateTime.Now.ToString("yyyy-MM-dd");
txtReceiptDate.Text = datestring;
FillIndentNo();
Session["LineItem"] = null;
BtnUpdateHeader.Visible = false;
txtIndentDate.Attributes.Add("readonly", "readonly");
txtInvoiceDate.Attributes.Add("readonly", "readonly");
if (Request.QueryString["PreNo"] != null)
{
GetUnPostedReferenceData(Request.QueryString["PreNo"]);
}
}
}
[System.Web.Script.Services.ScriptMethod()]
[System.Web.Services.WebMethod]
public static List<string> GetProductDescription(string prefixText)
{
CreamBell_DMS_WebApps.App_Code.Global obj = new Global();
string query = "Select ITEMID +'-(' + PRODUCT_NAME+')' as PRODUCT_NAME, ITEMID,PRODUCT_GROUP, PRODUCT_SUBCATEGORY from ax.INVENTTABLE where " +
"replace(replace(ITEMID, char(9), ''), char(13) + char(10), '') Like @ProductCode+'%'";
SqlConnection conn = obj.GetConnection();
SqlCommand cmd = new SqlCommand(query, conn);
cmd.Parameters.AddWithValue("@ProductCode", prefixText);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
List<string> ProductDetails = new List<string>();
for (int i = 0; i < dt.Rows.Count; i++)
{
ProductDetails.Add(dt.Rows[i]["ITEMID"].ToString());
}
return ProductDetails;
}
protected void BtnGetProductDetails_Click(object sender, EventArgs e)
{
try {
LblMessage.Text = "";
if (txtProductCode.Text != string.Empty)
{
CreamBell_DMS_WebApps.App_Code.Global obj = new Global();
ProductLitre = 0;
ProductWeight= 0;
string queryFillProductDetails = "Select ITEMID +'-(' + PRODUCT_NAME+')' as PRODUCT_NAME, ITEMID,PRODUCT_GROUP, PRODUCT_SUBCATEGORY," +
" CAST(ROUND(PRODUCT_MRP,2) as NUMERIC(10,2)) as PRODUCT_MRP ,CAST(ROUND(LTR,2) as NUMERIC(10,2)) as LTR, " +
" CAST(ROUND(NETWEIGHTPCS,2) as NUMERIC(10,2)) as NETWEIGHTPCS " +
"from ax.INVENTTABLE where replace(replace(ITEMID, char(9), ''), char(13) + char(10), '')= '" + txtProductCode.Text.Trim().ToString() + "'";
DataTable dtProductDetails = obj.GetData(queryFillProductDetails);
if (dtProductDetails.Rows.Count > 0 && dtProductDetails.Rows.Count == 1)
{
txtProductDesc.Text = dtProductDetails.Rows[0]["PRODUCT_NAME"].ToString();
txtMRP.Text = dtProductDetails.Rows[0]["PRODUCT_MRP"].ToString();
txtWeight.Text = dtProductDetails.Rows[0]["NETWEIGHTPCS"].ToString();
txtVolume.Text = dtProductDetails.Rows[0]["LTR"].ToString();
ProductWeight = Convert.ToDecimal(dtProductDetails.Rows[0]["NETWEIGHTPCS"].ToString());
ProductLitre = Convert.ToDecimal(dtProductDetails.Rows[0]["LTR"].ToString());
}
if (dtProductDetails.Rows.Count > 1)
{
//this.Page.ClientScript.RegisterStartupScript(GetType(), "Alert", " alert('Product Code Issue: We Have Duplicate Records for this Product Code !');", true);
LblMessage.Text = "Product Code Issue: We Have Duplicate Records for this Product Code !";
// string message = "alert('Product Code Issue: We Have Duplicate Records for this Product Code !');";
//ScriptManager.RegisterClientScriptBlock((sender as Control), this.GetType(), "alert", message, true);
}
if (dtProductDetails.Rows.Count == 0)
{
//this.Page.ClientScript.RegisterStartupScript(GetType(), "Alert", " alert('Product Code Issue: No Such Produt Code Exist !');", true);
LblMessage.Text = "Product Code Issue: No Such Produt Code Exist !";
//string message = "alert('Product Code Issue: No Such Produt Code Exist !');";
//ScriptManager.RegisterClientScriptBlock((sender as Control), this.GetType(), "alert", message, true);
}
}
else
{
txtProductCode.Focus();
//this.Page.ClientScript.RegisterStartupScript(GetType(), "Alert", " alert('Please Provide Product Code Here !');", true);
LblMessage.Text = "Please Provide Product Code Here !";
// string message = " alert('Please Provide Product Code Here !');";
//ScriptManager.RegisterClientScriptBlock((sender as Control), this.GetType(), "alert", message, true);
}
}
catch (Exception ex)
{
ErrorSignal.FromCurrentContext().Raise(ex);
}
}
private bool ValidateManualEntry()
{
bool b = false;
if (txtInvoiceNo.Text == string.Empty)
{
LblMessage.Text = "► Please Provide Invoice No.";
txtInvoiceNo.Focus();
b = false;
return b;
}
if (txtInvoiceDate.Text == string.Empty)
{
LblMessage.Text = "► Please Provide Invoice Date.";
txtInvoiceDate.Focus();
b = false;
return b;
}
if (txtProductCode.Text == string.Empty)
{
LblMessage.Text = "► Please Provide Product Code:";
txtProductCode.Focus();
b = false;
return b;
}
if (txtProductDesc.Text == string.Empty)
{
LblMessage.Text = "► Product Description Not Available:";
txtProductDesc.Focus();
b = false;
return b;
}
if (txtMRP.Text == string.Empty)
{
LblMessage.Text = "► Product MRP Not Available:";
txtMRP.Focus();
b = false;
return b;
}
if (txtEntryValue.Text == string.Empty || Convert.ToDecimal(txtEntryValue.Text) == 0)
{
LblMessage.Text = "► Please Provide " + LTEntryType.Text + " Value : and its cannot be zero.";
txtEntryValue.Focus();
b = false;
return b;
}
if (txtWeight.Text == string.Empty)
{
LblMessage.Text = "► Weight Cannot be empty or 0.";
txtWeight.Focus();
b = false;
return b;
}
if (txtVolume.Text == string.Empty)
{
LblMessage.Text = "► Volume Cannot be empty or 0:";
txtVolume.Focus();
b = false;
return b;
}
else
{
LblMessage.Text = string.Empty;
b = true;
}
return b;
}
/*
private string[] CalculateManualEntryMethod(decimal RateAmount, decimal EntryValueQty)
{
CreamBell_DMS_WebApps.App_Code.Global obj = new Global();
string[] returnResult = null;
try
{
if (DDLEntryType.SelectedItem.Text.ToString() == "Crate")
{
string[] ReturnArray = obj.CalculatePrice1(txtProductCode.Text, string.Empty, Convert.ToDecimal(txtEntryValue.Text), DDLEntryType.SelectedItem.Text.ToString());
EntryValueQty = Convert.ToDecimal(ReturnArray[0].ToString());
}
decimal RateValue = 0;
decimal TRDPerc = Convert.ToDecimal(txtTRDDiscPerc.Text);
decimal TRDValue = 0;
decimal PriceEqualValue = Convert.ToDecimal(txtPriceEqualValue.Text);
decimal VATPerc = Convert.ToDecimal(txtVATAddTAXPerc.Text);
decimal VATValue = 0;
decimal GrossRate = Convert.ToDecimal(txtGrossRate.Text);
decimal NetValue = 0;
decimal Weight = 0;
decimal Ltr = 0;
RateValue = Math.Round(RateAmount * EntryValueQty, 2);
TRDValue = Math.Round((RateValue * TRDPerc) / 100, 2);
VATValue = Math.Round((((RateValue - TRDValue) + PriceEqualValue) * VATPerc) / 100, 2);
NetValue = Math.Round(GrossRate * EntryValueQty, 2);
Weight = Math.Round((Convert.ToDecimal(txtWeight.Text) * EntryValueQty) / 1000, 2);
Ltr = Math.Round((Convert.ToDecimal(txtVolume.Text) * EntryValueQty) / 1000, 2);
returnResult = new string[6];
returnResult[0] = RateValue.ToString();
returnResult[1] = TRDValue.ToString();
returnResult[2] = VATValue.ToString();
returnResult[3] = NetValue.ToString();
returnResult[4] = Weight.ToString();
returnResult[5] = Ltr.ToString();
return returnResult;
}
catch (Exception)
{
return returnResult;
}
}
*/
private string[] GetBOXCRATELITRECalculatedValueFromGlobal()
{
string[] ReturnArray = null;
CreamBell_DMS_WebApps.App_Code.Global obj = new Global();
try
{
ReturnArray = obj.CalculatePrice1(txtProductCode.Text, string.Empty, Convert.ToDecimal(txtEntryValue.Text), DDLEntryType.SelectedItem.Text.ToString());
return ReturnArray;
}
catch (Exception ex)
{
ErrorSignal.FromCurrentContext().Raise(ex);
LblMessage.Text = ex.Message.ToString();
return ReturnArray;
}
}
protected void BtnRefresh_Click(object sender, EventArgs e)
{
ResetPageUnPostedData();
}
private void ResetPageUnpostedDataHeader()
{
LblMessage.Text = string.Empty;
txtProductCode.Text = string.Empty;
txtProductDesc.Text = string.Empty;
txtMRP.Text = string.Empty;
DDLEntryType.SelectedIndex = 0;
txtEntryValue.Text = string.Empty;
txtWeight.Text = string.Empty;
txtVolume.Text = string.Empty;
}
private void ResetPageUnPostedData()
{
LblMessage.Text = string.Empty;
txtProductCode.Text = string.Empty;
txtProductDesc.Text = string.Empty;
txtMRP.Text = string.Empty;
DDLEntryType.SelectedIndex = 0;
txtEntryValue.Text = string.Empty;
txtWeight.Text = string.Empty;
txtVolume.Text = string.Empty;
//free the Header Textbox
txtIndentDate.Text = string.Empty;
txtTransporterName.Text = string.Empty;
txttransporterNo.Text = string.Empty;
txtvehicleNo.Text = string.Empty;
txtInvoiceNo.Text = string.Empty;
txtInvoiceDate.Text = string.Empty;
txtVehicleType.Text = string.Empty;
txtReceiptValue.Text = "0";
GridFOCPurchItems.DataSource = null;
GridFOCPurchItems.Visible = false;
txtPurchDocumentNo.Text = string.Empty;
//Emtry grid view data
GridFOCPurchItems.DataSource = null;
GridFOCPurchItems.DataBind();
}
private void FillIndentNo()
{
try
{
CreamBell_DMS_WebApps.App_Code.Global obj = new Global();
string strQuery = " select distinct INDENT_NO as INDENT_NO from [ax].[ACXPURCHINDENTHEADER] PINDH where NOT EXISTS (Select PURCH_INDENTNO " +
" from [ax].[ACXPURCHINVRECIEPTHEADER] PIH where PINDH.INDENT_NO=PIH.PURCH_INDENTNO AND PINDH.SITEID = PIH.SITE_CODE) and PINDH.SITEID='" + Session["SiteCode"].ToString() +
"' and PINDH.STATUS=1 order by INDENT_NO desc";
DrpIndentNo.Items.Clear();
DrpIndentNo.Items.Add("-Select-");
obj.BindToDropDown(DrpIndentNo, strQuery, "INDENT_NO", "INDENT_NO");
}
catch (Exception ex)
{
ErrorSignal.FromCurrentContext().Raise(ex);
}
}
protected void DrpIndentNo_SelectedIndexChanged(object sender, EventArgs e)
{
try
{
txtIndentNo.Text = DrpIndentNo.Text;
if (DrpIndentNo.Text != "-Select-")
{
CreamBell_DMS_WebApps.App_Code.Global obj = new Global();
string strQuery = " select indent_date,invoice_no from [ax].[ACXPURCHINDENTHEADER] where indent_no = '" + DrpIndentNo.SelectedValue.ToString() + "'";
DataTable dt = obj.GetData(strQuery);
if (dt.Rows.Count > 0)
{
txtIndentDate.Text = Convert.ToDateTime(dt.Rows[0]["indent_date"]).ToString("dd-MMM-yyyy");
txtInvoiceNo.Text = dt.Rows[0]["invoice_no"].ToString();
}
}
}
catch (Exception ex)
{
ErrorSignal.FromCurrentContext().Raise(ex);
}
}
protected void BtnSavePreData_Click(object sender, EventArgs e)
{
bool b = ValidateManualEntry();
if (b)
{
PRESavePurchaseInvoiceReceiptToDB();
}
}
private void PRESavePurchaseInvoiceReceiptToDB()
{
try
{
string strCode = string.Empty;
CreamBell_DMS_WebApps.App_Code.Global obj = new Global();
conn = obj.GetConnection();
if (txtPurchDocumentNo.Text == string.Empty)
{
#region PO Number Generate
cmd = new SqlCommand();
transaction = conn.BeginTransaction();
cmd.Connection = conn;
cmd.Transaction = transaction;
cmd.CommandTimeout = 3600;
cmd.CommandType = CommandType.Text;
DataTable dtNumSeq = obj.GetNumSequenceNew(1, Session["SiteCode"].ToString(), Session["DATAAREAID"].ToString()); //st.Substring(st.Length - 6) + System.DateTime.Now.ToString("yyMMddhhmmss");
string NUMSEQ = string.Empty;
if (dtNumSeq != null)
{
strCode = dtNumSeq.Rows[0][0].ToString();
NUMSEQ = dtNumSeq.Rows[0][1].ToString();
}
else
{
return;
}
strCode = obj.GetNumSequence(1, Session["SiteCode"].ToString(), Session["DATAAREAID"].ToString());
cmd.CommandText = string.Empty;
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "ACX_ACXPURCHINVRECIEPTHEADERPRE";
#endregion
#region Header Insert Data
string queryRecID = "Select Count(RECID) as RECID from [ax].[ACXPURCHINVRECIEPTHEADERPRE]";
Int64 Recid = Convert.ToInt64(obj.GetScalarValue(queryRecID));
cmd.Parameters.Clear();
string indentno = string.Empty;
if (DrpIndentNo.SelectedItem.Text.ToString() == "-Select-")
{
indentno = "";
}
else
{
indentno = DrpIndentNo.SelectedItem.Text.ToString();
}
cmd.Parameters.AddWithValue("@Site_Code", Session["SiteCode"].ToString());
cmd.Parameters.AddWithValue("@Purchase_Indent_No", indentno);
cmd.Parameters.AddWithValue("@Purchase_Indent_Date", txtIndentDate.Text);
cmd.Parameters.AddWithValue("@Transporter_Code", txtTransporterName.Text);
cmd.Parameters.AddWithValue("@Document_No", strCode);
cmd.Parameters.AddWithValue("@DocumentDate", txtReceiptDate.Text);
cmd.Parameters.AddWithValue("@VEHICAL_No", txtvehicleNo.Text);
cmd.Parameters.AddWithValue("@Purchase_Reciept_No", strCode);
cmd.Parameters.AddWithValue("@Sale_InvoiceNo", txtInvoiceNo.Text.Trim().ToString());
cmd.Parameters.AddWithValue("@Sale_InvoiceDate", txtInvoiceDate.Text);
cmd.Parameters.AddWithValue("@VEHICAL_Type", txtVehicleType.Text);
cmd.Parameters.AddWithValue("@SO_No", string.Empty);
cmd.Parameters.AddWithValue("@Material_Value", Convert.ToDecimal(txtReceiptValue.Text));
cmd.Parameters.AddWithValue("@recid", Recid + 1);
cmd.Parameters.AddWithValue("@DATAAREAID", Session["DATAAREAID"].ToString());
cmd.Parameters.AddWithValue("@STATUS", 0); // for UnPosted Purchase Invoice Receipt Status//
cmd.Parameters.AddWithValue("@NUMSEQ", NUMSEQ);
cmd.Parameters.AddWithValue("@DRIVERNAME", txttransporterNo.Text.Trim().ToString());
cmd.ExecuteNonQuery();
txtPurchDocumentNo.Text = strCode;
//transaction.Commit();
#endregion
}
#region Line Insert Data on Same PURCH Order Number
cmd1 = new SqlCommand("[ACX_ACXPURCHINVRECIEPTLINEPRE]");
cmd1.Connection = conn;
if (transaction == null)
{
transaction = conn.BeginTransaction();
}
cmd1.Transaction = transaction;
cmd1.CommandTimeout = 3600;
cmd1.CommandType = CommandType.StoredProcedure;
string queryRecidLine = "Select Count(RECID) as RECID from [ax].[ACXPURCHINVRECIEPTLINEPRE]";
Int64 RecidLine = Convert.ToInt64(obj.GetScalarValue(queryRecidLine));
#endregion
string productNameCode = txtProductDesc.Text;
string[] str = productNameCode.Split('-');
string productCode = str[0].ToString();
strCode = txtPurchDocumentNo.Text;
string[] ReturnArray = null;
ReturnArray = obj.CalculatePrice1(txtProductCode.Text, string.Empty, Convert.ToDecimal(txtEntryValue.Text), DDLEntryType.SelectedItem.Text.ToString());
if (ReturnArray != null)
{
cmd1.Parameters.AddWithValue("@RECID", RecidLine + 1);
cmd1.Parameters.AddWithValue("@Site_Code", Session["SiteCode"].ToString());
cmd1.Parameters.AddWithValue("@Purchase_Reciept_No", strCode);
cmd1.Parameters.AddWithValue("@PRODUCT_CODE", productCode);
cmd1.Parameters.AddWithValue("@LINE_NO", RecidLine + 1);
cmd1.Parameters.AddWithValue("@DATAAREAID", Session["DATAAREAID"].ToString());
#region Crate Box Data Insert
if (ReturnArray[5].ToString() == "Box")
{
cmd1.Parameters.AddWithValue("@BOX", txtEntryValue.Text.Trim().ToString());
cmd1.Parameters.AddWithValue("@CRATES", ReturnArray[0].ToString());
cmd1.Parameters.AddWithValue("@LTR", ReturnArray[1].ToString());
cmd1.Parameters.AddWithValue("@RATE", 0);
cmd1.Parameters.AddWithValue("@UOM", ReturnArray[4].ToString());
cmd1.Parameters.AddWithValue("@BASICVALUE", 0);
cmd1.Parameters.AddWithValue("@TRDDISCPERC", 0);
cmd1.Parameters.AddWithValue("@TRDDISCVALUE", 0);
cmd1.Parameters.AddWithValue("@PRICEEQUALVALUE", 0);
cmd1.Parameters.AddWithValue("@VAT_INC_PERC", 0);
cmd1.Parameters.AddWithValue("@VAT_INC_PERC_VALUE", 0);
cmd1.Parameters.AddWithValue("@GROSSAMOUNT", 0);
cmd1.Parameters.AddWithValue("@DISCOUNT", 0);
cmd1.Parameters.AddWithValue("@TAX", 0);
cmd1.Parameters.AddWithValue("@TAXAMOUNT", 0);
cmd1.Parameters.AddWithValue("@AMOUNT", 0);
cmd1.Parameters.AddWithValue("@Remark", "FOC");
cmd1.ExecuteNonQuery();
}
transaction.Commit();
txtPurchDocumentNo.Text = strCode;
ShowRecords(txtPurchDocumentNo.Text.ToString());
UpdateAndShowTotalMaterialValue(txtPurchDocumentNo.Text.ToString());
ResetPageUnpostedDataHeader();
BtnUpdateHeader.Visible = true;
#endregion
}
}
catch (Exception ex)
{
ErrorSignal.FromCurrentContext().Raise(ex);
transaction.Rollback();
LblMessage.Text = ex.Message.ToString();
}
}
private void UpdateAndShowTotalMaterialValue(string PurchNo)
{
CreamBell_DMS_WebApps.App_Code.Global obj = new Global();
try
{
string query = "Select * from [ax].[ACXPURCHINVRECIEPTLINEPRE] WHERE PURCH_RECIEPTNO='" + PurchNo + "' " +
"and SITEID='" + Session["SiteCode"].ToString() + "' and DATAAREAID='" + Session["DATAAREAID"].ToString() + "'";
DataTable dt = obj.GetData(query);
if (dt.Rows.Count > 0)
{
decimal totalvalue = dt.AsEnumerable().Sum(row => row.Field<decimal>("AMOUNT"));
txtReceiptValue.Text = Math.Round(totalvalue, 2).ToString();
string UpdateMaterialValue = "UPDATE [ax].[ACXPURCHINVRECIEPTHEADERPRE] SET MATERIAL_VALUE = " + totalvalue + " where PURCH_RECIEPTNO='" + PurchNo + "' " +
" and SITE_CODE='" + Session["SiteCode"].ToString() + "' and DATAAREAID='" + Session["DATAAREAID"].ToString() + "'";
obj.ExecuteCommand(UpdateMaterialValue);
}
}
catch (Exception ex)
{
ErrorSignal.FromCurrentContext().Raise(ex);
LblMessage.Text = ex.Message.ToString();
}
}
private void ShowRecords(string PurchReceiptNumber)
{
CreamBell_DMS_WebApps.App_Code.Global obj = new Global();
DataTable dtHeader = null;
DataTable dtLine = null;
try
{
string queryHeader = "Select * from [ax].[ACXPURCHINVRECIEPTHEADERPRE] where PURCH_RECIEPTNO='" + PurchReceiptNumber + "' " +
" and SITE_CODE='" + Session["SiteCode"].ToString() + "' and DATAAREAID='" + Session["DATAAREAID"].ToString() + "'";
string queryLine = "Select PURCH_RECIEPTNO, LINE_NO,PRODUCT_CODE, BOX,CRATES,A.LTR,A.UOM,RATE,BASICVALUE,TRDDISCPERC,TRDDISCVALUE,PRICE_EQUALVALUE," +
"VAT_INC_PERC,VAT_INC_PERCVALUE,GROSSRATE,AMOUNT,(PRODUCT_CODE+'-'+ PRODUCT_NAME) AS PRODUCTDESC,PRODUCT_MRP from [ax].[ACXPURCHINVRECIEPTLINEPRE] A " +
" INNER JOIN AX.INVENTTABLE B ON A.PRODUCT_CODE = B.ITEMID WHERE PURCH_RECIEPTNO='" + PurchReceiptNumber + "' " +
" and SITEID='" + Session["SiteCode"].ToString() + "' and A.DATAAREAID='" + Session["DATAAREAID"].ToString() + "'";
//"dd-MMM-yyyy"
dtHeader = obj.GetData(queryHeader);
if (dtHeader.Rows[0]["PURCH_INDENTNO"].ToString() == string.Empty || dtHeader.Rows[0]["PURCH_INDENTNO"].ToString() == null)
{
DrpIndentNo.SelectedIndex = 0;
}
else
{
DrpIndentNo.SelectedItem.Text = dtHeader.Rows[0]["PURCH_INDENTNO"].ToString();
}
DateTime IndentDate = Convert.ToDateTime(dtHeader.Rows[0]["PURCH_INDENTDATE"].ToString());
txtIndentDate.Text = IndentDate.ToString("dd-MMM-yyyy");
txtTransporterName.Text = dtHeader.Rows[0]["TRANSPORTER_CODE"].ToString();
txtvehicleNo.Text = dtHeader.Rows[0]["VEHICAL_NO"].ToString();
DateTime ReceiptDate = Convert.ToDateTime(dtHeader.Rows[0]["DOCUMENT_DATE"].ToString());
txtReceiptDate.Text = ReceiptDate.ToString("dd-MMM-yyyy");
txtInvoiceNo.Text = dtHeader.Rows[0]["SALE_INVOICENO"].ToString();
DateTime InvcDate = Convert.ToDateTime(dtHeader.Rows[0]["SALE_INVOICEDATE"].ToString());
txtInvoiceDate.Text = InvcDate.ToString("dd-MMM-yyyy");
txttransporterNo.Text = dtHeader.Rows[0]["TRANSPORTER_CODE"].ToString();
txtVehicleType.Text = dtHeader.Rows[0]["VEHICAL_TYPE"].ToString();
decimal RecptValue = Convert.ToDecimal(dtHeader.Rows[0]["MATERIAL_VALUE"].ToString());
txtReceiptValue.Text = (Math.Round(RecptValue, 2)).ToString();
txtPurchDocumentNo.Text = PurchReceiptNumber;
dtLine = obj.GetData(queryLine);
if (dtLine.Rows.Count > 0)
{
GridFOCPurchItems.DataSource = dtLine;
GridFOCPurchItems.DataBind();
GridFOCPurchItems.Visible = true;
}
else
{
LblMessage.Text = "No Line Items Exist";
BtnUpdateHeader.Visible = false;
GridFOCPurchItems.DataSource = null;
GridFOCPurchItems.Visible = false;
}
}
catch (Exception ex)
{
ErrorSignal.FromCurrentContext().Raise(ex);
LblMessage.Text = ex.Message.ToString();
}
}
protected void BtnUpdateHeader_Click(object sender, EventArgs e)
{
UpdateHeader(txtPurchDocumentNo.Text);
}
private void UpdateHeader(string PurchInvcNo)
{
CreamBell_DMS_WebApps.App_Code.Global obj = new Global();
conn = obj.GetConnection();
try
{
if (txtPurchDocumentNo.Text != string.Empty)
{
#region Update Header
string QueryUpdate = " UPDATE [ax].[ACXPURCHINVRECIEPTHEADERPRE] SET PURCH_INDENTNO= @PurchIndentNo," +
" PURCH_INDENTDATE= @PURCH_INDENTDATE, SALE_INVOICEDATE=@SALE_INVOICEDATE, SALE_INVOICENO = @SALE_INVOICENO," +
" TRANSPORTER_CODE= @TRANSPORTER_CODE, VEHICAL_NO = @VEHICAL_NO, VEHICAL_TYPE= @VEHICAL_TYPE " +
" where PURCH_RECIEPTNO='" + txtPurchDocumentNo.Text + "' " +
" and SITE_CODE='" + Session["SiteCode"].ToString() + "' and DATAAREAID='" + Session["DATAAREAID"].ToString() + "'";
cmd = new SqlCommand(QueryUpdate);
transaction = conn.BeginTransaction();
cmd.Connection = conn;
cmd.Transaction = transaction;
cmd.CommandTimeout = 3600;
cmd.CommandType = CommandType.Text;
string strindentNo = string.Empty;
if (DrpIndentNo.SelectedItem.Text == "-Select-")
{
strindentNo = "";
}
else
{
strindentNo = DrpIndentNo.SelectedItem.Text;
}
cmd.Parameters.Clear();
cmd.Parameters.AddWithValue("@PurchIndentNo", strindentNo);
cmd.Parameters.AddWithValue("@PURCH_INDENTDATE", txtIndentDate.Text);
cmd.Parameters.AddWithValue("@SALE_INVOICEDATE", txtInvoiceDate.Text);
cmd.Parameters.AddWithValue("@SALE_INVOICENO", txtInvoiceNo.Text);
cmd.Parameters.AddWithValue("@TRANSPORTER_CODE", txtTransporterName.Text);
cmd.Parameters.AddWithValue("@VEHICAL_NO", txtvehicleNo.Text);
cmd.Parameters.AddWithValue("@VEHICAL_TYPE", txtVehicleType.Text);
cmd.ExecuteNonQuery();
transaction.Commit();
#endregion
}
}
catch (Exception ex)
{
ErrorSignal.FromCurrentContext().Raise(ex);
LblMessage.Text = ex.Message.ToString();
}
}
protected void GridFOCPurchItems_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
try
{
HiddenField hiddenfield = (HiddenField)GridFOCPurchItems.Rows[e.RowIndex].FindControl("HiddenValueLineNo");
CreamBell_DMS_WebApps.App_Code.Global obj = new Global();
string query = "Delete from [ax].[ACXPURCHINVRECIEPTLINEPRE] where PURCH_RECIEPTNO='" + txtPurchDocumentNo.Text + "' " +
" and LINE_NO = " + hiddenfield.Value + " and SITEID='" + Session["SiteCode"].ToString() + "' and DATAAREAID='" + Session["DATAAREAID"].ToString() + "'";
obj.ExecuteCommand(query);
ShowRecords(txtPurchDocumentNo.Text);
UpdateAndShowTotalMaterialValue(txtPurchDocumentNo.Text);
}
catch (Exception ex)
{
ErrorSignal.FromCurrentContext().Raise(ex);
}
}
protected void btnPostPurchaseInvoice_Click(object sender, EventArgs e)
{
POSTPurchaseInvoiceReceipt(txtPurchDocumentNo.Text);
}
private void POSTPurchaseInvoiceReceipt(string PrePurchReceiptNo)
{
try
{
string PostDocumentNo = string.Empty;
CreamBell_DMS_WebApps.App_Code.Global obj = new Global();
conn = obj.GetConnection();
if (txtPurchDocumentNo.Text != string.Empty)
{
#region Get PreSaved Data Header and Line
string queryPreHeader = "Select * from [ax].[ACXPURCHINVRECIEPTHEADERPRE] where PURCH_RECIEPTNO='" + PrePurchReceiptNo + "' " +
" and SITE_CODE='" + Session["SiteCode"].ToString() + "' and DATAAREAID='" + Session["DATAAREAID"].ToString() + "'";
string queryPreLine = "Select * from [ax].[ACXPURCHINVRECIEPTLINEPRE] WHERE PURCH_RECIEPTNO='" + PrePurchReceiptNo + "' " +
" and SITEID='" + Session["SiteCode"].ToString() + "' and DATAAREAID='" + Session["DATAAREAID"].ToString() + "'";
DataTable dtHeaderPre = obj.GetData(queryPreHeader);
DataTable dtLinePre = obj.GetData(queryPreLine);
#endregion
if (dtHeaderPre.Rows.Count > 0 && dtLinePre.Rows.Count > 0)
{
#region Generate New Posted Invoice Number
cmd = new SqlCommand();
transaction = conn.BeginTransaction();
cmd.Connection = conn;
cmd.Transaction = transaction;
cmd.CommandTimeout = 3600;
cmd.CommandType = CommandType.Text;
DataTable dtNumSeq = obj.GetNumSequenceNew(2, Session["SiteCode"].ToString(), Session["DATAAREAID"].ToString());
string NUMSEQ = string.Empty;
if (dtNumSeq != null)
{
PostDocumentNo = dtNumSeq.Rows[0][0].ToString();
NUMSEQ = dtNumSeq.Rows[0][1].ToString();
}
else
{
return;
}
#endregion
string queryRecID = "Select Count(RECID) as RECID from [ax].[ACXPURCHINVRECIEPTHEADER]";
Int64 Recid = Convert.ToInt64(obj.GetScalarValue(queryRecID));
cmd.CommandText = string.Empty;
cmd.CommandType = CommandType.Text;
cmd.CommandText = " INSERT INTO [ax].[ACXPURCHINVRECIEPTHEADER] ( Document_No,DATAAREAID,RECID,Document_Date,Purch_IndentNo,Purch_IndentDate, " +
" SO_No,SO_Date,STATUS,Material_Value,Purch_RecieptNo,Sale_InvoiceDate,Sale_InvoiceNo,Site_Code,Transporter_Code,VEHICAL_No," +
" VEHICAL_Type,PREDOCUMENT_NO,NUMSEQ) values ( @Document_No,@DATAAREAID,@RECID,@Document_Date,@Purch_IndentNo,@Purch_IndentDate, " +
" @SO_No,@SO_Date,@STATUS,@Material_Value,@Purch_RecieptNo,@Sale_InvoiceDate,@Sale_InvoiceNo,@Site_Code,@Transporter_Code,@VEHICAL_No," +
" @VEHICAL_Type,@PREDOCUMENT_NO,@NUMSEQ)";
#region Insert Header
for (int i = 0; i < dtHeaderPre.Rows.Count; i++)
{
cmd.Parameters.Clear();
cmd.Parameters.AddWithValue("@Document_No", PostDocumentNo);
cmd.Parameters.AddWithValue("@DATAAREAID", dtHeaderPre.Rows[0]["DATAAREAID"].ToString());
cmd.Parameters.AddWithValue("@RECID", Recid + 1);
cmd.Parameters.AddWithValue("@Document_Date", DateTime.Now);
cmd.Parameters.AddWithValue("@Purch_IndentNo", dtHeaderPre.Rows[0]["Purch_IndentNo"].ToString());
cmd.Parameters.AddWithValue("@Purch_IndentDate", dtHeaderPre.Rows[0]["Purch_IndentDate"].ToString());
cmd.Parameters.AddWithValue("@SO_No", dtHeaderPre.Rows[0]["SO_No"].ToString());
cmd.Parameters.AddWithValue("@SO_Date", dtHeaderPre.Rows[0]["SO_Date"].ToString());
cmd.Parameters.AddWithValue("@STATUS", 1);
cmd.Parameters.AddWithValue("@Material_Value", Convert.ToDecimal(dtHeaderPre.Rows[0]["Material_Value"].ToString()));
cmd.Parameters.AddWithValue("@Purch_RecieptNo", PostDocumentNo);
cmd.Parameters.AddWithValue("@Sale_InvoiceDate", dtHeaderPre.Rows[0]["Sale_InvoiceDate"].ToString());
cmd.Parameters.AddWithValue("@Sale_InvoiceNo", dtHeaderPre.Rows[0]["Sale_InvoiceNo"].ToString());
cmd.Parameters.AddWithValue("@Site_Code", dtHeaderPre.Rows[0]["Site_Code"].ToString());
cmd.Parameters.AddWithValue("@Transporter_Code", dtHeaderPre.Rows[0]["Transporter_Code"].ToString());
cmd.Parameters.AddWithValue("@VEHICAL_No", dtHeaderPre.Rows[0]["VEHICAL_No"].ToString());
cmd.Parameters.AddWithValue("@VEHICAL_Type", dtHeaderPre.Rows[0]["VEHICAL_Type"].ToString());
cmd.Parameters.AddWithValue("@PREDOCUMENT_NO", PrePurchReceiptNo);
cmd.Parameters.AddWithValue("@NUMSEQ", NUMSEQ);
cmd.ExecuteNonQuery();
}
#endregion
cmd1 = new SqlCommand();
cmd1.Connection = conn;
cmd1.Transaction = transaction;
cmd1.CommandTimeout = 3600;
cmd1.CommandType = CommandType.Text;
string queryLineRecID = "Select Count(RECID) as RECID from [ax].[ACXPURCHINVRECIEPTLINE]";
Int64 recid = Convert.ToInt64(obj.GetScalarValue(queryLineRecID));
cmd1.CommandText = string.Empty;
cmd1.CommandText = " INSERT INTO [ax].[ACXPURCHINVRECIEPTLINE] ( Purch_RecieptNo,DATAAREAID,RECID,Amount,Box,Crates,Discount,Line_No, " +
" Ltr,Product_Code,Rate, Siteid,TAX,TAXAMOUNT,UOM,BASICVALUE,TRDDISCPERC,TRDDISCVALUE,PRICE_EQUALVALUE,VAT_INC_PERC, " +
" VAT_INC_PERCVALUE,GROSSRATE,Remark ) Values ( @Purch_RecieptNo,@DATAAREAID,@RECID,@Amount,@Box,@Crates,@Discount,@Line_No," +
" @Ltr,@Product_Code,@Rate, @Siteid,@TAX,@TAXAMOUNT,@UOM,@BASICVALUE,@TRDDISCPERC,@TRDDISCVALUE,@PRICE_EQUALVALUE, " +
" @VAT_INC_PERC,@VAT_INC_PERCVALUE,@GROSSRATE,@Remark )";
#region Line Insert
for (int p = 0; p < dtLinePre.Rows.Count; p++)
{
cmd1.Parameters.Clear();
cmd1.Parameters.AddWithValue("@Purch_RecieptNo", PostDocumentNo);
cmd1.Parameters.AddWithValue("@DATAAREAID", dtLinePre.Rows[p]["DATAAREAID"].ToString());
cmd1.Parameters.AddWithValue("@RECID", p + recid + 1);
cmd1.Parameters.AddWithValue("@Amount", Convert.ToDecimal(dtLinePre.Rows[p]["Amount"].ToString()));
cmd1.Parameters.AddWithValue("@Box", Convert.ToDecimal(dtLinePre.Rows[p]["Box"].ToString()));
cmd1.Parameters.AddWithValue("@Crates", Convert.ToDecimal(dtLinePre.Rows[p]["Crates"].ToString()));
cmd1.Parameters.AddWithValue("@Discount", Convert.ToDecimal(dtLinePre.Rows[p]["Discount"].ToString()));
cmd1.Parameters.AddWithValue("@Line_No", p + recid + 1);
cmd1.Parameters.AddWithValue("@Ltr", Convert.ToDecimal(dtLinePre.Rows[p]["Ltr"].ToString()));
cmd1.Parameters.AddWithValue("@Product_Code", dtLinePre.Rows[p]["Product_Code"].ToString());
cmd1.Parameters.AddWithValue("@Rate", Convert.ToDecimal(dtLinePre.Rows[p]["Rate"].ToString()));
cmd1.Parameters.AddWithValue("@Siteid", dtLinePre.Rows[p]["Siteid"].ToString());
cmd1.Parameters.AddWithValue("@TAX", Convert.ToDecimal(dtLinePre.Rows[p]["TAX"].ToString()));
cmd1.Parameters.AddWithValue("@TAXAMOUNT", Convert.ToDecimal(dtLinePre.Rows[p]["TAXAMOUNT"].ToString()));
cmd1.Parameters.AddWithValue("@UOM", dtLinePre.Rows[p]["UOM"].ToString());
cmd1.Parameters.AddWithValue("@BASICVALUE", Convert.ToDecimal(dtLinePre.Rows[p]["BASICVALUE"].ToString()));
cmd1.Parameters.AddWithValue("@TRDDISCPERC", Convert.ToDecimal(dtLinePre.Rows[p]["TRDDISCPERC"].ToString()));
cmd1.Parameters.AddWithValue("@TRDDISCVALUE", Convert.ToDecimal(dtLinePre.Rows[p]["TRDDISCVALUE"].ToString()));
cmd1.Parameters.AddWithValue("@PRICE_EQUALVALUE", Convert.ToDecimal(dtLinePre.Rows[p]["PRICE_EQUALVALUE"].ToString()));
cmd1.Parameters.AddWithValue("@VAT_INC_PERC", Convert.ToDecimal(dtLinePre.Rows[p]["VAT_INC_PERC"].ToString()));
cmd1.Parameters.AddWithValue("@VAT_INC_PERCVALUE", Convert.ToDecimal(dtLinePre.Rows[p]["VAT_INC_PERCVALUE"].ToString()));
cmd1.Parameters.AddWithValue("@GROSSRATE", Convert.ToDecimal(dtLinePre.Rows[p]["GROSSRATE"].ToString()));
cmd1.Parameters.AddWithValue("@Remark", dtLinePre.Rows[p]["Remark"].ToString());
cmd1.ExecuteNonQuery();
}
#endregion
transaction.Commit();
//ScriptManager.RegisterStartupScript(this, this.GetType(), "Alert", " alert('Purchase Invoice Posted Successfully ! Document Number : " + PostDocumentNo + " ');", true);
LblMessage.Text = "Purchase Invoice Posted Successfully ! Document Number : " + PostDocumentNo + "";
// string message = "alert('Purchase Invoice Posted Successfully ! Document Number : " + PostDocumentNo + " ');";
//ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "alert", message, true);
UpdatePostedStatusInPreTable();
UpdateTransTable(PostDocumentNo);
txtPurchDocumentNo.Text = string.Empty;
RefreshCompletePage();
}
}
else
{
// ScriptManager.RegisterStartupScript(this, this.GetType(), "Alert", " alert(' No Data to Save. Please Add Line Items and Header Details First !! ');", true);
LblMessage.Text = "No Data to Save. Please Add Line Items and Header Details First !! ";
//string message = "alert(' No Data to Save. Please Add Line Items and Header Details First !! ');";
//ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "alert", message, true);
}
}
catch (Exception ex)
{
ErrorSignal.FromCurrentContext().Raise(ex);
transaction.Rollback();
LblMessage.Text = ex.Message.ToString();
}
}
private void RefreshCompletePage()
{
LblMessage.Text = string.Empty;
txtProductCode.Text = string.Empty;
txtProductDesc.Text = string.Empty;
txtMRP.Text = string.Empty;
DDLEntryType.SelectedIndex = 0;
txtEntryValue.Text = string.Empty;
txtWeight.Text = string.Empty;
txtVolume.Text = string.Empty;
BtnUpdateHeader.Visible = false;
DrpIndentNo.SelectedIndex = 0;
FillIndentNo();
txtIndentDate.Text = string.Empty;
txtTransporterName.Text = string.Empty;
txttransporterNo.Text = string.Empty;
txtvehicleNo.Text = string.Empty;
txtInvoiceNo.Text = string.Empty;
txtInvoiceDate.Text = string.Empty;
txtVehicleType.Text = string.Empty;
txtReceiptValue.Text = "0";
GridFOCPurchItems.DataSource = null;
GridFOCPurchItems.Visible = false;
txtPurchDocumentNo.Text = string.Empty;
}
private void UpdatePostedStatusInPreTable()
{
CreamBell_DMS_WebApps.App_Code.Global obj = new Global();
try
{
if (txtPurchDocumentNo.Text != string.Empty)
{
#region Update Pre Header Status
string QueryUpdate = " UPDATE [ax].[ACXPURCHINVRECIEPTHEADERPRE] SET STATUS = 1 where PURCH_RECIEPTNO='" + txtPurchDocumentNo.Text + "' " +
" and SITE_CODE='" + Session["SiteCode"].ToString() + "' and DATAAREAID='" + Session["DATAAREAID"].ToString() + "'";
obj.ExecuteCommand(QueryUpdate);
#endregion
}
}
catch (Exception ex)
{
ErrorSignal.FromCurrentContext().Raise(ex);
LblMessage.Text = ex.Message.ToString();
}
}
public void UpdateTransTable(string PostedDocumentNo)
{
try
{
CreamBell_DMS_WebApps.App_Code.Global obj = new App_Code.Global();
conn = obj.GetConnection();
string TransLocation = "";
string query1 = "select MainWarehouse from ax.inventsite where siteid='" + Session["SiteCode"].ToString() + "'";
DataTable dt = new DataTable();
dt = obj.GetData(query1);
if (dt.Rows.Count > 0)
{
TransLocation = dt.Rows[0]["MainWarehouse"].ToString();
}
string st = Session["SiteCode"].ToString();
string TransId = st.Substring(st.Length - 6) + System.DateTime.Now.ToString("yymmddhhmmss");
cmd = new SqlCommand();
cmd.Connection = conn;
cmd.CommandTimeout = 3600;
cmd.CommandText = string.Empty;
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "[ACX_PURCHINVC_UPDATEINVENTTRANS]";
cmd.Parameters.Clear();
cmd.Parameters.AddWithValue("@SITECODE", Session["SiteCode"].ToString());
cmd.Parameters.AddWithValue("@DOCUMENTPURCHRECEIPTNUMBER", PostedDocumentNo);
cmd.Parameters.AddWithValue("@DATAAREAID", Session["DATAAREAID"].ToString());
cmd.Parameters.AddWithValue("@TRANSID", TransId);
cmd.Parameters.AddWithValue("@WAREHOUSE", TransLocation);
cmd.Parameters.AddWithValue("@TRANSTYPE", 1);
cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
ErrorSignal.FromCurrentContext().Raise(ex);
LblMessage.Text = "Error: Inventory Update Issue - " + ex.Message.ToString();
}
}
private void GetUnPostedReferenceData(string queryString)
{
if (Request.QueryString["PreNo"].ToString() != string.Empty)
{
string ReferenceNo = Request.QueryString["PreNo"].ToString();
bool b = CheckPostedStatus(ReferenceNo);
if (b == false)
{
ShowRecords(ReferenceNo);
}
}
}
private bool CheckPostedStatus(string ReferenceNo)
{
bool checkStatus = false;
LblMessage.Text = "";
try
{
CreamBell_DMS_WebApps.App_Code.Global obj = new Global();
string query = " Select [STATUS] from [ax].[ACXPURCHINVRECIEPTHEADERPRE] WHERE SITE_CODE='" + Session["SiteCode"].ToString() + "' AND DATAAREAID='" + Session["DATAAREAID"].ToString() + "' AND DOCUMENT_NO='" + ReferenceNo + "' ";
object status = obj.GetScalarValue(query);
if (status != null || status != string.Empty)
{
string str = status.ToString();
if (str == "1")
{
checkStatus = true;
//ScriptManager.RegisterStartupScript(this, this.GetType(), "Alert", " alert(' Reference Number Not Found !! Redirecting back to previous page ...');", true);
LblMessage.Text = "Reference Number Not Found !! Redirecting back to previous page ...";
//string message = "alert(' Reference Number Not Found !! Redirecting back to previous page ...');";
//ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "alert", message, true);
Response.Redirect("frmPurchUnPostList.aspx");
return checkStatus;
}
}
else
{
checkStatus = true;
// ScriptManager.RegisterStartupScript(this, this.GetType(), "Alert", " alert(' Reference Status Not Exists !! Redirecting back to previous page ...');", true);
LblMessage.Text = "Reference Status Not Exists !! Redirecting back to previous page ...";
//string message = "alert(' Reference Status Not Exists !! Redirecting back to previous page ...');";
//ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "alert", message, true);
Response.Redirect("frmPurchUnPostList.aspx");
return checkStatus;
}
return checkStatus;
}
catch (Exception ex)
{
ErrorSignal.FromCurrentContext().Raise(ex);
LblMessage.Text = ex.Message.ToString();
return checkStatus;
}
}
private bool ValidateManualEntryExcel()
{
bool b = true;
if (txtInvoiceNo.Text == string.Empty)
{
LblMessage.Text = "► Please Provide Invoice No.";
txtInvoiceNo.Focus();
b = false;
return b;
}
if (txtInvoiceDate.Text == string.Empty)
{
LblMessage.Text = "► Please Provide Invoice Date.";
txtInvoiceDate.Focus();
b = false;
return b;
}
//if (txtReceiptValue.Text == string.Empty)
//{
// LblMessage.Text = "► Please Provide Receipt Value.";
// txtReceiptValue.Focus();
// b = false;
// return b;
//}
return b;
}
protected void btnUplaod_Click(object sender, EventArgs e)
{
try
{
LblMessage.Text = "";
bool b = ValidateManualEntryExcel();
if (b)
{
if (AsyncFileUpload1.HasFile)
{
// #region
//bool contains = true;
string fileName = System.IO.Path.GetFileName(AsyncFileUpload1.PostedFile.FileName);
AsyncFileUpload1.PostedFile.SaveAs(Server.MapPath("~/Uploads/" + fileName));
string excelPath = Server.MapPath("~/Uploads/") + Path.GetFileName(AsyncFileUpload1.PostedFile.FileName);
string conString = string.Empty;
string extension = Path.GetExtension(AsyncFileUpload1.PostedFile.FileName);
DataTable dtExcelData = new DataTable();
//excel upload
dtExcelData = CreamBell_DMS_WebApps.App_Code.ExcelUpload.ImportExcelXLS(Server.MapPath("~/Uploads/" + fileName), true);
string strCode = string.Empty;
CreamBell_DMS_WebApps.App_Code.Global obj = new Global();
conn = obj.GetConnection();
#region PO Number Generate
cmd = new SqlCommand();
transaction = conn.BeginTransaction();
cmd.Connection = conn;
cmd.Transaction = transaction;
cmd.CommandTimeout = 3600;
cmd.CommandType = CommandType.Text;
DataTable dtNumSeq = obj.GetNumSequenceNew(1, Session["SiteCode"].ToString(), Session["DATAAREAID"].ToString());
string NUMSEQ = string.Empty;
if (dtNumSeq != null)
{
strCode = dtNumSeq.Rows[0][0].ToString();
NUMSEQ = dtNumSeq.Rows[0][1].ToString();
}
else
{
return;
}
strCode = obj.GetNumSequence(1, Session["SiteCode"].ToString(), Session["DATAAREAID"].ToString());
cmd.CommandText = string.Empty;
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "[ACX_ACXPURCHINVRECIEPTHEADERPRE]";
#endregion
#region Header Insert Data
string queryRecID = "Select Count(RECID) as RECID from [ax].[ACXPURCHINVRECIEPTHEADERPRE]";
Int64 Recid = Convert.ToInt64(obj.GetScalarValue(queryRecID));
cmd.Parameters.Clear();
string indentno = string.Empty;
if (DrpIndentNo.SelectedItem.Text.ToString() == "-Select-")
{
indentno = "";
}
else
{
indentno = DrpIndentNo.SelectedItem.Text.ToString();
}
cmd.Parameters.AddWithValue("@Site_Code", Session["SiteCode"].ToString());
cmd.Parameters.AddWithValue("@Purchase_Indent_No", indentno);
cmd.Parameters.AddWithValue("@Purchase_Indent_Date", txtIndentDate.Text);
cmd.Parameters.AddWithValue("@Transporter_Code", txtTransporterName.Text);
cmd.Parameters.AddWithValue("@Document_No", strCode);
cmd.Parameters.AddWithValue("@DocumentDate", txtReceiptDate.Text);
cmd.Parameters.AddWithValue("@VEHICAL_No", txtvehicleNo.Text);
cmd.Parameters.AddWithValue("@Purchase_Reciept_No", strCode);
cmd.Parameters.AddWithValue("@Sale_InvoiceNo", txtInvoiceNo.Text.Trim().ToString());
cmd.Parameters.AddWithValue("@Sale_InvoiceDate", txtInvoiceDate.Text);
cmd.Parameters.AddWithValue("@VEHICAL_Type", txtVehicleType.Text);
cmd.Parameters.AddWithValue("@SO_No", string.Empty);
cmd.Parameters.AddWithValue("@Material_Value", "0");
cmd.Parameters.AddWithValue("@recid", Recid + 1);
cmd.Parameters.AddWithValue("@DATAAREAID", Session["DATAAREAID"].ToString());
cmd.Parameters.AddWithValue("@STATUS", 0); // for UnPosted Purchase Invoice Receipt Status//
cmd.Parameters.AddWithValue("@NUMSEQ", NUMSEQ);
cmd.Parameters.AddWithValue("@DRIVERNAME", txttransporterNo.Text.Trim().ToString());
#endregion
#region Line Insert Data on Same PURCH Order Number
cmd1 = new SqlCommand("[ACX_ACXPURCHINVRECIEPTLINEPRE]");
cmd1.Connection = conn;
if (transaction == null)
{
transaction = conn.BeginTransaction();
}
cmd1.Transaction = transaction;
cmd1.CommandTimeout = 3600;
cmd1.CommandType = CommandType.StoredProcedure;
string queryRecidLine = "Select Count(RECID) as RECID from [ax].[ACXPURCHINVRECIEPTLINEPRE]";
Int64 RecidLine = Convert.ToInt64(obj.GetScalarValue(queryRecidLine));
#endregion
string productNameCode = txtProductDesc.Text;
string[] str = productNameCode.Split('-');
string productCode = str[0].ToString();
//strCode = txtPurchDocumentNo.Text;
DataTable dtForShownUnuploadData = new DataTable();
dtForShownUnuploadData.Columns.Add("ProductCode");
dtForShownUnuploadData.Columns.Add("Qty");
//dtForShownUnuploadData.Columns.Add("Rate");
//dtForShownUnuploadData.Columns.Add("TRD");
//dtForShownUnuploadData.Columns.Add("Value");
//dtForShownUnuploadData.Columns.Add("Vat");
//dtForShownUnuploadData.Columns.Add("Remark");
int j = 0;
int no = 0;
for (int i = 0; i < dtExcelData.Rows.Count; i++)
{
string sqlstr = "select ItemID from ax.inventTable where ItemID = '" + dtExcelData.Rows[i]["ProductCode"].ToString() + "'";
object objcheckproductcode = obj.GetScalarValue(sqlstr);
if (objcheckproductcode == null)
{
dtForShownUnuploadData.Rows.Add();
dtForShownUnuploadData.Rows[j]["ProductCode"] = dtExcelData.Rows[i]["ProductCode"].ToString();
dtForShownUnuploadData.Rows[j]["Qty"] = dtExcelData.Rows[i]["Qty"].ToString();
//dtForShownUnuploadData.Rows[j]["Rate"] = dtExcelData.Rows[i]["Rate"].ToString();
//dtForShownUnuploadData.Rows[j]["TRD"] = dtExcelData.Rows[i]["TRD"].ToString();
//dtForShownUnuploadData.Rows[j]["Value"] = dtExcelData.Rows[i]["Value"].ToString();
//dtForShownUnuploadData.Rows[j]["Vat"] = dtExcelData.Rows[i]["Vat"].ToString();
//dtForShownUnuploadData.Rows[j]["Remark"] = dtExcelData.Rows[i]["Remark"].ToString();
j += 1;
continue;
}
try
{
decimal Qty = Convert.ToDecimal(dtExcelData.Rows[i]["Qty"]);
//decimal Rate = Convert.ToDecimal(dtExcelData.Rows[i]["Rate"]);
//decimal TRD = Convert.ToDecimal(dtExcelData.Rows[i]["TRD"]);
//decimal Value = Convert.ToDecimal(dtExcelData.Rows[i]["Value"]);
//decimal Vat = Convert.ToDecimal(dtExcelData.Rows[i]["Vat"]);
if (Qty == 0)
{
dtForShownUnuploadData.Rows.Add();
dtForShownUnuploadData.Rows[j]["ProductCode"] = dtExcelData.Rows[i]["ProductCode"].ToString();
//dtForShownUnuploadData.Rows[j]["Qty"] = dtExcelData.Rows[i]["Qty"].ToString();
//dtForShownUnuploadData.Rows[j]["Rate"] = dtExcelData.Rows[i]["Rate"].ToString();
//dtForShownUnuploadData.Rows[j]["TRD"] = dtExcelData.Rows[i]["TRD"].ToString();
//dtForShownUnuploadData.Rows[j]["Value"] = dtExcelData.Rows[i]["Value"].ToString();
//dtForShownUnuploadData.Rows[j]["Vat"] = dtExcelData.Rows[i]["Vat"].ToString();
//dtForShownUnuploadData.Rows[j]["Remark"] = dtExcelData.Rows[i]["Remark"].ToString();
j += 1;
continue;
}
}
catch (Exception ex)
{
ErrorSignal.FromCurrentContext().Raise(ex);
dtForShownUnuploadData.Rows.Add();
dtForShownUnuploadData.Rows[j]["ProductCode"] = dtExcelData.Rows[i]["ProductCode"].ToString();
dtForShownUnuploadData.Rows[j]["Qty"] = dtExcelData.Rows[i]["Qty"].ToString();
//dtForShownUnuploadData.Rows[j]["Rate"] = dtExcelData.Rows[i]["Rate"].ToString();
//dtForShownUnuploadData.Rows[j]["TRD"] = dtExcelData.Rows[i]["TRD"].ToString();
//dtForShownUnuploadData.Rows[j]["Value"] = dtExcelData.Rows[i]["Value"].ToString();
//dtForShownUnuploadData.Rows[j]["Vat"] = dtExcelData.Rows[i]["Vat"].ToString();
//dtForShownUnuploadData.Rows[j]["Remark"] = dtExcelData.Rows[i]["Remark"].ToString();
j += 1;
continue;
}
cmd1.Parameters.Clear();
string[] ReturnArray = null;
ReturnArray = obj.CalculatePrice1(dtExcelData.Rows[i]["ProductCode"].ToString(), string.Empty, Convert.ToDecimal(dtExcelData.Rows[i]["Qty"].ToString()), DDLEntryType.SelectedItem.Text.ToString());
if (ReturnArray != null)
{
cmd1.Parameters.AddWithValue("@RECID", RecidLine + 1 + i);
cmd1.Parameters.AddWithValue("@Site_Code", Session["SiteCode"].ToString());
cmd1.Parameters.AddWithValue("@Purchase_Reciept_No", strCode);
cmd1.Parameters.AddWithValue("@PRODUCT_CODE", dtExcelData.Rows[i]["ProductCode"].ToString());
cmd1.Parameters.AddWithValue("@LINE_NO", RecidLine + 1 + i);
cmd1.Parameters.AddWithValue("@DATAAREAID", Session["DATAAREAID"].ToString());
#region Crate Box Data Insert
if (ReturnArray[5].ToString() == "Box")
{
cmd1.Parameters.AddWithValue("@BOX", dtExcelData.Rows[i]["Qty"].ToString());
cmd1.Parameters.AddWithValue("@CRATES", ReturnArray[0].ToString());
cmd1.Parameters.AddWithValue("@LTR", ReturnArray[1].ToString());
cmd1.Parameters.AddWithValue("@RATE", 0);
cmd1.Parameters.AddWithValue("@UOM", ReturnArray[4].ToString());
cmd1.Parameters.AddWithValue("@BASICVALUE", 0);
cmd1.Parameters.AddWithValue("@TRDDISCPERC", 0);
cmd1.Parameters.AddWithValue("@TRDDISCVALUE", 0);
cmd1.Parameters.AddWithValue("@PRICEEQUALVALUE", 0);
cmd1.Parameters.AddWithValue("@VAT_INC_PERC",0);
cmd1.Parameters.AddWithValue("@VAT_INC_PERC_VALUE", 0);
cmd1.Parameters.AddWithValue("@GROSSAMOUNT", 0);
cmd1.Parameters.AddWithValue("@DISCOUNT", 0);
cmd1.Parameters.AddWithValue("@TAX", 0);
cmd1.Parameters.AddWithValue("@TAXAMOUNT", 0);
cmd1.Parameters.AddWithValue("@AMOUNT", 0);
cmd1.Parameters.AddWithValue("@Remark", "FOC");
cmd1.ExecuteNonQuery();
no += 1;
}
#endregion
}
}
cmd.ExecuteNonQuery();
transaction.Commit();
ShowRecords(strCode);
UpdateAndShowTotalMaterialValue(strCode);
BtnUpdateHeader.Visible = true;
LblMessage.Text = "Records Uploaded Successfully. Total Records : " + dtExcelData.Rows.Count + ". Uploaded : " + no + " Records.";
if (dtForShownUnuploadData.Rows.Count > 0)
{
gridviewRecordNotExist.DataSource = dtForShownUnuploadData;
gridviewRecordNotExist.DataBind();
ModalPopupExtender1.Show();
}
else
{
gridviewRecordNotExist.DataSource = null;
gridviewRecordNotExist.DataBind();
}
}
}
}
catch (Exception ex)
{
ErrorSignal.FromCurrentContext().Raise(ex);
transaction.Rollback();
LblMessage.Text = ex.Message.ToString();
}
}
protected void rdoManualEntry_CheckedChanged(object sender, EventArgs e)
{
RadioButton rdo = (RadioButton)sender;
if (rdo.ID == "rdoManualEntry")
{
panelAddLine.Visible = true;
AsyncFileUpload1.Visible = false;
btnUplaod.Visible = false;
LblMessage.Text = "";
txtIndentDate.Text = string.Empty;
txtTransporterName.Text = string.Empty;
txttransporterNo.Text = string.Empty;
txtvehicleNo.Text = string.Empty;
txtInvoiceNo.Text = string.Empty;
txtInvoiceDate.Text = string.Empty;
txtVehicleType.Text = string.Empty;
GridFOCPurchItems.DataSource = null;
GridFOCPurchItems.Visible = false;
txtPurchDocumentNo.Text = string.Empty;
GridFOCPurchItems.DataSource = null;
GridFOCPurchItems.DataBind();
txtPurchDocumentNo.Text = "";
}
else
{
panelAddLine.Visible = false;
AsyncFileUpload1.Visible = true;
btnUplaod.Visible = true;
LblMessage.Text = "";
txtIndentDate.Text = string.Empty;
txtTransporterName.Text = string.Empty;
txttransporterNo.Text = string.Empty;
txtvehicleNo.Text = string.Empty;
txtInvoiceNo.Text = string.Empty;
txtInvoiceDate.Text = string.Empty;
txtVehicleType.Text = string.Empty;
GridFOCPurchItems.DataSource = null;
GridFOCPurchItems.Visible = false;
txtPurchDocumentNo.Text = string.Empty;
txtPurchDocumentNo.Text = "";
GridFOCPurchItems.DataSource = null;
GridFOCPurchItems.DataBind();
}
}
protected void txtEntryValue_TextChanged(object sender, EventArgs e)
{
try
{
CreamBell_DMS_WebApps.App_Code.Global obj = new Global();
decimal EntryValueQty = 0;
EntryValueQty = Convert.ToDecimal(txtEntryValue.Text);
if (EntryValueQty != 0)
{
txtWeight.Text = Convert.ToString(Math.Round((ProductWeight * EntryValueQty) / 1000, 2));
txtVolume.Text = Convert.ToString(Math.Round((ProductLitre * EntryValueQty) / 1000, 2));
}
else
{
LblMessage.Text = "Entered Quantity always greater than zero..!!";
}
}
catch (Exception ex)
{
ErrorSignal.FromCurrentContext().Raise(ex);
LblMessage.Text = ex.Message.ToString();
}
}
}
} |
using UnityEngine;
[System.Serializable]
public class array2d {
public Renderer[] renderers;
public int[] materialNumbers;
}
public class ColorPickerTester : MonoBehaviour
{
public array2d[] paintSection;
private Renderer[] currentRenderers;
private int[] currentMatNums;
public ColorPicker picker;
// Use this for initialization
void Start ()
{
setPaintSection(0);
picker.CurrentColor = currentRenderers[0].materials[0].color;
picker.onValueChanged.AddListener(color =>
{
for (int i = 0; i < currentRenderers.Length; ++i)
{
currentRenderers[i].materials[currentMatNums[i]].color = picker.CurrentColor;
}
});
}
public void setPaintSection(int _num) {
currentRenderers = paintSection[_num].renderers;
currentMatNums = paintSection[_num].materialNumbers;
picker.CurrentColor = currentRenderers[0].materials[currentMatNums[0]].color;
}
}
|
using JT808.Protocol.Attributes;
using JT808.Protocol.Formatters;
using JT808.Protocol.MessagePack;
namespace JT808.Protocol.MessageBody
{
/// <summary>
/// SMS 消息重传次数
/// 0x8103_0x0007
/// </summary>
public class JT808_0x8103_0x0007 : JT808_0x8103_BodyBase, IJT808MessagePackFormatter<JT808_0x8103_0x0007>
{
public override uint ParamId { get; set; } = 0x0007;
/// <summary>
/// 数据 长度
/// </summary>
public override byte ParamLength { get; set; } = 4;
/// <summary>
/// SMS 消息重传次数
/// </summary>
public uint ParamValue { get; set; }
public JT808_0x8103_0x0007 Deserialize(ref JT808MessagePackReader reader, IJT808Config config)
{
JT808_0x8103_0x0007 jT808_0x8103_0x0007 = new JT808_0x8103_0x0007();
jT808_0x8103_0x0007.ParamId = reader.ReadUInt32();
jT808_0x8103_0x0007.ParamLength = reader.ReadByte();
jT808_0x8103_0x0007.ParamValue = reader.ReadUInt32();
return jT808_0x8103_0x0007;
}
public void Serialize(ref JT808MessagePackWriter writer, JT808_0x8103_0x0007 value, IJT808Config config)
{
writer.WriteUInt32(value.ParamId);
writer.WriteByte(value.ParamLength);
writer.WriteUInt32(value.ParamValue);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
using System.ComponentModel.DataAnnotations;
namespace TheQuest.Models
{
public class Enemy
{
public Enemy()
{
this.Stats = new HashSet<Stats>();
}
[Key]
public int EnemyId { get; set; }
public string Name { get; set; }
public ICollection<Stats> Stats { get; set; }
public int ItemId { get; set; }
public Item Item { get; set; }
public int Currency { get; set; }
public int MapId { get; set; }
public Map Map { get; set; }
public float Longitude { get; set; }
public float Latitude { get; set; }
}
}
|
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using System;
using System.Reflection;
namespace KFrame
{
/// <summary>
/// Class KFrameMiddlewareExtensions.
/// </summary>
public static class KFrameMiddlewareExtensions
{
/// <summary>
/// Uses the k frame.
/// </summary>
/// <param name="app">The application.</param>
/// <param name="assemblies">The assemblies.</param>
/// <returns>IApplicationBuilder.</returns>
/// <exception cref="System.ArgumentNullException">app</exception>
public static IApplicationBuilder UseKFrame(this IApplicationBuilder app, params Assembly[] assemblies)
{
if (app == null)
throw new ArgumentNullException(nameof(app));
var sources = KFrameRepository.FindSourcesFromAssembly(assemblies);
return app.UseMiddleware<KFrameMiddleware>(new KFrameOptions { }, sources);
}
/// <summary>
/// Uses the k frame.
/// </summary>
/// <param name="app">The application.</param>
/// <param name="requestPath">The request path.</param>
/// <param name="assemblies">The assemblies.</param>
/// <returns>IApplicationBuilder.</returns>
/// <exception cref="System.ArgumentNullException">app</exception>
public static IApplicationBuilder UseKFrame(this IApplicationBuilder app, string requestPath, params Assembly[] assemblies)
{
if (app == null)
throw new ArgumentNullException(nameof(app));
var sources = KFrameRepository.FindSourcesFromAssembly(assemblies);
return app.UseMiddleware<KFrameMiddleware>(new KFrameOptions
{
RequestPath = new PathString(requestPath)
}, sources);
}
/// <summary>Uses the k frame.</summary>
/// <param name="app">The application.</param>
/// <param name="log">The logger.</param>
/// <param name="assemblies">The assemblies.</param>
/// <returns>IApplicationBuilder.</returns>
/// <exception cref="System.ArgumentNullException">app</exception>
public static IApplicationBuilder UseKFrame(this IApplicationBuilder app, ILogger log, params Assembly[] assemblies)
{
if (app == null)
throw new ArgumentNullException(nameof(app));
var sources = KFrameRepository.FindSourcesFromAssembly(assemblies);
return app.UseMiddleware<KFrameMiddleware>(new KFrameOptions
{
Log = log,
}, sources);
}
/// <summary>
/// Uses the k frame.
/// </summary>
/// <param name="app">The application.</param>
/// <param name="requestPath">The request path.</param>
/// <param name="log">The logger.</param>
/// <param name="assemblies">The assemblies.</param>
/// <returns>IApplicationBuilder.</returns>
/// <exception cref="System.ArgumentNullException">app</exception>
public static IApplicationBuilder UseKFrame(this IApplicationBuilder app, string requestPath, ILogger log, params Assembly[] assemblies)
{
if (app == null)
throw new ArgumentNullException(nameof(app));
var sources = KFrameRepository.FindSourcesFromAssembly(assemblies);
return app.UseMiddleware<KFrameMiddleware>(new KFrameOptions
{
RequestPath = new PathString(requestPath),
Log = log,
}, sources);
}
/// <summary>
/// Uses the k frame.
/// </summary>
/// <param name="app">The application.</param>
/// <param name="options">The options.</param>
/// <param name="assemblys">The assemblys.</param>
/// <returns>IApplicationBuilder.</returns>
/// <exception cref="System.ArgumentNullException">app</exception>
/// <exception cref="System.ArgumentNullException">options</exception>
public static IApplicationBuilder UseKFrame(this IApplicationBuilder app, KFrameOptions options, params Assembly[] assemblys)
{
if (app == null)
throw new ArgumentNullException(nameof(app));
if (options == null)
throw new ArgumentNullException(nameof(options));
var sources = KFrameRepository.FindSourcesFromAssembly(assemblys);
return app.UseMiddleware<KFrameMiddleware>(options, sources);
}
/// <summary>
/// Uses the k frame.
/// </summary>
/// <param name="app">The application.</param>
/// <param name="options">The options.</param>
/// <param name="requestPath">The request path.</param>
/// <param name="assemblys">The assemblys.</param>
/// <returns>IApplicationBuilder.</returns>
/// <exception cref="System.ArgumentNullException">app</exception>
/// <exception cref="System.ArgumentNullException">options</exception>
public static IApplicationBuilder UseKFrame(this IApplicationBuilder app, KFrameOptions options, string requestPath, params Assembly[] assemblys)
{
if (app == null)
throw new ArgumentNullException(nameof(app));
if (options == null)
throw new ArgumentNullException(nameof(options));
options.RequestPath = requestPath;
var sources = KFrameRepository.FindSourcesFromAssembly(assemblys);
return app.UseMiddleware<KFrameMiddleware>(options, sources);
}
}
}
|
using Edument.CQRS;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Events.Cafe
{
public class DrinksOrdered : IEvent
{
public Guid Id { get; set; }
public List<OrderedItem> Items;
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Assistenza.BufDalsi.Web.Models.SensoreViewModels
{
public class DeleteSensoreViewModel
{
public int Id { get; set; }
public int ipt_Id { get; set; }
public int clt_Id { get; set; }
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.UI;
public class Interactable : MonoBehaviour
{
public bool canInteract = false;
public GameObject canvas;
public int cluesFound = 0;
void Start()
{
}
private void Update()
{
if (canInteract)
{
Interact();
}
}
private void OnTriggerEnter2D(Collider2D other)
{
if(other.tag == "Player")
{
canInteract = true;
}
}
private void OnTriggerExit2D(Collider2D other)
{
if(other.tag == "Player")
{
canInteract = false;
}
}
public void Interact()
{
if (Input.GetKeyDown(KeyCode.X))
{
canvas.SetActive(true);
cluesFound++;
}
if(cluesFound >= 2)
{
SceneManager.LoadScene("SpaceCruiseWinScreen");
}
}
}
|
// Copyright (c) 2020, mParticle, Inc
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// 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.
using System;
using System.Collections.Generic;
using MP.Json;
using MP.Json.Validation;
using Xunit;
namespace JsonSchemaTestSuite.Draft201909
{
public class UniqueItems
{
/// <summary>
/// 1 - uniqueItems validation
/// </summary>
[Theory]
[InlineData(
"unique array of integers is valid",
"[ 1, 2 ]",
true
)]
[InlineData(
"non-unique array of integers is invalid",
"[ 1, 1 ]",
false
)]
[InlineData(
"numbers are unique if mathematically unequal",
"[ 1, 1, 1 ]",
false
)]
[InlineData(
"false is not equal to zero",
"[ 0, false ]",
true
)]
[InlineData(
"true is not equal to one",
"[ 1, true ]",
true
)]
[InlineData(
"unique array of objects is valid",
"[ { 'foo':'bar' }, { 'foo':'baz' } ]",
true
)]
[InlineData(
"non-unique array of objects is invalid",
"[ { 'foo':'bar' }, { 'foo':'bar' } ]",
false
)]
[InlineData(
"unique array of nested objects is valid",
"[ { 'foo':{ 'bar':{ 'baz':true } } }, { 'foo':{ 'bar':{ 'baz':false } } } ]",
true
)]
[InlineData(
"non-unique array of nested objects is invalid",
"[ { 'foo':{ 'bar':{ 'baz':true } } }, { 'foo':{ 'bar':{ 'baz':true } } } ]",
false
)]
[InlineData(
"unique array of arrays is valid",
"[ [ 'foo' ], [ 'bar' ] ]",
true
)]
[InlineData(
"non-unique array of arrays is invalid",
"[ [ 'foo' ], [ 'foo' ] ]",
false
)]
[InlineData(
"1 and true are unique",
"[ 1, true ]",
true
)]
[InlineData(
"0 and false are unique",
"[ 0, false ]",
true
)]
[InlineData(
"unique heterogeneous types are valid",
"[ { }, [ 1 ], true, null, 1 ]",
true
)]
[InlineData(
"non-unique heterogeneous types are invalid",
"[ { }, [ 1 ], true, null, { }, 1 ]",
false
)]
public void UniqueItemsValidation(string desc, string data, bool expected)
{
// uniqueItems validation
Console.Error.WriteLine(desc);
string schemaData = "{ 'uniqueItems':true }";
MPJson schemaJson = MPJson.Parse(schemaData);
MPJson json = MPJson.Parse(data);
MPSchema schema = schemaJson;
var validator = new JsonValidator { Strict = true, Version = SchemaVersion.Draft201909 };
bool actual = validator.Validate(schema, json);
Assert.Equal(expected, actual);
}
/// <summary>
/// 2 - uniqueItems with an array of items
/// </summary>
[Theory]
[InlineData(
"[false, true] from items array is valid",
"[ false, true ]",
true
)]
[InlineData(
"[true, false] from items array is valid",
"[ true, false ]",
true
)]
[InlineData(
"[false, false] from items array is not valid",
"[ false, false ]",
false
)]
[InlineData(
"[true, true] from items array is not valid",
"[ true, true ]",
false
)]
[InlineData(
"unique array extended from [false, true] is valid",
"[ false, true, 'foo', 'bar' ]",
true
)]
[InlineData(
"unique array extended from [true, false] is valid",
"[ true, false, 'foo', 'bar' ]",
true
)]
[InlineData(
"non-unique array extended from [false, true] is not valid",
"[ false, true, 'foo', 'foo' ]",
false
)]
[InlineData(
"non-unique array extended from [true, false] is not valid",
"[ true, false, 'foo', 'foo' ]",
false
)]
public void UniqueItemsWithAnArrayOfItems(string desc, string data, bool expected)
{
// uniqueItems with an array of items
Console.Error.WriteLine(desc);
string schemaData = "{ 'items':[ { 'type':'boolean' }, { 'type':'boolean' } ], 'uniqueItems':true }";
MPJson schemaJson = MPJson.Parse(schemaData);
MPJson json = MPJson.Parse(data);
MPSchema schema = schemaJson;
var validator = new JsonValidator { Strict = true, Version = SchemaVersion.Draft201909 };
bool actual = validator.Validate(schema, json);
Assert.Equal(expected, actual);
}
/// <summary>
/// 3 - uniqueItems with an array of items and additionalItems=false
/// </summary>
[Theory]
[InlineData(
"[false, true] from items array is valid",
"[ false, true ]",
true
)]
[InlineData(
"[true, false] from items array is valid",
"[ true, false ]",
true
)]
[InlineData(
"[false, false] from items array is not valid",
"[ false, false ]",
false
)]
[InlineData(
"[true, true] from items array is not valid",
"[ true, true ]",
false
)]
[InlineData(
"extra items are invalid even if unique",
"[ false, true, null ]",
false
)]
public void UniqueItemsWithAnArrayOfItemsAndAdditionalItemsFalse(string desc, string data, bool expected)
{
// uniqueItems with an array of items and additionalItems=false
Console.Error.WriteLine(desc);
string schemaData = "{ 'additionalItems':false, 'items':[ { 'type':'boolean' }, { 'type':'boolean' } ], 'uniqueItems':true }";
MPJson schemaJson = MPJson.Parse(schemaData);
MPJson json = MPJson.Parse(data);
MPSchema schema = schemaJson;
var validator = new JsonValidator { Strict = true, Version = SchemaVersion.Draft201909 };
bool actual = validator.Validate(schema, json);
Assert.Equal(expected, actual);
}
}
}
|
namespace Mall.Infrastructure.DomainCore
{
/// <summary>
/// 标识继承该类的是一个聚合
/// </summary>
public class Aggregate : Entity
{
}
}
|
using System;
using System.Runtime.InteropServices;
namespace Vlc.DotNet.Core.Interops.Signatures
{
[StructLayout(LayoutKind.Sequential)]
internal struct AudioOutputDescriptionStructureInternal
{
public IntPtr Name;
public IntPtr Description;
public IntPtr NextAudioOutputDescription;
}
public struct AudioOutputDescriptionStructure
{
public string Name;
public string Description;
}
}
|
using UnityEngine;
using System.Collections;
public class EffectFadeOut : MonoBehaviour
{
public ParticleSystem[] particleSystems;
public UITweener[] tweeners;
public void OnDisable()
{
for (int i = 0; i < tweeners.Length; i++)
{
if (tweeners[i] != null)
tweeners[i].ResetToBeginning();
}
}
public void BeginFadeOut()
{
for (int i = 0; i < particleSystems.Length; i++)
{
if (particleSystems[i] != null)
particleSystems[i].Stop(false);
}
for (int i = 0; i < tweeners.Length; i++)
{
if (tweeners[i] != null)
{
tweeners[i].PlayForward();
}
}
}
public void EnableFadeOut()
{
for (int i = 0; i < tweeners.Length; i++)
{
if (tweeners[i] != null)
{
tweeners[i].enabled = false;
}
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class EnemySpawn : MonoBehaviour
{
[SerializeField] private GameObject enemyPrefab;
[SerializeField] private GameObject player;
[SerializeField] private GameObject spawnpoint;
private int spawnOffset = 12;
private Vector3 playerpos;
private Vector3 spawnpos;
private bool wasSpawned;
// Start is called before the first frame update
void Start()
{
wasSpawned = false;
spawnpos = spawnpoint.transform.position;
}
// Update is called once per frame
void Update()
{
Spawn();
}
//spawns enemy when its right outside the line of sight;
void Spawn()
{
playerpos = player.transform.position;
if (!wasSpawned)
{
if (playerpos.x > (spawnpos.x - spawnOffset))
{
Instantiate(enemyPrefab, spawnpos,spawnpoint.transform.rotation);
wasSpawned = true;
Destroy(spawnpoint);
}
}
}
}
|
using System;
namespace NASTYADANYA
{
public class Asin : IOneArgumentCalculator
{
/// <summary>
/// calculate Asim function
/// </summary>
/// <param name="firstArgument"> any number </param>
/// <returns> result in rads </returns>
public double Calculate(double firstArgument)
{
return Math.Asin(firstArgument);
}
}
} |
using System;
using System.Linq;
using System.Text.RegularExpressions;
using Formulas;
using SS;
namespace SpreadsheetGUI
{
/// <summary>
/// Simple struct that will take a cell name (A1) and convert to a cell row/column. Also takes a cell column/row
/// and converts it to a cell name (A1). Given a spreadsheet, it will return a value.
/// </summary>
public struct GuiCell
{
public string CellName;
public int CellColumn;
public int CellRow;
const string Letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
/// <summary>
/// Takes a row and a column and will convert to a cell name.
/// </summary>
public GuiCell(int column, int row)
{
//Setup the struct
CellName = string.Empty;
CellColumn = column;
CellRow = row;
//Set the cell name.
CellName = GetCellName(column, row);
}
/// <summary>
/// Takes a cellname and will convert to row/col.
/// </summary>
/// <param name="cellName"></param>
public GuiCell(string cellName)
{
//Setup the struct
CellName = cellName;
CellColumn = 0;
CellRow = 0;
//Set the cell row and column.
GetCellIndex(cellName);
}
/// <summary>
/// Returns the cell name.
/// </summary>
private string GetCellName(int column, int row)
{
string cellName = string.Empty;
while (column >= 0)
{
cellName += Letters[column % 26];
column -= 26;
}
cellName += row + 1;
return cellName;
}
/// <summary>
/// Calculates the cells row and column given a cell name.
/// </summary>
private void GetCellIndex(string CellName)
{
Match rowMatch = new Regex("([0-9]+)").Match(CellName);
foreach (char letter in CellName)
{
if (char.IsLetter(letter)) CellColumn += letter - 65;
}
CellRow = int.Parse(rowMatch.Groups[0].Value)-1;
}
/// <summary>
/// Returns the cell value from a given spreadsheet.
/// </summary>
public string GetCellValue(Spreadsheet spreadsheet)
{
var cellValue = spreadsheet.GetCellValue(CellName);
if (cellValue is FormulaError)
{
FormulaError error = (FormulaError) cellValue;
return error.Reason;
}
return cellValue.ToString();
}
/// <summary>
/// Returns the cell contents given a spreadsheet.
/// </summary>
public string GetCellContents(Spreadsheet spreadsheet)
{
var value = spreadsheet.GetCellContents(CellName);
if (value is Formula)
{
return "=" + value;
}
if (value is FormulaError)
{
return "ERROR";
}
return value.ToString();
}
}
}
|
using ChutesAndLadders.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Chute
{
public static class Demo3aExtensions
{
public static void Demo3a_GeneticAnalysis(this GameBoard board)
{
int maxOptions = 0;
int totalConditions = 0;
int totalConditionalOptions = 0;
for (int startingPoint = 0; startingPoint < 100; startingPoint++)
{
for (byte spin = 1; spin < 7; spin++)
{
var endPoints = board.GetLegalEndpoints(startingPoint, spin);
int currentOptions = endPoints.Count();
if ((currentOptions > 1) && (!endPoints.Contains(100)))
{
totalConditions++;
totalConditionalOptions += currentOptions;
if (currentOptions > maxOptions)
maxOptions = currentOptions;
Console.WriteLine($"{startingPoint},{spin},{currentOptions}");
}
}
}
Console.WriteLine($"Max Options: {maxOptions}");
Console.WriteLine($"Total Conditions: {totalConditions}");
Console.WriteLine($"Total Conditional Options: {totalConditionalOptions}");
}
}
}
|
using Terraria;
using Terraria.ID;
using Terraria.ModLoader;
using static Terraria.ModLoader.ModContent;
namespace NauticaMod.Items
{
public class MetalSalvage : ModItem
{
public override void SetStaticDefaults()
{
Tooltip.SetDefault("Composed primarily of titanium.");
}
public override void SetDefaults() {
item.width = 32;
item.height = 32;
item.maxStack = 99;
item.rare = ItemRarityID.White;
item.consumable = false;
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using ApplicationCore.Entities;
using ApplicationCore.Services;
using AutoMapper;
using Microsoft.AspNetCore.Mvc;
using Web.ViewModels;
namespace Web.Controllers
{
[Route("api/[controller]")]
public class ProductController : Controller
{
private readonly IProductService _productService;
private readonly IMapper _mapper;
public ProductController(
IProductService productService, IMapper mapper
)
{
_productService = productService;
_mapper = mapper;
}
[HttpGet("[action]")]
public async Task<IEnumerable<ProductListItemVM>> List()
{
var products = await _productService.ListAsync(0, int.MaxValue);
var prductItemsVM = _mapper.Map<IEnumerable<Product>, List<ProductListItemVM>>(products);
return prductItemsVM;
}
}
} |
namespace Core
{
/// <summary>
/// Represents base link info for action responses
/// </summary>
public class BaseLinkInfo
{
/// <summary>
/// Link Path
/// </summary>
public string Href { get; set; }
/// <summary>
/// The link belongs to which page, previous, next, self ... etc
/// </summary>
public string Rel { get; set; }
/// <summary>
/// Hangi HTTP metot kullanılacak GET,POST,PUT ... vs
/// </summary>
public string Method { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using UFSoft.UBF.UI.ControlModel;
using UFSoft.UBF.UI.WebControlAdapter;
using U9.VOB.HBHCommon.HBHCommonUI;
using UFIDA.U9.SM.SO;
using System.Collections.Specialized;
using UFIDA.U9.CBO.SCM.Enums;
namespace U9.VOB.Cus.HBHTianRiSheng.UIPlugin
{
public class SO_UIPlugin : UFSoft.UBF.UI.Custom.ExtendedPartBase
{ // 特价订单、零售订单、套餐订单
public const string Cons_SOVouchersDocTypeCode = ",SO03,SO04,SO08,SO09,";
UFSoft.UBF.UI.IView.IPart part;
UFIDA.U9.SCM.SM.SOUIModel.StandardSOMainUIFormWebPart _strongPart;
IUFDataGrid dgLine;
List<IUFControl> lstPriceCtrl = new List<IUFControl>();
IUFButton btnHBHRefresh;
IUFButton btnSOVouchers;
//public const string Const_SaleDeptID = "SaleDept259";
//IUFDataGrid DataGrid10;
//IUFFldReferenceColumn itemRef;
public override void AfterInit(UFSoft.UBF.UI.IView.IPart Part, EventArgs args)
{
base.AfterInit(Part, args);
part = Part;
_strongPart = Part as UFIDA.U9.SCM.SM.SOUIModel.StandardSOMainUIFormWebPart;
//_strongPart.Cust_Discount01_TextChanged
// Cust_Discount01
//this.ChangedBeforeDept58.AddTypeParams("ParentTaskID", this.TaskId);
// Card3 TabControl0 TabPageBase Cust_Discount01
string cardName = "Card3";
string tabCtrlName = "TabControl0";
string tabPgName = "TabPageBusiness";
string refName = "Cust_Discount01";
string dgTabCtrlName = "TabControl1";
string dgTabPageName = "TabPageLine";
string datagridName = "DataGrid4";
string dgTabTranName = "TabPageTran";
//string finallyPriceCtrlName = "FinallyPriceTC140";
//string discountRateCtrlName = "DiscountRate40";
//string totalMoneyTCCtrlName = "TotalMoneyTC01";
//string netMoneyTCCtrlName = "NetMoneyTC179";
//string taxMoneyTCCtrlName = "TaxMoneyTC163";
List<string> lstPriceCtrlName = new List<string>();
lstPriceCtrlName.Add("FinallyPriceTC140");
lstPriceCtrlName.Add("DiscountRate40");
lstPriceCtrlName.Add("TotalMoneyTC01");
lstPriceCtrlName.Add("NetMoneyTC179");
lstPriceCtrlName.Add("TaxMoneyTC163");
IUFCard card3 = (IUFCard)part.GetUFControlByName(part.TopLevelContainer, cardName);
if (card3 != null)
{
IUFTabControl tc0 = (IUFTabControl)part.GetUFControlByName(card3, tabCtrlName);
if (tc0 != null
&& tc0.TabPages != null
&& tc0.TabPages.Count > 0
)
{
IUFTabPage tp1 = null;
foreach (IUFTabPage page in tc0.TabPages)
{
if (page != null
&& page.ID == tabPgName
)
{
tp1 = page;
break;
}
}
if (tp1 != null)
{
IUFFldReference refDiscount = (IUFFldReference)part.GetUFControlByName(tp1, refName);
if (refDiscount != null)
{
refDiscount.AddTypeParams("ParentTaskID", _strongPart.TaskId);
}
}
}
IUFTabControl tc1 = (IUFTabControl)part.GetUFControlByName(card3, dgTabCtrlName);
if (tc1 != null
&& tc1.TabPages != null
&& tc1.TabPages.Count > 0
)
{
IUFTabPage tpline = null;
foreach (IUFTabPage page in tc1.TabPages)
{
if (page != null
&& page.ID == dgTabPageName
)
{
tpline = page;
break;
}
}
if (tpline != null)
{
dgLine = (IUFDataGrid)part.GetUFControlByName(tpline, datagridName);
}
IUFTabPage tpTran = null;
foreach (IUFTabPage page in tc1.TabPages)
{
if (page != null
&& page.ID == dgTabTranName
)
{
tpTran = page;
break;
}
}
if (tpTran != null)
{
foreach (string ctrlName in lstPriceCtrlName)
{
IUFControl ctrl = part.GetUFControlByName(tpTran, ctrlName);
if (ctrl != null)
{
lstPriceCtrl.Add(ctrl);
}
}
}
}
}
// Card0 19
string card0Name = "Card0";
IUFCard card0 = (IUFCard)part.GetUFControlByName(part.TopLevelContainer, card0Name);
btnHBHRefresh = new UFWebButtonAdapter();
btnHBHRefresh.Text = "刷新";
btnHBHRefresh.ID = "btnHBHRefresh";
btnHBHRefresh.AutoPostBack = true;
btnHBHRefresh.Visible = false;
btnHBHRefresh.Click += new EventHandler(btnHBHRefresh_Click);
card0.Controls.Add(btnHBHRefresh);
UICommonHelper.Layout(card0, btnHBHRefresh, 18, 0);
btnSOVouchers = new UFWebButtonAdapter();
btnSOVouchers.Text = "抵用劵";
btnSOVouchers.ID = "btnSOVouchers";
btnSOVouchers.AutoPostBack = true;
btnSOVouchers.Visible = true;
btnSOVouchers.Click += new EventHandler(btnSOVouchers_Click);
card0.Controls.Add(btnSOVouchers);
UICommonHelper.Layout(card0, btnSOVouchers, 18, 0);
}
public override void AfterEventProcess(UFSoft.UBF.UI.IView.IPart Part, string eventName, object sender, EventArgs args)
{
base.AfterEventProcess(Part, eventName, sender, args);
//UFSoft.UBF.UI.WebControlAdapter.UFWebReferenceAdapter web = sender as UFSoft.UBF.UI.WebControlAdapter.UFWebReferenceAdapter;
//if (web != null && web.UIField.Name == "ReqDepartment")
//{
//}
UFSoft.UBF.UI.WebControlAdapter.UFWebButton4ToolbarAdapter webButton = sender as UFSoft.UBF.UI.WebControlAdapter.UFWebButton4ToolbarAdapter;
if (webButton != null
&& webButton.ID == "BtnCopy"
)
{
UFIDA.U9.SCM.SM.SOUIModel.SORecord head = _strongPart.Model.SO.FocusedRecord;
if (head != null)
{
head.DescFlexField_PubDescSeg13 = string.Empty;
head.DescFlexField_PubDescSeg14 = string.Empty;
head.DescFlexField_PubDescSeg15 = string.Empty;
}
}
}
void btnHBHRefresh_Click(object sender, EventArgs e)
{
_strongPart.Action.NavigateAction.Refresh(null);
}
void btnSOVouchers_Click(object sender, EventArgs e)
{
_strongPart.Model.ClearErrorMessage();
UFIDA.U9.SCM.SM.SOUIModel.SORecord head = _strongPart.Model.SO.FocusedRecord;
if (head != null
&& head.Status == (int)SODocStatusEnumData.Open
)
{
string strDocType = head.DocumentType_Code;
if (Cons_SOVouchersDocTypeCode.Contains("," + strDocType + ","))
{
_strongPart.BtnSave_Click(sender, e);
//curPart.CurrentState[Const_PriceModifyTable] = null;
//curPart.ShowAtlasModalDialog(btnHBHRefresh,"23ff31c2-e6af-4eda-b1ce-e82432f90c18", "采购订单调价", "800", "390", curPart.TaskId.ToString(), null, true, false, true,PartShowType.ShowModal,true);
head = _strongPart.Model.SO.FocusedRecord;
if (head.ID > 0
&& !_strongPart.Model.ErrorMessage.hasErrorMessage
)
{
NameValueCollection nvc = new NameValueCollection();
nvc.Add("SOID", head.ID.ToString());
nvc.Add("SODocNo", head.DocNo);
// [FormRegister("U9.VOB.Cus.HBHTianRiSheng.HBHTianRiShengUI","SOVouchersUIModel.SOVouchersUIFormWebPart", "U9.VOB.Cus.HBHTianRiSheng.HBHTianRiShengUI.WebPart", "4ef54a6c-9ad1-41a7-a0f6-e9915e38112c","WebPart", "False", 686, 504)]
_strongPart.ShowAtlasModalDialog(
// curPart.GetUFControlByName(curPart.TopLevelContainer, "btnReLoad")
btnHBHRefresh
, "7f428875-185e-4ff8-886c-d22615c74ab8", "订单抵用劵", "690", "510"
, _strongPart.TaskId.ToString(), nvc, true, false, false
);
}
}
}
}
public override void AfterRender(UFSoft.UBF.UI.IView.IPart Part, EventArgs args)
{
base.AfterRender(Part, args);
UFIDA.U9.SCM.SM.SOUIModel.SORecord head = _strongPart.Model.SO.FocusedRecord;
UFIDA.U9.SCM.SM.SOUIModel.SO_SOLinesRecord line = _strongPart.Model.SO_SOLines.FocusedRecord;
if (head != null
)
{
if (IsUnchangeFinallyPrice(head.DocumentType_Code)
&& IsUnchangeFinallyPrice(line)
)
{
SetPriceControlStatus(false);
}
else
{
SetPriceControlStatus(true);
}
string strDocType = head.DocumentType_Code;
if (head.Status == (int)SODocStatusEnumData.Open
&& Cons_SOVouchersDocTypeCode.Contains("," + strDocType + ",")
)
{
btnSOVouchers.Enabled = true;
}
else
{
btnSOVouchers.Enabled = false;
}
}
}
private void SetPriceControlStatus(bool bl)
{
if (dgLine != null)
{
List<string> lstColumn = new List<string>();
lstColumn.Add("FinallyPriceTC");
lstColumn.Add("DiscountRate");
lstColumn.Add("TotalMoneyTC");
lstColumn.Add("NetMoneyTC");
lstColumn.Add("TaxMoneyTC");
//IUFDataGridColumn col = dgLine.Columns["FinallyPriceTC"];
foreach (string str in lstColumn)
{
IUFDataGridColumn col = dgLine.Columns[str];
if (col != null)
{
col.Enabled = bl;
}
}
}
if (lstPriceCtrl != null
&& lstPriceCtrl.Count > 0
)
{
foreach (IUFControl ctrl in lstPriceCtrl)
{
if (ctrl != null)
{
ctrl.Enabled = bl;
}
}
}
}
private bool IsUnchangeFinallyPrice(string str)
{
if (!string.IsNullOrWhiteSpace(str)
&& (str == "SO03"
|| str == "SO08"
|| str.StartsWith("KZ")
)
)
{
return true;
}
return false;
}
private bool IsUnchangeFinallyPrice(UFIDA.U9.SCM.SM.SOUIModel.SO_SOLinesRecord line)
{
if (line != null
&& line.FreeType == (int)FreeTypeEnumData.Present
)
{
return false;
}
return true;
}
}
}
|
using System;
using System.Web.Configuration;
using Boxofon.Web.Model;
using Microsoft.WindowsAzure.Storage;
using Microsoft.WindowsAzure.Storage.Table;
using ServiceStack.Text;
namespace Boxofon.Web.Infrastructure
{
public class AzureStorageTwilioPhoneNumberRepository : ITwilioPhoneNumberRepository, IRequireInitialization
{
private readonly CloudStorageAccount _storageAccount;
public AzureStorageTwilioPhoneNumberRepository()
{
_storageAccount = CloudStorageAccount.Parse(WebConfigurationManager.AppSettings["azure:StorageConnectionString"]);
}
public void Initialize()
{
Table().CreateIfNotExists();
}
protected CloudTable Table()
{
return _storageAccount.CreateCloudTableClient().GetTableReference("TwilioPhoneNumbers");
}
public TwilioPhoneNumber GetByPhoneNumber(string phoneNumber)
{
var op = TableOperation.Retrieve<TwilioPhoneNumberEntity>(phoneNumber, phoneNumber);
var result = Table().Execute(op);
return result.Result == null ? null : ((TwilioPhoneNumberEntity)result.Result).ToTwilioPhoneNumber();
}
public void Save(TwilioPhoneNumber phoneNumber)
{
var entity = new TwilioPhoneNumberEntity(phoneNumber);
var op = TableOperation.InsertOrReplace(entity);
Table().Execute(op);
}
public class TwilioPhoneNumberEntity : TableEntity
{
public string PhoneNumber { get { return PartitionKey; } }
public string FriendlyName { get; set; }
public string TwilioAccountSid { get; set; }
public Guid UserId { get; set; }
public TwilioPhoneNumberEntity()
{
}
public TwilioPhoneNumberEntity(TwilioPhoneNumber phoneNumber)
{
PartitionKey = phoneNumber.PhoneNumber;
RowKey = phoneNumber.PhoneNumber;
FriendlyName = phoneNumber.FriendlyName;
TwilioAccountSid = phoneNumber.TwilioAccountSid;
UserId = phoneNumber.UserId;
}
public TwilioPhoneNumber ToTwilioPhoneNumber()
{
return new TwilioPhoneNumber
{
PhoneNumber = PhoneNumber,
FriendlyName = FriendlyName,
TwilioAccountSid = TwilioAccountSid,
UserId = UserId
};
}
}
}
} |
using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices; //DllImport
using System.Windows.Forms;
using System.IO;
namespace SDI_LCS
{
#region 설명
/*////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////*/
#endregion
#region Control INI File
//------------------------------------------------------------------------------
// INI Class
//------------------------------------------------------------------------------
public class IniControl
{
static public string g_ini_file = @"C:\LCS_LOG\Config\\setup.ini";
//------------------------------------------------------------------------------
[DllImport("kernel32")]
public static extern bool WritePrivateProfileString(string lpAppName, string lpKeyName, string lpString, string lpFileName);
[DllImport("kernel32")]
public static extern uint GetPrivateProfileInt(string lpAppName, string lpKeyName, int nDefault, string lpFileName);
[DllImport("kernel32")]
public static extern int GetPrivateProfileString(string lpAppName, string lpKeyName, string lpDefault, StringBuilder lpReturnedString, int nSize, string lpFileName);
//------------------------------------------------------------------------------
public static int ReadInteger(string fileName, string IpAppName, string IpKeyName, int Default)
{
try
{
string inifile = g_ini_file; //Path + File
StringBuilder result = new StringBuilder(255);
IniControl.GetPrivateProfileString(IpAppName, IpKeyName, "error", result, 255, inifile);
if (result.ToString() == "error")
{
return Default;
}
else
{
return Convert.ToInt16(result);
}
}
catch
{
return Default;
}
}
//------------------------------------------------------------------------------
public static Boolean ReadBool(string fileName, string IpAppName, string IpKeyName)
{
string inifile = g_ini_file; //Path + File
StringBuilder result = new StringBuilder(255);
IniControl.GetPrivateProfileString(IpAppName, IpKeyName, "error", result, 255, inifile);
if (result.ToString() == "True" || result.ToString() == "1")
{
return true;
}
else
{
return false;
}
}
//------------------------------------------------------------------------------
public static string ReadString(string fileName, string IpAppName, string IpKeyName, string Default)
{
string inifile = g_ini_file; //Path + File
StringBuilder result = new StringBuilder(255);
IniControl.GetPrivateProfileString(IpAppName, IpKeyName, "error", result, 255, inifile);
if (result.ToString() == "error")
{
return Default;
}
else
{
return result.ToString();
}
}
//------------------------------------------------------------------------------
public static string getIni(string fileName, string IpAppName, string IpKeyName)
{
string inifile = g_ini_file; //Path + File
if (fileName != "")
inifile = fileName;
StringBuilder result = new StringBuilder(255);
IniControl.GetPrivateProfileString(IpAppName, IpKeyName, "error", result, 255, inifile);
return result.ToString();
}
//------------------------------------------------------------------------------
public static Boolean setIni(string fileName, string IpAppName, string IpKeyName, string IpValue)
{
string inifile = g_ini_file; //Path + File
if (fileName != "")
inifile = fileName;
IniControl.WritePrivateProfileString(IpAppName, IpKeyName, IpValue, inifile);
return true;
}
//------------------------------------------------------------------------------
public static Boolean setIni(string filePath, string fileName, string IpAppName, string IpKeyName, string IpValue)
{
string inifile = filePath + g_ini_file;
IniControl.WritePrivateProfileString(IpAppName, IpKeyName, IpValue, inifile);
return true;
}
}
#endregion
}
|
using Chess.v4.Engine.Extensions;
using Chess.v4.Engine.Reference;
using Chess.v4.Models;
using Chess.v4.Models.Enums;
using System;
using System.Collections.Generic;
namespace Chess.v4.Engine.Utility
{
public static class DiagonalEngine
{
private static List<int> File = GeneralEngine.GetEntireFile(7);
public static List<int> GetDiagonalLine(int location, int destination)
{
var _isDiagonal = IsDiagonal(location, destination);
if (!_isDiagonal)
{
throw new Exception("You're doing it wrong! GetDiagonalLine has to be used with a diagonal.");
}
var direction = getDirectionByMovePositions(location, destination);
var result = new List<int>();
var increment = getIteratorByDirectionEnum(direction);
// pick the higer of the two numbers and go up until just before you reach the destination
var positionCursorTerminator = location > destination ? location : destination;
var positionCursor = location + increment;
while (positionCursor < positionCursorTerminator)
{
result.Add(positionCursor);
positionCursor += increment;
}
return result;
}
public static List<AttackedSquare> GetDiagonalLine(GameState gameState, Square square, Piece attackingPiece, DiagonalDirection direction)
{
var attacks = new List<AttackedSquare>();
var diagonalLine = getIteratorByDirectionEnum(direction);
var position = square.Index;
var attackPosition = square.Index;
do
{
if (!canDoDiagonalsFromStartPosition(position, diagonalLine))
{
break;
}
attackPosition = attackPosition + diagonalLine;
var moveViability = GeneralEngine.DetermineMoveViability(gameState, attackingPiece, attackPosition);
//I don't think either of these conditions should occur.
if (!moveViability.IsValidCoordinate || moveViability.SquareToAdd == null)
{
continue;
}
var attack = new AttackedSquare(square, moveViability.SquareToAdd, isProtecting: moveViability.IsTeamPiece);
attacks.Add(attack);
if (moveViability.SquareToAdd.Occupied)
{
break;
}
} while (isValidDiagonalCoordinate(attackPosition));
return attacks;
}
public static void GetDiagonals(GameState gameState, Square square, List<AttackedSquare> accumulator)
{
foreach (var direction in GeneralReference.DiagonalLines)
{
var attacks = GetDiagonalLine(gameState, square, square.Piece, direction);
accumulator.AddRange(attacks);
}
}
public static List<int> GetEntireDiagonalByFile(int file, DiagonalDirectionFromFileNumber direction)
{
var list = new List<int>();
var increment = getDiagonalIncrement(direction);
var numberOfSquares = howFarToGo(file, direction);
var index = file;
for (int i = 0; i < numberOfSquares; i++)
{
list.Add(index);
index = index + increment;
}
return list;
}
public static List<Square> GetEntireDiagonalByFile(GameState gameState, int file, DiagonalDirectionFromFileNumber direction)
{
var indexes = GetEntireDiagonalByFile(file, direction);
var list = new List<Square>();
//optimize, a linq join here would perform better
indexes.ForEach(a => list.Add(gameState.Squares.GetSquare(a)));
return list;
}
public static List<int> GetEntireDiagonalByPosition(int position)
{
var list = new List<int>();
foreach (var direction in GeneralReference.DiagonalLines)
{
var result = getEntireDiagonalLine(direction, position);
list.AddRange(result);
}
return list;
}
public static bool IsDiagonal(int p1, int p2)
{
var list = GetEntireDiagonalByPosition(p1);
return list.Contains(p2);
}
private static bool canDoDiagonalsFromStartPosition(int startPosition, int direction)
{
var isLeftSide = startPosition % 8 == 0;
var isRightSide = startPosition % 8 == 7;
if (isLeftSide && (direction == 7 || direction == -9)) { return false; }
if (isRightSide && (direction == -7 || direction == 9)) { return false; }
return true;
}
private static int getDiagonalIncrement(DiagonalDirectionFromFileNumber direction)
{
return direction == DiagonalDirectionFromFileNumber.Left ? 7 : 9;
}
private static List<int> getEntireDiagonalLine(DiagonalDirection direction, int position)
{
var list = new List<int> { position };
var increment = 0;
var currentPosition = position;
switch (direction)
{
case DiagonalDirection.UpLeft:
if (position % 8 == 0) { return list; }
if (position > 56) { return list; }
increment = 7;
while (currentPosition <= 63)
{
currentPosition = currentPosition + increment;
if (currentPosition <= 63)
{
list.Add(currentPosition);
}
if (currentPosition % 8 == 0) { break; }
}
break;
case DiagonalDirection.UpRight:
if (File.Contains(position)) { return list; }
if (position > 56) { return list; }
increment = 9;
while (currentPosition <= 63)
{
currentPosition = currentPosition + increment;
if (currentPosition <= 63)
{
list.Add(currentPosition);
}
if (File.Contains(currentPosition)) { break; }
}
break;
case DiagonalDirection.DownLeft:
if (position % 8 == 0) { return list; }
if (position < 7) { return list; }
increment = -9;
while (currentPosition >= 0)
{
currentPosition = currentPosition + increment;
if (currentPosition >= 0)
{
list.Add(currentPosition);
}
if (currentPosition % 8 == 0) { break; }
}
break;
case DiagonalDirection.DownRight:
if (File.Contains(position)) { return list; }
if (position < 7) { return list; }
increment = -7;
while (currentPosition >= 0)
{
currentPosition = currentPosition + increment;
if (currentPosition >= 0)
{
list.Add(currentPosition);
}
if (File.Contains(currentPosition)) { break; }
}
break;
case DiagonalDirection.Invalid:
default:
break;
}
return list;
}
private static int getIteratorByDirectionEnum(DiagonalDirection direction)
{
switch (direction)
{
case DiagonalDirection.UpLeft:
return 7;
case DiagonalDirection.UpRight:
return 9;
case DiagonalDirection.DownLeft:
return -9;
case DiagonalDirection.DownRight:
return -7;
}
throw new Exception($"getIteratorByDirectionEnum(): Invalid Direction { direction }");
}
private static DiagonalDirection getDirectionByMovePositions(int location, int destination)
{
var distance = destination - location;
var nine = Math.Abs(distance) % 9;
var seven = Math.Abs(distance) % 7;
if (nine == 0)
{
return distance > 0 ? DiagonalDirection.UpLeft : DiagonalDirection.DownRight;
}
if (seven == 0)
{
return distance > 0 ? DiagonalDirection.UpRight : DiagonalDirection.DownLeft;
}
return DiagonalDirection.Invalid;
}
private static int howFarToGo(int file, DiagonalDirectionFromFileNumber direction)
{
return direction == DiagonalDirectionFromFileNumber.Left ? file + 1 : 8 - file;
}
private static bool isValidDiagonalCoordinate(int position)
{
if (!GeneralEngine.IsValidCoordinate(position)) { return false; }
if (position % 8 == 0 || position % 8 == 7) { return false; }
if (position < 7 || position > 56) { return false; }
return true;
}
}
} |
using System;
using System.Collections.Generic;
using System.Text;
namespace Strategy
{
public class Player
{
private string _name;
private Strategy _strategy;
private int _winCount;
private int _loseCount;
private int _gameCount;
public Player(string name, Strategy strategy)
{
_name = name;
_strategy = strategy;
}
public Hand NextHand()
{
return _strategy.NextHand();
}
public void Win()
{
_strategy.Study(true);
_winCount++;
_gameCount++;
}
public void Lose()
{
_strategy.Study(false);
_loseCount++;
_gameCount++;
}
public void Even()
{
_gameCount++;
}
public override string ToString()
{
return $"[{_name}:{_gameCount} games, {_winCount} win, {_loseCount} lose]";
}
}
}
|
using System;
namespace ConsoleApp4
{
class Program
{
static void Main(string[] args)
{
int[][] myArray = new int[3][];
myArray[0] = new int[4];
}
}
}
|
using System;
using System.Threading;
using System.Collections.Generic;
using System.Collections.Concurrent;
using System.Diagnostics;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using System.Threading.Tasks;
namespace VoxelSpace {
public class PlanetTerrainGenerator : VoxelChunkProducer {
public Vector3 NoiseOffset = new Vector3(12.4f, -385.46f, 1356.231f);
public float NoiseFrequency = 0.05f;
public float SurfaceLevel = 64;
public float MaxHeight = 16;
public Vector3 CaveNoiseOffset = new Vector3(54.1f, -53.5f, -5043.2f);
public float CaveNoiseFrequency = 0.1f;
public float CaveNoiseThreshold = 0.4f;
public VoxelType Stone;
public VoxelType Dirt;
public VoxelType Grass;
VoxelData _stoneData;
VoxelData _dirtData;
VoxelData _grassData;
public PlanetTerrainGenerator() : base() {}
protected override void Process() {
var index = Volume.Index;
_stoneData = new VoxelData(index.Add(Stone));
_dirtData = new VoxelData(index.Add(Dirt));
_grassData = new VoxelData(index.Add(Grass));
float radius = SurfaceLevel + MaxHeight;
int chunkRadius = (int) MathF.Ceiling(radius / VoxelChunk.SIZE);
for (int i = -chunkRadius; i < chunkRadius; i ++) {
for (int j = -chunkRadius; j < chunkRadius; j ++) {
for (int k = -chunkRadius; k < chunkRadius; k ++) {
var chunk = Volume.AddChunk(new Coords(i, j, k));
}
}
}
Parallel.ForEach(Volume, GenerateChunk);
}
// protected override void StartGeneration() {
// _chunkWorkerGroup.StartTask(Volume);
// }
// protected override bool UpdateGeneration() {
// bool isDone = _chunkWorkerGroup.UpdateTask();
// if (isDone) {
// Logger.Info(this, _chunkWorkerGroup.GetCompletionMessage("Generated {0} chunks"));
// }
// return isDone;
// }
unsafe void GenerateChunk(VoxelChunk chunk) {
if (ChunkIsInterior(chunk)) {
for (int i = 0; i < VoxelChunk.SIZE; i ++) {
for (int j = 0; j < VoxelChunk.SIZE; j ++) {
for (int k = 0; k < VoxelChunk.SIZE; k ++) {
if (IsInCave(chunk.LocalToVolumeCoords(new Coords(i, j, k)))) {
*chunk.VoxelData[i, j, k] = VoxelData.Empty;
}
else {
*chunk.VoxelData[i, j, k] = _stoneData;
}
}
}
}
}
else {
for (int i = 0; i < VoxelChunk.SIZE; i ++) {
for (int j = 0; j < VoxelChunk.SIZE; j ++) {
for (int k = 0; k < VoxelChunk.SIZE; k ++) {
var vc = chunk.LocalToVolumeCoords(new Coords(i, j, k));
if (IsInCave(vc)) {
* chunk.VoxelData[i, j, k] = VoxelData.Empty;
}
else {
var vpos = vc + Vector3.One * 0.5f;
var vposMag = new Vector3(
MathF.Abs(vpos.X),
MathF.Abs(vpos.Y),
MathF.Abs(vpos.Z)
);
var max = MathF.Max(vposMag.X, MathF.Max(vposMag.Y, vposMag.Z));
vpos.Normalize();
var noise = Perlin.Noise(vpos * SurfaceLevel * NoiseFrequency);
noise = (noise + 1) / 2f;
float height = SurfaceLevel + noise * MaxHeight;
int stack = (int) MathF.Ceiling(height) - (int) MathF.Ceiling(max);
VoxelData data;
if (stack < 0) {
data = VoxelData.Empty;
}
else if (stack == 0) {
data = _grassData;
}
else if (stack < 3) {
data = _dirtData;
}
else {
data = _stoneData;
}
*chunk.VoxelData[i, j, k] = data;
}
}
}
}
}
Produce(chunk);
}
// return true of a set of global coords are inside the empty space of a cave
bool IsInCave(Coords c) {
var noise = Perlin.Noise((Vector3) c * CaveNoiseFrequency);
noise = (noise + 1 ) / 2;
return noise < CaveNoiseThreshold;
}
// return true if chunk is below the heightmapped surface, meaning it is completely
// solid and doesnt need to be generated
bool ChunkIsInterior(VoxelChunk chunk) {
var pos = (chunk.Coords * VoxelChunk.SIZE) + (Vector3.One * VoxelChunk.SIZE / 2f);
var max = MathF.Max(
MathF.Abs(pos.X),
MathF.Max(
MathF.Abs(pos.Y),
MathF.Abs(pos.Z)
)
);
return max + VoxelChunk.SIZE / 2f < SurfaceLevel;
}
}
} |
using System;
using System.Collections.Generic;
using System.Text;
namespace AppointmentManagement.Entities.Concrete.Procedure
{
public class uspGetVendorOrderLine
{
public Guid OrderLineID { get; set; }
public string OrderNumber { get; set; }
public string WarehouseDescription { get; set; }
public byte ItemTypeCode { get; set; }
public string ItemCode { get; set; }
public string ItemDescription { get; set; }
public string ColorCode{ get; set; }
public string ItemDim1Code { get; set; }
public double Qty1 { get; set; }
public double RemainingOrderQty1 { get; set; }
public DateTime DeliveryDate { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
namespace EasyDev.SQMS
{
[Serializable]
public class UserInfo : ICloneable
{
public string Password { get; set; }
public string RoleID { get; set; }
public string RoleName { get; set; }
public string Passport { get; set; }
public string EmployeeName { get; set; }
public DataTable Roles { get; set; }
public DataTable Permissions { get; set; }
public string PassportID { get; set; }
public string EmployeeID { get; set; }
public string OrganizationID { get; set; }
public string OrganizationName { get; set; }
public string DepartmentID { get; set; }
public string DepartmentName { get; set; }
#region ICloneable 成员
/// <summary>
/// 深度复制用户信息对象
/// </summary>
/// <returns></returns>
public object Clone()
{
UserInfo ui = new UserInfo();
ui.DepartmentID = this.DepartmentID;
ui.DepartmentName = this.DepartmentName;
ui.EmployeeID = this.EmployeeID;
ui.EmployeeName = this.EmployeeName;
ui.OrganizationID = this.OrganizationID;
ui.OrganizationName = this.OrganizationName;
ui.Passport = this.Passport;
ui.PassportID = this.PassportID;
ui.Password = this.Password;
ui.Permissions = this.Permissions.Copy();
ui.RoleID = this.RoleID;
ui.RoleName = this.RoleName;
ui.Roles = this.Roles.Copy();
return ui;
}
#endregion
}
} |
using CoreLib.Commons;
using CoreLib.Models;
using CoreLib.Utils;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DatabaseDAL.DataAccess
{
public class DatabaseSalary
{
public static CResult InsertSalary(Salary salary)
{
CSQL objSQL = new CSQL(CommonConstants.CONNECTION_STRING);
CResult objResult;
try
{
if (objSQL._OpenConnection() == false)
return objResult = new CResult { ErrorCode = -1, ErrorMessage = "Open Connection False!", Data = null };
// input param
SqlParameter prmEmpCode = new SqlParameter("@EmpCode", SqlDbType.NVarChar, 50);
prmEmpCode.Direction = ParameterDirection.Input;
objSQL.Command.Parameters.Add(prmEmpCode);
SqlParameter prmMoney = new SqlParameter("@Money", SqlDbType.BigInt);
prmMoney.Direction = ParameterDirection.Input;
objSQL.Command.Parameters.Add(prmMoney);
SqlParameter prmSalaryType = new SqlParameter("@SalaryType", SqlDbType.NVarChar, 50);
prmSalaryType.Direction = ParameterDirection.Input;
objSQL.Command.Parameters.Add(prmSalaryType);
// output param
SqlParameter Message = new SqlParameter("@Message", SqlDbType.NVarChar, 100);
Message.Direction = ParameterDirection.Output;
objSQL.Command.Parameters.Add(Message);
SqlParameter ErrCode = new SqlParameter("@ErrCode", SqlDbType.Int);
ErrCode.Direction = ParameterDirection.Output;
objSQL.Command.Parameters.Add(ErrCode);
// set value
prmEmpCode.Value = salary.EmpCode;
prmMoney.Value = salary.Money;
prmSalaryType.Value = salary.SalaryType;
objSQL.ExecuteSP(CommonConstants.SP_INSERT_SALARY);
var errCode = int.Parse(ErrCode.Value.ToString());
return objResult = new CResult { ErrorCode = errCode, ErrorMessage = Message.Value.ToString(), Data = null };
}
catch (Exception ex)
{
objResult = new CResult { ErrorCode = -1, ErrorMessage = ex.Message, Data = null };
}
return objResult;
}
public static CResult DeleteSalary(int id)
{
CSQL objSQL = new CSQL(CommonConstants.CONNECTION_STRING);
CResult objResult;
try
{
if (objSQL._OpenConnection() == false)
return objResult = new CResult { ErrorCode = -1, ErrorMessage = "Open Connection False!", Data = null };
// input param
SqlParameter prmID = new SqlParameter("@Id", SqlDbType.Int);
prmID.Direction = ParameterDirection.Input;
objSQL.Command.Parameters.Add(prmID);
// output param
SqlParameter Message = new SqlParameter("@Message", SqlDbType.NVarChar, 100);
Message.Direction = ParameterDirection.Output;
objSQL.Command.Parameters.Add(Message);
SqlParameter ErrCode = new SqlParameter("@ErrCode", SqlDbType.NVarChar, 100);
ErrCode.Direction = ParameterDirection.Output;
objSQL.Command.Parameters.Add(ErrCode);
// set value
prmID.Value = id;
objSQL.ExecuteSP(CommonConstants.SP_DELETE_SALARY);
var errCode = int.Parse(ErrCode.Value.ToString());
return objResult = new CResult { ErrorCode = errCode, ErrorMessage = Message.Value.ToString(), Data = null };
}
catch (Exception ex)
{
objResult = new CResult { ErrorCode = -1, ErrorMessage = ex.Message, Data = null };
}
return objResult;
}
public static List<Salary> SearchSalary(Salary salary)
{
CSQL objSQL = new CSQL(CommonConstants.CONNECTION_STRING);
try
{
if (objSQL._OpenConnection() == false)
throw new Exception("Không thể kết nối");
//input param
SqlParameter prmEmpCode = new SqlParameter("@EmpCode", SqlDbType.NVarChar, 50);
prmEmpCode.Direction = ParameterDirection.Input;
objSQL.Command.Parameters.Add(prmEmpCode);
SqlParameter prmSalaryType = new SqlParameter("@SalaryType", SqlDbType.NVarChar, 50);
prmSalaryType.Direction = ParameterDirection.Input;
objSQL.Command.Parameters.Add(prmSalaryType);
SqlParameter prmFullName = new SqlParameter("@FullName", SqlDbType.NVarChar, 200);
prmFullName.Direction = ParameterDirection.Input;
objSQL.Command.Parameters.Add(prmFullName);
// set value param
prmSalaryType.Value = salary.SalaryType;
prmFullName.Value = salary.FullName;
prmEmpCode.Value = salary.EmpCode;
SqlDataReader reader = objSQL.GetDataReaderFromSP(CommonConstants.SP_GET_SALARY);
var List = new List<Salary>();
while (reader.Read())
{
try
{
Salary salary2 = new Salary();
salary2.ID = Common.SafeGetInt(reader, "ID");
salary2.EmpCode = Common.SafeGetString(reader, "EmpCode");
salary2.SalaryType = Common.SafeGetString(reader, "SalaryType");
salary2.Money = (double)Common.SafeGetDecimal(reader, "Money");
salary2.FullName = Common.SafeGetString(reader, "FullName");
List.Add(salary2);
}
catch (Exception ex)
{
ex.ToString();
}
}
return List;
}
catch (Exception ex)
{
// Ghi thông tin ra file
}
finally
{
objSQL._CloseConnection();
}
return new List<Salary>();
}
}
}
|
using JiebaNet.Segmenter;
using Masuit.LuceneEFCore.SearchEngine;
using Masuit.LuceneEFCore.SearchEngine.Extensions;
using Masuit.LuceneEFCore.SearchEngine.Interfaces;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.OpenApi.Models;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using WebSearchDemo.Database;
namespace WebSearchDemo
{
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<DataContext>(db =>
{
db.UseInMemoryDatabase("test");
//db.UseSqlServer("Data Source=.;Initial Catalog=MyBlogs;Integrated Security=True");
});
services.AddSearchEngine<DataContext>(new LuceneIndexerOptions()
{
Path = "lucene"
});
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new OpenApiInfo
{
Version = "v1",
Title = $"接口文档",
Description = $"HTTP API ",
Contact = new OpenApiContact { Name = "懒得勤快", Email = "admin@masuit.com", Url = new Uri("https://masuit.coom") },
License = new OpenApiLicense { Name = "懒得勤快", Url = new Uri("https://masuit.com") }
});
c.IncludeXmlComments(AppContext.BaseDirectory + "WebSearchDemo.xml");
}); //配置swagger
services.AddControllers();
services.AddControllersWithViews().SetCompatibilityVersion(CompatibilityVersion.Latest);
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env, DataContext db, ISearchEngine<DataContext> searchEngine)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
new JiebaSegmenter().AddWord("会声会影"); //添加自定义词库
new JiebaSegmenter().AddWord("思杰马克丁"); //添加自定义词库
new JiebaSegmenter().AddWord("TeamViewer"); //添加自定义词库
db.Post.AddRange(JsonConvert.DeserializeObject<List<Post>>(File.ReadAllText(AppContext.BaseDirectory + "Posts.json")));
db.SaveChanges();
searchEngine.DeleteIndex();
searchEngine.CreateIndex(new List<string>()
{
nameof(Post)
});
app.UseSwagger().UseSwaggerUI(c =>
{
c.SwaggerEndpoint($"/swagger/v1/swagger.json", "懒得勤快的博客,搜索引擎测试");
}); //配置swagger
app.UseRouting().UseEndpoints(endpoints =>
{
endpoints.MapControllers(); // 属性路由
endpoints.MapControllerRoute("default", "{controller=Home}/{action=Index}/{id?}"); // 默认路由
});
}
}
}
|
using Sentry.Extensions.Logging;
namespace Sentry.AzureFunctions.Worker;
/// <summary>
/// Sentry Azure Functions integration options
/// </summary>
public class SentryAzureFunctionsOptions : SentryLoggingOptions
{
}
|
using System;
using System.Net;
using System.Reflection;
using System.Windows.Forms;
namespace CodeFiscaleGenerator.Infrastucture
{
internal sealed class ViewState
{
private readonly ComboBox _label;
private readonly ComboBox _registrationStatus;
private readonly ComboBox _subRegistrationStatus;
private readonly TextBox _codeFiscale;
private readonly CheckBox _clone;
private readonly Label _message;
public ViewState(ComboBox label, ComboBox registrationStatus, ComboBox subRegistrationStatus, TextBox codeFiscale, CheckBox clone, Label message)
{
_label = label;
_registrationStatus = registrationStatus;
_subRegistrationStatus = subRegistrationStatus;
_codeFiscale = codeFiscale;
_clone = clone;
_message = message;
label.Items.Add(new ComboBoxItem(1, "Gioco"));
label.Items.Add(new ComboBoxItem(4, "Italy"));
label.Items.Add(new ComboBoxItem(5, "Party"));
label.SelectedIndex = 0;
object[] possibleErros =
{
new ComboBoxItem(1024, "OK"),
new ComboBoxItem(1025, "KO"),
new ComboBoxItem(1402, "TO")
};
FillComboBox(registrationStatus, possibleErros);
FillComboBox(subRegistrationStatus, possibleErros);
}
public int SelectedSubregistrationId
{
get { return ((ComboBoxItem)_subRegistrationStatus.SelectedItem).Id; }
}
public int SelectedRegistrationId
{
get { return ((ComboBoxItem)_registrationStatus.SelectedItem).Id; }
}
public int SelectedLabelId
{
get { return ((ComboBoxItem)_label.SelectedItem).Id; }
}
public string CodeFiscale
{
get { return _codeFiscale.Text; }
}
public Version AssemblyVersion
{
get
{
return Assembly.GetEntryAssembly().GetName().Version;
}
}
public void SetCodeFiscale(string code)
{
_codeFiscale.Text = code;
}
public void SetRegistrationId(int id)
{
SetComboBoxById(_registrationStatus, id);
}
public void SetSubRegistrationId(int id)
{
SetComboBoxById(_subRegistrationStatus, id);
}
public void SetupTrustRelationshipForSSL()
{
ServicePointManager.ServerCertificateValidationCallback = delegate
{
return true;
};
}
public void SetCloneState(bool state)
{
_clone.Checked = state;
}
public void AddMessage(string message)
{
_message.Text = message;
}
public void ClearMessage()
{
_message.Text = string.Empty;
}
private void FillComboBox(ComboBox cbox, object[] values)
{
cbox.Items.AddRange(values);
cbox.SelectedIndex = 0;
}
private void SetComboBoxById(ComboBox cbox, int id)
{
foreach (var item in cbox.Items)
{
if (((ComboBoxItem)item).Id.Equals(id))
{
cbox.SelectedItem = item;
}
}
}
}
}
|
namespace StarBastard.Core.Gameplay
{
public class ResourceDelta
{
public int Food { get; set; }
public int Ore { get; set; }
public int Tech { get; set; }
public void AddOre(int amount)
{
Food += amount;
}
public void AddFood(int amount)
{
Ore += amount;
}
public void AddTech(int amount)
{
Tech += amount;
}
}
}
|
using System.Linq;
using System.Threading.Tasks;
using System.Collections.Generic;
using PluralKit.Core;
namespace PluralKit.Bot
{
public class Member
{
private readonly IDatabase _db;
private readonly ModelRepository _repo;
private readonly EmbedService _embeds;
public Member(EmbedService embeds, IDatabase db, ModelRepository repo)
{
_embeds = embeds;
_db = db;
_repo = repo;
}
public async Task NewMember(Context ctx) {
if (ctx.System == null) throw Errors.NoSystemError;
var memberName = ctx.RemainderOrNull() ?? throw new PKSyntaxError("You must pass a member name.");
// Hard name length cap
if (memberName.Length > Limits.MaxMemberNameLength) throw Errors.MemberNameTooLongError(memberName.Length);
// Warn if there's already a member by this name
var existingMember = await _db.Execute(c => _repo.GetMemberByName(c, ctx.System.Id, memberName));
if (existingMember != null) {
var msg = $"{Emojis.Warn} You already have a member in your system with the name \"{existingMember.NameFor(ctx)}\" (with ID `{existingMember.Hid}`). Do you want to create another member with the same name?";
if (!await ctx.PromptYesNo(msg)) throw new PKError("Member creation cancelled.");
}
await using var conn = await _db.Obtain();
// Enforce per-system member limit
var memberCount = await _repo.GetSystemMemberCount(conn, ctx.System.Id);
var memberLimit = ctx.System.MemberLimitOverride ?? Limits.MaxMemberCount;
if (memberCount >= memberLimit)
throw Errors.MemberLimitReachedError(memberLimit);
// Create the member
var member = await _repo.CreateMember(conn, ctx.System.Id, memberName);
memberCount++;
// Send confirmation and space hint
await ctx.Reply($"{Emojis.Success} Member \"{memberName}\" (`{member.Hid}`) registered! Check out the getting started page for how to get a member up and running: https://pluralkit.me/start#members");
if (memberName.Contains(" "))
await ctx.Reply($"{Emojis.Note} Note that this member's name contains spaces. You will need to surround it with \"double quotes\" when using commands referring to it, or just use the member's 5-character ID (which is `{member.Hid}`).");
if (memberCount >= Limits.MaxMemberCount)
await ctx.Reply($"{Emojis.Warn} You have reached the per-system member limit ({Limits.MaxMemberCount}). You will be unable to create additional members until existing members are deleted.");
else if (memberCount >= Limits.MaxMembersWarnThreshold)
await ctx.Reply($"{Emojis.Warn} You are approaching the per-system member limit ({memberCount} / {Limits.MaxMemberCount} members). Please review your member list for unused or duplicate members.");
}
public async Task MemberRandom(Context ctx)
{
ctx.CheckSystem();
var randGen = new global::System.Random();
//Maybe move this somewhere else in the file structure since it doesn't need to get created at every command
// TODO: don't buffer these, find something else to do ig
var members = await _db.Execute(c =>
{
if (ctx.MatchFlag("all", "a"))
return _repo.GetSystemMembers(c, ctx.System.Id);
return _repo.GetSystemMembers(c, ctx.System.Id)
.Where(m => m.MemberVisibility == PrivacyLevel.Public);
}).ToListAsync();
if (members == null || !members.Any())
throw Errors.NoMembersError;
var randInt = randGen.Next(members.Count);
await ctx.Reply(embed: await _embeds.CreateMemberEmbed(ctx.System, members[randInt], ctx.Guild, ctx.LookupContextFor(ctx.System)));
}
public async Task ViewMember(Context ctx, PKMember target)
{
var system = await _db.Execute(c => _repo.GetSystem(c, target.System));
await ctx.Reply(embed: await _embeds.CreateMemberEmbed(system, target, ctx.Guild, ctx.LookupContextFor(system)));
}
}
} |
using Core.EntityFramework;
using System;
using System.Data.Entity;
using System.Linq;
using System.Linq.Expressions;
namespace Core.Data
{
public class GenericRepository<T> : IDisposable, IGenericRepository<T> where T : class
{
private readonly EntityFramework.PadraoContext _context;
public PadraoContext getContext
{
get { return EntityFramework.ContextManager.Current; }
}
public GenericRepository()
{
this._context = getContext;
}
public void Insert(T entity)
{
_context.Entry(entity).State = System.Data.Entity.EntityState.Added;
}
public void Delete(T entity)
{
_context.Entry(entity).State = System.Data.Entity.EntityState.Deleted;
}
public void Update(T entity)
{
_context.Entry(entity).State = System.Data.Entity.EntityState.Modified;
}
public IQueryable<T> SearchFor(System.Linq.Expressions.Expression<Func<T, bool>> predicate = null)
{
return (predicate == null ? _context.Set<T>() : _context.Set<T>().Where(predicate));
}
public IQueryable<T> OrderByField(IQueryable<T> q, string SortField, bool Ascending)
{
var param = Expression.Parameter(typeof(T), "p");
var prop = Expression.Property(param, SortField);
var exp = Expression.Lambda(prop, param);
string method = Ascending ? "OrderBy" : "OrderByDescending";
Type[] types = new Type[] { q.ElementType, exp.Body.Type };
var mce = Expression.Call(typeof(Queryable), method, types, q.Expression, exp);
return q.Provider.CreateQuery<T>(mce);
}
public IQueryable<T> SearchFor(string coluna, bool orderbydesc = false, System.Linq.Expressions.Expression<Func<T, bool>> predicate = null)
{
IQueryable<T> lista;
IQueryable<T> listaDados = (predicate == null ? _context.Set<T>() : _context.Set<T>().Where(predicate));
lista = listaDados.AsQueryable();
return String.IsNullOrEmpty(coluna) ? lista : OrderByField(lista, coluna, orderbydesc);
}
public IQueryable<T> SearchFor(string coluna, bool orderbydesc = false, int start = 1, int size = 25, System.Linq.Expressions.Expression<Func<T, bool>> predicate = null)
{
IQueryable<T> lista;
IQueryable<T> listaDados = (predicate == null ? _context.Set<T>() : _context.Set<T>().Where(predicate));
lista = listaDados.AsQueryable();
return String.IsNullOrEmpty(coluna) ? lista.Skip(((start - 1) * size)).Take(size) : OrderByField(lista, coluna, orderbydesc).Skip(((start - 1) * size)).Take(size);
}
public IQueryable<T> SearchFor(string coluna, bool orderbydesc = false, int start = 1, int size = 25, System.Linq.Expressions.Expression<Func<T, bool>> predicate = null, out int totalRows)
{
IQueryable<T> lista;
IQueryable<T> listaDados = (predicate == null ? _context.Set<T>() : _context.Set<T>().Where(predicate));
lista = listaDados.AsQueryable();
totalRows = lista.Count();
return String.IsNullOrEmpty(coluna) ? lista.Skip(((start - 1) * size)).Take(size) : OrderByField(lista, coluna, orderbydesc).Skip(((start - 1) * size)).Take(size);
}
public int CommandSQL(String SQL, params object[] parameters)
{
return _context.Database.ExecuteSqlCommand(SQL, parameters);
}
public IQueryable<T> AllIncluding(params System.Linq.Expressions.Expression<Func<T, object>>[] includeProperties)
{
IQueryable<T> query = _context.Set<T>();
foreach (var includeProperty in includeProperties)
{
query = query.Include(includeProperty);
}
return query;
}
public T DetalhePredicate(System.Linq.Expressions.Expression<Func<T, bool>> predicate)
{
return _context.Set<T>().FirstOrDefault(predicate);
}
public T Detalhe(Int32 id)
{
return _context.Set<T>().Find(id);
}
public T Detalhe(Guid id)
{
return _context.Set<T>().Find(id);
}
public void Dispose()
{
_context.Dispose();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ParallelSerializer
{
public abstract class TaskBase<T> : ISerializationTask
{
public byte[] SerializationResult { get; protected set; }
public TaskTreeNode TaskTreeNode { get; set; }
protected IScheduler Scheduler { get; }
protected T Object { get; }
protected SerializationContext SerializationContext { get; }
public TaskBase(T obj, SerializationContext context, IScheduler scheduler)
{
Object = obj;
SerializationContext = context;
Scheduler = scheduler;
SerializationContext.StartTask(this);
}
public abstract void SerializeObject(object state);
protected virtual void AddSubTask(ISerializationTask task)
{
var child = new TaskTreeNode { Task = task, Parent = TaskTreeNode };
task.TaskTreeNode = child;
var last = TaskTreeNode.Children.LastOrDefault();
if (last != null)
{
last.NextSibling = child;
}
TaskTreeNode.Children.Add(child);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
namespace Database_V3.Updaters
{
class ProductUpdater
{
public static void Run()
{
XmlDocument doc = new XmlDocument();
doc.Load(Program.BaseURL + "products");
string xmlcontents = doc.InnerXml;
XmlElement xelRoot = doc.DocumentElement;
XmlNodeList xnlNodes = xelRoot.SelectNodes("/Products/Product");
foreach (XmlNode xndNode in xnlNodes)
{
Entities db = new Entities();
Products p = new Products();
p.EAN = xndNode["EAN"].InnerText;
p.Title = xndNode["Title"].InnerText;
p.Brand = xndNode["Brand"].InnerText;
p.Shortdescription = xndNode["Shortdescription"].InnerText;
p.FullDescription = xndNode["Fulldescription"].InnerText;
p.Image = xndNode["Image"].InnerText;
p.Weight = xndNode["Weight"].InnerText;
p.Price = decimal.Parse(xndNode["Price"].InnerText);
p.Category = xndNode["Category"].InnerText;
p.Subcategory = xndNode["Subcategory"].InnerText;
p.SubSubcategory = xndNode["Subsubcategory"].InnerText;
p.Image = xndNode["Image"].InnerText;
var original = db.Products.Find(p.EAN);
if (original != null)
{
db.Entry(original).CurrentValues.SetValues(p);
db.SaveChanges();
}
else
{
db.Products.Add(p);
db.SaveChanges();
}
}
Console.WriteLine("Finished Product Table Routine");
}
}
}
|
using Dapper;
using Discount.Grpc.Core.Entities;
using Discount.Grpc.Core.Interfaces;
using Npgsql;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Discount.Grpc.Infrastructure.Repositories
{
public class DiscountRepository : IDiscountRepository
{
private readonly INpgConnectionString _connectionString;
public DiscountRepository(INpgConnectionString connectionString)
{
_connectionString = connectionString;
}
public NpgsqlConnection CreateNpgConnectionScope()
{
return new NpgsqlConnection(_connectionString.ConnectionString);
}
public async Task<IList<Coupon>> GetAllDiscounts()
{
await using var connection = CreateNpgConnectionScope();
var coupons = await connection.QueryAsync<Coupon>
("SELECT * FROM Coupon");
return coupons.ToList();
}
public async Task<Coupon> GetDiscount(string productId)
{
await using var connection = CreateNpgConnectionScope();
var coupon = await connection.QueryFirstOrDefaultAsync<Coupon>
("SELECT * FROM Coupon WHERE ProductId = @ProductId", new { ProductId = productId });
return coupon ?? new Coupon { ProductId = productId, Description = "No discount available", Amount = 0 };
}
public async Task<bool> CreateDiscount(Coupon coupon)
{
await using var connection = CreateNpgConnectionScope();
bool success = await connection.ExecuteAsync
("INSERT INTO Coupon (ProductId, Description, Amount) VALUES (@ProductId, @Description, @Amount)",
new { coupon.ProductId, coupon.Description, coupon.Amount }) > 0;
return success;
}
public async Task<bool> UpdateDiscount(Coupon coupon)
{
await using var connection = CreateNpgConnectionScope();
bool success = await connection.ExecuteAsync
("UPDATE Coupon SET ProductId = @ProductId, Description = @Description, Amount = @Amount WHERE Id = @Id",
new { coupon.ProductId, coupon.Description, coupon.Amount, coupon.Id }) > 0;
return success;
}
public async Task<bool> DeleteDiscount(string productId)
{
await using var connection = CreateNpgConnectionScope();
bool success = await connection.ExecuteAsync
("DELETE FROM Coupon WHERE ProductId = @ProductId",
new { ProductId = productId }) > 0;
return success;
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CiclosForWhile
{
class Program
{
static void Main(string[] args)
{
//while
//for
//parte 1 valor de la iteracion
//parte 2 condicion
//parte 3 aumento o decremento
int tabla;
// int i = 1; // parte 1
Console.WriteLine("Ingrese el numero de la tabla que quiere calcular");
tabla = int.Parse(Console.ReadLine());
//parte 2
// while(i <= 10)
// {
// Console.WriteLine("" + tabla * i);
// i++; //parte 3
for (int i = 1; i <= 10; i++)
{
Console.WriteLine("" + tabla * i);
}
Console.ReadKey();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Runtime.Serialization;
using Aquamonix.Mobile.Lib.Extensions;
namespace Aquamonix.Mobile.Lib.Domain
{
[DataContract]
public class DeviceStatus : ICloneable<DeviceStatus>, IMergeable<DeviceStatus>
{
[DataMember(Name = PropertyNames.Value)]
public string Value { get; set; }
[DataMember(Name = PropertyNames.Severity)]
public string Severity { get; set; }
[DataMember(Name = PropertyNames.UpdatedDateUtc)]
public string UpdatedDateUtc { get; set; }
public DeviceStatus Clone()
{
return new DeviceStatus() { Severity = this.Severity, UpdatedDateUtc = this.UpdatedDateUtc, Value = this.Value };
}
public void MergeFromParent(DeviceStatus parent, bool removeIfMissingFromParent, bool parentIsMetadata)
{
if (parent != null)
{
this.Value = MergeExtensions.MergeProperty(this.Value, parent.Value, removeIfMissingFromParent, parentIsMetadata);
this.Severity = MergeExtensions.MergeProperty(this.Severity, parent.Severity, removeIfMissingFromParent, parentIsMetadata);
this.UpdatedDateUtc = MergeExtensions.MergeProperty(this.UpdatedDateUtc, parent.UpdatedDateUtc, removeIfMissingFromParent, parentIsMetadata);
}
}
}
} |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
namespace Robot.Frontend
{
public class Program
{
public static void Main(string[] args)
{
CreateHostBuilder(args).Build().Run();
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureAppConfiguration((context, config) => {
if (!Uri.TryCreate(Assembly.GetExecutingAssembly().CodeBase, UriKind.RelativeOrAbsolute, out var uri)) {
throw new Exception("Cannot determine file system path of executing assembly");
}
var path = Path.GetDirectoryName(uri.LocalPath);
if (string.IsNullOrEmpty(path)) {
throw new Exception("Cannot determine file system path of executing assembly");
}
config.AddJsonFile(Path.Combine(path, "hosting.json"), optional:true, reloadOnChange:true);
})
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
});
}
}
|
using System.Configuration;
namespace mp3Service
{
public static class Config
{
public static string FlacPath
{
get { return ConfigurationManager.AppSettings[@"FlacPath"]; }
}
public static string BasePath
{
get { return ConfigurationManager.AppSettings[@"BasePath"]; }
}
public static string NetworkPath
{
get { return ConfigurationManager.AppSettings[@"NetworkPath"]; }
}
public static string LocalPath
{
get { return ConfigurationManager.AppSettings[@"LocalPath"]; }
}
public static string PollInterval
{
get { return ConfigurationManager.AppSettings["PollInterval"]; }
}
public static string IncludeShare
{
get { return ConfigurationManager.AppSettings["IncludeShare"]; }
}
public static string DesktopPath
{
get { return ConfigurationManager.AppSettings["DesktopPath"]; }
}
}
}
|
namespace MessageOutbox.Outbox
{
public interface IMessage
{
string Id { get; }
}
public class Message : IMessage
{
public Message(string id)
{
Id = id;
}
public string Id { get; }
}
} |
namespace Tutorial.LinqToEntities
{
#if EF
using System.Data.Common;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.Data.SqlClient;
using System.Linq;
using System.Transactions;
using IDbContextTransaction = System.Data.Entity.DbContextTransaction;
using IsolationLevel = System.Data.IsolationLevel;
#else
using System.Data.Common;
using System.Data.SqlClient;
using System.Linq;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Storage;
using IsolationLevel = System.Data.IsolationLevel;
#endif
internal static partial class Transactions
{
internal static void ExecutionStrategy2(AdventureWorks adventureWorks)
{
adventureWorks.Database.CreateExecutionStrategy().Execute(() =>
{
// Single retry operation, which can have custom transactions.
});
}
}
internal static partial class Transactions
{
internal static void Default(AdventureWorks adventureWorks)
{
ProductCategory category = adventureWorks.ProductCategories.First();
category.Name = "Update"; // Valid value.g
ProductSubcategory subcategory = adventureWorks.ProductSubcategories.First();
subcategory.ProductCategoryID = -1; // Invalid value.
try
{
adventureWorks.SaveChanges();
}
catch (DbUpdateException exception)
{
exception.WriteLine();
// System.Data.Entity.Infrastructure.DbUpdateException: An error occurred while updating the entries. See the inner exception for details.
// ---> System.Data.Entity.Core.UpdateException: An error occurred while updating the entries. See the inner exception for details.
// ---> System.Data.SqlClient.SqlException: The UPDATE statement conflicted with the FOREIGN KEY constraint "FK_ProductSubcategory_ProductCategory_ProductCategoryID". The conflict occurred in database "D:\ONEDRIVE\WORKS\DRAFTS\CODESNIPPETS\DATA\ADVENTUREWORKS_DATA.MDF", table "Production.ProductCategory", column 'ProductCategoryID'. The statement has been terminated.
adventureWorks.Entry(category).Reload();
category.Name.WriteLine(); // Accessories
adventureWorks.Entry(subcategory).Reload();
subcategory.ProductCategoryID.WriteLine(); // 1
}
}
}
public static partial class DbContextExtensions
{
public static readonly string CurrentIsolationLevelSql = $@"
SELECT
CASE transaction_isolation_level
WHEN 0 THEN N'{IsolationLevel.Unspecified}'
WHEN 1 THEN N'{IsolationLevel.ReadUncommitted}'
WHEN 2 THEN N'{IsolationLevel.ReadCommitted}'
WHEN 3 THEN N'{IsolationLevel.RepeatableRead}'
WHEN 4 THEN N'{IsolationLevel.Serializable}'
WHEN 5 THEN N'{IsolationLevel.Snapshot}'
END
FROM sys.dm_exec_sessions
WHERE session_id = @@SPID";
#if EF
public static string CurrentIsolationLevel(this DbContext context) =>
context.Database.SqlQuery<string>(CurrentIsolationLevelSql).Single();
#else
public static string CurrentIsolationLevel(this DbContext context)
{
using (DbCommand command = context.Database.GetDbConnection().CreateCommand())
{
command.CommandText = CurrentIsolationLevelSql;
command.Transaction = context.Database.CurrentTransaction.GetDbTransaction();
return (string)command.ExecuteScalar();
}
}
#endif
}
internal static partial class Transactions
{
internal static void DbContextTransaction(AdventureWorks adventureWorks)
{
adventureWorks.Database.CreateExecutionStrategy().Execute(() =>
{
using (IDbContextTransaction transaction = adventureWorks.Database.BeginTransaction(
IsolationLevel.ReadUncommitted))
{
try
{
adventureWorks.CurrentIsolationLevel().WriteLine(); // ReadUncommitted
ProductCategory category = new ProductCategory() { Name = nameof(ProductCategory) };
adventureWorks.ProductCategories.Add(category);
adventureWorks.SaveChanges().WriteLine(); // 1
adventureWorks.Database.ExecuteSqlCommand(
sql: "DELETE FROM [Production].[ProductCategory] WHERE [Name] = {0}",
parameters: nameof(ProductCategory)).WriteLine(); // 1
transaction.Commit();
}
catch
{
transaction.Rollback();
throw;
}
}
});
}
}
internal static partial class Transactions
{
internal static void DbTransaction()
{
using (DbConnection connection = new SqlConnection(ConnectionStrings.AdventureWorks))
{
connection.Open();
using (DbTransaction transaction = connection.BeginTransaction(IsolationLevel.RepeatableRead))
{
try
{
using (AdventureWorks adventureWorks = new AdventureWorks(connection))
{
adventureWorks.Database.CreateExecutionStrategy().Execute(() =>
{
adventureWorks.Database.UseTransaction(transaction);
adventureWorks.CurrentIsolationLevel().WriteLine(); // RepeatableRead
ProductCategory category = new ProductCategory() { Name = nameof(ProductCategory) };
adventureWorks.ProductCategories.Add(category);
adventureWorks.SaveChanges().WriteLine(); // 1.
});
}
using (DbCommand command = connection.CreateCommand())
{
command.CommandText = "DELETE FROM [Production].[ProductCategory] WHERE [Name] = @p0";
DbParameter parameter = command.CreateParameter();
parameter.ParameterName = "@p0";
parameter.Value = nameof(ProductCategory);
command.Parameters.Add(parameter);
command.Transaction = transaction;
command.ExecuteNonQuery().WriteLine(); // 1
}
transaction.Commit();
}
catch
{
transaction.Rollback();
throw;
}
}
}
}
#if EF
// https://github.com/dotnet/corefx/issues/22484
// SqlClient transaction support was added recently in 6de0d94
// It will be included in the 2.1.0 release.
internal static void TransactionScope()
{
new ExecutionStrategy().Execute(() =>
{
using (TransactionScope scope = new TransactionScope(
scopeOption: TransactionScopeOption.Required,
transactionOptions: new TransactionOptions()
{
IsolationLevel = System.Transactions.IsolationLevel.Serializable
}))
{
using (DbConnection connection = new SqlConnection(ConnectionStrings.AdventureWorks))
using (DbCommand command = connection.CreateCommand())
{
command.CommandText = DbContextExtensions.CurrentIsolationLevelSql;
connection.Open();
using (DbDataReader reader = command.ExecuteReader())
{
reader.Read();
reader[0].WriteLine(); // RepeatableRead
}
}
using (AdventureWorks adventureWorks = new AdventureWorks())
{
ProductCategory category = new ProductCategory() { Name = nameof(ProductCategory) };
adventureWorks.ProductCategories.Add(category);
adventureWorks.SaveChanges().WriteLine(); // 1
}
using (AdventureWorks adventureWorks = new AdventureWorks())
{
adventureWorks.CurrentIsolationLevel().WriteLine(); // Serializable
}
using (DbConnection connection = new SqlConnection(ConnectionStrings.AdventureWorks))
using (DbCommand command = connection.CreateCommand())
{
command.CommandText = "DELETE FROM [Production].[ProductCategory] WHERE [Name] = @p0";
DbParameter parameter = command.CreateParameter();
parameter.ParameterName = "@p0";
parameter.Value = nameof(ProductCategory);
command.Parameters.Add(parameter);
connection.Open();
command.ExecuteNonQuery().WriteLine(); // 1
}
scope.Complete();
}
});
}
#endif
}
} |
using gView.Framework.Data;
using gView.Framework.Geometry;
using gView.Framework.Network;
using gView.Framework.Network.Algorthm;
using gView.Framework.Network.Tracers;
using gView.Framework.system;
using gView.Framework.UI;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace gView.Network.Framework.Network.Tracers
{
public abstract class TraceConnectedTargetNode : INetworkTracer, IProgressReporterEvent
{
protected abstract NetworkNodeType TargetNodeType { get; }
#region INetworkTracer Members
virtual public string Name
{
get { return "Trace Connected Nodes"; }
}
public bool CanTrace(NetworkTracerInputCollection input)
{
if (input == null)
{
return false;
}
return input.Collect(NetworkTracerInputType.SourceNode).Count == 1 ||
input.Collect(NetworkTracerInputType.SoruceEdge).Count == 1;
}
async public Task<NetworkTracerOutputCollection> Trace(INetworkFeatureClass network, NetworkTracerInputCollection input, gView.Framework.system.ICancelTracker cancelTraker)
{
if (network == null || !CanTrace(input))
{
return null;
}
GraphTable gt = new GraphTable(network.GraphTableAdapter());
NetworkSourceInput sourceNode = null;
NetworkSourceEdgeInput sourceEdge = null;
if (input.Collect(NetworkTracerInputType.SourceNode).Count == 1)
{
sourceNode = input.Collect(NetworkTracerInputType.SourceNode)[0] as NetworkSourceInput;
}
else if (input.Collect(NetworkTracerInputType.SoruceEdge).Count == 1)
{
sourceEdge = input.Collect(NetworkTracerInputType.SoruceEdge)[0] as NetworkSourceEdgeInput;
}
else
{
return null;
}
Dijkstra dijkstra = new Dijkstra(cancelTraker);
dijkstra.reportProgress += this.ReportProgress;
dijkstra.ApplySwitchState = input.Contains(NetworkTracerInputType.IgnoreSwitches) == false &&
network.HasDisabledSwitches;
Dijkstra.ApplyInputIds(dijkstra, input);
if (sourceNode != null)
{
dijkstra.Calculate(gt, sourceNode.NodeId);
}
else if (sourceEdge != null)
{
IGraphEdge graphEdge = gt.QueryEdge(sourceEdge.EdgeId);
if (graphEdge == null)
{
return null;
}
bool n1_2_n2 = gt.QueryN1ToN2(graphEdge.N1, graphEdge.N2) != null;
bool n2_2_n1 = gt.QueryN1ToN2(graphEdge.N2, graphEdge.N1) != null;
bool n1switchState = dijkstra.ApplySwitchState ? gt.SwitchState(graphEdge.N1) : true;
bool n2switchState = dijkstra.ApplySwitchState ? gt.SwitchState(graphEdge.N2) : true;
if (n1_2_n2 && n1switchState == true)
{
dijkstra.Calculate(gt, graphEdge.N1);
}
else if (n2_2_n1 && n2switchState == true)
{
dijkstra.Calculate(gt, graphEdge.N2);
}
else
{
return null;
}
}
Dijkstra.Nodes dijkstraNodes = dijkstra.DijkstraNodesWithMaxDistance(double.MaxValue);
if (dijkstraNodes == null)
{
return null;
}
ProgressReport report = (ReportProgress != null ? new ProgressReport() : null);
#region Collect EdgedIds
if (report != null)
{
report.Message = "Collected Edges...";
report.featurePos = 0;
report.featureMax = dijkstraNodes.Count;
ReportProgress(report);
}
NetworkInputForbiddenEdgeIds forbiddenEdgeIds = (input.Contains(NetworkTracerInputType.ForbiddenEdgeIds)) ? input.Collect(NetworkTracerInputType.ForbiddenEdgeIds)[0] as NetworkInputForbiddenEdgeIds : null;
NetworkInputForbiddenStartNodeEdgeIds forbiddenStartNodeEdgeIds = (input.Contains(NetworkTracerInputType.ForbiddenStartNodeEdgeIds)) ? input.Collect(NetworkTracerInputType.ForbiddenStartNodeEdgeIds)[0] as NetworkInputForbiddenStartNodeEdgeIds : null;
int counter = 0;
List<int> edgeIds = new List<int>();
List<int> nodeIds = new List<int>();
foreach (Dijkstra.Node dijkstraNode in dijkstraNodes)
{
if (gt.GetNodeType(dijkstraNode.Id) == TargetNodeType)
{
nodeIds.Add(dijkstraNode.Id);
}
if (dijkstra.ApplySwitchState)
{
if (gt.SwitchState(dijkstraNode.Id) == false) // hier ist Schluss!!
{
continue;
}
}
GraphTableRows gtRows = gt.QueryN1(dijkstraNode.Id);
if (gtRows == null)
{
continue;
}
foreach (IGraphTableRow gtRow in gtRows)
{
int eid = gtRow.EID;
if (sourceNode != null &&
forbiddenStartNodeEdgeIds != null && dijkstraNode.Id == sourceNode.NodeId &&
forbiddenStartNodeEdgeIds.Ids.Contains(eid))
{
continue;
}
if (forbiddenEdgeIds != null && forbiddenEdgeIds.Ids.Contains(eid))
{
continue;
}
int index = edgeIds.BinarySearch(eid);
if (index < 0)
{
edgeIds.Insert(~index, eid);
}
}
counter++;
if (report != null && counter % 1000 == 0)
{
report.featurePos = counter;
ReportProgress(report);
}
}
#endregion
NetworkTracerOutputCollection output = new NetworkTracerOutputCollection();
if (report != null)
{
report.Message = "Add Edges...";
report.featurePos = 0;
report.featureMax = edgeIds.Count;
ReportProgress(report);
}
#region Collection Nodes
counter = 0;
foreach (int nodeId in nodeIds)
{
int fcId = gt.GetNodeFcid(nodeId);
IFeature nodeFeature = await network.GetNodeFeature(nodeId);
if (nodeFeature != null && nodeFeature.Shape is IPoint)
{
//outputCollection.Add(new NetworkNodeFlagOuput(endNode.Id, nodeFeature.Shape as IPoint));
output.Add(new NetworkFlagOutput(nodeFeature.Shape as IPoint,
new NetworkFlagOutput.NodeFeatureData(nodeId, fcId, Convert.ToInt32(nodeFeature["OID"]), TargetNodeType.ToString())));
}
counter++;
if (report != null && counter % 1000 == 0)
{
report.featurePos = counter;
ReportProgress(report);
}
}
#endregion
#region Collection Edges
counter = 0;
NetworkPathOutput pathOutput = new NetworkPathOutput();
foreach (int edgeId in edgeIds)
{
pathOutput.Add(new NetworkEdgeOutput(edgeId));
counter++;
if (report != null && counter % 1000 == 0)
{
report.featurePos = counter;
ReportProgress(report);
}
}
output.Add(pathOutput);
if (input.Collect(NetworkTracerInputType.AppendNodeFlags).Count > 0)
{
await Helper.AppendNodeFlags(network, gt, Helper.NodeIds(dijkstraNodes), output);
}
#endregion
return output;
}
#endregion
#region IProgressReporterEvent Member
public event ProgressReporterEvent ReportProgress;
#endregion
}
[RegisterPlugInAttribute("EBBF514D-DF17-4D57-82C8-6FA73C1D31CB")]
public class TraceConnectedSources : TraceConnectedTargetNode
{
protected override NetworkNodeType TargetNodeType
{
get { return NetworkNodeType.Source; }
}
public override string Name
{
get
{
return "Trace Connected Sources";
}
}
}
[RegisterPlugInAttribute("3B0338A7-EB79-44FB-91DD-1B85054366AB")]
public class TraceConnectedSinks : TraceConnectedTargetNode
{
protected override NetworkNodeType TargetNodeType
{
get { return NetworkNodeType.Sink; }
}
public override string Name
{
get
{
return "Trace Connected Sinks";
}
}
}
[RegisterPlugInAttribute("39F2A6FD-C6F8-4036-9E92-DE611E609F47")]
public class TraceConnectedTrafficCross : TraceConnectedTargetNode
{
protected override NetworkNodeType TargetNodeType
{
get { return NetworkNodeType.Traffic_Cross; }
}
public override string Name
{
get
{
return "Trace Connected Traffic Cross";
}
}
}
[RegisterPlugInAttribute("26F1C494-7B2A-4D96-9D7C-10E58EF9646F")]
public class TraceConnectedTrafficLight : TraceConnectedTargetNode
{
protected override NetworkNodeType TargetNodeType
{
get { return NetworkNodeType.Traffic_Light; }
}
public override string Name
{
get
{
return "Trace Connected Traffic Light";
}
}
}
[RegisterPlugInAttribute("299D0F08-00BF-474B-BF79-22A6CD93F79D")]
public class TraceConnectedTrafficRoundabout : TraceConnectedTargetNode
{
protected override NetworkNodeType TargetNodeType
{
get { return NetworkNodeType.Traffic_Roundabout; }
}
public override string Name
{
get
{
return "Trace Connected Traffic Roundabout";
}
}
}
[RegisterPlugInAttribute("31EA1275-CCE3-48B0-B78F-3A0E784312CE")]
public class TraceConnectedTrafficStop : TraceConnectedTargetNode
{
protected override NetworkNodeType TargetNodeType
{
get { return NetworkNodeType.Traffic_Stop; }
}
public override string Name
{
get
{
return "Trace Connected Traffic Stop";
}
}
}
[RegisterPlugInAttribute("90F7F489-20FE-490B-B294-D1E763E8B129")]
public class TraceConnectedGasStation : TraceConnectedTargetNode
{
protected override NetworkNodeType TargetNodeType
{
get { return NetworkNodeType.Gas_Station; }
}
public override string Name
{
get
{
return "Trace Connected Gas Station";
}
}
}
[RegisterPlugInAttribute("B50F603B-ABEC-4788-A91D-9072FD6D8571")]
public class TraceConnectedGasSwitch : TraceConnectedTargetNode
{
protected override NetworkNodeType TargetNodeType
{
get { return NetworkNodeType.Gas_Switch; }
}
public override string Name
{
get
{
return "Trace Connected Gas Switch";
}
}
}
[RegisterPlugInAttribute("74D6FA1B-FBB1-4359-BAC5-86E9BD53AB06")]
public class TraceConnectedGasCustomer : TraceConnectedTargetNode
{
protected override NetworkNodeType TargetNodeType
{
get { return NetworkNodeType.Gas_Customer; }
}
public override string Name
{
get
{
return "Trace Connected Gas Customer";
}
}
}
[RegisterPlugInAttribute("8F844FC2-D810-44A9-97D1-E41B4D60117F")]
public class TraceConnectedGasStop : TraceConnectedTargetNode
{
protected override NetworkNodeType TargetNodeType
{
get { return NetworkNodeType.Gas_Stop; }
}
public override string Name
{
get
{
return "Trace Connected Gas Stop";
}
}
}
[RegisterPlugInAttribute("9BCEB61C-CC2C-4347-A48D-78BD1A96FCC2")]
public class TraceConnectedElectricityCustomer : TraceConnectedTargetNode
{
protected override NetworkNodeType TargetNodeType
{
get { return NetworkNodeType.Electricity_Customer; }
}
public override string Name
{
get
{
return "Trace Connected Electricity Customer";
}
}
}
[RegisterPlugInAttribute("2D1D5100-1756-44E9-B51B-A0690B68DB47")]
public class TraceConnectedElectricityJunctionBox : TraceConnectedTargetNode
{
protected override NetworkNodeType TargetNodeType
{
get { return NetworkNodeType.Electricity_JunctionBox; }
}
public override string Name
{
get
{
return "Trace Connected Electricity JunctionBox";
}
}
}
[RegisterPlugInAttribute("6E5745B1-4E51-4C94-AD51-E1504A3A359D")]
public class TraceConnectedElectrictiyStation : TraceConnectedTargetNode
{
protected override NetworkNodeType TargetNodeType
{
get { return NetworkNodeType.Electrictiy_Station; }
}
public override string Name
{
get
{
return "Trace Connected Electrictiy Station";
}
}
}
}
|
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
/// <summary>
/// message manager.
/// </summary>
public static class CMessageManager {
#region Types
public delegate void MessageDelegate(CMessages.eMessages m,object data);
#endregion
#region Public Fields
public static MessageDelegate MessageEvent;
#endregion
#region Private Fields
private static List<IMessageObsever> _observers;// list of observers.used by NotifyObservers().
private static CMessages.eMessages _message; // message itself. All messages need to add to the enumerator first.
private static object _data; // message's data.Cant be null when no data needed.
#endregion
#region Conusructors
static CMessageManager(){
_observers = new List<IMessageObsever>();
}
#endregion
#region Public Methods
/// <summary>
/// Registers the observer.
/// </summary>
/// <param name='o'>
/// o object will recive messages.
/// </param>
public static void RegisterObserver(IMessageObsever o){
if (_observers.Contains(o) == false)
_observers.Add(o);
}
public static void RegisterObserver(MessageDelegate o){
MessageEvent += o;
}
/// <summary>
/// Removes the observer.
/// </summary>
/// <param name='o'>
/// object that do not want to receive messages.
/// </param>
public static bool RemoveObserver(IMessageObsever o){
if (_observers.Count > 0)
return _observers.Remove(o);
return true;
}
public static void RemoveObserver(MessageDelegate o){
MessageEvent -= o;
}
/// <summary>
/// Sends the message to all observers.
/// </summary>
/// <param name='m'>
/// Message
/// </param>
/// <param name='data'>
/// Data that message carry.
/// In case message has no data set it to null.
/// </param>
public static void SendMessage(CMessages.eMessages m,object data)
{
_message = m;
_data = data;
NotifyObsevers();
}
#endregion
#region Private Methods
/// <summary>
/// Notifies the obsevers.
/// This function called when message was sent.
/// </summary>
private static void NotifyObsevers(){
MessageEvent(_message, _data);
for(int i = 0; i < _observers.Count ; i++)
{
_observers[i].OnMessage(_message,_data);
}
}
#endregion
}
|
using System;
[Serializable]
public class GException0 : ApplicationException
{
public GException0()
{
}
public GException0(string string_0) : base(string_0)
{
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace labirinto
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
KeyDown += new KeyEventHandler(Form1_KeyDown);
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void Label36_Click(object sender, EventArgs e)
{
}
private void Label48_Click(object sender, EventArgs e)
{
}
int perdeu = 0;
private void loose_Tick(object sender, EventArgs e)
{
/*if (pictureBox1.Bounds.IntersectsWith(label1.Bounds) || pictureBox1.Bounds.IntersectsWith(label2.Bounds) || pictureBox1.Bounds.IntersectsWith(label3.Bounds) || pictureBox1.Bounds.IntersectsWith(label4.Bounds) || pictureBox1.Bounds.IntersectsWith(label5.Bounds) || pictureBox1.Bounds.IntersectsWith(label6.Bounds) || pictureBox1.Bounds.IntersectsWith(label7.Bounds) || pictureBox1.Bounds.IntersectsWith(label8.Bounds) || pictureBox1.Bounds.IntersectsWith(label9.Bounds) || pictureBox1.Bounds.IntersectsWith(label10.Bounds))
if (pictureBox1.Bounds.IntersectsWith(label11.Bounds) || pictureBox1.Bounds.IntersectsWith(label12.Bounds) || pictureBox1.Bounds.IntersectsWith(label13.Bounds) || pictureBox1.Bounds.IntersectsWith(label14.Bounds) || pictureBox1.Bounds.IntersectsWith(label15.Bounds) || pictureBox1.Bounds.IntersectsWith(label16.Bounds) || pictureBox1.Bounds.IntersectsWith(label17.Bounds) || pictureBox1.Bounds.IntersectsWith(label18.Bounds) || pictureBox1.Bounds.IntersectsWith(label19.Bounds) || pictureBox1.Bounds.IntersectsWith(label20.Bounds))
if (pictureBox1.Bounds.IntersectsWith(label21.Bounds) || pictureBox1.Bounds.IntersectsWith(label22.Bounds) || pictureBox1.Bounds.IntersectsWith(label23.Bounds) || pictureBox1.Bounds.IntersectsWith(label24.Bounds) || pictureBox1.Bounds.IntersectsWith(label25.Bounds) || pictureBox1.Bounds.IntersectsWith(label26.Bounds) || pictureBox1.Bounds.IntersectsWith(label27.Bounds) || pictureBox1.Bounds.IntersectsWith(label28.Bounds) || pictureBox1.Bounds.IntersectsWith(label29.Bounds) || pictureBox1.Bounds.IntersectsWith(label30.Bounds))
{
perdeu = true;
}*/
if (pictureBox1.Bounds.IntersectsWith(pictureBox5.Bounds))
{
perdeu += 1;
}
}
private void Form1_KeyDown(object sender, KeyEventArgs e)
{
if (perdeu == 0)
{
if (e.KeyCode == Keys.Right) pictureBox1.Left += 8;
else if (e.KeyCode == Keys.Left) pictureBox1.Left -= 8;
else if (e.KeyCode == Keys.Up) pictureBox1.Top -= 8;
else if (e.KeyCode == Keys.Down) pictureBox1.Top += 8;
}
}
private void Timer1_Tick(object sender, EventArgs e)
{
}
}
}
|
using UnityEngine;
using System.Collections;
public class GroundClick : MonoBehaviour {
public GameObject objectPrefab;
void OnMouseDown() {
Ray ray = Camera.main.ScreenPointToRay (Input.mousePosition);
RaycastHit hit;
if (Physics.Raycast (ray, out hit, Mathf.Infinity)) {
SpawnSth(hit.point);
}
}
void SpawnSth(Vector3 point) {
GameObject go = (GameObject)Instantiate(objectPrefab);
go.transform.position = point + new Vector3(0,0.01f, 0);
var filter = go.GetComponent<MeshFilter> ();
Mesh mesh = new Mesh ();
// setting the pivot manualy.
float width = 1;
float length = 5;
Vector3[] vertices = {
new Vector3(0,0,-width / 2),
new Vector3(length,0,-width / 2),
new Vector3(length,0,width/2),
new Vector3(0,0,width/2)
};
Vector2[] uv = {
new Vector2(0,0),
new Vector2(length,0),
new Vector2(length,1),
new Vector2(0,1)
};
Vector3[] normals = {
Vector3.up,
Vector3.up,
Vector3.up,
Vector3.up
};
int[] triangles = {
2,1,0,
0,3,2
};
mesh.vertices = vertices;
mesh.triangles = triangles;
mesh.uv = uv;
mesh.normals = normals;
filter.mesh = mesh;
// set up tiling.
// niestety poniewaz tutaj wykorzystujemy juz wlasna kopie materialu - mamy dodatkowo jeden draw call
// per object!!
// prosty sposob zeby to przejsc to ATLASy czyli wybierasz poprostu czesc z tekstury i wtey
// jedna tekstura jest wysylana - czyli 1 material, 2 teksutry.
// Vector2 texScale = new Vector2 (length, 1);
// var renderer = go.GetComponent<MeshRenderer> ().material.mainTextureScale = texScale;
}
}
|
using System.Diagnostics.CodeAnalysis;
namespace System.ComponentModel.DataAnnotations.Schema
{
/// <summary>
/// Denotes that a property or class should be excluded from database mapping.
/// </summary>
[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Class, AllowMultiple = false)]
[SuppressMessage("Microsoft.Performance", "CA1813:AvoidUnsealedAttributes", Justification = "We want users to be able to extend this class")]
public class NotMappedAttribute : Attribute
{
}
} |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace PopHealthUploader
{
public class Logger
{
public const string Extension = ".log";
public string Identifier { get; set; }
public string LogPath { get; set; }
protected string LogFilePath { get; set; }
public Logger(string identifier, string path)
{
Identifier = identifier;
LogPath = path;
InitializeFilePath();
}
public void InitializeFilePath()
{
LogFilePath = Path.Combine(LogPath, Identifier + Extension);
}
public void Write(string text, bool timestamp = true)
{
var builder = new StringBuilder();
if (timestamp)
{
builder.AppendFormat("{0} - ", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
}
builder.AppendFormat("{0}\r\n", text);
File.AppendAllText(LogFilePath, builder.ToString());
}
public void WriteException(Exception exception)
{
var builder = new StringBuilder();
builder.AppendFormat("Caught the following exception:\r\n{0}\r\n{1}\r\n", exception.Message, exception.StackTrace);
Write(builder.ToString());
}
}
}
|
// <copyright file="SecondTask.cs" company="MyCompany.com">
// Contains the solutions to tasks of the 'Methods in detail' module.
// </copyright>
// <author>Daryn Akhmetov</author>
namespace Methods_in_detail
{
using System;
using System.Diagnostics;
using System.Linq;
/// <summary>
/// Contains implementation of the given by the task algorithm.
/// </summary>
public static class SecondTask
{
/// <summary>
/// Calculates the greatest common divisor of the given numbers using Euclidean algorithm.
/// </summary>
/// <param name="executionTime">Execution time of the method.</param>
/// <param name="numbers">Numbers for which we calculate the greatest common divisor.</param>
/// <returns>Greatest common divisor of the given numbers.</returns>
public static int CalculateGCDUsingEuclidAlgorithm(out double executionTime, params int[] numbers)
{
// Start measuring the execution time.
var watch = Stopwatch.StartNew();
if (numbers.Length == 1)
{
throw new ArgumentException("GCD calculation has been called for one number.");
}
var greatestCommonDivisor = numbers[0];
// Since GCD(x, y, z) = GCD(GCD(x, y), z), we can calculate GCD for any amount of numbers.
for (var i = 1; i < numbers.Length; i++)
{
greatestCommonDivisor = CalculateGCDOfTwoNumbersUsingEuclidAlgorithm(greatestCommonDivisor, numbers[i]);
}
// Get the elapsed time.
watch.Stop();
executionTime = watch.Elapsed.TotalMilliseconds;
return greatestCommonDivisor;
}
/// <summary>
/// Calculates the greatest common divisor of two numbers using Euclidean algorithm.
/// </summary>
/// <param name="number1">First number.</param>
/// <param name="number2">Second number.</param>
/// <returns>Greatest common divisor of two given numbers.</returns>
public static int CalculateGCDOfTwoNumbersUsingEuclidAlgorithm(int number1, int number2)
{
// GCD(0, x) == x; GCD(x, 0) == x, GCD(0,0) == 0
if (number1 == 0 || number2 == 0)
{
return number1 == 0 ? number2 : number1;
}
// Define the largest and smallest of the two numbers.
var largestNumber = number1 > number2 ? number1 : number2;
var smallestNumber = number1 > number2 ? number2 : number1;
var greatestCommonDivisor = smallestNumber;
// According to Euclid's algorithm, to find the GCD of two integers, you need to
// divide the largest number by smallest number and then sequentially divide the
// divisor by the remainder until the remainder is zero.
while (largestNumber % smallestNumber != 0)
{
largestNumber -= smallestNumber;
if (smallestNumber > largestNumber)
{
greatestCommonDivisor = largestNumber;
largestNumber = smallestNumber;
smallestNumber = greatestCommonDivisor;
}
}
return greatestCommonDivisor;
}
/// <summary>
/// Calculates the greatest common divisor of the given numbers using Stein's algorithm.
/// </summary>
/// <param name="executionTime">Execution time of the method.</param>
/// <param name="numbers">Numbers for which we calculate the greatest common divisor.</param>
/// <returns>Greatest common divisor of the given numbers.</returns>
public static int CalculateGCDUsingSteinAlgorithm(out double executionTime, params int[] numbers)
{
// Start measuring the execution time.
var watch = Stopwatch.StartNew();
if (numbers.Length == 1)
{
throw new ArgumentException("GCD calculation has been called for one number.");
}
var greatestCommonDivisor = numbers[0];
// Since GCD(x, y, z) = GCD(GCD(x, y), z), we can calculate GCD for any amount of numbers.
for (var i = 1; i < numbers.Length; i++)
{
greatestCommonDivisor = CalculateGCDOfTwoNumbersUsingSteinAlgorithm(greatestCommonDivisor, numbers[i]);
}
// Get the elapsed time.
watch.Stop();
executionTime = watch.Elapsed.TotalMilliseconds;
return greatestCommonDivisor;
}
/// <summary>
/// Calculates the greatest common divisor of two numbers using Stein's algorithm.
/// </summary>
/// <param name="number1">First number.</param>
/// <param name="number2">Second number.</param>
/// <returns>Greatest common divisor of two given numbers.</returns>
public static int CalculateGCDOfTwoNumbersUsingSteinAlgorithm(int number1, int number2)
{
// GCD(0, x) == x; GCD(x, 0) == x, GCD(0,0) == 0.
if (number1 == 0 || number2 == 0)
{
return number1 == 0 ? number2 : number1;
}
// Remember number of divisions.
var numberOfDivisions1 = 0;
var numberOfDivisions2 = 0;
// GCD(2x, 2y) = 2*GCD(x, y) so we can divide each number by 2 until one of the number becomes odd.
while (number1 % 2 == 0)
{
numberOfDivisions1++;
number1 = number1 / 2;
}
while (number2 % 2 == 0)
{
numberOfDivisions2++;
number2 = number2 / 2;
}
// Get the minimum number of divisions.
var numberOfDivisions = numberOfDivisions1 < numberOfDivisions2 ? numberOfDivisions1 : numberOfDivisions2;
// According to Euclid's algorithm, to find the GCD of two integers, you need to
// divide the largest number by smallest number and then sequentially divide the
// divisor by the remainder until the remainder is zero.
while (number1 != 0)
{
// Denote number1 as the largest number so we need to swap numbers if necessary.
if (number2 > number1)
{
var temp = number2;
number2 = number1;
number1 = temp;
}
// GCD(x, y) = GCD(| x − y |, min(x, y)), if x and y are both odd.
number1 = number1 - number2;
// Remove factors of 2 in number1.
while (number1 % 2 == 0 && number1 != 0)
{
number1 = number1 / 2;
}
}
// GCD(2x, 2y) = 2*GCD(x, y) so we should restore factors of 2, if necessary.
var greatestCommonDivisor = numberOfDivisions == 0 ? number2 : 2 * numberOfDivisions * number2;
return greatestCommonDivisor;
}
}
} |
using DFC.ServiceTaxonomy.GraphSync.Models;
using OrchardCore.ContentManagement;
using YesSql.Indexes;
namespace DFC.ServiceTaxonomy.GraphSync.Indexes
{
public class GraphSyncPartIndex : MapIndex
{
public string? ContentItemId { get; set; }
public string? NodeId { get; set; }
}
public class GraphSyncPartIndexProvider : IndexProvider<ContentItem>
{
public override void Describe(DescribeContext<ContentItem> context)
{
context.For<GraphSyncPartIndex>()
.Map(contentItem =>
{
var text = contentItem.As<GraphSyncPart>()?.Text;
if (!string.IsNullOrEmpty(text) && (contentItem.Published || contentItem.Latest))
{
return new GraphSyncPartIndex {ContentItemId = contentItem.ContentItemId, NodeId = text};
}
#pragma warning disable CS8603 // Possible null reference return.
return null;
#pragma warning restore CS8603 // Possible null reference return.
});
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
public class Program
{
public static void Main()
{
string[] cars = Console.ReadLine().Split();
Queue<string> carsForService = new Queue<string>(cars);
Stack<string> servedCars = new Stack<string>();
string[] input = Console.ReadLine().Split('-');
while (input[0] != "End")
{
if (input[0] == "Service")
{
if (carsForService.Count > 0)
{
string currentServedCar = carsForService.Dequeue();
Console.WriteLine($"Vehicle {currentServedCar} got served.");
servedCars.Push(currentServedCar);
}
}
else if (input[0] == "CarInfo")
{
string checkCar = input[1];
if (servedCars.Contains(checkCar))
{
Console.WriteLine("Served.");
}
else
{
Console.WriteLine("Still waiting for service.");
}
}
else if (input[0] == "History")
{
if (servedCars.Count > 0)
{
Console.WriteLine($"{string.Join(", ", servedCars.ToList())}");
}
}
input = Console.ReadLine().Split('-');
}
if (carsForService.Count > 0)
{
Console.WriteLine($"Vehicles for service: {string.Join(", ", carsForService.ToList())}");
}
if (servedCars.Count > 0)
{
Console.WriteLine($"Served vehicles: {string.Join(", ", servedCars.ToList())}");
}
}
} |
using System;
namespace Cake.Markdown_Pdf
{
public interface IMarkdownPdfRunner
{
IMarkdownPdfRunner Run(Action<MarkdownPdfRunnerSettings> configure = null);
IMarkdownPdfRunner Run(MarkdownPdfRunnerSettings settings);
}
} |
using System;
using System.Collections.Generic;
using System.Text;
namespace CodingInterview
{
internal class LeftRotation
{
private int[] arrExample;
public LeftRotation(int[] arrExample)
{
this.arrExample = arrExample;
}
internal void Rotate(int times)
{
int nextIndex = times;
while(nextIndex < arrExample.Length)
{
for (int i = nextIndex; i > nextIndex - times; i--)
{
var element = arrExample[i];
arrExample[i] = arrExample[i - 1];
arrExample[i - 1] = element;
}
nextIndex++;
}
}
internal string RotateTrick(int times)
{
List<string> results = new List<string>();
for (int i = times; i < arrExample.Length; i++)
{
results.Add(arrExample[i].ToString());
}
for (int i = 0; i < times; i++)
{
results.Add(arrExample[i].ToString());
}
return String.Join(" ", results);
}
internal void RotateDotNet(int times)
{
int[] rotated = new int[arrExample.Length];
System.Array.Copy(arrExample, times, rotated, 0, arrExample.Length - times);
System.Array.Copy(arrExample, 0, rotated, arrExample.Length - times, times);
arrExample = rotated;
}
internal int[] Array()
{
return arrExample;
}
internal string Print()
{
return String.Join(" ", arrExample);
}
}
} |
/* Copyright 2020-2020 Sannel Software, L.L.C.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.*/
using System;
using System.Collections.Generic;
using System.Text;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Threading.Tasks;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Sannel.House.Base.MQTT.Interfaces;
using Sannel.House.Base.Sensor;
using Sannel.House.SensorLogging.Interfaces;
namespace Sannel.House.SensorLogging.Listener
{
public class SensorDataSubscriber : IMqttTopicSubscriber
{
private readonly ILogger logger;
private readonly IServiceProvider provider;
public SensorDataSubscriber(IServiceProvider provider, ILogger<SensorDataSubscriber> logger, IConfiguration configuration)
{
this.provider = provider ?? throw new ArgumentNullException(nameof(provider));
this.logger = logger ?? throw new ArgumentNullException(nameof(logger));
Topic = (configuration ?? throw new ArgumentNullException(nameof(configuration)))["MQTT:SensorLoggingTopic"];
}
public string Topic
{
get;
private set;
}
public async void Message(string topic, string message)
=> await MessageAsync(topic, message);
internal async Task MessageAsync(string topic, string message)
{
using var scope = provider.CreateScope();
var service = scope.ServiceProvider.GetService<ISensorService>();
if(service is null)
{
logger.LogWarning("Unable to resolve service {service}", nameof(ISensorService));
return;
}
if(string.IsNullOrWhiteSpace(message))
{
logger.LogError("Received invalid message on topic {0}", topic);
return;
}
var options = new JsonSerializerOptions()
{
PropertyNameCaseInsensitive = true
};
options.Converters.Add(new JsonStringEnumConverter());
try
{
var reading = JsonSerializer.Deserialize<FieldReading>(message, options);
if (logger.IsEnabled(LogLevel.Debug))
{
logger.LogDebug($"topic={topic} message={message}");
}
if (reading is null)
{
logger.LogError($"Received invalid message on topic {topic}");
return;
}
if (reading.MacAddress.HasValue)
{
await service.AddSensorEntryAsync(reading.SensorType, reading.Values, reading.MacAddress.Value);
}
else if (reading.Uuid.HasValue)
{
await service.AddSensorEntryAsync(reading.SensorType, reading.Values, reading.Uuid.Value);
}
else if (!string.IsNullOrWhiteSpace(reading.Manufacture) && !string.IsNullOrWhiteSpace(reading.ManufactureId))
{
await service.AddSensorEntryAsync(reading.SensorType,
reading.Values, reading.Manufacture, reading.ManufactureId);
}
else
{
logger.LogError($"Invalid reading on topic {topic} message={message}");
}
}
catch(JsonException exception)
{
logger.LogError(exception, "JsonException from Message. Topic={0}", topic);
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Paiza_log
{
class Program
{
static void Main(string[] args)
{
//ミニコンピュータ
//var a = 0;
//var b = 0;
//var line = System.Console.ReadLine();
//var x = int.Parse(line);
//var lists = new int[x];
//var orders = new string[x];
//for (var i = 0; i < lists.Length; i++)
//{
// orders[i] = System.Console.ReadLine();
//}
//foreach (var order in orders)
//{
// var od = order.Split(' ');
// if (od[0] == "SET")
// {
// if (od[1] == "1")
// {
// a = int.Parse(od[2]);
// }
// else
// {
// b = int.Parse(od[2]);
// }
// }
// else if (od[0] == "ADD")
// {
// b = a + int.Parse(od[1]);
// }
// else
// {
// b = a - int.Parse(od[1]);
// }
//}
//System.Console.WriteLine($"{a} {b}");
//完全数とほぼ完全数
//var line = System.Console.ReadLine();
//var lists = new string[int.Parse(line)];
//var nums = new int[int.Parse(line)];
//for (var i = 0; i < lists.Length; i++)
//{
// var num = System.Console.ReadLine();
// nums[i] = int.Parse(num);
//}
//foreach (var num in nums)
//{
// var count = 0;
// for (var i = 1; i < num; i++)
// {
// if (num % i == 0)
// {
// count += i;
// }
// else
// {
// continue;
// }
// }
// if (count == num)
// {
// System.Console.WriteLine("perfect");
// }
// else if (num - count == 1)
// {
// System.Console.WriteLine("nearly");
// }
// else
// {
// System.Console.WriteLine("neither");
// }
//}
//温度差計算
//var line = System.Console.ReadLine();
//string[] nums = line.Split(' ');
//var x = int.Parse(nums[0]);
//var y = int.Parse(nums[1]);
//System.Console.WriteLine(x - y);
//Leet文字列
// var line = System.Console.ReadLine();
//var a = line.Replace("A", "4");
//var b = a.Replace("E", "3");
//var c = b.Replace("G", "6");
//var d = c.Replace("I", "1");
//var e = d.Replace("O", "0");
//var f = e.Replace("S", "5");
//var g = f.Replace("Z", "2");
//System.Console.WriteLine(g);
//三角形の内角の和
//var line = System.Console.ReadLine();
//var num = System.Console.ReadLine();
//System.Console.WriteLine(180 - int.Parse(line) - int.Parse(num));
//数字の桁数
//var line = System.Console.ReadLine();
//System.Console.WriteLine(line.ToString().Length);
//サイコロの裏面
//var line = System.Console.ReadLine();
//var num = 7 - int.Parse(line);
//System.Console.WriteLine(num);
//忘年会の予算
// var line = System.Console.ReadLine();
//string[] nums = line.Split(' ');
//var x = int.Parse(nums[0]);
//var y = int.Parse(nums[1]);
//System.Console.WriteLine(x * 6000 + y * 4000);
//縦書きと横書き
//var line = System.Console.ReadLine();
//string[] lists = new string[int.Parse(line)];
//for (var i = 0; i < lists.Length; i++)
//{
// var list = System.Console.ReadLine();
// lists[i] = list;
//}
//// 配列内の各要素を" "で区切って連結
//string data = string.Join(" ", lists);
//// 変数の中身を表示
//System.Console.WriteLine(data);
//イルミネーションの数
//var line = Console.ReadLine();
//string[] nums = line.Split(' ');
//var x = double.Parse(nums[0]);
//var y = double.Parse(nums[1]);
//var z = double.Parse(nums[2]);
//var result = Math.Ceiling(x / y) * z;
//Console.WriteLine(result);
//契約の交渉
//var line = Console.ReadLine();
//var y = line.Replace("n", "");
//Console.WriteLine(y.Length);
//家族で分ける
// var line = System.Console.ReadLine();
//var nums = System.Console.ReadLine();
//var lists = nums.Split(' ');
//var h = int.Parse(lists[0]);
//var w = int.Parse(lists[1]);
//var result = h * w % int.Parse(line);
//System.Console.WriteLine(result);
//ワインのキャッチコピー
//var line = System.Console.ReadLine();
//var str = "Best in";
//System.Console.WriteLine($"{str} {line}");
//自動でチャージ
//var line = System.Console.ReadLine();
//var num = int.Parse(line);
//if (num >= 10000)
//{
// System.Console.WriteLine(num);
//}
//else
//{
// System.Console.WriteLine(num + 10000);
//}
//西暦の計算
//var line = System.Console.ReadLine();
//var nums = line.Split(' ');
//var num1 = int.Parse(nums[0]);
//var num2 = int.Parse(nums[1]);
//System.Console.WriteLine(num2 - num1);
//カード並べ
//var line = Console.ReadLine();
//var numbers = line.Split(' ');
//int[] intArray = numbers.Select(int.Parse).ToArray();
//Array.Sort(intArray);
//var num1 = intArray[3] * 10;
//var num2 = intArray[2] * 10;
//var result = num1 + num2 + intArray[0] + intArray[1];
//Console.WriteLine(result);
//テストの採点
//var line = Console.ReadLine();
//var lines = line.Split(' ');
//int[] lists = lines.Select(int.Parse).ToArray();
//var members = new List<int>();
//for (var i = 0; i < lists[0]; i++)
//{
// var eles = Console.ReadLine();
// var ele = eles.Split(' ');
// var nums = ele.Select(int.Parse).ToArray();
// if (lists[1] != 0)
// {
// if ((nums[0] - nums[1] * 5 - lists[1]) < 0)
// {
// continue;
// }
// else
// {
// members.Add(i + 1);
// }
// }
// else
// {
// members.Add(i + 1);
// }
//}
//foreach (var mem in members)
//{
// Console.WriteLine(mem);
//}
//ログのフィルター
//var line = Console.ReadLine();
//var imp = Console.ReadLine();
//var str = new List<string>();
//for (var i = 0; i < int.Parse(line); i++)
//{
// var target = Console.ReadLine();
// var num = target.IndexOf(imp);
// if (num >= 0)
// {
// str.Add(target);
// }
// else
// {
// continue;
// }
//}
//if (str.Count == 0)
//{
// Console.WriteLine("None");
//}
//else
//{
// foreach (var s in str)
// {
// Console.WriteLine(s);
// }
//}
//数字の調査
//var line = Console.ReadLine();
//var nums = line.Split(' ').Select(int.Parse).ToArray();
//var num = nums[1];
//var orders = new List<int>();
//var lists = new List<int>();
//for (var i = 0; i < nums[0]; i++)
//{
// orders.Add(int.Parse(Console.ReadLine()));
//}
//while (true)
//{
// if (num == 0 || num == 1)
// {
// lists.Add(num);
// break;
// }
// lists.Add(num % 2);
// num = num / 2;
//}
//foreach (var ord in orders)
//{
// Console.WriteLine(lists[ord - 1]);
//}
// public class Hello
//{
// public static void Main()
// {
// // 自分の得意な言語で
// // Let's チャレンジ!!
// var line = System.Console.ReadLine();
// var result = 100 + 10 * int.Parse(line);
// System.Console.WriteLine(result);
// }
//}
//先生の宿題
//var line = System.Console.ReadLine();
//// System.Console.WriteLine(line);
//var src = line.Split(' ');
//var lists = new List<string>();
//lists.AddRange(src);
//var x = "x";
//var plus = "+";
//var num = lists.IndexOf(x);
//var judge = lists.IndexOf(plus);
//if (num == 4)
//{
// if (judge >= 0)
// {
// var result = int.Parse(lists[0]) + int.Parse(lists[2]);
// Console.WriteLine(result);
// }
// else
// {
// var result = int.Parse(lists[0]) - int.Parse(lists[2]);
// Console.WriteLine(result);
// }
//}
//else if (num == 2)
//{
// if (judge >= 0)
// {
// var result = int.Parse(lists[4]) - int.Parse(lists[0]);
// Console.WriteLine(result);
// }
// else
// {
// var result = int.Parse(lists[0]) - int.Parse(lists[4]);
// Console.WriteLine(result);
// }
//}
//else
//{
// if (judge >= 0)
// {
// var result = int.Parse(lists[4]) - int.Parse(lists[2]);
// Console.WriteLine(result);
// }
// else
// {
// var result = int.Parse(lists[4]) + int.Parse(lists[2]);
// Console.WriteLine(result);
// }
//}
//エレベーター
//var num = int.Parse(Console.ReadLine());
//var lists = new List<int>();
//var result = 0;
//for (var i = 0; i < num; i++)
//{
// if (i == 0)
// {
// var n = int.Parse(Console.ReadLine());
// result = n - 1;
// lists.Add(n);
// }
// else
// {
// var n = int.Parse(Console.ReadLine());
// lists.Add(n);
// if (lists[i - 1] >= lists[i])
// {
// result += lists[i - 1] - lists[i];
// }
// else
// {
// result += lists[i] - lists[i - 1];
// }
// }
//}
//Console.WriteLine(result);
//C035: 試験の合格判定
// var line = int.Parse(Console.ReadLine());
// var result = 0;
// for (var i = 0; i < line; i++)
// {
// var n = Console.ReadLine();
// var lists = n.Split(' ');
// if (lists[0] == "s")
// {
// var list = new List<string>();
// list.AddRange(lists);
// list.Remove("s");
// string[] new_src;
// new_src = list.ToArray();
// int[] intArray = new_src.Select(int.Parse).ToArray();
// int intSum = intArray.Sum();
// int s_Sum = intArray[1] + intArray[2];
// if (intSum >= 350 && s_Sum >= 160)
// {
// result++;
// }
// }
// else
// {
// var list = new List<string>();
// list.AddRange(lists);
// list.Remove("l");
// string[] new_src;
// new_src = list.ToArray();
// int[] intArray = new_src.Select(int.Parse).ToArray();
// int intSum = intArray.Sum();
// int s_Sum = intArray[3] + intArray[4];
// if (intSum >= 350 && s_Sum >= 160)
// {
// result++;
// }
// }
// }
// Console.WriteLine(result);
//var line = System.Console.ReadLine();
//var lines = line.Split(' ');
//var num = lines.Select(int.Parse).ToArray();
//var nums = new List<int>();
//nums.AddRange(num);
//var n = num[0];
//var r = n - (n / 10) * 10;
//Console.WriteLine(nums[0] + num[1] - 10 - 100);
//var line = int.Parse(System.Console.ReadLine());
//var num = int.Parse(System.Console.ReadLine());
//System.Console.WriteLine(line / num);
//var line = int.Parse(System.Console.ReadLine());
//System.Console.WriteLine(line * 60);
}
}
}
|
using System.Runtime.CompilerServices;
[assembly:InternalsVisibleTo("Unity.InternalAPIEngineBridge.020")]
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DMOBase
{
public interface IImporter
{
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace electronicstore
{
public partial class stock : Form
{
public stock()
{
InitializeComponent();
FormBorderStyle = FormBorderStyle.None;
}
private void stock_Load(object sender, EventArgs e)
{
// TODO: This line of code loads data into the 'electronicstockDataSet.tbl_stock' table. You can move, or remove it, as needed.
this.tbl_stockTableAdapter1.Fill(this.electronicstockDataSet.tbl_stock);
// TODO: This line of code loads data into the 'furnitureshopDataSet.tbl_stock' table. You can move, or remove it, as needed.
// TODO: This line of code loads data into the 'electronicproductDataSet.VIEW_PRODUCTS' table. You can move, or remove it, as needed.
this.vIEW_PRODUCTSTableAdapter.Fill(this.electronicproductDataSet.VIEW_PRODUCTS);
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
this.tbl_stockTableAdapter1.FillByID(this.electronicstockDataSet.tbl_stock,Convert.ToInt32(comboBox1.SelectedValue));
}
private void label2_Click(object sender, EventArgs e)
{
this.Close();
}
}
}
|
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace UnitTestProject
{
public class Performance
{
public static void PerformanceTest(Action action,int seconds=1)
{
Stopwatch sw = new Stopwatch();
sw.Start();
Task.Run(() => action.Invoke()).Wait();
sw.Stop();
Assert.IsTrue(sw.Elapsed < new TimeSpan(0, 0, seconds));
}
}
}
|
using SkiaSharp;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
namespace Schmidt_Homework1
{
public interface IPhotoSaver
{
//Interface for photo saver functionality
Task<Boolean> SaveAsync(SKData photoData, string saveFile);
}
}
|
using System.Reflection;
using System.Runtime.InteropServices;
[assembly: AssemblyTitle("Pathoschild.SlackArchiveSearch")]
[assembly: AssemblyDescription("A Windows console application which parses and searches an exported Slack archive.")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Pathoschild.SlackArchiveSearch")]
[assembly: AssemblyCopyright("")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: ComVisible(false)]
[assembly: Guid("7b01d673-c251-49cd-89c3-b677d1e09b58")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
|
using JT808.Protocol.Formatters;
using JT808.Protocol.MessagePack;
namespace JT808.Protocol.MessageBody
{
public class JT808_0x0200_0x2A : JT808_0x0200_BodyBase, IJT808MessagePackFormatter<JT808_0x0200_0x2A>
{
/// <summary>
/// IO状态位
/// </summary>
public ushort IOStatus { get; set; }
public override byte AttachInfoId { get; set; } = 0x2A;
public override byte AttachInfoLength { get; set; } = 2;
public JT808_0x0200_0x2A Deserialize(ref JT808MessagePackReader reader, IJT808Config config)
{
JT808_0x0200_0x2A jT808LocationAttachImpl0X2A = new JT808_0x0200_0x2A();
jT808LocationAttachImpl0X2A.AttachInfoId = reader.ReadByte();
jT808LocationAttachImpl0X2A.AttachInfoLength = reader.ReadByte();
jT808LocationAttachImpl0X2A.IOStatus = reader.ReadUInt16();
return jT808LocationAttachImpl0X2A;
}
public void Serialize(ref JT808MessagePackWriter writer, JT808_0x0200_0x2A value, IJT808Config config)
{
writer.WriteByte(value.AttachInfoId);
writer.WriteByte(value.AttachInfoLength);
writer.WriteUInt16(value.IOStatus);
}
}
}
|
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Plotter.Tweet.Processing;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace Plotter.Tests
{
public class TestBase
{
protected TestDBContext DBContext { get; set; }
[TestInitialize]
public void SetUpTest()
{
DBContext = new TestDBContext();
}
[TestCleanup]
public void TearDownTest()
{
Assert.IsFalse(DBContext.HasPendingChanges, "Database should not have pending changes at the end of a test.");
}
protected Tweet.Tweet TestTweet(Tweet.Tweet input)
{
Tweet.Tweet result = null;
ConcurrentQueue<Tweet.Tweet> queue = new ConcurrentQueue<Tweet.Tweet>();
QueueProcessor qp = new QueueProcessor(queue, DBContext);
qp.TweetReady += (sender, e) =>
{
result = e;
};
Task t = Task.Factory.StartNew(() =>
{
while (true)
{
Thread.Sleep(100);
if (result != null)
return;
}
});
queue.Enqueue(input);
t.Wait();
return result;
}
}
}
|
using System;
using xTile;
namespace Entoarox.DynamicDungeons.Tiles
{
internal abstract class Tile
{
/*********
** Fields
*********/
protected string Layer;
protected int X;
protected int Y;
/*********
** Public methods
*********/
public abstract void Apply(int x, int y, Map map);
public void Apply(Map map)
{
this.Apply(0, 0, map);
}
/*********
** Protected methods
*********/
protected Tile(int x, int y, string layer)
{
this.X = x >= 0 ? x : throw new ArgumentOutOfRangeException(nameof(x));
this.Y = y >= 0 ? y : throw new ArgumentOutOfRangeException(nameof(y));
this.Layer = layer ?? throw new ArgumentNullException(nameof(layer));
}
}
}
|
using System;
using System.Linq.Expressions;
using Xunit;
using ZKCloud.Extensions;
using ZKCloud.Test.Samples;
namespace ZKCloud.Test
{
/// <summary>
/// 扩展测试 - Lambda表达式扩展
/// </summary>
public partial class ExtensionTest
{
/// <summary>
/// 测试初始化
/// </summary>
public ExtensionTest()
{
_parameterExpression = Expression.Parameter(typeof(Sample), "t");
_expression1 = _parameterExpression.Property("StringValue").Call("Contains", Expression.Constant("A"));
_expression2 = _parameterExpression.Property("NullableDateValue")
.Property("Value")
.Property("Year")
.Greater(Expression.Constant(2000));
}
/// <summary>
/// 参数表达式
/// </summary>
private readonly ParameterExpression _parameterExpression;
/// <summary>
/// 表达式1
/// </summary>
private Expression _expression1;
/// <summary>
/// 表达式2
/// </summary>
private Expression _expression2;
/// <summary>
/// 测试And方法
/// </summary>
[Fact]
public void TestAnd()
{
var andExpression = _expression1.And(_expression2).ToLambda<Func<Sample, bool>>(_parameterExpression);
Expression<Func<Sample, bool>> expected = t =>
t.StringValue.Contains("A") && t.NullableDateValue.Value.Year > 2000;
Assert.Equal(expected.ToString(), andExpression.ToString());
Expression<Func<Sample, bool>> left = t => t.StringValue == "A";
Expression<Func<Sample, bool>> right = t => t.StringValue == "B";
expected = t => t.StringValue == "A" && t.StringValue == "B";
Assert.Equal(expected.ToString(), left.And(right).ToString());
}
/// <summary>
/// 测试模糊匹配
/// </summary>
[Fact]
public void TestContains()
{
_expression1 = _parameterExpression.Property("StringValue").Contains("a");
Assert.Equal("t => t.StringValue.Contains(\"a\")",
_expression1.ToLambda<Func<Sample, bool>>(_parameterExpression).ToString());
}
/// <summary>
/// 测试尾匹配
/// </summary>
[Fact]
public void TestEndsWith()
{
_expression1 = _parameterExpression.Property("StringValue").EndsWith("a");
Assert.Equal("t => t.StringValue.EndsWith(\"a\")",
_expression1.ToLambda<Func<Sample, bool>>(_parameterExpression).ToString());
}
/// <summary>
/// 测试相等
/// </summary>
[Fact]
public void TestEqual()
{
_expression1 = _parameterExpression.Property("IntValue").Equal(1);
Assert.Equal("t => (t.IntValue == 1)",
_expression1.ToLambda<Func<Sample, bool>>(_parameterExpression).ToString());
}
/// <summary>
/// 测试大于
/// </summary>
[Fact]
public void TestGreater()
{
_expression1 = _parameterExpression.Property("NullableIntValue").Greater(1);
Assert.Equal("t => (t.NullableIntValue > 1)",
_expression1.ToLambda<Func<Sample, bool>>(_parameterExpression).ToString());
}
/// <summary>
/// 测试大于等于
/// </summary>
[Fact]
public void TestGreaterEqual_Nullable()
{
_expression1 = _parameterExpression.Property("NullableIntValue").GreaterEqual(1);
Assert.Equal("t => (t.NullableIntValue >= 1)",
_expression1.ToLambda<Func<Sample, bool>>(_parameterExpression).ToString());
}
/// <summary>
/// 测试小于
/// </summary>
[Fact]
public void TestLess()
{
_expression1 = _parameterExpression.Property("NullableIntValue").Less(1);
Assert.Equal("t => (t.NullableIntValue < 1)",
_expression1.ToLambda<Func<Sample, bool>>(_parameterExpression).ToString());
}
/// <summary>
/// 测试小于等于
/// </summary>
[Fact]
public void TestLessEqual()
{
_expression1 = _parameterExpression.Property("NullableIntValue").LessEqual(1);
Assert.Equal("t => (t.NullableIntValue <= 1)",
_expression1.ToLambda<Func<Sample, bool>>(_parameterExpression).ToString());
}
/// <summary>
/// 测试不相等
/// </summary>
[Fact]
public void TestNotEqual()
{
_expression1 = _parameterExpression.Property("NullableIntValue").NotEqual(1);
Assert.Equal("t => (t.NullableIntValue != 1)",
_expression1.ToLambda<Func<Sample, bool>>(_parameterExpression).ToString());
}
/// <summary>
/// 测试Or方法
/// </summary>
[Fact]
public void TestOr()
{
var andExpression = _expression1.Or(_expression2).ToLambda<Func<Sample, bool>>(_parameterExpression);
Expression<Func<Sample, bool>> expected = t =>
t.StringValue.Contains("A") || t.NullableDateValue.Value.Year > 2000;
Assert.Equal(expected.ToString(), andExpression.ToString());
}
/// <summary>
/// 测试Or方法
/// </summary>
[Fact]
public void TestOr_2()
{
Expression<Func<Sample, bool>> left = t => t.StringValue == "A";
Expression<Func<Sample, bool>> right = t => t.StringValue == "B";
Expression<Func<Sample, bool>> expected = t => t.StringValue == "A" || t.StringValue == "B";
Assert.Equal(expected.ToString(), left.Or(right).ToString());
}
/// <summary>
/// 测试Or方法 - 左表达式为空
/// </summary>
[Fact]
public void TestOr_2_LeftIsNull()
{
Expression<Func<Sample, bool>> left = null;
Expression<Func<Sample, bool>> right = t => t.StringValue == "B";
Expression<Func<Sample, bool>> expected = t => t.StringValue == "B";
Assert.Equal(expected.ToString(), left.Or(right).ToString());
}
/// <summary>
/// 测试Or方法 - 右表达式为空
/// </summary>
[Fact]
public void TestOr_2_RightIsNull()
{
Expression<Func<Sample, bool>> left = t => t.StringValue == "A";
Expression<Func<Sample, bool>> right = null;
Expression<Func<Sample, bool>> expected = t => t.StringValue == "A";
Assert.Equal(expected.ToString(), left.Or(right).ToString());
}
/// <summary>
/// 测试Or方法 - 左表达式为空
/// </summary>
[Fact]
public void TestOr_LeftIsNull()
{
_expression1 = null;
var andExpression = _expression1.Or(_expression2).ToLambda<Func<Sample, bool>>(_parameterExpression);
Expression<Func<Sample, bool>> expected = t => t.NullableDateValue.Value.Year > 2000;
Assert.Equal(expected.ToString(), andExpression.ToString());
}
/// <summary>
/// 测试Or方法 - 右表达式为空
/// </summary>
[Fact]
public void TestOr_RightIsNull()
{
_expression2 = null;
var andExpression = _expression1.Or(_expression2).ToLambda<Func<Sample, bool>>(_parameterExpression);
Expression<Func<Sample, bool>> expected = t => t.StringValue.Contains("A");
Assert.Equal(expected.ToString(), andExpression.ToString());
}
/// <summary>
/// 测试头匹配
/// </summary>
[Fact]
public void TestStartsWith()
{
_expression1 = _parameterExpression.Property("StringValue").StartsWith("a");
Assert.Equal("t => t.StringValue.StartsWith(\"a\")",
_expression1.ToLambda<Func<Sample, bool>>(_parameterExpression).ToString());
}
/// <summary>
/// 获取lambda表达式成员值
/// </summary>
[Fact]
public void TestValue_LambdaExpression()
{
Expression<Func<Sample, bool>> expression = test => test.StringValue == "A";
Assert.Equal("A", expression.Value());
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Journey.WebApp.Data;
using Journey.WebApp.Models;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
namespace Journey.WebApp.Controllers
{
[Authorize]
public class TripCitiesController : Controller
{
private readonly JourneyDBContext _context;
public TripCitiesController(JourneyDBContext context)
{
_context = context;
}
public IActionResult Create(long? id)
{
if (id == null)
{
return NotFound();
}
var tripCity = new TripCities();
tripCity.TripId = (long)id;
return View("Edit", tripCity);
}
// GET: TravelersTrips/Edit/5
public async Task<IActionResult> Edit(long? id)
{
if (id == null)
{
return NotFound();
}
var tripCities = await _context.TripCities.Include(tc => tc.City).FirstOrDefaultAsync(tc => tc.Id == id);
if (tripCities == null)
{
return NotFound();
}
return View(tripCities);
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Edit(TripCities tripCities, City city)
{
if (ModelState.IsValid)
{
var cityID = await MyUtility.CityFindOrAdd(_context, city);
tripCities.CityId = cityID;
if (tripCities.Id == 0)
{
_context.Add(tripCities);
}
else
{
_context.Update(tripCities);
}
await _context.SaveChangesAsync();
return RedirectToAction("Index", "TravelerTrips", null);
}
return View(tripCities);
}
public async Task<IActionResult> Details(long? id)
{
if (id == null)
{
return NotFound();
}
var tripCity = await _context.TripCities.Include(tc => tc.Trip)
.ThenInclude(t => t.TripCities)
.Include(tc => tc.City)
.Include(tc => tc.TripDetails)
.ThenInclude(td => td.TripActivities)
.FirstOrDefaultAsync(tc => tc.Id == id);
if (tripCity == null)
{
return NotFound();
}
ViewBag.trip = tripCity.Trip.TripName;
ViewBag.city = tripCity.City.CityName;
ViewBag.current = tripCity.Id;
var tripCityIds = tripCity.Trip.TripCities.OrderBy(tc => tc.StartDate).Select(tc => tc.Id).ToArray();
var index = Array.IndexOf(tripCityIds, id);
var indexNext = tripCityIds[index + 1 >= tripCityIds.Length ? 0 : index + 1];
var indexPrev = tripCityIds[index - 1 < 0 ? tripCityIds.Length - 1 : index - 1];
var nextCity = await _context.TripCities.Include(tc => tc.City)
.FirstOrDefaultAsync(tc => tc.Id == indexNext);
var prevCity = await _context.TripCities.Include(tc => tc.City)
.FirstOrDefaultAsync(tc => tc.Id == indexPrev);
ViewBag.next = indexNext;
ViewBag.previous = indexPrev;
ViewBag.nextCity = nextCity.City.CityName;
ViewBag.prevCity = prevCity.City.CityName;
return View(tripCity.TripDetails);
}
public async Task<IActionResult> Delete(long? id)
{
if (id == null)
{
return NotFound();
}
var tripCities = await _context.TripCities.Include(tc => tc.City)
.Include(t => t.Trip)
.FirstOrDefaultAsync(tc => tc.Id == id);
if (tripCities == null)
{
return NotFound();
}
return View(tripCities);
}
// POST: TravelersTrips/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public async Task<IActionResult> DeleteConfirmed(long id)
{
var tripCities = await _context.TripCities.Include(tc => tc.City)
.Include(t => t.Trip)
.FirstOrDefaultAsync(tc => tc.Id == id);
_context.TripCities.Remove(tripCities);
await _context.SaveChangesAsync();
return RedirectToAction("Index", "TravelerTrips", null);
}
}
} |
using System.Diagnostics;
using System.Security.Principal;
using Manor.ConnectionStrings.Configuration;
using Manor.ConnectionStrings.DbTypes;
using Manor.Utilities.Extensions;
namespace Manor.ConnectionStrings.Configurators
{
public class ManualConfigurator : IConnectionStringConfigurator
{
private readonly string _dataSource;
private readonly string _user;
private readonly string _password;
public EDbType DbType { get; set; }
public ManualConfigurator(string dataSource, string user, string password)
{
_dataSource = dataSource;
_user = user;
_password = password;
DbType = EDbType.Unkown;
}
public void Configure()
{
bool connectionStringFromCmdLineExists = false;
bool connectionStringFromXmlFileExists = false;
if (!string.IsNullOrEmpty(_user) &&
!string.IsNullOrEmpty(_password))
{
connectionStringFromCmdLineExists = true;
}
var loader = new ConnectionStringLoader();
var connectionStrings = loader.Load();
if (connectionStrings != null &&
connectionStrings.Count > 0)
{
connectionStringFromXmlFileExists = true;
}
OracleConnectionString connectString;
if (connectionStringFromCmdLineExists)
{
connectString = new OracleConnectionString(_dataSource, _user, _password);
}
else if (connectionStringFromXmlFileExists)
{
connectString = connectionStrings[_dataSource] as OracleConnectionString;
Debug.Assert(connectString != null, "connectString != null");
if (connectString.HasProxyUserAndPassword)
{
connectString.User = WindowsIdentity.GetCurrent().NameWithoutDomain();
connectString.Password = null;
}
Debug.Assert(connectString != null, "ConnectionString not of type OracleConnectionString?");
}
else
{
throw new ConnectionStringRegistryException(
"No Database ConnectionString configuration found. Please use command-line or xml-config.");
}
if (DbType == EDbType.Unkown && DbMode == EDatabaseMode.Unkown)
{
var databaseTypesLoader = new DatabaseTypesLoader();
var dbTypes = databaseTypesLoader.Load();
DbType = dbTypes.GetDbType(_dataSource);
DbMode = dbTypes.GetDbMode(_dataSource);
}
if (DbType == EDbType.Unkown)
throw new ConnectionStringRegistryException(string.Format("Unkown database type [{0}]", _dataSource));
if (DbMode == EDatabaseMode.Unkown)
throw new ConnectionStringRegistryException(string.Format("Unkown database mode [{0}]", _dataSource));
connectString.ConnectionPooling = true;
ConnectionStringRegistry.Instance().DatabaseMode = DbMode;
ConnectionStringRegistry.Instance().Add(DbType, connectString);
}
}
} |
using MonoDevelop.Ide;
using MonoDevelop.Projects;
using MonoDevelop.Projects.Dom;
using MonoDevelop.Projects.Dom.Parser;
using System;
using System.Collections.Generic;
using System.IO;
namespace MonoDevelop.NUnit
{
public class NUnitProjectTestSuite : NUnitAssemblyTestSuite
{
private DotNetProject project;
private string resultsPath;
private string storeId;
protected override string AssemblyPath
{
get
{
return this.project.GetOutputFileName(IdeApp.get_Workspace().get_ActiveConfiguration());
}
}
protected override string TestInfoCachePath
{
get
{
return System.IO.Path.Combine(this.resultsPath, this.storeId + ".test-cache");
}
}
protected override System.Collections.Generic.IEnumerable<string> SupportAssemblies
{
get
{
DotNetProject dotNetProject = base.OwnerSolutionItem as DotNetProject;
if (dotNetProject != null)
{
foreach (ProjectReference current in dotNetProject.get_References())
{
if (current.get_ReferenceType() != 2 && !current.get_LocalCopy())
{
try
{
string[] referencedFileNames = current.GetReferencedFileNames(IdeApp.get_Workspace().get_ActiveConfiguration());
for (int i = 0; i < referencedFileNames.Length; i++)
{
string text = referencedFileNames[i];
yield return text;
}
}
finally
{
}
}
}
}
yield break;
}
}
public NUnitProjectTestSuite(DotNetProject project) : base(project.get_Name(), project)
{
this.storeId = System.IO.Path.GetFileName(project.get_FileName());
this.resultsPath = System.IO.Path.Combine(project.get_BaseDirectory(), "test-results");
base.ResultsStore = new XmlResultsStore(this.resultsPath, this.storeId);
this.project = project;
project.add_NameChanged(new SolutionItemRenamedEventHandler(this.OnProjectRenamed));
IdeApp.get_ProjectOperations().add_EndBuild(new BuildEventHandler(this.OnProjectBuilt));
}
public static NUnitProjectTestSuite CreateTest(DotNetProject project)
{
NUnitProjectTestSuite result;
foreach (ProjectReference p in project.get_References())
{
if (p.get_Reference().IndexOf("nunit.framework", System.StringComparison.OrdinalIgnoreCase) != -1 || p.get_Reference().IndexOf("nunit.core", System.StringComparison.OrdinalIgnoreCase) != -1)
{
result = new NUnitProjectTestSuite(project);
return result;
}
}
result = null;
return result;
}
protected override SourceCodeLocation GetSourceCodeLocation(string fullClassName, string methodName)
{
ProjectDom ctx = ProjectDomService.GetProjectDom(this.project);
IType cls = ctx.GetType(fullClassName);
SourceCodeLocation result;
if (cls == null)
{
result = null;
}
else
{
DomLocation location;
foreach (IMethod met in cls.get_Methods())
{
if (met.get_Name() == methodName)
{
string arg_85_0 = cls.get_CompilationUnit().get_FileName();
location = met.get_Location();
int arg_85_1 = location.get_Line();
location = met.get_Location();
result = new SourceCodeLocation(arg_85_0, arg_85_1, location.get_Column());
return result;
}
}
string arg_E0_0 = cls.get_CompilationUnit().get_FileName();
location = cls.get_Location();
int arg_E0_1 = location.get_Line();
location = cls.get_Location();
result = new SourceCodeLocation(arg_E0_0, arg_E0_1, location.get_Column());
}
return result;
}
public override void Dispose()
{
this.project.remove_NameChanged(new SolutionItemRenamedEventHandler(this.OnProjectRenamed));
IdeApp.get_ProjectOperations().remove_EndBuild(new BuildEventHandler(this.OnProjectBuilt));
base.Dispose();
}
private void OnProjectRenamed(object sender, SolutionItemRenamedEventArgs e)
{
UnitTestGroup parent = base.Parent as UnitTestGroup;
if (parent != null)
{
parent.UpdateTests();
}
}
private void OnProjectBuilt(object s, BuildEventArgs args)
{
if (base.RefreshRequired)
{
base.UpdateTests();
}
}
}
}
|
using System.Windows.Forms;
namespace gView.Plugins.Editor.Dialogs
{
public partial class FormDistance : Form
{
public FormDistance()
{
InitializeComponent();
}
public double Distance
{
get
{
return (double)numDistance.Value;
}
set
{
numDistance.Value = (decimal)value;
}
}
}
} |
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using FluentValidation;
using MediatR;
using SFA.DAS.CommitmentsV2.Shared.Interfaces;
using SFA.DAS.CommitmentsV2.Api.Client;
using SFA.DAS.ProviderCommitments.Infrastructure.OuterApi.Requests.Cohorts;
using SFA.DAS.ProviderCommitments.Interfaces;
namespace SFA.DAS.ProviderCommitments.Application.Commands.CreateCohort
{
public class CreateCohortHandler : IRequestHandler<CreateCohortRequest, CreateCohortResponse>
{
private readonly IValidator<CreateCohortRequest> _validator;
private readonly ICommitmentsApiClient _apiClient;
private readonly IOuterApiService _outerApi;
private readonly IMapper<CreateCohortRequest, CreateCohortApimRequest> _mapper;
public CreateCohortHandler(
IValidator<CreateCohortRequest> validator,
ICommitmentsApiClient apiClient,
IOuterApiService outerApi,
IMapper<CreateCohortRequest, CreateCohortApimRequest> mapper)
{
_validator = validator;
_apiClient = apiClient;
_outerApi = outerApi;
_mapper = mapper;
}
public async Task<CreateCohortResponse> Handle(CreateCohortRequest request, CancellationToken cancellationToken)
{
ValidateAndThrow(request);
var apiRequest = await _mapper.Map(request).ConfigureAwait(false);
var apiResult = await _outerApi.CreateCohort(apiRequest).ConfigureAwait(false);
var apprenticeships = await _apiClient.GetDraftApprenticeships(apiResult.CohortId, cancellationToken);
long? draftApprenticeshipId = null;
bool hasStandardOptions = false;
if (apprenticeships.DraftApprenticeships.Count == 1)
{
var draftApprenticeship = await _apiClient.GetDraftApprenticeship(apiResult.CohortId,
apprenticeships.DraftApprenticeships.First().Id, cancellationToken);
draftApprenticeshipId = draftApprenticeship.Id;
hasStandardOptions = draftApprenticeship.HasStandardOptions;
}
return new CreateCohortResponse
{
CohortId = apiResult.CohortId,
CohortReference = apiResult.CohortReference,
HasStandardOptions = hasStandardOptions,
DraftApprenticeshipId = draftApprenticeshipId,
};
}
private void ValidateAndThrow(CreateCohortRequest request)
{
var validationResult = _validator.Validate(request);
if (!validationResult.IsValid)
{
throw new ValidationException(validationResult.Errors);
}
}
}
}
|
// -----------------------------------------------------------------------
// <copyright company="Fireasy"
// email="faib920?126.com"
// qq="55570729">
// (c) Copyright Fireasy. All rights reserved.
// </copyright>
// -----------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Data;
namespace Fireasy.Data.Schema
{
/// <summary>
/// MySql相关数据库架构信息的获取方法。
/// </summary>
public sealed class MySqlSchema : SchemaBase
{
public MySqlSchema()
{
AddRestrictionIndex<Database>(s => s.Name);
AddRestrictionIndex<Table>(s => s.Catalog, s => s.Schema, s => s.Name, s => s.Type);
AddRestrictionIndex<Column>(s => s.Catalog, s => s.Schema, s => s.TableName, s => s.Name);
AddRestrictionIndex<View>(s => s.Catalog, s => s.Schema, s => s.Name);
AddRestrictionIndex<ViewColumn>(s => s.Catalog, s => s.Schema, s => s.ViewName, s => s.Name);
AddRestrictionIndex<User>(s => s.Name);
AddRestrictionIndex<Procedure>(s => s.Catalog, s => s.Schema, s => s.Name, s => s.Type);
AddRestrictionIndex<ProcedureParameter>(s => s.Catalog, s => s.Schema, s => s.ProcedureName, null, s => s.Name);
AddRestrictionIndex<Index>(s => s.Catalog, s => s.Schema, s => s.TableName, s => s.Name);
AddRestrictionIndex<IndexColumn>(s => s.Catalog, s => s.Schema, s => s.TableName, s => s.Name, s => s.ColumnName);
AddRestrictionIndex<ForeignKey>(s => s.Catalog, s => s.Schema, s => s.TableName, s => s.Name);
}
protected override IEnumerable<Database> GetDatabases(IDatabase database, string[] restrictionValues)
{
var sql = "SHOW DATABASES";
if (restrictionValues != null && restrictionValues.Length == 1)
{
sql += $" LIKE '{restrictionValues[0]}'";
}
return ParseMetadata(database, sql, null, (wrapper, reader) => new Database
{
Name = wrapper.GetString(reader, 0),
CreateDate = wrapper.GetDateTime(reader, 1)
});
}
protected override IEnumerable<User> GetUsers(IDatabase database, string[] restrictionValues)
{
var parameters = new ParameterCollection();
SqlCommand sql = "SELECT HOST, USER FROM MYSQL.USER WHERE (NAME = ?NAME OR ?NAME IS NULL)";
ParameteRestrition(parameters, "NAME", 0, restrictionValues);
return ParseMetadata(database, sql, parameters, (wrapper, reader) => new User
{
Name = wrapper.GetString(reader, 1)
});
}
protected override IEnumerable<Table> GetTables(IDatabase database, string[] restrictionValues)
{
var parameters = new ParameterCollection();
SqlCommand sql = @"
SELECT
TABLE_CATALOG,
TABLE_SCHEMA,
TABLE_NAME,
TABLE_TYPE,
TABLE_COMMENT
FROM INFORMATION_SCHEMA.TABLES T
WHERE (TABLE_CATALOG = ?CATALOG OR ?CATALOG IS NULL)
AND (T.TABLE_SCHEMA = ?SCHEMA OR ?SCHEMA IS NULL)
AND (T.TABLE_NAME = ?NAME OR ?NAME IS NULL)
AND (T.TABLE_TYPE = ?TABLETYPE OR ?TABLETYPE IS NULL)
ORDER BY T.TABLE_CATALOG, T.TABLE_SCHEMA, T.TABLE_NAME";
ParameteRestrition(parameters, "CATALOG", 0, restrictionValues);
ParameteRestrition(parameters, "SCHEMA", 1, restrictionValues);
ParameteRestrition(parameters, "NAME", 2, restrictionValues);
ParameteRestrition(parameters, "TABLETYPE", 3, restrictionValues);
return ParseMetadata(database, sql, parameters, (wrapper, reader) => new Table
{
Catalog = wrapper.GetString(reader, 0),
Schema = wrapper.GetString(reader, 1),
Name = wrapper.GetString(reader, 2),
Type = wrapper.GetString(reader, 3),
Description = wrapper.GetString(reader, 4)
});
}
protected override IEnumerable<Column> GetColumns(IDatabase database, string[] restrictionValues)
{
var parameters = new ParameterCollection();
SqlCommand sql = @"
SELECT T.TABLE_CATALOG,
T.TABLE_SCHEMA,
T.TABLE_NAME,
T.COLUMN_NAME,
T.DATA_TYPE,
T.CHARACTER_MAXIMUM_LENGTH,
T.NUMERIC_PRECISION,
T.NUMERIC_SCALE,
T.IS_NULLABLE,
T.COLUMN_KEY,
T.COLUMN_DEFAULT,
T.COLUMN_COMMENT,
T.EXTRA
FROM INFORMATION_SCHEMA.COLUMNS T
JOIN INFORMATION_SCHEMA.TABLES O
ON O.TABLE_SCHEMA = T.TABLE_SCHEMA AND O.TABLE_NAME = T.TABLE_NAME
WHERE (T.TABLE_CATALOG = ?CATALOG OR ?CATALOG IS NULL) AND
(T.TABLE_SCHEMA = ?SCHEMA OR ?SCHEMA IS NULL) AND
(T.TABLE_NAME = ?TABLENAME OR ?TABLENAME IS NULL) AND
(T.COLUMN_NAME = ?COLUMNNAME OR ?COLUMNNAME IS NULL)
ORDER BY T.TABLE_CATALOG, T.TABLE_SCHEMA, T.TABLE_NAME";
ParameteRestrition(parameters, "CATALOG", 0, restrictionValues);
ParameteRestrition(parameters, "SCHEMA", 1, restrictionValues);
ParameteRestrition(parameters, "TABLENAME", 2, restrictionValues);
ParameteRestrition(parameters, "COLUMNNAME", 3, restrictionValues);
return ParseMetadata(database, sql, parameters, (wrapper, reader) => new Column
{
Catalog = wrapper.GetString(reader, 0),
Schema = wrapper.GetString(reader, 1),
TableName = wrapper.GetString(reader, 2),
Name = wrapper.GetString(reader, 3),
DataType = wrapper.GetString(reader, 4),
Length = wrapper.GetInt32(reader, 5),
NumericPrecision = wrapper.GetInt32(reader, 6),
NumericScale = wrapper.GetInt32(reader, 7),
IsNullable = wrapper.GetString(reader, 8) == "YES",
IsPrimaryKey = wrapper.GetString(reader, 9) == "PRI",
Default = wrapper.GetString(reader, 10),
Description = wrapper.GetString(reader, 11),
Autoincrement = !wrapper.IsDbNull(reader, 12) && wrapper.GetString(reader, 12).IndexOf("auto_increment") != -1
});
}
protected override IEnumerable<View> GetViews(IDatabase database, string[] restrictionValues)
{
var parameters = new ParameterCollection();
SqlCommand sql = @"
SELECT T.TABLE_CATALOG,
T.TABLE_SCHEMA,
T.TABLE_NAME
FROM
INFORMATION_SCHEMA.VIEWS T
WHERE AND (T.TABLE_CATALOG = ?CATALOG OR ?CATALOG IS NULL)
AND (T.TABLE_SCHEMA = ?SCHEMA OR ?SCHEMA IS NULL)
AND (T.TABLE_NAME = ?NAME OR ?NAME IS NULL)
ORDER BY T.TABLE_CATALOG, T.TABLE_SCHEMA, T.TABLE_NAME";
ParameteRestrition(parameters, "CATALOG", 0, restrictionValues);
ParameteRestrition(parameters, "SCHEMA", 1, restrictionValues);
ParameteRestrition(parameters, "NAME", 2, restrictionValues);
return ParseMetadata(database, sql, parameters, (wrapper, reader) => new View
{
Catalog = wrapper.GetString(reader, 0),
Schema = wrapper.GetString(reader, 1),
Name = wrapper.GetString(reader, 2)
});
}
protected override IEnumerable<ViewColumn> GetViewColumns(IDatabase database, string[] restrictionValues)
{
var parameters = new ParameterCollection();
SqlCommand sql = @"
SELECT T.TABLE_CATALOG,
T.TABLE_SCHEMA,
T.TABLE_NAME,
T.COLUMN_NAME
FROM INFORMATION_SCHEMA.COLUMNS T
WHERE (T.TABLE_CATALOG = ?CATALOG OR ?CATALOG IS NULL) AND
(T.TABLE_SCHEMA = ?SCHEMA OR ?SCHEMA IS NULL) AND
(T.TABLE_NAME = ?TABLENAME OR ?TABLENAME IS NULL) AND
(T.COLUMN_NAME = ?COLUMNNAME OR ?COLUMNNAME IS NULL)
ORDER BY T.TABLE_CATALOG, T.TABLE_SCHEMA, T.TABLE_NAME";
ParameteRestrition(parameters, "CATALOG", 0, restrictionValues);
ParameteRestrition(parameters, "SCHEMA", 1, restrictionValues);
ParameteRestrition(parameters, "TABLENAME", 2, restrictionValues);
ParameteRestrition(parameters, "COLUMNNAME", 3, restrictionValues);
return ParseMetadata(database, sql, parameters, (wrapper, reader) => new ViewColumn
{
Catalog = wrapper.GetString(reader, 0),
Schema = wrapper.GetString(reader, 1),
ViewName = wrapper.GetString(reader, 2),
Name = wrapper.GetString(reader, 3)
});
}
protected override IEnumerable<ForeignKey> GetForeignKeys(IDatabase database, string[] restrictionValues)
{
var parameters = new ParameterCollection();
SqlCommand sql = @"
SELECT
T.CONSTRAINT_CATALOG,
T.CONSTRAINT_SCHEMA,
T.CONSTRAINT_NAME,
T.TABLE_NAME,
T.COLUMN_NAME,
T.REFERENCED_TABLE_NAME,
T.REFERENCED_COLUMN_NAME
FROM
INFORMATION_SCHEMA.KEY_COLUMN_USAGE T
WHERE (T.CONSTRAINT_CATALOG = ?CATALOG OR ?CATALOG IS NULL) AND
(T.CONSTRAINT_SCHEMA = ?SCHEMA OR ?SCHEMA IS NULL) AND
(T.TABLE_NAME = ?TABLENAME OR ?TABLENAME IS NULL) AND
(T.CONSTRAINT_NAME = ?NAME OR ?NAME IS NULL) AND
REFERENCED_TABLE_NAME IS NOT NULL";
ParameteRestrition(parameters, "CATALOG", 0, restrictionValues);
ParameteRestrition(parameters, "SCHEMA", 1, restrictionValues);
ParameteRestrition(parameters, "TABLENAME", 2, restrictionValues);
ParameteRestrition(parameters, "NAME", 3, restrictionValues);
return ParseMetadata(database, sql, parameters, (wrapper, reader) => new ForeignKey
{
Catalog = wrapper.GetString(reader, 0),
Schema = wrapper.GetString(reader, 1),
Name = wrapper.GetString(reader, 2),
TableName = wrapper.GetString(reader, 3),
ColumnName = wrapper.GetString(reader, 4),
PKTable = wrapper.GetString(reader, 5),
PKColumn = wrapper.GetString(reader, 6),
});
}
protected override IEnumerable<Procedure> GetProcedures(IDatabase database, string[] restrictionValues)
{
var parameters = new ParameterCollection();
SqlCommand sql = @"
SELECT
SPECIFIC_NAME,
ROUTINE_CATALOG,
ROUTINE_SCHEMA,
ROUTINE_NAME,
ROUTINE_TYPE
FROM INFORMATION_SCHEMA.ROUTINES
WHERE (SPECIFIC_CATALOG = @CATALOG OR (@CATALOG IS NULL))
AND (SPECIFIC_SCHEMA = @OWNER OR (@OWNER IS NULL))
AND (SPECIFIC_NAME = @NAME OR (@NAME IS NULL))
AND (ROUTINE_TYPE = @TYPE OR (@TYPE IS NULL))
ORDER BY SPECIFIC_CATALOG, SPECIFIC_SCHEMA, SPECIFIC_NAME";
ParameteRestrition(parameters, "CATALOG", 0, restrictionValues);
ParameteRestrition(parameters, "OWNER", 1, restrictionValues);
ParameteRestrition(parameters, "NAME", 2, restrictionValues);
ParameteRestrition(parameters, "TYPE", 3, restrictionValues);
return ParseMetadata(database, sql, parameters, (wrapper, reader) => new Procedure
{
Catalog = wrapper.GetString(reader, 0),
Schema = wrapper.GetString(reader, 1),
Name = wrapper.GetString(reader, 2),
Type = wrapper.GetString(reader, 6)
});
}
protected override IEnumerable<ProcedureParameter> GetProcedureParameters(IDatabase database, string[] restrictionValues)
{
var parameters = new ParameterCollection();
SqlCommand sql = @"
SELECT
SPECIFIC_CATALOG,
SPECIFIC_SCHEMA,
SPECIFIC_NAME,
ORDINAL_POSITION,
PARAMETER_MODE,
PARAMETER_NAME,
DATA_TYPE,
CHARACTER_MAXIMUM_LENGTH,
NUMERIC_PRECISION,
NUMERIC_SCALE
WHERE (SPECIFIC_CATALOG = @CATALOG OR (@CATALOG IS NULL))
AND (SPECIFIC_SCHEMA = @OWNER OR (@OWNER IS NULL))
AND (SPECIFIC_NAME = @NAME OR (@NAME IS NULL))
AND (PARAMETER_NAME = @PARAMETER OR (@PARAMETER IS NULL))
ORDER BY SPECIFIC_CATALOG, SPECIFIC_SCHEMA, SPECIFIC_NAME, PARAMETER_NAME";
ParameteRestrition(parameters, "CATALOG", 0, restrictionValues);
ParameteRestrition(parameters, "OWNER", 1, restrictionValues);
ParameteRestrition(parameters, "NAME", 2, restrictionValues);
ParameteRestrition(parameters, "PARAMETER", 3, restrictionValues);
return ParseMetadata(database, sql, parameters, (wrapper, reader) => new ProcedureParameter
{
Catalog = wrapper.GetString(reader, 0),
Schema = wrapper.GetString(reader, 1),
ProcedureName = wrapper.GetString(reader, 2),
Name = wrapper.GetString(reader, 5),
Direction = wrapper.GetString(reader, 4) == "IN" ? ParameterDirection.Input : ParameterDirection.Output,
NumericPrecision = wrapper.GetInt32(reader, 8),
NumericScale = wrapper.GetInt32(reader, 9),
DataType = wrapper.GetString(reader, 6),
Length = wrapper.GetInt64(reader, 7)
});
}
}
}
|
using Chloe.ViewComponents.FooterComponent.Contracts;
using Chloe.ViewModels;
using System.Threading.Tasks;
namespace Chloe.ViewComponents.FooterComponent
{
public class FooterComponent : IFooterComponent
{
public FooterComponent()
{
this.ComponentType = ComponentType.Footer;
this.ViewName = "Footer";
}
public ComponentType ComponentType { get; set; }
public string ViewName { get; set; }
public Task InvokeAsync()
{
return Task.Run(() => { return new { }; });
}
public string ViewLocation { get { return string.Format("Components/_{0}", this.ViewName); } }
}
}
|
using System;
using System.Linq;
namespace Task_3
{
class Polygon
{
private int sidesNumber;
private double radius;
public double Perimeter
{
get
{
return 2 * sidesNumber * radius * Math.Sin(Math.PI / sidesNumber);
}
}
public double Area
{
get
{
return 0.5 * Perimeter * radius;
}
}
public Polygon(int sidesNumber, double radius)
{
if (sidesNumber < 3)
{
throw new ArgumentException($"\nIncorrect number of the polygon's sides. Min value must be at least 3. Now: {sidesNumber}.\n");
}
this.sidesNumber = sidesNumber;
if (radius <= 0)
{
throw new ArgumentException($"\nIncorrect value of the radius. Min value must be more than 0. Now: {radius}.\n");
}
this.radius = radius;
}
public void PolygonData(ConsoleColor color = ConsoleColor.Gray)
{
Console.WriteLine($"Fields:\n\tThe number of sides: {sidesNumber}\n\tThe value of the radius: {radius}\n");
Console.Write($"Properties:\n\tPerimeter value: {Perimeter}\n\tArea value: ");
Console.ForegroundColor = color;
Console.WriteLine($"{Area}\n");
Console.ResetColor();
}
}
class Program
{
static void Add(ref Polygon[] polygons, Polygon newPolygon)
{
Array.Resize(ref polygons, polygons.Length + 1);
polygons[polygons.Length - 1] = newPolygon;
}
static void Add(ref double[] areas, Polygon newPolygon)
{
Array.Resize(ref areas, areas.Length + 1);
areas[areas.Length - 1] = newPolygon.Area;
}
static void Main(string[] args)
{
Polygon[] polygons = new Polygon[0];
double[] areas = new double[0];
do
{
for (int i = 0; i < polygons.Length; i++)
{
if (areas[i] == areas.Min()) { polygons[i].PolygonData(ConsoleColor.Green); continue; }
if (areas[i] == areas.Max()) { polygons[i].PolygonData(ConsoleColor.Red); continue; }
polygons[i].PolygonData();
}
Console.WriteLine($"Enter the count of the sides of the new polygon:");
if (!int.TryParse(Console.ReadLine(), out int sidesNumber))
{
Console.WriteLine("\nIncorrect input\n");
return;
}
Console.WriteLine($"\nEnter the value of the radius of the new polygon:");
if (!double.TryParse(Console.ReadLine(), out double radius))
{
Console.WriteLine("\nIncorrect input\n");
return;
}
if (sidesNumber == 0 && radius == 0)
{
return;
}
try
{
Polygon newPolygon = new Polygon(sidesNumber, radius);
Add(ref polygons, newPolygon);
Add(ref areas, newPolygon);
}
catch (ArgumentException exception)
{
Console.WriteLine(exception.Message);
Console.WriteLine("Press any key to continue.");
Console.ReadKey();
}
Console.Clear();
} while (true);
}
}
}
|
namespace Foundry.Messaging.Infrastructure
{
public interface IBus
{
void Send<TMessage>(TMessage message);
TReply SendAndWaitForReply<TMessage, TReply>(TMessage message);
}
} |
using System;
using System.Collections.Generic;
using System.Text;
using WebScrapingRobot.Context;
using WebScrapingRobot.Model;
using WebScrapingRobot.Repository.Interface;
namespace WebScrapingRobot.Repository
{
public class AgencyOfficeLocationRepository : IRepository<AgencyOfficeLocation>
{
public void Add(AgencyOfficeLocation model)
{
using (var context = new FBOContext())
{
context.AgencyOfficeLocations.Add(model);
context.SaveChanges();
}
}
public void AddRange(List<AgencyOfficeLocation> listModel)
{
using (var context = new FBOContext())
{
context.AgencyOfficeLocations.AddRange(listModel);
context.SaveChanges();
}
}
}
}
|
namespace OpenUi
{
public enum FormButtonTypes
{
close,
}
} |
using System;
using System.Runtime.InteropServices;
using Vlc.DotNet.Core.Interops;
using Vlc.DotNet.Core.Interops.Signatures;
namespace Vlc.DotNet.Core
{
public sealed partial class VlcMediaPlayer
{
private EventCallback myOnMediaPlayerScrambledChangedInternalEventCallback;
public event EventHandler<VlcMediaPlayerScrambledChangedEventArgs> ScrambledChanged;
private void OnMediaPlayerScrambledChangedInternal(IntPtr ptr)
{
var args = MarshalHelper.PtrToStructure<VlcEventArg>(ptr);
OnMediaPlayerScrambledChanged(args.eventArgsUnion.MediaPlayerScrambledChanged.NewScrambled);
}
public void OnMediaPlayerScrambledChanged(int newScrambled)
{
ScrambledChanged?.Invoke(this, new VlcMediaPlayerScrambledChangedEventArgs(newScrambled));
}
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.