text stringlengths 13 6.01M |
|---|
using System;
using DelftTools.Hydro.CrossSections.DataSets;
using DelftTools.TestUtils;
using NUnit.Framework;
namespace DelftTools.Tests.Hydo.DataSets
{
[TestFixture]
public class FastXYZDataTableTest
{
readonly Random random = new Random();
[Test]
[Category(TestCategory.Performance)]
public void SerializeAndDeserialize()
{
FastDataTableTestHelper.TestSerializationIsFastAndCorrect<FastXYZDataTable>(40, 30,
(t) =>
t.AddCrossSectionXYZRow(
random.NextDouble(),
random.NextDouble(),
random.NextDouble()));
}
}
} |
namespace Cs_Notas.Infra.Data.Migrations
{
using System;
using System.Data.Entity.Migrations;
public partial class Conjuntos : DbMigration
{
public override void Up()
{
CreateTable(
"dbo.Conjuntos",
c => new
{
ConjuntoId = c.Int(nullable: false, identity: true),
IdAto = c.Int(nullable: false),
Ordem = c.Int(nullable: false),
Codigo = c.Int(nullable: false),
Natureza = c.Int(nullable: false),
TipoAto = c.String(maxLength: 100, unicode: false),
LavradoRj = c.String(maxLength: 1, unicode: false),
UfOrigem = c.String(maxLength: 2, unicode: false),
CodigoServentia = c.Int(nullable: false),
Serventia = c.String(maxLength: 150, unicode: false),
Selo = c.String(maxLength: 9, unicode: false),
Aleatorio = c.String(maxLength: 3, unicode: false),
IndSelo = c.String(maxLength: 1, unicode: false),
Data = c.DateTime(nullable: false, precision: 0),
TipoLivro = c.String(maxLength: 1, unicode: false),
Livro = c.String(maxLength: 18, unicode: false),
Folhas = c.String(maxLength: 10, unicode: false),
Ato = c.String(maxLength: 10, unicode: false),
Valor = c.Decimal(nullable: false, precision: 18, scale: 2),
Participantes = c.String(maxLength: 255, unicode: false),
Procuracao = c.String(maxLength: 1, unicode: false),
OrigemDataAto = c.DateTime(nullable: false, precision: 0),
OrigemLivro = c.String(maxLength: 25, unicode: false),
OrigemFolhaInicio = c.String(maxLength: 25, unicode: false),
OrigemFolhaFim = c.String(maxLength: 25, unicode: false),
OrigemNumeroAto = c.String(maxLength: 25, unicode: false),
OrigemLavrado = c.String(maxLength: 2, unicode: false),
OrigemTipoLivro = c.String(maxLength: 100, unicode: false),
OrigemOutorgado = c.String(maxLength: 1, unicode: false),
OrigemServentia = c.String(maxLength: 250, unicode: false),
OrigemUf = c.String(maxLength: 250, unicode: false),
OrigemNotificacao = c.String(maxLength: 25, unicode: false),
})
.PrimaryKey(t => t.ConjuntoId);
}
public override void Down()
{
DropTable("dbo.Conjuntos");
}
}
}
|
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.Collections;
namespace Shipwreck.TypeScriptModels.Decompiler.Transformations.Types
{
[TestClass]
public sealed class TypeDeclarationTest
{
private sealed class InheritedTestClass : ArrayList
{
}
private sealed class ImplementedTestClass : IDisposable
{
public void Dispose()
{
}
}
private sealed class InheritedAndImplementedTestClass : ArrayList, IDisposable
{
public void Dispose()
{
}
}
[TestMethod]
public void TypeDeclarationTest_Inherited()
{
var c = new TypeTranslationContext<InheritedTestClass>().Result;
Assert.IsNotNull(c);
}
[TestMethod]
public void TypeDeclarationTest_Implemented()
{
var c = new TypeTranslationContext<ImplementedTestClass>().Result;
Assert.IsNotNull(c);
}
[TestMethod]
public void TypeDeclarationTest_InheritedAndImplemented()
{
var c = new TypeTranslationContext<InheritedAndImplementedTestClass>().Result;
Assert.IsNotNull(c);
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace EBS.Query.DTO
{
public class SearchOutInOrder
{
public string Code { get; set; }
public string Status { get; set; }
public int SupplierId { get; set; }
/// <summary>
/// 多个逗号分隔
/// </summary>
public string StoreId { get; set; }
public string ProductCodeOrBarCode { get; set; }
public string ProductName { get; set; }
public DateTime? StartDate { get; set; }
public DateTime? EndDate { get; set; }
/// <summary>
/// 业务类别
/// </summary>
public int OutInOrderTypeId { get; set; }
/// <summary>
/// 出入库类别
/// </summary>
public int OutInInventory { get; set; }
public string AuditName { get; set; }
}
}
|
using System.Collections.Generic;
using System.Linq;
namespace Glass
{
public class Assembly
{
private readonly System.Reflection.Assembly assembly;
public Assembly(System.Reflection.Assembly assembly)
{
this.assembly = assembly;
}
public IEnumerable<Type> Types
{
get
{
return assembly.GetTypes().Select(type => new Type(type));
}
}
public override string ToString()
{
return assembly.FullName;
}
protected bool Equals(Assembly other)
{
return Equals(assembly, other.assembly);
}
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj))
return false;
if (ReferenceEquals(this, obj))
return true;
if (obj.GetType() != this.GetType())
return false;
return Equals((Assembly) obj);
}
public override int GetHashCode()
{
return (assembly != null ? assembly.GetHashCode() : 0);
}
public static bool operator ==(Assembly left, Assembly right)
{
return Equals(left, right);
}
public static bool operator !=(Assembly left, Assembly right)
{
return !Equals(left, right);
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using TMPro;
public class NotePrefab : MonoBehaviour
{
public string prev;
public string text;
public void InitNote(string prev, string text)
{
this.prev = prev;
this.text = text;
transform.GetChild(0).GetComponent<TextMeshProUGUI>().text = prev;
}
}
|
using UnityEngine;
public class CopyCameraRotation : MonoBehaviour
{
[HideInInspector] public Transform myTransform;
[Header("rotation offset")]
public Vector3 rotOffset;
[Header("lock")]
public bool lockX;
public bool lockY;
public bool lockZ;
void Start()
{
myTransform = transform;
}
void Update()
{
Vector3 r1 = Camera.main.transform.forward;
if ( lockX )
{
r1.y = 0f;
}
Vector3 r2 = r1.normalized;
Quaternion targetRot = Quaternion.LookRotation(r2) * Quaternion.Euler(rotOffset);
myTransform.rotation = targetRot;
}
}
|
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ACT.DFAssist.Toolkits
{
class LineDb : IEnumerable<KeyValuePair<string, string>>, IEnumerator<KeyValuePair<string, string>>
{
private Dictionary<string, string> _db = new Dictionary<string, string>();
public LineDb(string ctx)
{
ParseLines(ctx);
}
public LineDb(string filename, Encoding enc)
{
string s = File.ReadAllText(filename, enc);
ParseLines(s);
}
private void ParseLines(string ctx)
{
_db.Clear();
var ss = ctx.Split(new char[] { '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries);
foreach (var l in ss)
{
var div = l.IndexOf('=');
if (div <= 0)
continue;
var name = l.Substring(0, div);
if (name[0] == '#' || name.StartsWith("//"))
continue;
var value = l.Substring(div + 1);
_db.Add(name.Trim(), value.Trim());
}
}
public string Get(string name)
{
if (!_db.TryGetValue(name, out string value))
return name;
return value;
}
public bool Try(string name, out string value)
{
return _db.TryGetValue(name, out value);
}
public IEnumerator<KeyValuePair<string, string>> GetEnumerator()
{
return _db.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return _db.GetEnumerator();
}
public void Dispose()
{
}
public bool MoveNext()
{
throw new NotImplementedException();
}
public void Reset()
{
throw new NotImplementedException();
}
public int Count { get { return _db.Count; } }
public KeyValuePair<string, string> Current => throw new NotImplementedException();
object IEnumerator.Current => throw new NotImplementedException();
public string this[string index]
{
get
{
return Get(index);
}
}
}
}
|
// Copyright (c) Simple Injector Contributors. All rights reserved.
// Licensed under the MIT License. See LICENSE file in the project root for license information.
namespace SimpleInjector.Integration.ServiceCollection
{
using Microsoft.Extensions.Logging;
// This class will only be used when a future version of Microsoft.Extensions.Logging.Logger<T> gets a
// second constructor. In that case Simple Injector can't resolve Microsoft.Extensions.Logging.Logger<T>
// and it falls back to this self-defined class.
internal sealed class Logger<T> : Microsoft.Extensions.Logging.Logger<T>
{
// This constructor needs to be public for Simple Injector to create this type.
public Logger(ILoggerFactory factory) : base(factory)
{
}
}
} |
namespace Avanade.Plugin.IdentityProvider.Ids4Adfs.Configuration
{
public class AppSettings
{
public static readonly string SectionName = "Sitecore:ExternalIdentityProviders:IdentityProviders:Ids4Adfs";
public Ids4AdfsIdentityProvider Ids4AdfsIdentityProvider { get; set; } = new Ids4AdfsIdentityProvider();
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class UserPlayer : MonoBehaviour {
public float x;
public float[] ys;
private int curInd = 0;
public static int numTroops = 0;
// Containing the different types of trrops, each index matches to
// a different type, sorted in increasing order of the troop type's
// power.
public List<GameObject> troops;
// Use this for initialization
void Start () {
transform.position = new Vector3(x, ys[0], 0);
}
void Update()
{
if (Input.GetKeyDown("up"))
MoveUp();
else if (Input.GetKeyDown("down"))
MoveDown();
for (int i = 1; i <= troops.Count; ++i)
{
if (Input.GetKeyDown(i.ToString()))
{
DeployTroop(i-1);
}
}
}
protected void DeployTroop(int troopTypeInd)
{
Troop troop = Instantiate(troops[troopTypeInd], transform.position, Quaternion.identity).GetComponent<Troop>();
troop.setId(numTroops);
numTroops++;
}
public void MoveUp()
{
if (curInd == ys.Length - 1)
{
return;
}
curInd += 1;
transform.position = new Vector3(x, ys[curInd], 0);
}
public void MoveDown()
{
if (curInd == 0)
{
return;
}
curInd -= 1;
transform.position = new Vector3(x, ys[curInd], 0);
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
namespace NetDDD.Core.Contracts
{
public interface IEventHandlerProvider
{
IDomainEventHandler GetHandler(string name);
IEnumerable<IDomainEventHandler> GetHandlers(Type eventType);
}
}
|
using Pobs.Domain.Entities;
namespace Pobs.Domain.QueryObjects
{
public class QuestionSearchResult
{
public Question Question { get; set; }
public double MatchScore { get; set; }
}
}
|
namespace SharpStore.Services
{
using Data;
public abstract class Service
{
public readonly SharpStoreContext context;
protected Service(SharpStoreContext context)
{
this.context = context;
}
}
}
|
using UnityEngine;
using System.Collections;
public class MissNote : MonoBehaviour
{
public void OnTriggerEnter2D(Collider2D col)
{
if (col.CompareTag("UNLOAD"))
{
gameObject.SetActive(false);
}
}
public void PlayNote(string type)
{
Debug.Log("MissNote >>> PlayNote");
Evaluate();
}
public void Evaluate()
{
Debug.Log("MissNote >>> Evaluate");
int resultIdx = 3;
int points = 0;
LevelManager.Instance.HandleEvaluationResult(resultIdx, points);
}
}
|
// Copyright © 2020 Void-Intelligence All Rights Reserved.
using Nomad.Core;
namespace Vortex.Metrics.Utility
{
public interface IMetric
{
public double Evaluate(Matrix actual, Matrix expected);
}
}
|
using Microsoft.AspNetCore.Identity;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace feedback.Models
{
public class CustomUser : IdentityUser<int>
{
public UserProfile ProfileData { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace dolgozat
{
class Program
{
static void Main(string[] args)
{
int[] tomb = new int[100];
Random r = new Random();
char meh;
char[] abc = new char[35] { 'a', 'á', 'b', 'c', 'd', 'e', 'é', 'f', 'g', 'h', 'i', 'í', 'j', 'k', 'l', 'm', 'n', 'o', 'ó', 'ö', 'ő', 'p', 'q', 'r', 's', 't', 'u', 'ú', 'ü', 'ű', 'v', 'w', 'x', 'y', 'z' };
string szo = "";
string csakbetuk = "";
int prim = 0;
for (int i = 0; i < tomb.Length; i++)
{
tomb[i] = r.Next(1, 1000);
}
for (int i = 0; i < tomb.Length; i++)
{
if ((tomb[i] > 9) && (tomb[i] < 100))
{
meh = Convert.ToChar(tomb[i]);
szo = szo + meh;
Console.WriteLine(meh);
}
}
Console.WriteLine("összerakott szó: " + szo);
char[] szetszedve = szo.ToArray();
for (int i = 0; i < abc.Length; i++)
{
for (int j = 0; j < szo.Length; j++)
{
if ((szo[j].ToString() == abc[i].ToString().ToUpper()) || (szo[j] == abc[i]))
{
csakbetuk = csakbetuk + szo[j];
}
}
}
Console.WriteLine("csak betűk: " + csakbetuk);
for (int i = 0; i < szo.Length; i++)
{
prim = (char)(csakbetuk[i]);
if (csakbetuk[i] > 1)
{
for (i = 2; i <= Math.Sqrt(csakbetuk[i]); i++)
{
if (csakbetuk[i] % i == 0)
{
//Console.WriteLine("Nem prím! ");
break;
}
}
}
if (i > Math.Sqrt(csakbetuk[i]))
{
Console.WriteLine(csakbetuk[i]);
break;
}
}
Console.WriteLine("A szó kiválogatva: " + csakbetuk);
Console.ReadKey();
}
}
}
|
using System;
using System.Collections.Generic;
namespace PopulationFitness.Models
{
public class Epochs
{
public readonly List<Epoch> All;
public Epochs()
{
All = new List<Epoch>();
}
/***
* Adds an epoch with the specified start year.
* Sets the end year of the preceding epoch to the year
* before the start of this epoch (if there is a previous epoch)
*
* @param epoch
*/
public void AddNextEpoch(Epoch epoch)
{
if (All.Count > 0)
{
Last.EndYear = epoch.StartYear - 1;
epoch.PrevEnvironmentCapacity = Last.EnvironmentCapacity;
}
else
{
epoch.PrevEnvironmentCapacity = epoch.EnvironmentCapacity;
}
All.Add(epoch);
}
public void AddAll(List<Epoch> epochs)
{
foreach (Epoch e in epochs)
{
AddNextEpoch(e);
}
}
/***
* Set the end year of the readonly epoch
*
* @param last_year
*/
public void SetFinalEpochYear(int last_year)
{
Last.EndYear = last_year;
}
/***
*
* @return the last epoch
*/
public Epoch Last
{
get
{
return All[All.Count - 1];
}
}
public Epoch First
{
get
{
return All[0];
}
}
/**
* Reduces the populations for all epochs by the same ratio
*
* P' = P/ratio
*
* @param ratio
*/
public void ReducePopulation(int ratio)
{
foreach (Epoch epoch in All)
{
epoch.ReducePopulation(ratio);
}
}
/**
* Increases the populations for all epochs by the same ratio
*
* P' = P * ratio
*
* @param ratio
*/
public void IncreasePopulation(int ratio)
{
foreach (Epoch epoch in All)
{
epoch.IncreasePopulation(ratio);
}
}
public void PrintFitnessFactors()
{
foreach (Epoch epoch in All)
{
Console.Write("Epoch ");
Console.Write(epoch.StartYear);
Console.Write(" f=");
Console.WriteLine(epoch.Fitness());
}
}
}
}
|
using UnityEngine;
public class EnterDoor : MonoBehaviour {
[SerializeField]
string direction;
// Update is called once per frame
void OnCollisionEnter2D(Collision2D col) {
if (col.gameObject.tag == "Player") {
/*This script used for reference, Shouldn't be using it.
* GameObject dungeon = GameObject.FindGameObjectWithTag("Dungeon");
DungeonGeneration dungeonGeneration = dungeon.GetComponent<DungeonGeneration> ();
Room room = dungeonGeneration.CurrentRoom();
dungeonGeneration.MoveToRoom(room.Neighbor(this.direction));
SceneManager.LoadScene("RoomGenerator");
*/
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Pe.Stracon.SGC.Aplicacion.TransferObject.Response.Contractual
{
/// <summary>
/// Representa el objeto response de Bienes
/// </summary>
/// <remarks>
/// Creación : GMD 20150803 <br />
/// Modificación : <br />
/// </remarks>
public class ReporteBienesContratoResponse
{
/// <summary>
/// Código de Unidad Operativa
/// </summary>
public string CodigoUnidadOperativa { get; set; }
/// <summary>
/// Código de Tipo de Bien
/// </summary>
public string CodigoTipoBien { get; set; }
/// <summary>
/// Ruc de Proveedor
/// </summary>
public string RucProveedor { get; set; }
/// <summary>
/// Nombre de Proveedor
/// </summary>
public string NombreProveedor { get; set; }
/// <summary>
/// Número de Contrato
/// </summary>
public string NumeroContrato { get; set; }
/// <summary>
/// Número de Serie
/// </summary>
public string NumeroSerie { get; set; }
/// <summary>
/// Mes
/// </summary>
public string Mes { get; set; }
/// <summary>
/// Ano
/// </summary>
public string Ano { get; set; }
}
}
|
// <copyright file="GTcpClient.cs" company="Firoozeh Technology LTD">
// Copyright (C) 2019 Firoozeh Technology LTD. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// </copyright>
/**
* @author Alireza Ghodrati
*/
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using FiroozehGameService.Core.Socket.PacketHelper;
using FiroozehGameService.Handlers;
using FiroozehGameService.Models;
using FiroozehGameService.Models.BasicApi;
using FiroozehGameService.Models.Enums.GSLive;
using FiroozehGameService.Models.EventArgs;
using FiroozehGameService.Models.GSLive.Command;
using Timer = System.Timers.Timer;
namespace FiroozehGameService.Core.Socket
{
internal abstract class GTcpClient
{
internal EventHandler<SocketDataReceived> DataReceived;
protected void OnDataReceived(SocketDataReceived arg)
{
DataReceived?.Invoke(this, arg);
}
protected void OnClosed(ErrorArg errorArg)
{
IsAvailable = false;
if (Type == GSLiveType.Command)
CommandEventHandlers.GsCommandClientError?.Invoke(null, new GameServiceException(errorArg.Error));
else TurnBasedEventHandlers.GsTurnBasedClientError?.Invoke(null, new GameServiceException(errorArg.Error));
}
internal abstract void Init(CommandInfo info, string cipher);
internal abstract void Send(Packet packet);
internal abstract Task SendAsync(Packet packet);
protected abstract Task SendAsync(byte[] payload);
internal abstract void AddToSendQueue(Packet packet);
protected abstract void Suspend();
internal abstract void StartReceiving();
internal abstract void StartSending();
internal abstract void StopReceiving(bool isGraceful);
internal abstract bool IsConnected();
#region Fields
protected const short CommandTimeOutWait = 700;
protected const short TurnTimeOutWait = 500;
protected const short SendQueueInterval = 100;
protected const short TcpTimeout = 2000;
protected const int BufferOffset = 0;
protected int BufferReceivedBytes = 0;
private const short BufferCapacity = 8192;
protected Thread RecvThread;
protected Timer SendQueueTimer;
protected CommandInfo CommandInfo;
protected Area Area;
protected string Key;
protected bool IsAvailable, IsSendingQueue;
protected GSLiveType Type;
protected CancellationTokenSource OperationCancellationToken;
protected readonly byte[] Buffer = new byte[BufferCapacity];
protected readonly object SendTempQueueLock = new object();
protected readonly StringBuilder DataBuilder = new StringBuilder();
protected readonly List<Packet> SendQueue = new List<Packet>();
protected readonly List<Packet> SendTempQueue = new List<Packet>();
protected readonly IValidator PacketValidator = new JsonDataValidator();
protected readonly IDeserializer PacketDeserializer = new PacketDeserializer();
protected readonly ISerializer PacketSerializer = new PacketSerializer();
#endregion
}
} |
namespace com.Sconit.Entity.SI.SD_ORD
{
using System;
using System.Collections.Generic;
[Serializable]
public class InspectDetail
{
public Int32 Id { get; set; }
public string InspectNo { get; set; }
public Int32 Sequence { get; set; }
public string Item { get; set; }
public string ItemDescription { get; set; }
public string ReferenceItemCode { get; set; }
public Decimal UnitCount { get; set; }
public string Uom { get; set; }
public string BaseUom { get; set; }
public Decimal UnitQty { get; set; }
public string HuId { get; set; }
public string LotNo { get; set; }
public string LocationFrom { get; set; }
public string CurrentLocation { get; set; }
public Decimal InspectQty { get; set; }
public Decimal QualifyQty { get; set; }
public Decimal RejectQty { get; set; }
public Boolean IsJudge { get; set; }
#region 辅助字段
public decimal CurrentQty { get; set; }
public decimal Carton { get; set; }
#endregion
}
}
|
using Abp.AspNetCore.Mvc.Controllers;
namespace Dg.Fifth.Web.Controllers
{
public abstract class FifthControllerBase: AbpController
{
protected FifthControllerBase()
{
LocalizationSourceName = FifthConsts.LocalizationSourceName;
}
}
} |
using System;
using SFA.DAS.ProviderCommitments.Infrastructure.OuterApi.Types;
namespace SFA.DAS.ProviderCommitments.Infrastructure.OuterApi.Requests.DraftApprenticeships
{
public class GetEditDraftApprenticeshipRequest : IGetApiRequest
{
public long ProviderId { get; }
public long CohortId { get; }
public long DraftApprenticeshipId { get; }
public string CourseCode { get; }
public GetEditDraftApprenticeshipRequest(long providerId, long cohortId, long draftApprenticeshipId, string courseCode)
{
ProviderId = providerId;
CohortId = cohortId;
DraftApprenticeshipId = draftApprenticeshipId;
CourseCode = courseCode;
}
public string GetUrl => $"provider/{ProviderId}/unapproved/{CohortId}/apprentices/{DraftApprenticeshipId}/edit?courseCode={CourseCode}";
}
public class GetEditDraftApprenticeshipResponse
{
public Guid? ReservationId { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public DateTime? DateOfBirth { get; set; }
public string Email { get; set; }
public string Uln { get; set; }
public DeliveryModel DeliveryModel { get; set; }
public string CourseCode { get; set; }
public string StandardUId { get; set; }
public string CourseName { get; set; }
public bool HasStandardOptions { get; set; }
public string TrainingCourseOption { get; set; }
public DateTime? StartDate { get; set; }
public DateTime? ActualStartDate { get; set; }
public DateTime? EndDate { get; set; }
public int? Cost { get; set; }
public int? EmploymentPrice { get; set; }
public DateTime? EmploymentEndDate { get; set; }
public string EmployerReference { get; set; }
public string ProviderReference { get; set; }
public long ProviderId { get; set; }
public long AccountLegalEntityId { get; set; }
public string ProviderName { get; set; }
public string LegalEntityName { get; set; }
public bool IsContinuation { get; set; }
public bool HasMultipleDeliveryModelOptions { get; set; }
public bool HasUnavailableDeliveryModel { get; set; }
public bool? RecognisePriorLearning { get; set; }
public int? DurationReducedBy { get; set; }
public int? PriceReducedBy { get; set; }
public bool RecognisingPriorLearningStillNeedsToBeConsidered { get; set; }
public bool RecognisingPriorLearningExtendedStillNeedsToBeConsidered { get; set; }
public bool? IsOnFlexiPaymentPilot { get; set; }
public bool? EmailAddressConfirmed { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using NetNote.Models;
using NetNote.ViewModels;
namespace NetNote.Pages
{
public class LoginModel : PageModel
{
private SignInManager<NoteUser> _signInManager;
public LoginModel(SignInManager<NoteUser> signInManager)
{
_signInManager = signInManager;
}
[BindProperty]
public LoginViewModel Login { get; set; }
[BindProperty(SupportsGet =true)]
public string ReturnUrl { get; set; }
public async Task<IActionResult> OnPostAsync()
{
if (!ModelState.IsValid)
{
return Page();
}
var result = await _signInManager.PasswordSignInAsync(Login.UserName, Login.Password, Login.RememberMe, lockoutOnFailure: false);
if (result.Succeeded)
{
return RedirectToPage("./Index");
}
else
{
ModelState.AddModelError("", "Óû§Ãû»òÃÜÂë´íÎó");
return Page();
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace Mettes_Planteskole
{
public partial class kasseAfslut : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
//slet lige session
string navn = ProduktKurven.Kurven.KurvensNavnISession;
Session.Remove(navn);
Response.Redirect("default.aspx");
}
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public enum PrimaryWeaponType {
Staff,
Sword
}
|
using Alabo.Framework.Core.Enums.Enum;
using Alabo.Framework.Themes.Domain.Enums;
using System.ComponentModel.DataAnnotations;
namespace Alabo.Framework.Themes.Dtos {
/// <summary>
/// 终端页面获取
/// </summary>
public class ClientPageInput {
/// <summary>
/// 终端配置
/// </summary>
[Display(Name = "终端配置")]
public ClientType ClientType { get; set; }
/// <summary>
/// 类型
/// </summary>
public ThemeType Type { get; set; }
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ObjectInFrustum : MonoBehaviour
{
private Renderer _renderer;
private Camera _cam;
protected virtual void Start()
{
_renderer = GetComponent<Renderer>();
_cam = Camera.main;
}
public bool IsObjectInFrustum()
{
Plane[] planes = GeometryUtility.CalculateFrustumPlanes(_cam);
return GeometryUtility.TestPlanesAABB(planes, _renderer.bounds);
}
} |
using System;
namespace Казино_777
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Дабро пожаловать в Казино 777)");
Console.WriteLine("\nНапишите ваше Имя");
string ima = Console.ReadLine();
Console.Clear();
Console.WriteLine("Напишите возраст");
int a;
a = int.Parse(Console.ReadLine());
Console.Clear();
if (a < 18)
{
Console.WriteLine("Лица до 18 лет к игре не допускаются!");
}
else
{
Console.WriteLine("Введите размер ставки(от 1 до 1000)");
}
int c;
c = int.Parse(Console.ReadLine());
Random r = new Random();
if (c < 500)
{
int num = r.Next(1500);
Console.Clear();
if (num == 100)
{
Console.WriteLine($"111\n\nУху! {ima} Вы выйграли!!!!!!");
}
else if (num == 200)
{
Console.WriteLine($"222\n\nУху! {ima} Вы выйграли!!!!!!");
}
else if (num == 300)
{
Console.WriteLine($"333\n\nУху! {ima} Вы выйграли!!!!!!");
}
else if (num == 400)
{
Console.WriteLine($"444\n\nУху! {ima} Вы выйграли!!!!!!");
}
else if (num == 500)
{
Console.WriteLine($"555\n\nУху! {ima} Вы выйграли!!!!!!");
}
else if (num == 600)
{
Console.WriteLine($"666\n\nУху! {ima} Вы выйграли!!!!!!");
}
else if (num == 1500)
{
Console.WriteLine($"777\n\nУху! {ima} Вы выйграли!!!!!!");
}
else if (num == 800)
{
Console.WriteLine($"888\n\nУху! {ima} Вы выйграли!!!!!!");
}
else if (num == 900)
{
Console.WriteLine($"999\n\nУху! {ima} Вы выйграли!!!!!!");
}
else
{
Console.WriteLine("К сожелению вы проиграли!");
}
}
else if (c > 500)
{
int num = r.Next(150);
Console.Clear();
if (num == 10)
{
Console.WriteLine($"011\nУху!");
}
else if (num == 20)
{
Console.WriteLine($"822\nУху!");
}
else if (num == 30)
{
Console.WriteLine($"334\nУху!");
}
else if (num == 40)
{
Console.WriteLine($"044\nУху!");
}
else if (num == 50)
{
Console.WriteLine($"044\nУху!");
}
else if (num == 60)
{
Console.WriteLine($"044\nУху!");
}
else if (num == 150)
{
Console.WriteLine($"044\nУху!");
}
else if (num == 80)
{
Console.WriteLine($"044\nУху!");
}
else if (num == 90)
{
Console.WriteLine($"044\nУху!");
}
else
{
Console.WriteLine("К сожелению вы проиграли!");
}
}
}
}
}
|
using GalaSoft.MvvmLight;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MuggleTranslator.ViewModel
{
public class MainViewModel : ViewModelBase
{
#region BindingProperty
private bool _locked;
public bool Locked
{
get => _locked;
set
{
_locked = value;
RaisePropertyChanged(nameof(Locked));
}
}
#endregion
}
}
|
using Microsoft.EntityFrameworkCore;
namespace SavySodaDemo.Data
{
public class RazorPagesGameContext : DbContext
{
public RazorPagesGameContext (
DbContextOptions<RazorPagesGameContext> options)
: base(options)
{
}
public DbSet<SavySodaDemo.Models.Game> Game { get; set; }
}
}
|
namespace HeadFirstExamples.DuckBehavior.Contracts
{
public interface IFlyBehavior
{
void Fly();
}
}
|
using Pe.Stracon.SGC.Infraestructura.QueryModel.Base;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Pe.Stracon.SGC.Infraestructura.QueryModel.Contractual
{
/// <summary>
/// Representa los datos de la Variable
/// </summary>
/// <remarks>
/// Creación: GMD 20150527 <br />
/// Modificación: <br />
/// </remarks>
public class VariableLogic : Logic
{
/// <summary>
/// Código de Variable
/// </summary>
public Guid CodigoVariable { get; set; }
/// <summary>
/// Código de Plantilla
/// </summary>
public Guid? CodigoPlantilla { get; set; }
/// <summary>
/// Identificador
/// </summary>
public string Identificador { get; set; }
/// <summary>
/// Nombre
/// </summary>
public string Nombre { get; set; }
/// <summary>
/// Código de Tipo de Variable
/// </summary>
public string CodigoTipo { get; set; }
/// <summary>
/// Indicador de Variable Global
/// </summary>
public bool? IndicadorGlobal { get; set; }
/// <summary>
/// Descripción de Tipo de Variable
/// </summary>
public string DescripcionTipoVariable { get; set; }
/// <summary>
/// Indicador de Variable de Sistema
/// </summary>
public bool IndicadorVariableSistema { get; set; }
/// <summary>
/// Descripcion
/// </summary>
public string Descripcion { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Data;
using Capa_de_Negocios_ONG_SYS;
namespace ONG_SYS
{
/// <summary>
/// Lógica de interacción para FRM_Administracion_Proveedores.xaml
/// </summary>
public partial class FRM_Administracion_Proveedores : Window
{
private string idProveedor = null;
CN_Proveedores objetoCN = new CN_Proveedores();
public FRM_Administracion_Proveedores()
{
InitializeComponent();
ListarProvincia();
}
private void MostrarProveedores()
{
CN_Proveedores objec = new CN_Proveedores();
dgvProveedores.SetBinding(ItemsControl.ItemsSourceProperty, new Binding { Source = objec.mostrarProveedores() });
}
public void ListarProvincia()
{
CN_Proveedores objCNPro = new CN_Proveedores();
cmb_Provincia.ItemsSource = objCNPro.GetProvincias();
this.cmb_Provincia.DisplayMemberPath = "Nombre";
this.cmb_Provincia.SelectedValuePath = "Id";
}
private void limpiarForm()
{
TXT_ID_PROVEEDOR.Clear();
TXT_Nombre_Proveedor_P.Clear();
TXT_RUC.Clear();
cmb_Provincia.Text = "";
TXT_Ciudad.Clear();
TXT_direccion.Clear();
TXT_Telefono.Clear();
}
private void btn_Regresar_P_Click(object sender, RoutedEventArgs e)
{
this.Hide();
FRM_MENU_PRINCIPAL paginaanteriorP = new FRM_MENU_PRINCIPAL();
paginaanteriorP.ShowDialog();
this.Close();
}
private void TXT_RUC_PreviewTextInput(object sender, TextCompositionEventArgs e)
{
if (!char.IsDigit(e.Text, e.Text.Length - 1))
e.Handled = true;
}
private void TXT_Telefono_PreviewTextInput(object sender, TextCompositionEventArgs e)
{
if (!char.IsDigit(e.Text, e.Text.Length - 1))
e.Handled = true;
}
private void TXT_Ciudad_PreviewTextInput(object sender, TextCompositionEventArgs e)
{
if (!System.Text.RegularExpressions.Regex.IsMatch(e.Text, "^[a-zA-Z]"))
{
e.Handled = true;
}
}
private void btn_Agregar_NS_Click(object sender, RoutedEventArgs e)
{
CN_Proveedores NPro = new CN_Proveedores();
if (VERIFICA_IDENTIFICACION.VerificaIdentificacion(TXT_RUC.Text) == false || TXT_RUC.Text.Length < 13)
{
MessageBox.Show("Verifique el ruc del proveedor");
return;
}
else if (string.IsNullOrEmpty(TXT_Nombre_Proveedor_P.Text))
{
MessageBox.Show("Verifique que el campo Nombre del proveedor se encuentre lleno");
return;
}
else if (string.IsNullOrEmpty(TXT_RUC.Text))
{
MessageBox.Show("Verifique que el campo RUC se encuentre lleno");
return;
}
else if (cmb_Provincia.SelectedIndex == -1)
{
MessageBox.Show("Verifique que se haya escogido una Provincia");
return;
}
else if (string.IsNullOrEmpty(TXT_Ciudad.Text))
{
MessageBox.Show("Verifique que el campo Ciudad se encuentre lleno");
return;
}
else if (string.IsNullOrEmpty(TXT_direccion.Text))
{
MessageBox.Show("Verifique que el campo Dirección se encuentre lleno");
return;
}
else if (string.IsNullOrEmpty(TXT_Telefono.Text))
{
MessageBox.Show("Verifique que el campo Teléfono se encuentre lleno");
return;
}
else if (VERIFICA_IDENTIFICACION.VerificaIdentificacion(TXT_RUC.Text) == true)
{
NPro.InsertarProv(TXT_Nombre_Proveedor_P.Text, TXT_RUC.Text, Convert.ToInt32(cmb_Provincia.SelectedValue), TXT_Ciudad.Text, TXT_direccion.Text, TXT_Telefono.Text);
MessageBox.Show("Proveedor Ingresado Correctamente");
//MostrarProveedores();
limpiarForm();
return;
}
}
private void btn_ELIMINAR_P_Click(object sender, RoutedEventArgs e)
{
if (dgvProveedores.SelectedItem == null)
{
MessageBox.Show("Verifique si se selecciono algún campo");
}
else
{
try
{
objetoCN.EliminarProv(idProveedor);
MessageBox.Show("Se ha eliminado correctamente");
dgvProveedores.SetBinding(ItemsControl.ItemsSourceProperty, new Binding { Source = new DataTable() });
limpiarForm();
//MostrarProveedores();
}
catch (Exception ex)
{
MessageBox.Show("No se puede eliminar al proveedor porque tiene productos que lo incluyen");
}
}
}
private void btn_ACTUALIZAR_S_Click(object sender, RoutedEventArgs e)
{
if (VERIFICA_IDENTIFICACION.VerificaIdentificacion(TXT_RUC.Text) == false || TXT_RUC.Text.Length < 13)
{
MessageBox.Show("Verifique el ruc del proveedor");
return;
}
else if (string.IsNullOrEmpty(TXT_Nombre_Proveedor_P.Text))
{
MessageBox.Show("Verifique que el campo Nombre del proveedor se encuentre lleno");
return;
}
else if (string.IsNullOrEmpty(TXT_RUC.Text))
{
MessageBox.Show("Verifique que el campo RUC se encuentre lleno");
return;
}
else if (cmb_Provincia.SelectedIndex == -1)
{
MessageBox.Show("Verifique que se haya escogido una Provincia");
return;
}
else if (string.IsNullOrEmpty(TXT_Ciudad.Text))
{
MessageBox.Show("Verifique que el campo Ciudad se encuentre lleno");
return;
}
else if (string.IsNullOrEmpty(TXT_direccion.Text))
{
MessageBox.Show("Verifique que el campo Dirección se encuentre lleno");
return;
}
else if (string.IsNullOrEmpty(TXT_Telefono.Text))
{
MessageBox.Show("Verifique que el campo Teléfono se encuentre lleno");
return;
}
else if (dgvProveedores.SelectedItem == null)
{
MessageBox.Show("Verifique que algun dato se encuentre seleccionado");
return;
}
else if (VERIFICA_IDENTIFICACION.VerificaIdentificacion(TXT_RUC.Text) == true)
{
objetoCN.EditarProd(TXT_Nombre_Proveedor_P.Text, TXT_RUC.Text, Convert.ToInt32(cmb_Provincia.SelectedValue), TXT_Ciudad.Text, TXT_direccion.Text, TXT_Telefono.Text, idProveedor);
MessageBox.Show("Se actualizo correctamente");
// MostrarProveedores();
limpiarForm();
btn_Agregar_NS.IsEnabled = true;
btn_ACTUALIZAR_S.IsEnabled = false;
btn_ELIMINAR_P.IsEnabled = false;
btn_Regresar_P.IsEnabled = true;
}
}
private void dgvProveedores_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
DataRowView rowView = dgvProveedores.SelectedItem as DataRowView;
if (dgvProveedores.SelectedItem != null)
{
}
if (rowView != null)
{
cmb_Provincia.Text = rowView[3].ToString();
TXT_Nombre_Proveedor_P.Text = rowView[1].ToString();
TXT_RUC.Text = rowView[2].ToString();
TXT_Ciudad.Text = rowView[4].ToString();
TXT_direccion.Text = rowView[5].ToString();
TXT_Telefono.Text = rowView[6].ToString();
TXT_ID_PROVEEDOR.Text = rowView[0].ToString();
idProveedor = rowView[0].ToString();
btn_Agregar_NS.IsEnabled = false;
btn_ACTUALIZAR_S.IsEnabled = true;
btn_ELIMINAR_P.IsEnabled = true;
btn_Regresar_P.IsEnabled = true;
TXT_ID_PROVEEDOR.IsEnabled = false;
TXT_Nombre_Proveedor_P.IsEnabled = false;
TXT_RUC.IsEnabled = false;
cmb_Provincia.IsEnabled = true;
TXT_Ciudad.IsEnabled = true;
TXT_direccion.IsEnabled = true;
TXT_Telefono.IsEnabled = true;
}
else
{
btn_Agregar_NS.IsEnabled = true;
btn_ACTUALIZAR_S.IsEnabled = false;
btn_ELIMINAR_P.IsEnabled = false;
btn_Regresar_P.IsEnabled = true;
TXT_ID_PROVEEDOR.IsEnabled = false;
TXT_Nombre_Proveedor_P.IsEnabled = true;
TXT_RUC.IsEnabled = true;
cmb_Provincia.IsEnabled = true;
TXT_Ciudad.IsEnabled = true;
TXT_direccion.IsEnabled = true;
TXT_Telefono.IsEnabled = true;
}
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
btn_Agregar_NS.IsEnabled = true;
btn_ACTUALIZAR_S.IsEnabled = false;
btn_ELIMINAR_P.IsEnabled = false;
btn_Regresar_P.IsEnabled = true;
}
private void dgvProveedores_Loaded(object sender, RoutedEventArgs e)
{
//MostrarProveedores();
}
private void BTN_BuscarProveedor_Click(object sender, RoutedEventArgs e)
{
dgvProveedores.SetBinding(ItemsControl.ItemsSourceProperty, new Binding { Source = objetoCN.Buscar(TXT_BUSCAR_Proveedor.Text) });
limpiarForm();
}
private void TXT_BUSCAR_Proveedor_LostFocus(object sender, RoutedEventArgs e)
{
if (string.IsNullOrEmpty(TXT_BUSCAR_Proveedor.Text))
{
TXT_BUSCAR_Proveedor.Visibility = System.Windows.Visibility.Collapsed;
Waterfall_TXT_BUSCAR_Proveedor.Visibility = System.Windows.Visibility.Visible;
}
}
private void Waterfall_TXT_BUSCAR_Proveedor_GotFocus(object sender, RoutedEventArgs e)
{
Waterfall_TXT_BUSCAR_Proveedor.Visibility = System.Windows.Visibility.Collapsed;
TXT_BUSCAR_Proveedor.Visibility = System.Windows.Visibility.Visible;
TXT_BUSCAR_Proveedor.Focus();
}
}
}
|
using ISE.Framework.Server.Core.DataAccessBase;
using ISE.SM.Common.DTO;
using ISE.SM.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ISE.SM.DataAccess
{
public class SessionTDataAccess : TDataAccess<SecuritySession, SecuritySessionDto, SecuritySessionRepository>
{
public SessionTDataAccess()
: base(new SecuritySessionRepository())
{
}
}
}
|
using Pe.Stracon.SGC.Aplicacion.TransferObject.Base;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Pe.Stracon.SGC.Aplicacion.TransferObject.Request.Contractual
{
/// <summary>
/// Representa el objeto response de Proceso Auditoria
/// </summary>
/// <remarks>
/// Creación : GMD 20150520 <br />
/// Modificación : <br />
/// </remarks>
public class ProcesoAuditoriaResponse : Filtro
{
/// <summary>
/// Codigo Auditoria
/// </summary>
public string CodigoAuditoria { get; set; }
/// <summary>
/// Codigo Unidad Operativa
/// </summary>
public string CodigoUnidadOperativa { get; set; }
/// <summary>
/// Descripcion Unidad Operativa
/// </summary>
public string DescripcionUnidadOperativa { get; set; }
/// <summary>
/// Fecha Planificada
/// </summary>
public DateTime FechaPlanificada { get; set; }
/// <summary>
/// Fecha Planificada String
/// </summary>
public string FechaPlanificadaString { get; set; }
/// <summary>
/// Fecha Ejecucion
/// </summary>
public DateTime? FechaEjecucion { get; set; }
/// <summary>
/// Fecha Planificada String
/// </summary>
public string FechaEjecucionString { get; set; }
/// <summary>
/// Cantidad Auditadas
/// </summary>
public Int16? CantidadAuditadas { get; set; }
/// <summary>
/// Cantidad Observadas
/// </summary>
public Int16? CantidadObservadas { get; set; }
/// <summary>
/// Resultado Auditoria
/// </summary>
public string ResultadoAuditoria { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace HandlingWordRules
{
public class cntEinWrdsStartB : ICountingRulesStrategy
{
//Requirement 2/Rule 2 : For all the words starts with “b” or “B”, count the total number of “e” or “E” in the words, save the
//result to file “count_of_e_in_words_starting_with_b.txt”
//The method: ruleImplementation gets implemented with the business requirement
public float ruleImplementation(List<string> inputWordsList)
{
var filteredList = inputWordsList.AsEnumerable().Where(lambda => lambda.StartsWith("B"));
float totalEinFilteredList = filteredList.AsEnumerable().Where(x => x.Contains("e")).LongCount();
return totalEinFilteredList;
string[] lines = { totalEinFilteredList.ToString() };
System.IO.File.WriteAllLines(@"C:\Users\Public\TestFolder\count_of_e_in_words_starting_with_b.txt", lines);
throw new NotImplementedException();
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class ShadowingRenderer : MonoBehaviour
{
public float maxTime;
public float time;
public Image timeBar;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
timeBar.fillAmount = time / maxTime;
}
}
|
using gView.Framework.UI;
using System;
namespace gView.Win.DataSources.GeoJson.UI.ExplorerObjects
{
class GeoJsonServiceConnectionsIcon : IExplorerIcon
{
#region IExplorerIcon Members
public Guid GUID
{
get
{
return new Guid("B2533892-923D-4FC7-AD45-115855D67C42");
}
}
public System.Drawing.Image Image
{
get
{
return global::gView.Win.DataSources.GeoJson.UI.Properties.Resources.json_16;
}
}
#endregion
}
class GeoJsonServiceNewConnectionIcon : IExplorerIcon
{
#region IExplorerIcon Members
public Guid GUID
{
get
{
return new Guid("CD88930C-1110-49C4-9F2A-A641E416E3A7");
}
}
public System.Drawing.Image Image
{
get
{
return global::gView.Win.DataSources.GeoJson.UI.Properties.Resources.gps_point;
}
}
#endregion
}
public class GeoJsonServicePointIcon : IExplorerIcon
{
#region IExplorerIcon Members
public Guid GUID
{
get { return new Guid("D7256D73-2AC9-45F5-AF2B-E60DCFFC0041"); }
}
public System.Drawing.Image Image
{
get { return global::gView.Win.DataSources.GeoJson.UI.Properties.Resources.img_32; }
}
#endregion
}
public class GeoJsonServiceLineIcon : IExplorerIcon
{
#region IExplorerIcon Members
public Guid GUID
{
get { return new Guid("02B673EB-463B-4C73-AA8B-3FFBFE31E9A6"); }
}
public System.Drawing.Image Image
{
get { return global::gView.Win.DataSources.GeoJson.UI.Properties.Resources.img_33; }
}
#endregion
}
public class GeoJsonServicePolygonIcon : IExplorerIcon
{
#region IExplorerIcon Members
public Guid GUID
{
get { return new Guid("02B673EB-463B-4C73-AA8B-3FFBFE31E9A6"); }
}
public System.Drawing.Image Image
{
get { return global::gView.Win.DataSources.GeoJson.UI.Properties.Resources.img_34; }
}
#endregion
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using TypeGen.AcceptanceTest.GeneratorTestingUtils;
using TypeGen.AcceptanceTest.SelfContainedGeneratorTest;
using TypeGen.Core.Test.GeneratorTestingUtils;
using TypeGen.Core.TypeAnnotations;
using Xunit;
using Gen = TypeGen.Core.Generator;
namespace TypeGen.AcceptanceTest.Issues
{
public class CircularGenericConstraint
{
/// <summary>
/// Looks into generating classes and interfaces with circular type constraints
/// </summary>
/// <param name="type"></param>
/// <returns></returns>
[Theory]
[InlineData(typeof(RecursiveConstraintClass<>), @"TypeGen.AcceptanceTest.Issues.CircularGenericConstraint.Expected.RecursiveConstraintClass.ts")]
[InlineData(typeof(IRecursiveConstraintInterface<>), @"TypeGen.AcceptanceTest.Issues.CircularGenericConstraint.Expected.IRecursiveConstraintInterface.ts")]
[InlineData(typeof(IRecursiveConstraintInterfaceWithClassConstraint<>), @"TypeGen.AcceptanceTest.Issues.CircularGenericConstraint.Expected.IRecursiveConstraintInterfaceWithClassConstraint.ts")]
[InlineData(typeof(IRecursiveConstraintInterfaceWithStructConstraint<>), @"TypeGen.AcceptanceTest.Issues.CircularGenericConstraint.Expected.IRecursiveConstraintInterfaceWithStructConstraint.ts")]
[InlineData(typeof(IMultipleConstraintInterface<>), @"TypeGen.AcceptanceTest.Issues.CircularGenericConstraint.Expected.IMultipleConstraintInterface.ts")]
[InlineData(typeof(ICicrularConstraintInterface<,>), @"TypeGen.AcceptanceTest.Issues.CircularGenericConstraint.Expected.ICicrularConstraintInterface.ts")]
public async Task GeneratesCorrectly(Type type, string expectedLocation)
{
await new SelfContainedGeneratorTest.SelfContainedGeneratorTest().TestGenerate(type, expectedLocation);
}
}
}
|
//
// --------------------------------------------------------------------------
// Gurux Ltd
//
//
//
// Filename: $HeadURL: svn://utopia/projects/GXDeviceEditor/Development/AddIns/DLMS/GXObisEditor/ObisMainForm.cs $
//
// Version: $Revision: 870 $,
// $Date: 2009-09-29 17:21:48 +0300 (ti, 29 syys 2009) $
// $Author: airija $
//
// Copyright (c) Gurux Ltd
//
//---------------------------------------------------------------------------
//
// DESCRIPTION
//
// This file is a part of Gurux Device Framework.
//
// Gurux Device Framework is Open Source software; you can redistribute it
// and/or modify it under the terms of the GNU General Public License
// as published by the Free Software Foundation; version 2 of the License.
// Gurux Device Framework is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
// See the GNU General Public License for more details.
//
// This code is licensed under the GNU General Public License v2.
// Full text may be retrieved at http://www.gnu.org/licenses/gpl-2.0.txt
//---------------------------------------------------------------------------
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
namespace GXObisEditor
{
/// <summary>
/// Summary description for ObisMainForm.
/// </summary>
public class ObisMainForm : System.Windows.Forms.Form
{
#region definitions
private System.Windows.Forms.Panel panel1;
private System.Windows.Forms.Panel panel2;
private System.Windows.Forms.Splitter splitter1;
private System.Windows.Forms.TreeView ObisTree;
private System.Windows.Forms.MainMenu mainMenu1;
private System.Windows.Forms.MenuItem FileMnu;
private System.Windows.Forms.MenuItem OpenMnu;
private System.Windows.Forms.MenuItem SaveMnu;
private System.Windows.Forms.MenuItem SplitterMnu;
private System.Windows.Forms.MenuItem ExitMnu;
private System.Windows.Forms.Label NameLbl;
private System.Windows.Forms.TextBox NameTb;
private System.Windows.Forms.TextBox TypeTb;
private System.Windows.Forms.Label TypeLbl;
private System.Windows.Forms.TextBox DescriptionTb;
private System.Windows.Forms.Label DescriptionLbl;
private System.Windows.Forms.ComboBox InterfaceCb;
private System.Windows.Forms.TextBox InterfaceTb;
private System.Windows.Forms.Button RemoveInterfaceBtn;
private System.Windows.Forms.Button AddInterfaceBtn;
private System.Windows.Forms.Label InterfacesLbl;
private System.Windows.Forms.Button ApplyBtn;
private System.Windows.Forms.GroupBox groupBox1;
private System.Windows.Forms.MenuItem NewMnu;
private System.ComponentModel.IContainer components;
private System.Windows.Forms.ToolBar toolBar1;
private System.Windows.Forms.ToolBarButton OpenTBtn;
private System.Windows.Forms.ToolBarButton SaveTBtn;
private System.Windows.Forms.ToolBarButton Split1TBtn;
private System.Windows.Forms.ToolBarButton AddTBtn;
private System.Windows.Forms.ToolBarButton RemoveTBtn;
private System.Windows.Forms.MenuItem ToolsMnu;
private System.Windows.Forms.MenuItem AddMnu;
private System.Windows.Forms.MenuItem RemoveMnu;
private System.Windows.Forms.ToolBarButton NewTBtn;
private System.Windows.Forms.ImageList ToolBarImageList;
private System.Windows.Forms.ContextMenu contextMenu1;
private System.Windows.Forms.MenuItem AddContextMnu;
private System.Windows.Forms.MenuItem RemoveContextMnu;
private System.Windows.Forms.Button ResetBtn;
private System.Windows.Forms.MenuItem SaveAsMnu;
private ObisManufacturer m_Manufacturer = null;
bool m_ClearSaveFailed = false;
private System.Windows.Forms.TextBox PrimaryIDTb;
private System.Windows.Forms.Label PrimaryIDLbl;
private System.Windows.Forms.Label PrimaryIDSizeLbl;
private System.Windows.Forms.TextBox PrimaryIDSizeTb;
private System.Windows.Forms.TextBox SecondaryIDSizeTb;
private System.Windows.Forms.Label SecondaryIDSizeLbl;
private System.Windows.Forms.TextBox SecondaryIDTb;
private System.Windows.Forms.Label SecondaryIDLbl;
private System.Windows.Forms.CheckBox UseLNCb;
bool m_Dirty = false;
System.Resources.ResourceManager m_Resources = null;
private System.Windows.Forms.MenuItem TestMnu;
private System.Windows.Forms.MenuItem menuItem1;
private System.Windows.Forms.MenuItem LanguageMnu;
GuruxDLMS.CCDLMSOBISParser m_parser = null;
private System.Windows.Forms.TextBox LowAccessIDSizeTb;
private System.Windows.Forms.Label LowAccessIDSizeLbl;
private System.Windows.Forms.TextBox LowAccessIDTb;
private System.Windows.Forms.Label LowAccessIDLbl;
private System.Windows.Forms.TextBox HighAccessIDSizeTb;
private System.Windows.Forms.Label HighAccessIDSizeLbl;
private System.Windows.Forms.TextBox HighAccessIDTb;
private System.Windows.Forms.Label HighAccessIDLbl;
private System.Windows.Forms.CheckBox SupportNetworkSpecificSettingsCb;
string m_CurrentLanguage = string.Empty;
#endregion
public ObisMainForm()
{
//
// Required for Windows Form Designer support
//
InitializeComponent();
m_Resources = new System.Resources.ResourceManager("GXObisEditor.strings", this.GetType().Assembly);
UpdateResources();
Application.Idle += new EventHandler(Application_Idle);
m_parser = new GuruxDLMS.CCDLMSOBISParser();
SetupResources();
}
private void SetupResources()
{
string lang = null;
Microsoft.Win32.RegistryKey subKey = null;
Microsoft.Win32.RegistryKey key = Microsoft.Win32.Registry.CurrentUser.CreateSubKey("Software\\Gurux\\GXDeviceEditor");
if(key != null)
{
subKey = key.OpenSubKey("General");
}
lang = "en";
if(subKey != null)
{
lang = (string) subKey.GetValue("Language");
}
try
{
System.Threading.Thread.CurrentThread.CurrentUICulture = System.Threading.Thread.CurrentThread.CurrentCulture = System.Globalization.CultureInfo.CreateSpecificCulture(lang);
}
catch//Set english as default language.
{
lang = "en";
System.Threading.Thread.CurrentThread.CurrentUICulture = System.Threading.Thread.CurrentThread.CurrentCulture = System.Globalization.CultureInfo.CreateSpecificCulture(lang);
}
MenuItem item;
foreach(System.Globalization.CultureInfo it in GetAvailableLanguages())
{
string str = it.NativeName;
int len = str.IndexOf("(");
if (len > 0)
{
str = str.Substring(0, len);
}
item = this.LanguageMnu.MenuItems.Add(str);
item.Click += new System.EventHandler(this.OnChangeLanguage);
if (lang == it.TwoLetterISOLanguageName)
{
item.Checked = true;
}
}
UpdateResources();
}
/// <summary>
/// Update resources
/// </summary>
void UpdateResources()
{
this.Text = m_Resources.GetString("ApplicationTxt");
FileMnu.Text = m_Resources.GetString("FileTxt");
NewTBtn.Text = NewMnu.Text = m_Resources.GetString("NewTxt");
OpenTBtn.Text = OpenMnu.Text = m_Resources.GetString("OpenTxt");
SaveTBtn.Text = SaveMnu.Text = m_Resources.GetString("SaveTxt");
SaveAsMnu.Text = m_Resources.GetString("SaveAsTxt");
ExitMnu.Text = m_Resources.GetString("ExitTxt");
ToolsMnu.Text = m_Resources.GetString("ToolsTxt");
AddTBtn.Text = AddMnu.Text = m_Resources.GetString("AddTxt");
RemoveTBtn.Text = RemoveMnu.Text = m_Resources.GetString("RemoveTxt");
NameLbl.Text = m_Resources.GetString("NameTxt");
TypeLbl.Text = m_Resources.GetString("TypeTxt");
DescriptionLbl.Text = m_Resources.GetString("DecriptionTxt");
InterfacesLbl.Text = m_Resources.GetString("InterfacesTxt");
AddInterfaceBtn.Text = m_Resources.GetString("AddInterfaceTxt");
RemoveInterfaceBtn.Text = m_Resources.GetString("RemoveInterfaceTxt");
//Bad translations and couldn't come up with better ones
//PrimaryIDLbl.Text = m_Resources.GetString("PrimaryIDTxt");
//PrimaryIDSizeLbl.Text = m_Resources.GetString("PrimaryIDSizeTxt");
//SecondaryIDLbl.Text = m_Resources.GetString("SecondaryIDTxt");
//SecondaryIDSizeLbl.Text = m_Resources.GetString("SecondaryIDSizeTxt");
UseLNCb.Text = m_Resources.GetString("UseLNCbTxt");
SupportNetworkSpecificSettingsCb.Text = m_Resources.GetString("SupportNetworkSpecificSettingsTxt");
ApplyBtn.Text = m_Resources.GetString("ApplyTxt");
ResetBtn.Text = m_Resources.GetString("ResetTxt");
TestMnu.Text = m_Resources.GetString("TestObisCodesTxt");
LanguageMnu.Text = m_Resources.GetString("LanguageTxt");
}
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose( bool disposing )
{
if( disposing )
{
if (components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
System.Resources.ResourceManager resources = new System.Resources.ResourceManager(typeof(ObisMainForm));
this.panel1 = new System.Windows.Forms.Panel();
this.groupBox1 = new System.Windows.Forms.GroupBox();
this.SupportNetworkSpecificSettingsCb = new System.Windows.Forms.CheckBox();
this.HighAccessIDSizeTb = new System.Windows.Forms.TextBox();
this.HighAccessIDSizeLbl = new System.Windows.Forms.Label();
this.HighAccessIDTb = new System.Windows.Forms.TextBox();
this.HighAccessIDLbl = new System.Windows.Forms.Label();
this.LowAccessIDSizeTb = new System.Windows.Forms.TextBox();
this.LowAccessIDSizeLbl = new System.Windows.Forms.Label();
this.LowAccessIDTb = new System.Windows.Forms.TextBox();
this.LowAccessIDLbl = new System.Windows.Forms.Label();
this.UseLNCb = new System.Windows.Forms.CheckBox();
this.SecondaryIDSizeTb = new System.Windows.Forms.TextBox();
this.SecondaryIDSizeLbl = new System.Windows.Forms.Label();
this.SecondaryIDTb = new System.Windows.Forms.TextBox();
this.SecondaryIDLbl = new System.Windows.Forms.Label();
this.PrimaryIDSizeTb = new System.Windows.Forms.TextBox();
this.PrimaryIDSizeLbl = new System.Windows.Forms.Label();
this.PrimaryIDTb = new System.Windows.Forms.TextBox();
this.PrimaryIDLbl = new System.Windows.Forms.Label();
this.ResetBtn = new System.Windows.Forms.Button();
this.NameTb = new System.Windows.Forms.TextBox();
this.TypeTb = new System.Windows.Forms.TextBox();
this.TypeLbl = new System.Windows.Forms.Label();
this.InterfaceCb = new System.Windows.Forms.ComboBox();
this.RemoveInterfaceBtn = new System.Windows.Forms.Button();
this.NameLbl = new System.Windows.Forms.Label();
this.InterfacesLbl = new System.Windows.Forms.Label();
this.ApplyBtn = new System.Windows.Forms.Button();
this.DescriptionTb = new System.Windows.Forms.TextBox();
this.DescriptionLbl = new System.Windows.Forms.Label();
this.InterfaceTb = new System.Windows.Forms.TextBox();
this.AddInterfaceBtn = new System.Windows.Forms.Button();
this.panel2 = new System.Windows.Forms.Panel();
this.ObisTree = new System.Windows.Forms.TreeView();
this.contextMenu1 = new System.Windows.Forms.ContextMenu();
this.AddContextMnu = new System.Windows.Forms.MenuItem();
this.RemoveContextMnu = new System.Windows.Forms.MenuItem();
this.splitter1 = new System.Windows.Forms.Splitter();
this.mainMenu1 = new System.Windows.Forms.MainMenu();
this.FileMnu = new System.Windows.Forms.MenuItem();
this.NewMnu = new System.Windows.Forms.MenuItem();
this.OpenMnu = new System.Windows.Forms.MenuItem();
this.SaveMnu = new System.Windows.Forms.MenuItem();
this.SaveAsMnu = new System.Windows.Forms.MenuItem();
this.SplitterMnu = new System.Windows.Forms.MenuItem();
this.ExitMnu = new System.Windows.Forms.MenuItem();
this.ToolsMnu = new System.Windows.Forms.MenuItem();
this.AddMnu = new System.Windows.Forms.MenuItem();
this.RemoveMnu = new System.Windows.Forms.MenuItem();
this.TestMnu = new System.Windows.Forms.MenuItem();
this.menuItem1 = new System.Windows.Forms.MenuItem();
this.LanguageMnu = new System.Windows.Forms.MenuItem();
this.toolBar1 = new System.Windows.Forms.ToolBar();
this.NewTBtn = new System.Windows.Forms.ToolBarButton();
this.OpenTBtn = new System.Windows.Forms.ToolBarButton();
this.SaveTBtn = new System.Windows.Forms.ToolBarButton();
this.Split1TBtn = new System.Windows.Forms.ToolBarButton();
this.AddTBtn = new System.Windows.Forms.ToolBarButton();
this.RemoveTBtn = new System.Windows.Forms.ToolBarButton();
this.ToolBarImageList = new System.Windows.Forms.ImageList(this.components);
this.panel1.SuspendLayout();
this.groupBox1.SuspendLayout();
this.panel2.SuspendLayout();
this.SuspendLayout();
//
// panel1
//
this.panel1.Controls.Add(this.groupBox1);
this.panel1.Dock = System.Windows.Forms.DockStyle.Fill;
this.panel1.Location = new System.Drawing.Point(226, 42);
this.panel1.Name = "panel1";
this.panel1.Size = new System.Drawing.Size(406, 399);
this.panel1.TabIndex = 0;
//
// groupBox1
//
this.groupBox1.Controls.Add(this.SupportNetworkSpecificSettingsCb);
this.groupBox1.Controls.Add(this.HighAccessIDSizeTb);
this.groupBox1.Controls.Add(this.HighAccessIDSizeLbl);
this.groupBox1.Controls.Add(this.HighAccessIDTb);
this.groupBox1.Controls.Add(this.HighAccessIDLbl);
this.groupBox1.Controls.Add(this.LowAccessIDSizeTb);
this.groupBox1.Controls.Add(this.LowAccessIDSizeLbl);
this.groupBox1.Controls.Add(this.LowAccessIDTb);
this.groupBox1.Controls.Add(this.LowAccessIDLbl);
this.groupBox1.Controls.Add(this.UseLNCb);
this.groupBox1.Controls.Add(this.SecondaryIDSizeTb);
this.groupBox1.Controls.Add(this.SecondaryIDSizeLbl);
this.groupBox1.Controls.Add(this.SecondaryIDTb);
this.groupBox1.Controls.Add(this.SecondaryIDLbl);
this.groupBox1.Controls.Add(this.PrimaryIDSizeTb);
this.groupBox1.Controls.Add(this.PrimaryIDSizeLbl);
this.groupBox1.Controls.Add(this.PrimaryIDTb);
this.groupBox1.Controls.Add(this.PrimaryIDLbl);
this.groupBox1.Controls.Add(this.ResetBtn);
this.groupBox1.Controls.Add(this.NameTb);
this.groupBox1.Controls.Add(this.TypeTb);
this.groupBox1.Controls.Add(this.TypeLbl);
this.groupBox1.Controls.Add(this.InterfaceCb);
this.groupBox1.Controls.Add(this.RemoveInterfaceBtn);
this.groupBox1.Controls.Add(this.NameLbl);
this.groupBox1.Controls.Add(this.InterfacesLbl);
this.groupBox1.Controls.Add(this.ApplyBtn);
this.groupBox1.Controls.Add(this.DescriptionTb);
this.groupBox1.Controls.Add(this.DescriptionLbl);
this.groupBox1.Controls.Add(this.InterfaceTb);
this.groupBox1.Controls.Add(this.AddInterfaceBtn);
this.groupBox1.Location = new System.Drawing.Point(4, 4);
this.groupBox1.Name = "groupBox1";
this.groupBox1.Size = new System.Drawing.Size(396, 346);
this.groupBox1.TabIndex = 12;
this.groupBox1.TabStop = false;
//
// SupportNetworkSpecificSettingsCb
//
this.SupportNetworkSpecificSettingsCb.Location = new System.Drawing.Point(120, 292);
this.SupportNetworkSpecificSettingsCb.Name = "SupportNetworkSpecificSettingsCb";
this.SupportNetworkSpecificSettingsCb.Size = new System.Drawing.Size(256, 16);
this.SupportNetworkSpecificSettingsCb.TabIndex = 30;
this.SupportNetworkSpecificSettingsCb.Text = "Support Network Specific Settings";
//
// HighAccessIDSizeTb
//
this.HighAccessIDSizeTb.Enabled = false;
this.HighAccessIDSizeTb.Location = new System.Drawing.Point(292, 216);
this.HighAccessIDSizeTb.Name = "HighAccessIDSizeTb";
this.HighAccessIDSizeTb.Size = new System.Drawing.Size(88, 20);
this.HighAccessIDSizeTb.TabIndex = 29;
this.HighAccessIDSizeTb.Text = "";
//
// HighAccessIDSizeLbl
//
this.HighAccessIDSizeLbl.Location = new System.Drawing.Point(260, 216);
this.HighAccessIDSizeLbl.Name = "HighAccessIDSizeLbl";
this.HighAccessIDSizeLbl.Size = new System.Drawing.Size(32, 16);
this.HighAccessIDSizeLbl.TabIndex = 28;
this.HighAccessIDSizeLbl.Text = "Size:";
//
// HighAccessIDTb
//
this.HighAccessIDTb.Enabled = false;
this.HighAccessIDTb.Location = new System.Drawing.Point(120, 216);
this.HighAccessIDTb.Name = "HighAccessIDTb";
this.HighAccessIDTb.Size = new System.Drawing.Size(136, 20);
this.HighAccessIDTb.TabIndex = 27;
this.HighAccessIDTb.Text = "";
//
// HighAccessIDLbl
//
this.HighAccessIDLbl.Location = new System.Drawing.Point(8, 216);
this.HighAccessIDLbl.Name = "HighAccessIDLbl";
this.HighAccessIDLbl.Size = new System.Drawing.Size(108, 16);
this.HighAccessIDLbl.TabIndex = 26;
this.HighAccessIDLbl.Text = "High Access ID:";
//
// LowAccessIDSizeTb
//
this.LowAccessIDSizeTb.Enabled = false;
this.LowAccessIDSizeTb.Location = new System.Drawing.Point(292, 192);
this.LowAccessIDSizeTb.Name = "LowAccessIDSizeTb";
this.LowAccessIDSizeTb.Size = new System.Drawing.Size(88, 20);
this.LowAccessIDSizeTb.TabIndex = 25;
this.LowAccessIDSizeTb.Text = "";
//
// LowAccessIDSizeLbl
//
this.LowAccessIDSizeLbl.Location = new System.Drawing.Point(260, 192);
this.LowAccessIDSizeLbl.Name = "LowAccessIDSizeLbl";
this.LowAccessIDSizeLbl.Size = new System.Drawing.Size(32, 16);
this.LowAccessIDSizeLbl.TabIndex = 24;
this.LowAccessIDSizeLbl.Text = "Size:";
//
// LowAccessIDTb
//
this.LowAccessIDTb.Enabled = false;
this.LowAccessIDTb.Location = new System.Drawing.Point(120, 192);
this.LowAccessIDTb.Name = "LowAccessIDTb";
this.LowAccessIDTb.Size = new System.Drawing.Size(136, 20);
this.LowAccessIDTb.TabIndex = 23;
this.LowAccessIDTb.Text = "";
//
// LowAccessIDLbl
//
this.LowAccessIDLbl.Location = new System.Drawing.Point(8, 192);
this.LowAccessIDLbl.Name = "LowAccessIDLbl";
this.LowAccessIDLbl.Size = new System.Drawing.Size(108, 16);
this.LowAccessIDLbl.TabIndex = 22;
this.LowAccessIDLbl.Text = "Low Access ID:";
//
// UseLNCb
//
this.UseLNCb.Location = new System.Drawing.Point(120, 272);
this.UseLNCb.Name = "UseLNCb";
this.UseLNCb.Size = new System.Drawing.Size(256, 16);
this.UseLNCb.TabIndex = 21;
this.UseLNCb.Text = "Use LN";
//
// SecondaryIDSizeTb
//
this.SecondaryIDSizeTb.Enabled = false;
this.SecondaryIDSizeTb.Location = new System.Drawing.Point(292, 244);
this.SecondaryIDSizeTb.Name = "SecondaryIDSizeTb";
this.SecondaryIDSizeTb.Size = new System.Drawing.Size(88, 20);
this.SecondaryIDSizeTb.TabIndex = 20;
this.SecondaryIDSizeTb.Text = "";
//
// SecondaryIDSizeLbl
//
this.SecondaryIDSizeLbl.Location = new System.Drawing.Point(260, 244);
this.SecondaryIDSizeLbl.Name = "SecondaryIDSizeLbl";
this.SecondaryIDSizeLbl.Size = new System.Drawing.Size(32, 16);
this.SecondaryIDSizeLbl.TabIndex = 19;
this.SecondaryIDSizeLbl.Text = "Size:";
//
// SecondaryIDTb
//
this.SecondaryIDTb.Enabled = false;
this.SecondaryIDTb.Location = new System.Drawing.Point(120, 244);
this.SecondaryIDTb.Name = "SecondaryIDTb";
this.SecondaryIDTb.Size = new System.Drawing.Size(136, 20);
this.SecondaryIDTb.TabIndex = 18;
this.SecondaryIDTb.Text = "";
//
// SecondaryIDLbl
//
this.SecondaryIDLbl.Location = new System.Drawing.Point(8, 244);
this.SecondaryIDLbl.Name = "SecondaryIDLbl";
this.SecondaryIDLbl.Size = new System.Drawing.Size(108, 16);
this.SecondaryIDLbl.TabIndex = 17;
this.SecondaryIDLbl.Text = "Server ID:";
//
// PrimaryIDSizeTb
//
this.PrimaryIDSizeTb.Enabled = false;
this.PrimaryIDSizeTb.Location = new System.Drawing.Point(292, 168);
this.PrimaryIDSizeTb.Name = "PrimaryIDSizeTb";
this.PrimaryIDSizeTb.Size = new System.Drawing.Size(88, 20);
this.PrimaryIDSizeTb.TabIndex = 16;
this.PrimaryIDSizeTb.Text = "";
//
// PrimaryIDSizeLbl
//
this.PrimaryIDSizeLbl.Location = new System.Drawing.Point(260, 168);
this.PrimaryIDSizeLbl.Name = "PrimaryIDSizeLbl";
this.PrimaryIDSizeLbl.Size = new System.Drawing.Size(32, 16);
this.PrimaryIDSizeLbl.TabIndex = 15;
this.PrimaryIDSizeLbl.Text = "Size:";
//
// PrimaryIDTb
//
this.PrimaryIDTb.Enabled = false;
this.PrimaryIDTb.Location = new System.Drawing.Point(120, 168);
this.PrimaryIDTb.Name = "PrimaryIDTb";
this.PrimaryIDTb.Size = new System.Drawing.Size(136, 20);
this.PrimaryIDTb.TabIndex = 14;
this.PrimaryIDTb.Text = "";
//
// PrimaryIDLbl
//
this.PrimaryIDLbl.Location = new System.Drawing.Point(8, 168);
this.PrimaryIDLbl.Name = "PrimaryIDLbl";
this.PrimaryIDLbl.Size = new System.Drawing.Size(108, 16);
this.PrimaryIDLbl.TabIndex = 13;
this.PrimaryIDLbl.Text = "Default Client ID:";
//
// ResetBtn
//
this.ResetBtn.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.ResetBtn.Enabled = false;
this.ResetBtn.Location = new System.Drawing.Point(324, 314);
this.ResetBtn.Name = "ResetBtn";
this.ResetBtn.Size = new System.Drawing.Size(64, 24);
this.ResetBtn.TabIndex = 12;
this.ResetBtn.Text = "Reset";
this.ResetBtn.Click += new System.EventHandler(this.ResetBtn_Click);
//
// NameTb
//
this.NameTb.Enabled = false;
this.NameTb.Location = new System.Drawing.Point(120, 20);
this.NameTb.Name = "NameTb";
this.NameTb.Size = new System.Drawing.Size(260, 20);
this.NameTb.TabIndex = 1;
this.NameTb.Text = "";
//
// TypeTb
//
this.TypeTb.Enabled = false;
this.TypeTb.Location = new System.Drawing.Point(120, 44);
this.TypeTb.Name = "TypeTb";
this.TypeTb.Size = new System.Drawing.Size(260, 20);
this.TypeTb.TabIndex = 3;
this.TypeTb.Text = "";
//
// TypeLbl
//
this.TypeLbl.Location = new System.Drawing.Point(8, 44);
this.TypeLbl.Name = "TypeLbl";
this.TypeLbl.Size = new System.Drawing.Size(108, 16);
this.TypeLbl.TabIndex = 2;
this.TypeLbl.Text = "Type:";
//
// InterfaceCb
//
this.InterfaceCb.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.InterfaceCb.Enabled = false;
this.InterfaceCb.Location = new System.Drawing.Point(120, 140);
this.InterfaceCb.Name = "InterfaceCb";
this.InterfaceCb.Size = new System.Drawing.Size(196, 21);
this.InterfaceCb.TabIndex = 9;
//
// RemoveInterfaceBtn
//
this.RemoveInterfaceBtn.Enabled = false;
this.RemoveInterfaceBtn.Location = new System.Drawing.Point(320, 140);
this.RemoveInterfaceBtn.Name = "RemoveInterfaceBtn";
this.RemoveInterfaceBtn.Size = new System.Drawing.Size(60, 20);
this.RemoveInterfaceBtn.TabIndex = 10;
this.RemoveInterfaceBtn.Text = "Remove";
this.RemoveInterfaceBtn.Click += new System.EventHandler(this.RemoveInterfaceBtn_Click);
//
// NameLbl
//
this.NameLbl.Location = new System.Drawing.Point(8, 20);
this.NameLbl.Name = "NameLbl";
this.NameLbl.Size = new System.Drawing.Size(108, 16);
this.NameLbl.TabIndex = 0;
this.NameLbl.Text = "Name:";
//
// InterfacesLbl
//
this.InterfacesLbl.Location = new System.Drawing.Point(8, 116);
this.InterfacesLbl.Name = "InterfacesLbl";
this.InterfacesLbl.Size = new System.Drawing.Size(108, 16);
this.InterfacesLbl.TabIndex = 6;
this.InterfacesLbl.Text = "Interfaces:";
//
// ApplyBtn
//
this.ApplyBtn.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.ApplyBtn.Enabled = false;
this.ApplyBtn.Location = new System.Drawing.Point(252, 314);
this.ApplyBtn.Name = "ApplyBtn";
this.ApplyBtn.Size = new System.Drawing.Size(64, 24);
this.ApplyBtn.TabIndex = 11;
this.ApplyBtn.Text = "Apply";
this.ApplyBtn.Click += new System.EventHandler(this.ApplyBtn_Click);
//
// DescriptionTb
//
this.DescriptionTb.Enabled = false;
this.DescriptionTb.Location = new System.Drawing.Point(120, 68);
this.DescriptionTb.Multiline = true;
this.DescriptionTb.Name = "DescriptionTb";
this.DescriptionTb.Size = new System.Drawing.Size(260, 40);
this.DescriptionTb.TabIndex = 5;
this.DescriptionTb.Text = "";
//
// DescriptionLbl
//
this.DescriptionLbl.Location = new System.Drawing.Point(8, 68);
this.DescriptionLbl.Name = "DescriptionLbl";
this.DescriptionLbl.Size = new System.Drawing.Size(108, 16);
this.DescriptionLbl.TabIndex = 4;
this.DescriptionLbl.Text = "Decription:";
//
// InterfaceTb
//
this.InterfaceTb.Enabled = false;
this.InterfaceTb.Location = new System.Drawing.Point(120, 116);
this.InterfaceTb.Name = "InterfaceTb";
this.InterfaceTb.Size = new System.Drawing.Size(196, 20);
this.InterfaceTb.TabIndex = 7;
this.InterfaceTb.Text = "";
//
// AddInterfaceBtn
//
this.AddInterfaceBtn.Enabled = false;
this.AddInterfaceBtn.Location = new System.Drawing.Point(320, 116);
this.AddInterfaceBtn.Name = "AddInterfaceBtn";
this.AddInterfaceBtn.Size = new System.Drawing.Size(60, 20);
this.AddInterfaceBtn.TabIndex = 8;
this.AddInterfaceBtn.Text = "Add";
this.AddInterfaceBtn.Click += new System.EventHandler(this.AddInterfaceBtn_Click);
//
// panel2
//
this.panel2.Controls.Add(this.ObisTree);
this.panel2.Dock = System.Windows.Forms.DockStyle.Left;
this.panel2.Location = new System.Drawing.Point(0, 42);
this.panel2.Name = "panel2";
this.panel2.Size = new System.Drawing.Size(224, 399);
this.panel2.TabIndex = 1;
//
// ObisTree
//
this.ObisTree.ContextMenu = this.contextMenu1;
this.ObisTree.Dock = System.Windows.Forms.DockStyle.Fill;
this.ObisTree.HideSelection = false;
this.ObisTree.ImageIndex = -1;
this.ObisTree.Location = new System.Drawing.Point(0, 0);
this.ObisTree.Name = "ObisTree";
this.ObisTree.SelectedImageIndex = -1;
this.ObisTree.Size = new System.Drawing.Size(224, 399);
this.ObisTree.TabIndex = 0;
this.ObisTree.MouseDown += new System.Windows.Forms.MouseEventHandler(this.ObisTree_MouseDown);
this.ObisTree.AfterSelect += new System.Windows.Forms.TreeViewEventHandler(this.ObisTree_AfterSelect);
//
// contextMenu1
//
this.contextMenu1.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
this.AddContextMnu,
this.RemoveContextMnu});
//
// AddContextMnu
//
this.AddContextMnu.Index = 0;
this.AddContextMnu.Text = "Add";
this.AddContextMnu.Click += new System.EventHandler(this.AddMnu_Click);
//
// RemoveContextMnu
//
this.RemoveContextMnu.Index = 1;
this.RemoveContextMnu.Text = "Remove";
this.RemoveContextMnu.Click += new System.EventHandler(this.RemoveMnu_Click);
//
// splitter1
//
this.splitter1.Location = new System.Drawing.Point(224, 42);
this.splitter1.Name = "splitter1";
this.splitter1.Size = new System.Drawing.Size(2, 399);
this.splitter1.TabIndex = 2;
this.splitter1.TabStop = false;
//
// mainMenu1
//
this.mainMenu1.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
this.FileMnu,
this.ToolsMnu});
//
// FileMnu
//
this.FileMnu.Index = 0;
this.FileMnu.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
this.NewMnu,
this.OpenMnu,
this.SaveMnu,
this.SaveAsMnu,
this.SplitterMnu,
this.ExitMnu});
this.FileMnu.Text = "&File";
//
// NewMnu
//
this.NewMnu.Index = 0;
this.NewMnu.Shortcut = System.Windows.Forms.Shortcut.CtrlN;
this.NewMnu.Text = "&New";
this.NewMnu.Click += new System.EventHandler(this.NewMnu_Click);
//
// OpenMnu
//
this.OpenMnu.Index = 1;
this.OpenMnu.Shortcut = System.Windows.Forms.Shortcut.CtrlO;
this.OpenMnu.Text = "&Open";
this.OpenMnu.Click += new System.EventHandler(this.OpenMnu_Click);
//
// SaveMnu
//
this.SaveMnu.Enabled = false;
this.SaveMnu.Index = 2;
this.SaveMnu.Shortcut = System.Windows.Forms.Shortcut.CtrlS;
this.SaveMnu.Text = "&Save";
this.SaveMnu.Click += new System.EventHandler(this.SaveMnu_Click);
//
// SaveAsMnu
//
this.SaveAsMnu.Enabled = false;
this.SaveAsMnu.Index = 3;
this.SaveAsMnu.Text = "Save as...";
this.SaveAsMnu.Click += new System.EventHandler(this.SaveAsMnu_Click);
//
// SplitterMnu
//
this.SplitterMnu.Index = 4;
this.SplitterMnu.Text = "-";
//
// ExitMnu
//
this.ExitMnu.Index = 5;
this.ExitMnu.Text = "E&xit";
this.ExitMnu.Click += new System.EventHandler(this.ExitMnu_Click);
//
// ToolsMnu
//
this.ToolsMnu.Index = 1;
this.ToolsMnu.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
this.AddMnu,
this.RemoveMnu,
this.TestMnu,
this.menuItem1,
this.LanguageMnu});
this.ToolsMnu.Text = "&Tools";
//
// AddMnu
//
this.AddMnu.Enabled = false;
this.AddMnu.Index = 0;
this.AddMnu.Text = "&Add";
this.AddMnu.Click += new System.EventHandler(this.AddMnu_Click);
//
// RemoveMnu
//
this.RemoveMnu.Enabled = false;
this.RemoveMnu.Index = 1;
this.RemoveMnu.Shortcut = System.Windows.Forms.Shortcut.Del;
this.RemoveMnu.Text = "&Remove";
this.RemoveMnu.Click += new System.EventHandler(this.RemoveMnu_Click);
//
// TestMnu
//
this.TestMnu.Enabled = false;
this.TestMnu.Index = 2;
this.TestMnu.Text = "Test";
this.TestMnu.Click += new System.EventHandler(this.TestMnu_Click);
//
// menuItem1
//
this.menuItem1.Index = 3;
this.menuItem1.Text = "-";
//
// LanguageMnu
//
this.LanguageMnu.Index = 4;
this.LanguageMnu.Text = "Language";
//
// toolBar1
//
this.toolBar1.Appearance = System.Windows.Forms.ToolBarAppearance.Flat;
this.toolBar1.Buttons.AddRange(new System.Windows.Forms.ToolBarButton[] {
this.NewTBtn,
this.OpenTBtn,
this.SaveTBtn,
this.Split1TBtn,
this.AddTBtn,
this.RemoveTBtn});
this.toolBar1.ButtonSize = new System.Drawing.Size(23, 23);
this.toolBar1.DropDownArrows = true;
this.toolBar1.ImageList = this.ToolBarImageList;
this.toolBar1.Location = new System.Drawing.Point(0, 0);
this.toolBar1.Name = "toolBar1";
this.toolBar1.ShowToolTips = true;
this.toolBar1.Size = new System.Drawing.Size(632, 42);
this.toolBar1.TabIndex = 3;
this.toolBar1.ButtonClick += new System.Windows.Forms.ToolBarButtonClickEventHandler(this.toolBar1_ButtonClick);
//
// NewTBtn
//
this.NewTBtn.ImageIndex = 0;
this.NewTBtn.Text = "New";
this.NewTBtn.ToolTipText = "New";
//
// OpenTBtn
//
this.OpenTBtn.ImageIndex = 1;
this.OpenTBtn.Text = "Open";
this.OpenTBtn.ToolTipText = "Open";
//
// SaveTBtn
//
this.SaveTBtn.Enabled = false;
this.SaveTBtn.ImageIndex = 2;
this.SaveTBtn.Text = "Save";
this.SaveTBtn.ToolTipText = "Save";
//
// Split1TBtn
//
this.Split1TBtn.Style = System.Windows.Forms.ToolBarButtonStyle.Separator;
//
// AddTBtn
//
this.AddTBtn.Enabled = false;
this.AddTBtn.ImageIndex = 3;
this.AddTBtn.Text = "Add";
this.AddTBtn.ToolTipText = "Add";
//
// RemoveTBtn
//
this.RemoveTBtn.Enabled = false;
this.RemoveTBtn.ImageIndex = 9;
this.RemoveTBtn.Text = "Remove";
this.RemoveTBtn.ToolTipText = "Remove";
//
// ToolBarImageList
//
this.ToolBarImageList.ImageSize = new System.Drawing.Size(16, 16);
this.ToolBarImageList.ImageStream = ((System.Windows.Forms.ImageListStreamer)(resources.GetObject("ToolBarImageList.ImageStream")));
this.ToolBarImageList.TransparentColor = System.Drawing.Color.Magenta;
//
// ObisMainForm
//
this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
this.ClientSize = new System.Drawing.Size(632, 441);
this.Controls.Add(this.panel1);
this.Controls.Add(this.splitter1);
this.Controls.Add(this.panel2);
this.Controls.Add(this.toolBar1);
this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
this.Menu = this.mainMenu1;
this.Name = "ObisMainForm";
this.Text = "GXObisEditor";
this.panel1.ResumeLayout(false);
this.groupBox1.ResumeLayout(false);
this.panel2.ResumeLayout(false);
this.ResumeLayout(false);
}
#endregion
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.Run(new ObisMainForm());
}
private void BuildTree()
{
ObisTree.Nodes.Clear();
TreeNode rootNode = new TreeNode(m_Manufacturer.Name);
rootNode.Tag = m_Manufacturer;
ObisTree.Nodes.Add(rootNode);
TreeNode commonNode = new TreeNode("Common Properties");
commonNode.Tag = m_Manufacturer.CommonProperties;
foreach (ObisItem it in m_Manufacturer.CommonProperties)
{
TreeNode itemNode = new TreeNode(it.LN);
itemNode.Tag = it;
commonNode.Nodes.Add(itemNode);
}
rootNode.Nodes.Add(commonNode);
foreach (ObisDevice dev in m_Manufacturer.Devices)
{
TreeNode devNode = new TreeNode(dev.Name);
devNode.Tag = dev;
foreach (ObisItem it in dev.Items)
{
TreeNode itemNode = new TreeNode(it.LN);
itemNode.Tag = it;
devNode.Nodes.Add(itemNode);
}
rootNode.Nodes.Add(devNode);
}
ObisTree.SelectedNode = rootNode;
}
private void toolBar1_ButtonClick(object sender, System.Windows.Forms.ToolBarButtonClickEventArgs e)
{
try
{
if (e.Button == NewTBtn)
{
NewMnu_Click(null, null);
}
else if (e.Button == OpenTBtn)
{
OpenMnu_Click(null, null);
}
else if (e.Button == SaveTBtn)
{
SaveMnu_Click(null, null);
}
else if (e.Button == AddTBtn)
{
AddMnu_Click(null, null);
}
else if (e.Button == RemoveTBtn)
{
RemoveMnu_Click(null, null);
}
}
catch (Exception Ex)
{
MessageBox.Show(Ex.Message);
}
}
private void NewMnu_Click(object sender, System.EventArgs e)
{
if (!BeforeClearCheck())
{
return;
}
m_Manufacturer = new ObisManufacturer("Manufacturer", 0, "");
TestMnu.Enabled = SaveAsMnu.Enabled = SaveMnu.Enabled = SaveTBtn.Enabled = true;
BuildTree();
}
private void OpenMnu_Click(object sender, System.EventArgs e)
{
if (!BeforeClearCheck())
{
return;
}
ObisManufacturer mnf = new ObisManufacturer();
OpenFileDialog dlg = new OpenFileDialog();
dlg.ValidateNames = true;
dlg.Filter = "XML OBIS files (*.obx)|*.obx|All files (*.*)|*.*";
dlg.Multiselect = false;
if (dlg.ShowDialog() == DialogResult.OK)
{
mnf.Load(dlg.FileName);
m_Manufacturer = mnf;
BuildTree();
TestMnu.Enabled = SaveAsMnu.Enabled = SaveMnu.Enabled = SaveTBtn.Enabled = true;
}
m_Dirty = false;
}
private void SaveMnu_Click(object sender, System.EventArgs e)
{
if (m_Manufacturer.FilePath == string.Empty)
{
SaveAsMnu_Click(null, null);
}
else
{
m_Manufacturer.Save(m_Manufacturer.FilePath);
}
m_Dirty = false;
}
private void ExitMnu_Click(object sender, System.EventArgs e)
{
if (BeforeClearCheck())
{
this.Close();
}
}
private void AddMnu_Click(object sender, System.EventArgs e)
{
if (ObisTree.SelectedNode == null || ObisTree.SelectedNode.Tag == null)
{
//Do nothing, because this should not happen
}
else if (ObisTree.SelectedNode.Tag is ObisManufacturer)
{
//Add device
ObisDevice dev = new ObisDevice("Device");
m_Manufacturer.Devices.Add(dev);
TreeNode newNode = new TreeNode("Device");
newNode.Tag = dev;
ObisTree.SelectedNode.Nodes.Add(newNode);
ObisTree.SelectedNode.Expand();
ObisTree.SelectedNode = newNode;
}
else if(ObisTree.SelectedNode.Tag is ObisDevice)
{
ObisItem newItem = AddItem(((ObisDevice) ObisTree.SelectedNode.Tag).Items);
TreeNode newNode = new TreeNode(newItem.LN);
newNode.Tag = newItem;
ObisTree.SelectedNode.Nodes.Add(newNode);
ObisTree.SelectedNode.Expand();
ObisTree.SelectedNode = newNode;
}
else if(ObisTree.SelectedNode.Tag is ObisItems)
{
ObisItem newItem = AddItem((ObisItems)ObisTree.SelectedNode.Tag);
TreeNode newNode = new TreeNode(newItem.LN);
newNode.Tag = newItem;
ObisTree.SelectedNode.Nodes.Add(newNode);
ObisTree.SelectedNode.Expand();
ObisTree.SelectedNode = newNode;
}
else if(ObisTree.SelectedNode.Tag is ObisItem)
{
ObisItem newItem = null;
if (ObisTree.SelectedNode.Parent.Tag is ObisDevice)
{
newItem = AddItem(((ObisDevice) ObisTree.SelectedNode.Parent.Tag).Items);
}
else
{
newItem = AddItem(((ObisItems) ObisTree.SelectedNode.Parent.Tag));
}
TreeNode newNode = new TreeNode(newItem.LN);
newNode.Tag = newItem;
ObisTree.SelectedNode.Parent.Nodes.Add(newNode);
ObisTree.SelectedNode = newNode;
}
m_Dirty = true;
}
private ObisItem AddItem(ObisItems parent)
{
ObisItem item = new ObisItem("1.2.3", 0, "");
parent.Add(item);
return item;
}
private void RemoveMnu_Click(object sender, System.EventArgs e)
{
if (!ObisTree.Focused)
{
return;
}
try
{
if(ObisTree.SelectedNode.Tag is ObisDevice)
{
ObisDevice dev = ((ObisDevice)ObisTree.SelectedNode.Tag);
TreeNode removedNode = ObisTree.SelectedNode;
ObisTree.SelectedNode = removedNode.Parent;
ObisTree.SelectedNode.Nodes.Remove(removedNode);
m_Manufacturer.Devices.Remove(dev);
m_Dirty = true;
}
else if(ObisTree.SelectedNode.Tag is ObisItem)
{
ObisItem item = ((ObisItem)ObisTree.SelectedNode.Tag);
if (ObisTree.SelectedNode.Parent.Tag is ObisItems)
{
m_Manufacturer.CommonProperties.Remove(item);
}
else //Under device
{
ObisDevice dev = (ObisDevice)ObisTree.SelectedNode.Parent.Tag;
dev.Items.Remove(item);
}
TreeNode removedNode = ObisTree.SelectedNode;
ObisTree.SelectedNode = removedNode.Parent;
ObisTree.SelectedNode.Nodes.Remove(removedNode);
m_Dirty = true;
}
}
catch (Exception Ex)
{
MessageBox.Show(Ex.Message);
}
}
private void SaveAsMnu_Click(object sender, System.EventArgs e)
{
SaveFileDialog dlg = new SaveFileDialog();
dlg.CheckPathExists = true;
dlg.ValidateNames = true;
dlg.Filter = "XML OBIS files (*.obx)|*.obx|All files (*.*)|*.*";
if (dlg.ShowDialog() == DialogResult.OK)
{
m_Manufacturer.Save(dlg.FileName);
m_Dirty = false;
}
else
{
m_ClearSaveFailed = true;
}
}
private bool BeforeClearCheck()
{
if (m_Manufacturer != null && m_Dirty)
{
DialogResult dr = MessageBox.Show(this, "Do you want to save current job?", "GXObisEditor", MessageBoxButtons.YesNoCancel);
if (dr == DialogResult.Cancel)
{
return false;
}
else if (dr == DialogResult.Yes)
{
m_ClearSaveFailed = false;
SaveMnu_Click(null, null);
return !m_ClearSaveFailed;
}
else if (dr == DialogResult.No)
{
return true;
}
else
{
return false;
}
}
else
{
return true;
}
}
private void ObisTree_AfterSelect(object sender, System.Windows.Forms.TreeViewEventArgs e)
{
//Reset everything just in case
AddContextMnu.Enabled = AddMnu.Enabled = AddTBtn.Enabled = RemoveContextMnu.Enabled = RemoveTBtn.Enabled = RemoveMnu.Enabled = false;
InterfaceCb.Items.Clear();
InterfaceTb.Text = string.Empty;
NameLbl.Text = "Name:";
NameTb.Text = string.Empty;
DescriptionTb.Text = string.Empty;
TypeTb.Text = string.Empty;
foreach (Control ctrl in groupBox1.Controls)
{
if (ctrl.Name.IndexOf("ID") != -1 && ctrl is TextBox)
{
((TextBox) ctrl).Text = "";
}
}
foreach (Control ctrl in groupBox1.Controls)
{
ctrl.Enabled = false;
}
if (ObisTree.SelectedNode != null && ObisTree.SelectedNode.Tag != null)
{
ApplyBtn.Enabled = ResetBtn.Enabled = true;
}
if (ObisTree.SelectedNode.Tag is ObisManufacturer)
{
AddContextMnu.Enabled = AddMnu.Enabled = AddTBtn.Enabled = true;
NameTb.Enabled = NameLbl.Enabled = DescriptionTb.Enabled = DescriptionLbl.Enabled = TypeTb.Enabled = TypeLbl.Enabled = true;
NameTb.Text = m_Manufacturer.Name;
DescriptionTb.Text = m_Manufacturer.Description;
TypeTb.Text = m_Manufacturer.Type.ToString();
}
else if(ObisTree.SelectedNode.Tag is ObisDevice)
{
AddContextMnu.Enabled = AddMnu.Enabled = AddTBtn.Enabled = RemoveContextMnu.Enabled = RemoveTBtn.Enabled = RemoveMnu.Enabled = true;
SupportNetworkSpecificSettingsCb.Enabled = UseLNCb.Enabled = NameTb.Enabled = NameLbl.Enabled = DescriptionTb.Enabled = DescriptionLbl.Enabled = TypeTb.Enabled = TypeLbl.Enabled = true;
foreach (Control ctrl in groupBox1.Controls)
{
if (ctrl.Name.IndexOf("ID") != -1)
{
ctrl.Enabled = true;
}
}
ObisDevice dev = (ObisDevice) ObisTree.SelectedNode.Tag;
NameTb.Text = dev.Name;
DescriptionTb.Text = dev.Description;
TypeTb.Text = dev.Type.ToString();
PrimaryIDTb.Text = dev.PrimaryDefaultID.ToString();
PrimaryIDSizeTb.Text = dev.PrimaryDefaultIDSize.ToString();
LowAccessIDTb.Text = dev.PrimaryLowID.ToString();
LowAccessIDSizeTb.Text = dev.PrimaryLowIDSize.ToString();
HighAccessIDTb.Text = dev.PrimaryHighID.ToString();
HighAccessIDSizeTb.Text = dev.PrimaryHighIDSize.ToString();
SecondaryIDTb.Text = dev.SecondaryID.ToString();
SecondaryIDSizeTb.Text = dev.SecondaryIDSize.ToString();
UseLNCb.Checked = dev.UseLN;
SupportNetworkSpecificSettingsCb.Checked = dev.SupportNetworkSpecificSettings;
}
else if(ObisTree.SelectedNode.Tag is ObisItems)
{
AddContextMnu.Enabled = AddMnu.Enabled = AddTBtn.Enabled = true;
RemoveContextMnu.Enabled = RemoveTBtn.Enabled = RemoveMnu.Enabled = false;
}
else if(ObisTree.SelectedNode.Tag is ObisItem)
{
NameTb.Enabled = NameLbl.Enabled = DescriptionTb.Enabled = DescriptionLbl.Enabled = TypeTb.Enabled = TypeLbl.Enabled = true;
foreach (Control ctrl in groupBox1.Controls)
{
if (ctrl.Name.ToLower().IndexOf("interface") != -1)
{
ctrl.Enabled = true;
}
}
AddContextMnu.Enabled = AddMnu.Enabled = AddTBtn.Enabled = RemoveContextMnu.Enabled = RemoveTBtn.Enabled = RemoveMnu.Enabled = true;
ObisItem item = (ObisItem) ObisTree.SelectedNode.Tag;
NameLbl.Text = "LN:";
NameTb.Text = item.LN;
DescriptionTb.Text = item.Description;
TypeTb.Text = item.Type.ToString();
foreach (int obisInterface in item.Interfaces)
{
InterfaceCb.Items.Add(obisInterface.ToString());
}
if (item.Interfaces.Count != 0)
{
InterfaceCb.SelectedIndex = 0;
}
}
}
private void ObisTree_MouseDown(object sender, System.Windows.Forms.MouseEventArgs e)
{
if (e.Button == MouseButtons.Right)
{
ObisTree.SelectedNode = ObisTree.GetNodeAt(e.X, e.Y);
}
}
private void ApplyBtn_Click(object sender, System.EventArgs e)
{
try
{
if (ObisTree.SelectedNode == null || ObisTree.SelectedNode.Tag == null)
{
throw new Exception("Nothing is selected in the tree.");
}
else if (NameTb.Text.Trim().Length == 0)
{
throw new Exception("Name can not be empty");
}
else if (ObisTree.SelectedNode.Tag is ObisManufacturer)
{
m_Manufacturer.Name = NameTb.Text;
ObisTree.SelectedNode.Text = NameTb.Text;
m_Manufacturer.Description = DescriptionTb.Text;
m_Manufacturer.Type = ConvertToInt(TypeTb.Text);
}
else if(ObisTree.SelectedNode.Tag is ObisDevice)
{
ObisDevice dev = (ObisDevice) ObisTree.SelectedNode.Tag;
dev.Name = NameTb.Text;
ObisTree.SelectedNode.Text = NameTb.Text;
dev.Description = DescriptionTb.Text;
dev.Type = ConvertToInt(TypeTb.Text);
dev.PrimaryDefaultID = ConvertToInt(PrimaryIDTb.Text);
dev.PrimaryDefaultIDSize = ConvertToInt(PrimaryIDSizeTb.Text);
dev.PrimaryLowID = ConvertToInt(LowAccessIDTb.Text);
dev.PrimaryLowIDSize = ConvertToInt(LowAccessIDSizeTb.Text);
dev.PrimaryHighID = ConvertToInt(HighAccessIDTb.Text);
dev.PrimaryHighIDSize = ConvertToInt(HighAccessIDSizeTb.Text);
dev.SecondaryID = ConvertToInt(SecondaryIDTb.Text);
dev.SecondaryIDSize = ConvertToInt(SecondaryIDSizeTb.Text);
dev.UseLN = UseLNCb.Checked;
dev.SupportNetworkSpecificSettings = SupportNetworkSpecificSettingsCb.Checked;
}
else if(ObisTree.SelectedNode.Tag is ObisItem)
{
ObisItem item = (ObisItem) ObisTree.SelectedNode.Tag;
item.LN = NameTb.Text;
ObisTree.SelectedNode.Text = NameTb.Text;
item.Description = DescriptionTb.Text;
item.Type = ConvertToInt(TypeTb.Text);
item.Interfaces.Clear();
foreach (string iface in InterfaceCb.Items)
{
item.Interfaces.Add(ConvertToInt(iface));
}
}
m_Dirty = true;
}
catch (Exception Ex)
{
MessageBox.Show(Ex.Message);
}
}
private int ConvertToInt(string Input)
{
double dOut = 0;
if (!double.TryParse(Input, System.Globalization.NumberStyles.Integer, System.Globalization.CultureInfo.CurrentCulture, out dOut))
{
throw new Exception("Value must be an integer.");
}
return (int)dOut;
}
private void ResetBtn_Click(object sender, System.EventArgs e)
{
TreeNode selNode = ObisTree.SelectedNode;
ObisTree.SelectedNode = null;
ObisTree.SelectedNode = selNode;
}
private void Application_Idle(object sender, EventArgs e)
{
string caption = string.Empty;
if (m_Manufacturer == null)
{
caption = "GXObisEditor";
}
else
{
caption ="GXObisEditor - " + m_Manufacturer.Name;
if (m_Dirty)
{
caption += "*";
}
}
if (this.Text != caption)
{
this.Text = caption;
}
}
private void AddInterfaceBtn_Click(object sender, System.EventArgs e)
{
try
{
ConvertToInt(InterfaceTb.Text);
InterfaceCb.Items.Add(InterfaceTb.Text);
InterfaceCb.SelectedIndex = InterfaceCb.Items.Count - 1;
}
catch (Exception Ex)
{
MessageBox.Show(Ex.Message);
}
}
private void RemoveInterfaceBtn_Click(object sender, System.EventArgs e)
{
if (InterfaceCb.SelectedItem is string && InterfaceCb.SelectedItem.ToString().Length > 0)
{
InterfaceCb.Items.Remove(InterfaceCb.SelectedItem);
if (InterfaceCb.Items.Count > 0)
{
InterfaceCb.SelectedIndex = 0;
}
}
}
private void HandleOBISID(System.Windows.Forms.TreeNodeCollection Nodes, bool Add)
{
foreach(TreeNode it in Nodes)
{
//Add sub items
if (!(it.Tag is ObisItem))
{
HandleOBISID(it.Nodes, Add);
return;
}
ObisItem item = (ObisItem) it.Tag;
if (Add)
{
m_parser.AddOBISCode(it.Text, (GuruxDLMS.DLMS_DATA_TYPE) item.Type, item.Description, item.Interfaces.Array);
}
int type = 0;
if (item.Interfaces.Count != 0)
{
type = item.Interfaces[0];
}
if (!Add)
{
string desc = m_parser.GetDescription(it.Text, (GuruxDLMS.DLMS_OBJECT_TYPE) type);
if (item.Description != desc)
{
MessageBox.Show("OBIS descriptions are different.\r\nGet: " + desc + "\r\nShould be: " + item.Description + "\r\n" + it.Text);
}
}
}
}
/// <summary>
/// Test all OBIS codes.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void TestMnu_Click(object sender, System.EventArgs e)
{
try
{
m_parser.ResetOBISCodes();
//Add all OBIS Codes
HandleOBISID(ObisTree.Nodes, true);
//Find OBIS codes.
HandleOBISID(ObisTree.Nodes, false);
MessageBox.Show("Done");
}
catch(Exception Ex)
{
MessageBox.Show(Ex.Message);
}
}
public System.Globalization.CultureInfo[] GetAvailableLanguages()
{
ArrayList list = new ArrayList();
System.Globalization.CultureInfo info = System.Globalization.CultureInfo.CreateSpecificCulture("En");
list.Add(info);
// Get the current application path
string strPath = System.IO.Path.GetDirectoryName(System.Windows.Forms.Application.ExecutablePath);
System.IO.DirectoryInfo di = new System.IO.DirectoryInfo(strPath);
foreach(System.IO.DirectoryInfo it in di.GetDirectories())
{
try
{
info = System.Globalization.CultureInfo.CreateSpecificCulture(it.Name);
list.Add(info);
}
catch
{
continue;
}
}
System.Globalization.CultureInfo[] infos = new System.Globalization.CultureInfo[list.Count];
list.CopyTo(infos);
return infos;
}
/// <summary>
/// Change selected language and update UI.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void OnChangeLanguage(object sender, System.EventArgs e)
{
string oldLanguage = m_CurrentLanguage;
try
{
foreach(MenuItem it in LanguageMnu.MenuItems)
{
it.Checked = false;
}
MenuItem item = (MenuItem) sender;
foreach (System.Globalization.CultureInfo it in System.Globalization.CultureInfo.GetCultures(System.Globalization.CultureTypes.SpecificCultures))
{
string str = it.NativeName;
int len = str.IndexOf("(");
if (len > 0)
{
str = str.Substring(0, len);
}
if (str == item.Text)
{
System.Threading.Thread.CurrentThread.CurrentUICulture = System.Threading.Thread.CurrentThread.CurrentCulture = it;
m_CurrentLanguage = it.TwoLetterISOLanguageName;
UpdateResources();
break;
}
}
item.Checked = true;
}
catch //Restore old language.
{
m_CurrentLanguage = oldLanguage;
System.Threading.Thread.CurrentThread.CurrentCulture = System.Globalization.CultureInfo.CreateSpecificCulture(m_CurrentLanguage);
}
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class BarcoMsg : MonoBehaviour
{
public GameObject junteMoney;
private void Start()
{
junteMoney.SetActive(false);
}
private void OnTriggerEnter(Collider other)
{
if(other.CompareTag("Player"))
{
junteMoney.SetActive(true);
}
}
private void OnTriggerExit(Collider other)
{
if(other.CompareTag("Player"))
{
junteMoney.SetActive(false);
}
}
}
|
using UnityEngine;
using System.Collections;
using IsoTools;
public class TesteFisica : MonoBehaviour {
public static TesteFisica _instance;
public IsoRigidbody iso_rigidyBody;
public IsoObject iso_object;
public void Awake()
{
if (_instance == null)
{
DontDestroyOnLoad(gameObject);
_instance = this;
}
else
{
if (this != _instance)
Destroy(gameObject);
}
iso_object = GetComponent<IsoObject>();
}
public static TesteFisica instance
{
get
{
if (_instance == null)
{
DontDestroyOnLoad(_instance);
_instance = FindObjectOfType<TesteFisica>() as TesteFisica;
}
return _instance;
}
}
void Start () {
}
void Update () {
iso_rigidyBody = GetComponent<IsoRigidbody>();
if (Input.GetKey(KeyCode.R))
{
iso_object.position += Vector3.one;
Debug.Log("VAlor da gravidade = " + iso_rigidyBody.useGravity);
Debug.Log("VAlor de isoWorld = " + iso_object.isoWorld._tileSize);
}
}
}
|
#region
using System;
using System.Collections.Generic;
using Plugin.XamJam.BugHound;
using Xamarin.Forms;
#endregion
namespace XamJam.Nav.Tab
{
/// <summary>
/// A collection of tabs where you can show one at a time
/// </summary>
public class TabScheme : INavScheme
{
private static readonly IBugHound Monitor = BugHound.ByType(typeof(TabScheme));
private TabDestination currentlyVisible;
private SexyTabbedView view;
public TabScheme(INavScheme parent)
{
Parent = parent;
}
public bool IsTabOnTop { get; set; } = Device.OS != TargetPlatform.iOS;
public IEnumerable<TabDestination> Children { get; private set; }
public Page TabbedPage { get; private set; }
public SchemeType SchemeType => SchemeType.TabScheme;
public INavScheme Parent { get; }
public Page CurrentPage => TabbedPage;
public bool IsDisplayed { get; set; } = false;
public void SetChildren(Func<View, ContentPage> pageCreator = null, params TabDestination[] children)
{
if (pageCreator == null)
pageCreator = v => new ContentPage {Content = v};
Children = children;
// every time a child is clicked on, show it's content
foreach (var child in children)
{
child.ClickedCommand = new Command(() => Show(child));
}
view = new SexyTabbedView(IsTabOnTop, children);
var page = pageCreator(view);
TabbedPage = page;
NavigationPage.SetHasNavigationBar(TabbedPage, false);
view.BindingContext = this;
}
public void Show(TabDestination showMe)
{
if (currentlyVisible != null)
{
currentlyVisible.IsSelected = false;
}
currentlyVisible = showMe;
Monitor.Debug($"Showing: {showMe.View.GetType()}");
view.Show(showMe);
currentlyVisible.IsSelected = true;
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Modelos;
using AcessoDados.Repositorio;
namespace Servicos
{
public class ItensNotaFiscalServico
{
ItensNotaFiscalRepositorio rep = new ItensNotaFiscalRepositorio();
public List<ItensNotaFiscal> ObterItensNF(int pagina = 1, int linhas = 5)
{
return rep.ObterItensNF(pagina, linhas);
}
public ItensNotaFiscal InstanciarItensNF()
{
ItensNotaFiscal ItensNF = new ItensNotaFiscal();
return ItensNF;
}
public int ObterQuantidadeItensNF()
{
try
{
return rep.ObterQuantidadeItensNF();
}
catch (Exception e)
{
throw e;
}
}
public ItensNotaFiscal ObterItemNF(long Pid)
{
return rep.ObterItemNF(Pid);
}
public IEnumerable<ItensNotaFiscal> ObterItensNFpNF(long PNFID)
{
try
{
return rep.ObterItensNFpNF(PNFID);
}
catch (Exception e)
{
throw e;
}
}
public Mensagem IncluirItensNF(ItensNotaFiscal PItensNF)
{
Mensagem msg = new Mensagem();
msg.Codigo = 0;
msg.Descricao = "Item NF gravado com sucesso";
try
{
rep.IncluirItensNF(PItensNF);
}
catch (Exception e)
{
msg.Codigo = 999;
msg.Descricao = "Erro gravar item: " + e.Message.ToString();
}
return msg;
}
public Mensagem AtualizarItensNF(ItensNotaFiscal PItensNF)
{
Mensagem msg = new Mensagem();
msg.Codigo = 0;
msg.Descricao = "Item NF alterado com sucesso";
try
{
rep.AtualizarItensNF(PItensNF);
}
catch (Exception e)
{
msg.Codigo = 999;
msg.Descricao = "Erro alterar item: " + e.Message.ToString();
}
return msg;
}
public Mensagem ExcluirItensNF(ItensNotaFiscal PItensNF)
{
Mensagem msg = new Mensagem();
msg.Codigo = 0;
msg.Descricao = "Item NF excluído com sucesso";
try
{
rep.ExcluirItensNF(PItensNF);
}
catch (Exception e)
{
msg.Codigo = 999;
msg.Descricao = "Erro excluir item: " + e.Message.ToString();
}
return msg;
}
public Mensagem ExcluirTodosItensNF(long pIDNF)
{
Mensagem msg = new Mensagem();
msg.Codigo = 0;
msg.Descricao = "Item NF excluído com sucesso";
try
{
rep.ExcluirTodosItensNF(pIDNF);
}
catch (Exception e)
{
msg.Codigo = 999;
msg.Descricao = "Erro excluir item: " + e.Message.ToString();
}
return msg;
}
public IEnumerable<ItensNotaFiscal> ObterItensNF(long pNFID)
{
return rep.ObterItensNF(pNFID);
}
}
} |
using UnityEngine;
using System.Collections;
public class Lars : Player
{
public Lars()
{
this.Name = "Lars";
this.PlayerSkin = Resources.Load<Sprite> ("Textures/LarsSkin");
}
}
|
using System;
namespace src.SmartSchool.WebAPI.V1.Dtos
{
/// <summary>
/// Versão 1: classe responsável pela difinição da entidade Aluno como Objeto de Transferência de Dados.
/// </summary>
public class AlunoDto
{
/// <summary>
/// Identificação de chave no banco de dados.
/// </summary>
public int Id { get; set; }
/// <summary>
/// Identificação de aluno(a) para negócios na instituição.
/// </summary>
public int Matricula { get; set; }
/// <summary>
/// Define o Nome e Sobrenome do aluno(a).
/// </summary>
public string Nome { get; set; }
/// <summary>
/// Define o Telefone de contato do aluno(a).
/// </summary>
public string Telefone { get; set; }
/// <summary>
/// Define a idade do aluno(a) através de cálculo relacionado a sua data de nascimento.
/// </summary>
public int Idade { get; set; }
/// <summary>
/// Aplica data de início de curso realizada pelo aluno(a).
/// </summary>
public DateTime DataIni { get; set; }
/// <summary>
/// Verifica se aluno(a) está ativo ou não.
/// </summary>
public bool Ativo { get; set; }
}
}
|
using KitStarter.Server.Library.Configuration.LoggingConfiguration;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
namespace KitStarter.Server.Library.Configuration
{
public class DefaultConfigLoader
{
public void ConfigProvider(IServiceCollection services, DefaultConfigProvider provider)
{
SetConfiguration<ConnectionStrings>(services, provider.ConnectionStrings);
SetConfiguration<STMPConnection>(services, provider.STMPConnection);
}
public DefaultConfigProvider GetConfigProvider(IConfiguration config)
{
DefaultConfigProvider configProvider = new DefaultConfigProvider()
{
ConnectionStrings = GetConfiguration<ConnectionStrings>(config, "ConnectionStrings"),
Logging = GetConfiguration<Logging>(config, "Logging"),
STMPConnection = GetConfiguration<STMPConnection>(config, "STMPConnection"),
AppSettings = GetConfiguration<AppSettings>(config, "AppSettings")
};
return configProvider;
}
private T GetConfiguration<T>(IConfiguration config, string Path) where T : class
{
return config.GetSection(Path).Get<T>();
}
private void SetConfiguration<T>(IServiceCollection services, T config) where T : class
{
services.AddSingleton(config);
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Oracle.ManagedDataAccess.Client;
namespace LivePerformance2016.CSharp.Data
{
public partial class Database : IData
{
private static string dataUser = "dbi310273";
private static string dataPass = "VadY179x3V";
private static string dataSrc = "//fhictora01.fhict.local:1521/fhictora";
//private static string dataUser = "LP16";
//private static string dataPass = "LP16";
//private static string dataSrc = "//localhost:1521/xe";
private static readonly string ConnectionString = "User Id=" + dataUser + ";Password=" + dataPass + ";Data Source=" + dataSrc + ";";
// Connectie voor de database
public static OracleConnection Connection
{
get
{
OracleConnection connection = new OracleConnection(ConnectionString);
connection.Open();
return connection;
}
}
}
}
|
using System.Collections.Generic;
using Lanches.Web.Models;
namespace Lanches.Web.ViewModels
{
public class LancheListViewModel
{
public IEnumerable<Lanche> Lanches { get; set; }
public string CategoriaAtual { get; set; }
}
} |
namespace DFC.ServiceTaxonomy.GraphVisualiser.Models.Owl
{
public partial class Namespace
{
public string? Name { get; set; }
public string? Iri { get; set; }
}
}
|
using RTBid.Core.Domain;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace RTBid.Core.Models
{
public class AuctionModel
{
public int AuctionId { get; set; }
public int ProductId { get; set; }
public string AuctionTitle { get; set; }
public int? NumberOfBidders { get; set; }
public int? NumberOfGuests { get; set; }
public DateTime CreatedDate { get; set; }
public DateTime? DeletedDate { get; set; }
public DateTime StartTime { get; set; }
public DateTime? ClosedTime { get; set; }
public DateTime? StartedTime { get; set; }
public decimal StartBid { get; set; }
public bool OpenSoon { get; set; }
public bool InAction { get; set; }
public bool ItemSold { get; set; }
public bool Rescheduled { get; set; }
public ProductModel Product { get; set; }
}
}
|
using Alabo.Industry.Shop.Carts.Domain.Services;
using Alabo.Test.Base.Attribute;
using Alabo.Test.Base.Core;
using Alabo.Test.Base.Core.Model;
using Xunit;
namespace Alabo.Test.Shop.Order.Domain.Service
{
public class ICartServiceTests : CoreTest
{
[Fact]
[TestMethod("AddCart_OrderProductInput")]
[TestIgnore]
public void AddCart_OrderProductInput_test()
{
//OrderProductInput orderProductInput = null;
//var result = Service<ICartService>().AddCart( orderProductInput);
//Assert.NotNull(result);
}
[Fact]
[TestMethod("GetCart_Int64")]
public void GetCart_Int64_test()
{
var userId = 0;
var result = Resolve<ICartService>().GetCart(userId);
Assert.NotNull(result);
}
[Fact]
[TestMethod("RemoveCart_OrderProductInput")]
[TestIgnore]
public void RemoveCart_OrderProductInput_test()
{
//OrderProductInput orderProductInput = null;
//var result = Service<ICartService>().RemoveCart( orderProductInput);
//Assert.NotNull(result);
}
[Fact]
[TestMethod("UpdateCart_OrderProductInput")]
[TestIgnore]
public void UpdateCart_OrderProductInput_test()
{
//OrderProductInput orderProductInput = null;
//var result = Service<ICartService>().UpdateCart( orderProductInput);
//Assert.NotNull(result);
}
}
} |
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
public class toggle_showTooltipInCenterOfObject : MonoBehaviour
{
Toggle toggle;
// Use this for initialization
void Start ()
{
toggle = GetComponent<Toggle> ();
toggle.onValueChanged.AddListener(ValueChanged);
}
void ValueChanged(bool value)
{
TooltipSetup.instance.showTooltipInCenterOfObject = value;
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class OnSyncCollision : MonoBehaviour {
int objectsInZone = 0;
void OnTriggerEnter(Collider other)
{
objectsInZone++;
//Debug.Log("Enter, objects: " + objectsInZone);
}
void OnTriggerStay(Collider other)
{
// one wave has objects to render both sides -> 2 waves == 4 objects
if (objectsInZone >= 4)
{
//Debug.Log("Breathe in sync");
// do sync stuff
// if player1 color/gradient is close to player2 color/gradient, then plane
}
}
void OnTriggerExit(Collider other)
{
objectsInZone--;
//Debug.Log("Exit, objects: " + objectsInZone);
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
/*
* tags: dp, LIS(Longest Increasing Subsequence)
* Time(mnlogn), Space(n), m=row(A), n=col(A)
* dp[i] is length of longest non-decreasing subsequence of A ending with A[i]
* dp[i] = max(dp[j]) + 1, if A[j]<=A[i], where j=[0..i-1]
*/
namespace leetcode
{
public class Lc87_Scramble_String
{
// try find first cut, then left and right should be scrambled strings
public bool IsScramble(string s1, string s2)
{
if (s1 == s2) return true;
int n = s1.Length;
var count = new int[256];
// make sure they have same char set
for (int i = 0; i < n; i++)
{
count[s1[i]]++;
count[s2[i]]--;
}
if (count.Any(c => c != 0))
return false;
for (int i = 0; i < n-1; i++)
{
if (IsScramble(s1.Substring(0, i + 1), s2.Substring(0, i + 1))
&& IsScramble(s1.Substring(i + 1), s2.Substring(i + 1)))
return true;
if (IsScramble(s1.Substring(n - 1 - i), s2.Substring(0, i + 1))
&& IsScramble(s1.Substring(0, n - 1 - i), s2.Substring(i + 1)))
return true;
}
return false;
}
public bool IsScramble2(string s1, string s2)
{
if (s1 == s2) return true;
int[] head = new int[256], tail = new int[256];
int balHead = 0, balTail = 0, n = s1.Length;
for (int i = 0; i < n-1; i++)
{
balHead += ++head[s1[i]] <= 0 ? -1 : 1;
balHead += --head[s2[i]] >= 0 ? -1 : 1;
balTail += ++tail[s1[n - 1 - i]] <= 0 ? -1 : 1;
balTail += --tail[s2[i]] >= 0 ? -1 : 1;
// good cut
if (balHead == 0 && IsScramble(s1.Substring(0, i + 1), s2.Substring(0, i + 1))
&& IsScramble(s1.Substring(i + 1), s2.Substring(i + 1)))
return true;
if (balTail == 0 && IsScramble(s1.Substring(n - 1 - i), s2.Substring(0, i + 1))
&& IsScramble(s1.Substring(0, n - 1 - i), s2.Substring(i + 1)))
return true;
}
return false;
}
public void Test()
{
Console.WriteLine(IsScramble("great", "rgeat") == true);
Console.WriteLine(IsScramble("abcde", "caebd") == false);
Console.WriteLine(IsScramble("unuzp", "nzuup") == true);
}
}
}
|
using UnityEngine;
using System.Collections;
public class UIToggleSprite : UIToggle {
public UISprite sprite;
public string normalSpriteName;
public string toggledSpriteName;
// Update is called once per frame
void Update () {
}
}
|
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Input;
namespace MinecraftToolsBoxSDK
{
public class BindOnEnterTextBox : TextBox
{
protected override void OnKeyDown(KeyEventArgs e)
{
base.OnKeyDown(e);
if (e.Key == Key.Enter)
{
BindingExpression bindingExpression = BindingOperations.GetBindingExpression(this, TextProperty);
if (bindingExpression != null)
bindingExpression.UpdateSource();
}
}
}
}
|
using AnyTest.MobileClient.Model;
using AnyTest.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xamarin.Forms;
using Xamarin.Forms.Xaml;
namespace AnyTest.MobileClient
{
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class QuestionCell : ViewCell
{
public TestPass Pass
{
get => GetValue(PassProperty) as TestPass;
set
{
SetValue(PassProperty, value);
OnPropertyChanged();
}
}
public QuestionCell()
{
InitializeComponent();
}
protected override void OnBindingContextChanged()
{
base.OnBindingContextChanged();
if(BindingContext is QuestionViewModel question)
{
AnswersList.HeightRequest = question.Answers.Count * 30 + 40;
}
}
public static readonly BindableProperty PassProperty = BindableProperty.Create("Pass", typeof(TestPass), typeof(QuestionCell), null);
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
using Microsoft.AspNet.Authorization;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Mvc;
using Microsoft.AspNet.Mvc.Rendering;
using Microsoft.Data.Entity;
using Microsoft.Extensions.Logging;
using Stolons.Models;
using Stolons.Services;
using Stolons.ViewModels.Account;
namespace Stolons.Controllers
{
[Authorize]
public class AccountController : Controller
{
private ApplicationDbContext _context;
private readonly UserManager<ApplicationUser> _userManager;
private readonly SignInManager<ApplicationUser> _signInManager;
private readonly ILogger _logger;
public AccountController(ApplicationDbContext context,
UserManager<ApplicationUser> userManager,
SignInManager<ApplicationUser> signInManager,
ILoggerFactory loggerFactory)
{
_context = context;
_userManager = userManager;
_signInManager = signInManager;
_logger = loggerFactory.CreateLogger<AccountController>();
}
//
// GET: /Account/Login
[HttpGet]
[AllowAnonymous]
public IActionResult Login(string returnUrl = null)
{
ViewData["ReturnUrl"] = returnUrl;
return View();
}
//
// POST: /Account/Login
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Login(LoginViewModel model, string returnUrl = null)
{
ViewData["ReturnUrl"] = returnUrl;
if (ModelState.IsValid)
{
//D'abord on regarde si il existe bien un User avec ce mail
User stolonsUser = _context.StolonsUsers.FirstOrDefault(x => x.Email.Equals(model.Email, StringComparison.CurrentCultureIgnoreCase));
if(stolonsUser == null)
{
ModelState.AddModelError(string.Empty, "L'adresse email saisie n'existe pas");
return View(model);
}
else
{
//On regarde si le compte de l'utilisateur est actif
if (!stolonsUser.Enable)
{
ModelState.AddModelError(string.Empty, "Votre compte a été bloqué. Veuillez contacter l'association pour connaitre la raison.");
return View(model);
}
// Il a un mot de passe, on le log si il est bon
// This doesn't count login failures towards account lockout
// To enable password failures to trigger account lockout, set lockoutOnFailure: true
var result = await _signInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, lockoutOnFailure: false);
if (result.Succeeded)
{
_logger.LogInformation(1, "User logged in.");
return RedirectToLocal(returnUrl);
}
if (result.IsLockedOut)
{
_logger.LogWarning(2, "User account locked out.");
return View("Lockout");
}
else
{
ModelState.AddModelError(string.Empty, "Erreur dans la saisie du mot de passe pour le compte : " + model.Email);
return View(model);
}
}
}
// If we got this far, something failed, redisplay form
return View(model);
}
//
// POST: /Account/LogOff
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> LogOff()
{
await _signInManager.SignOutAsync();
_logger.LogInformation(4, "User logged out.");
return RedirectToAction(nameof(HomeController.Index), "Home");
}
// GET: /Account/ConfirmEmail
[HttpGet]
[AllowAnonymous]
public async Task<IActionResult> ConfirmEmail(string userId, string code)
{
if (userId == null || code == null)
{
return View("Error");
}
var user = await _userManager.FindByIdAsync(userId);
if (user == null)
{
return View("Error");
}
var result = await _userManager.ConfirmEmailAsync(user, code);
return View(result.Succeeded ? "ConfirmEmail" : "Error");
}
[HttpGet]
[AllowAnonymous]
public IActionResult AccessDenied(string userId, string code)
{
return View();
}
#region Helpers
private void AddErrors(IdentityResult result)
{
foreach (var error in result.Errors)
{
ModelState.AddModelError(string.Empty, error.Description);
}
}
private IActionResult RedirectToLocal(string returnUrl)
{
if (Url.IsLocalUrl(returnUrl))
{
return Redirect(returnUrl);
}
else
{
return RedirectToAction(nameof(HomeController.Index), "Home");
}
}
#endregion
}
}
|
namespace ClassLibrary
{
/// <summary>
/// Описывает сотрудника-менеджера.
/// </summary>
public class Manager : Employee
{
/// <summary>
/// Хранит минимальную зарплату менеджера.
/// </summary>
const int minManagerSalary = 1300;
/// <summary>
/// Устанавливает зарплату менеджеру.
/// </summary>
/// <param name="dep"></param>
/// <returns>Зарплата менеджера.</returns>
public static int GetSalary(Dep dep)
{
// Подсчитываем зарплату менеджера.
int salary = 0;
// Суммируем зарплаты подчиненных сотрудников.
foreach (Worker worker in dep.Workers)
salary += worker.Salary;
// Вычисляем 15% суммарной зарплаты сотрудников.
salary = (int)(.15 * salary);
// Суммируем зарплаты подчиненных менеджеров.
foreach (Dep curDep in dep.Deps)
foreach (Manager manager in curDep.Managers)
salary += manager.Salary;
// Возвращаем значение minManagerSalary, если сумма оказалась меньше и если в отделе есть не только менеджеры.
return salary < minManagerSalary && (dep.Deps.Count > 0 || dep.Workers.Count > 0) ? minManagerSalary : salary;
}
/// <summary>
/// Инициализирует поля менеджера значениями по умолчанию.
/// </summary>
public Manager() : base() { }
/// <summary>
/// Инициализирует поля менеджера.
/// </summary>
/// <param name="name">Имя менеджера.</param>
public Manager(string name = null) : this() => Name = string.IsNullOrEmpty(name) ? "Noname" : name;
}
}
|
using Sentry.Extensibility;
using Sentry.Internal;
using Sentry.Internal.Extensions;
namespace Sentry.Protocol;
/// <summary>
/// Trace context data.
/// </summary>
public class Trace : ITraceContext, IJsonSerializable, ICloneable<Trace>, IUpdatable<Trace>
{
/// <summary>
/// Tells Sentry which type of context this is.
/// </summary>
public const string Type = "trace";
/// <inheritdoc />
public SpanId SpanId { get; set; }
/// <inheritdoc />
public SpanId? ParentSpanId { get; set; }
/// <inheritdoc />
public SentryId TraceId { get; set; }
/// <inheritdoc />
public string Operation { get; set; } = "";
/// <inheritdoc />
public string? Description { get; set; }
/// <inheritdoc />
public SpanStatus? Status { get; set; }
/// <inheritdoc />
public bool? IsSampled { get; internal set; }
/// <summary>
/// Clones this instance.
/// </summary>
internal Trace Clone() => ((ICloneable<Trace>)this).Clone();
Trace ICloneable<Trace>.Clone() => new()
{
SpanId = SpanId,
ParentSpanId = ParentSpanId,
TraceId = TraceId,
Operation = Operation,
Status = Status,
IsSampled = IsSampled
};
/// <summary>
/// Updates this instance with data from the properties in the <paramref name="source"/>,
/// unless there is already a value in the existing property.
/// </summary>
internal void UpdateFrom(Trace source) => ((IUpdatable<Trace>)this).UpdateFrom(source);
void IUpdatable.UpdateFrom(object source)
{
if (source is Trace trace)
{
((IUpdatable<Trace>)this).UpdateFrom(trace);
}
}
void IUpdatable<Trace>.UpdateFrom(Trace source)
{
SpanId = SpanId == default ? source.SpanId : SpanId;
ParentSpanId ??= source.ParentSpanId;
TraceId = TraceId == default ? source.TraceId : TraceId;
Operation = string.IsNullOrWhiteSpace(Operation) ? source.Operation : Operation;
Status ??= source.Status;
IsSampled ??= source.IsSampled;
}
/// <inheritdoc />
public void WriteTo(Utf8JsonWriter writer, IDiagnosticLogger? logger)
{
writer.WriteStartObject();
writer.WriteString("type", Type);
writer.WriteSerializableIfNotNull("span_id", SpanId.NullIfDefault(), logger);
writer.WriteSerializableIfNotNull("parent_span_id", ParentSpanId?.NullIfDefault(), logger);
writer.WriteSerializableIfNotNull("trace_id", TraceId.NullIfDefault(), logger);
writer.WriteStringIfNotWhiteSpace("op", Operation);
writer.WriteStringIfNotWhiteSpace("description", Description);
writer.WriteStringIfNotWhiteSpace("status", Status?.ToString().ToSnakeCase());
writer.WriteEndObject();
}
/// <summary>
/// Parses trace context from JSON.
/// </summary>
public static Trace FromJson(JsonElement json)
{
var spanId = json.GetPropertyOrNull("span_id")?.Pipe(SpanId.FromJson) ?? SpanId.Empty;
var parentSpanId = json.GetPropertyOrNull("parent_span_id")?.Pipe(SpanId.FromJson);
var traceId = json.GetPropertyOrNull("trace_id")?.Pipe(SentryId.FromJson) ?? SentryId.Empty;
var operation = json.GetPropertyOrNull("op")?.GetString() ?? "";
var description = json.GetPropertyOrNull("description")?.GetString();
var status = json.GetPropertyOrNull("status")?.GetString()?.Replace("_", "").ParseEnum<SpanStatus>();
var isSampled = json.GetPropertyOrNull("sampled")?.GetBoolean();
return new Trace
{
SpanId = spanId,
ParentSpanId = parentSpanId,
TraceId = traceId,
Operation = operation,
Description = description,
Status = status,
IsSampled = isSampled
};
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Content;
using TowerDefence.Creeps;
using TowerDefence.Bullets;
namespace TowerDefence.Towers
{
class IceTower : Tower
{
public IceTower(IServiceProvider serviceProvider, Vector2 position)
: base(serviceProvider,position)
{
base.Texture = content.Load<Texture2D>("Towers/IceTower");
base.Cost = 30;
base.Damage = 25;
base.startDamage = 25;
base.Range = 110;
base.Speed = 1;
base.totalSpentMoneyOnTower = cost;
}
public override Tower CreateTowerWithSamePosition()
{
Tower t = new IceTower(serviceProvider, this.Position);
return t;
}
public override void shootTheCreep(Creep creep)
{
Vector2 towerCenter = new Vector2(this.Position.X + this.Width / 2, this.Position.Y + this.Height / 2);
Bullet bullet = new IceBullet(serviceProvider, this.Damage, towerCenter, creep);
AliveBullets.Add(bullet);
}
}
}
|
using System;
namespace SelectionStatements
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello World!");
var favoriteNumber = 21;
Console.WriteLine("Try to guess my favorite number");
var guess = int.Parse(Console.ReadLine());
if (guess < favoriteNumber)
{
Console.WriteLine("too low");
}
else if (guess > favoriteNumber)
{
Console.WriteLine("too high");
}
else
{
Console.WriteLine("correct");
}
var team = Console.ReadLine();
switch (team)
{
case "chiefs":
Console.WriteLine("The chiefs are in the superbowl");
break;
case "patriots":
Console.WriteLine("The patriots are not in the superbowl");
break;
default:
Console.WriteLine($"The {team} and 49er's are in the superbowl");
break;
}
int teamName = 3;
switch (teamName)
{
case 0:
Console.WriteLine("Seahawks");
break;
case 1:
Console.WriteLine("Chiefs");
break;
case 2:
Console.WriteLine("Texans");
break;
case 3:
Console.WriteLine("49er's");
break;
case 4:
Console.WriteLine("Patriots");
break;
}
//int answer = 4;
//string response;
//if (answer < 9)
//{
// response = answer + " is less than nine";
//}
//else
//{
// response = answer + "greater than or equal to nine";
//}
var answer = 4;
var response = (answer < 9) ? $"{answer} is less than nine" : $"{answer} is greater than or equal to nine";
Console.WriteLine();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Text.Json.Serialization;
namespace FallstudieSem5.Models
{
[Table("Hazard")] // created Table with the Name Hazard
public class Hazard
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)] // used to set HazardId as PrimaryKey in the Database
public long HazardId { get; set; }
[Required(ErrorMessage = "Description is required")]
public string Description { get; set; }
public DateTime LastUpdated {get; set;}
[JsonIgnore]
public ICollection<Object> Objects { get; set; } // used to extend functionality to add, remove and update elements in the list
[Required(ErrorMessage = "DangerLevel is required")]
public DangerLevel DangerLevel { get; set; }
}
}
|
namespace News.Web
{
using System;
using System.Data.Entity;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using News.Model.Entity;
public partial class Model1 : DbContext
{
public Model1()
: base("name=db")
{
}
public virtual DbSet<posts> posts { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<posts>().ToTable("posts");
}
}
}
|
//
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license.
//
// Microsoft Bot Framework: http://botframework.com
//
// Personality Chat based Dialogs for Bot Builder:
// https://github.com/Microsoft/BotBuilder-PersonalityChat
//
// Copyright (c) Microsoft Corporation
// All rights reserved.
//
// MIT License:
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED ""AS IS"", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
namespace Microsoft.Bot.Builder.PersonalityChat
{
using System;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Microsoft.Bot.Builder.Dialogs;
using Microsoft.Bot.Connector;
using Microsoft.Bot.Builder.Internals.Fibers;
using System.Reflection;
using System.Linq;
using System.Web;
using Microsoft.Bot.Builder.PersonalityChat.Core;
[Serializable]
public class PersonalityChatDialog<TResult> : IDialog<IMessageActivity>
{
private PersonalityChatDialogOptions personalityChatDialogOptions = new PersonalityChatDialogOptions();
public PersonalityChatDialog()
{
}
public void SetPersonalityChatDialogOptions(PersonalityChatDialogOptions personalityChatDialogOptions)
{
this.personalityChatDialogOptions = personalityChatDialogOptions;
}
async Task IDialog<IMessageActivity>.StartAsync(IDialogContext context)
{
context.Wait(MessageReceivedAsync);
}
public async Task MessageReceivedAsync(IDialogContext context, IAwaitable<IMessageActivity> argument)
{
var message = await argument;
var userQuery = message.Text;
var personalityChatService = new PersonalityChatService(this.personalityChatDialogOptions);
var personalityChatResults = await personalityChatService.QueryServiceAsync(userQuery);
if (personalityChatDialogOptions.RespondOnlyIfChat && !personalityChatResults.IsChatQuery)
{
return;
}
string personalityChatResponse = this.GetResponse(personalityChatResults);
await this.PostPersonalityChatResponseToUser(context, personalityChatResponse);
}
public virtual string GetResponse(PersonalityChatResults personalityChatResults)
{
var matchedScenarios = personalityChatResults?.ScenarioList;
string response = string.Empty;
if (matchedScenarios != null)
{
var topScenario = matchedScenarios.FirstOrDefault();
if (topScenario?.Responses != null && topScenario.Score > this.personalityChatDialogOptions.ScenarioThresholdScore && topScenario.Responses.Count > 0)
{
Random randomGenerator = new Random();
int randomIndex = randomGenerator.Next(topScenario.Responses.Count);
response = topScenario.Responses[randomIndex];
}
}
return response;
}
public virtual async Task PostPersonalityChatResponseToUser(IDialogContext context, string personalityChatResponse)
{
if (!string.IsNullOrEmpty(personalityChatResponse))
{
await context.PostAsync(personalityChatResponse);
}
context.Done(true);
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
//**********************************************************************
//
// 文件名称(File Name):LoadTaskIdListRequest.CS
// 功能描述(Description):
// 作者(Author):Aministrator
// 日期(Create Date): 2017-05-26 10:38:57
//
// 修改记录(Revision History):
// R1:
// 修改作者:
// 修改日期:2017-05-26 10:38:57
// 修改理由:
//**********************************************************************
namespace ND.FluentTaskScheduling.Model.request
{
public class LoadTaskIdListRequest : RequestBase
{
/// <summary>
/// 任务调度状态
/// </summary>
public int TaskScheduleStatus { get; set; }
public int NodeId { get; set; }
}
}
|
// Copyright (c) 2018 FiiiLab Technology Ltd
// Distributed under the MIT software license, see the accompanying
// file LICENSE or or http://www.opensource.org/licenses/mit-license.php.
using System;
namespace FiiiCoin.Utility.Helper
{
public static class TimeHelper
{
public static DateTime EpochStartTime => new DateTime(1970, 1, 1, 0, 0, 0, System.DateTimeKind.Utc);
public static long EpochTime => (long)(DateTime.UtcNow - EpochStartTime).TotalMilliseconds;
}
public static class Time
{
public static DateTime EpochStartTime => new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
public static long EpochTime => (long)(DateTime.UtcNow - EpochStartTime).TotalMilliseconds;
public static long GetEpochTime(int year, int month, int day, int hour, int minute, int second)
{
return (long)(new DateTime(year, month, day, hour, minute, second, DateTimeKind.Utc).AddHours(-8) - EpochStartTime).TotalMilliseconds;
}
public static DateTime GetLocalDateTime(long timeStamp)
{
DateTime startTime = TimeZoneInfo.ConvertTime(new DateTime(1970, 1, 1), TimeZoneInfo.Local);//等价的建议写法
TimeSpan toNow = new TimeSpan(timeStamp * 10000);
return startTime.Add(toNow);
}
}
}
|
namespace MatchHexadecimalNumbers
{
using System;
using System.Linq;
using System.Text.RegularExpressions;
public class StartUp
{
public static void Main()
{
var hexNumbers = Console.ReadLine();
var pattern = @"\b(0x)?([0-9A-F]+)\b";
var matches = Regex.Matches(hexNumbers, pattern);
var validHexNums = matches
.Cast<Match>()
.Select(x => x.Value)
.ToArray();
Console.WriteLine(string.Join(" ", validHexNums));
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
namespace WpfApplication1
{
/// <summary>
/// Interaction logic for Build.xaml
/// </summary>
public class Prop
{
public string name { get; set; }
public int index { get; set; }
public Image flag { get; set; }
public Rectangle street { get; set; }
public Image bld { get; set; }
public Prop()
{ }
}
public partial class Build : Window
{
public Build()
{
InitializeComponent();
}
private void newSelection(object sender, SelectionChangedEventArgs e)
{
if (bProperty.SelectedItem != null)
{
var s = (Prop)bProperty.SelectedItem;
Cost.Visibility = Visibility.Visible;
Cost.Content = "$" + Convert.ToString(((Country)MainWindow.cdata.cells[s.index].prop).cost_to_build);
AddHouse.IsEnabled = (((Country)MainWindow.cdata.cells[s.index].prop).houses < 5);
}
else
{
Cost.Visibility = Visibility.Collapsed;
}
}
private void Bld_init(object sender, EventArgs e)
{
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
}
private void Add_house(object sender, RoutedEventArgs e)
{
var s = (Prop)bProperty.SelectedItem;
((Country)MainWindow.cdata.cells[s.index].prop).houses++;
var ih = (Image)MainWindow.cdata.wnd.FindName(s.name + "3");
ih.Source = new BitmapImage(new Uri("pack://application:,,,/WpfApplication1;component/Resources/home" + Convert.ToString(((Country)MainWindow.cdata.cells[s.index].prop).houses)+".png"));
AddHouse.IsEnabled = false;
s.bld.Source = ih.Source;
MainWindow.cdata.wnd.Build.IsEnabled = false;
Close();
}
private void newSelection(object sender, MouseButtonEventArgs e)
{
if (bProperty.SelectedItem != null)
{
var s = (Prop)bProperty.SelectedItem;
Cost.Visibility = Visibility.Visible;
Cost.Content = "$" + Convert.ToString(((Country)MainWindow.cdata.cells[s.index].prop).cost_to_build);
AddHouse.IsEnabled = (((Country)MainWindow.cdata.cells[s.index].prop).houses < 5);
}
else
{
Cost.Visibility = Visibility.Collapsed;
}
}
private void Window_ContentRendered(object sender, EventArgs e)
{
}
}
}
|
using AdminWebsite.Helper;
using FluentAssertions;
using NUnit.Framework;
using System;
using System.Collections.Generic;
using AdminWebsite.Services.Models;
namespace AdminWebsite.UnitTests.Helper
{
public class DateListMapperTest
{
[Test]
public void Should_return_range_of_dates_not_included_weekends()
{
var startDate = new DateTime(2020, 10, 1, 4, 30, 0, 0);
var endDate = new DateTime(2020, 10, 6, 4, 35, 0, 0);
var expectDays = 3;
var result = DateListMapper.GetListOfWorkingDates(startDate, endDate);
result.Count.Should().Be(expectDays);
}
[Test]
public void Should_return_empty_list_if_end_and_start_dates_is_the_same()
{
var startDate = new DateTime(2020, 10, 1);
var endDate = new DateTime(2020, 10, 1);
var expectDays = 0;
var result = DateListMapper.GetListOfWorkingDates(startDate, endDate);
result.Count.Should().Be(expectDays);
}
[Test]
public void Should_return_range_of_dates_not_included_weekends_and_public_holidays()
{
var startDate = new DateTime(2020, 10, 1, 4, 30, 0, 0);
var endDate = new DateTime(2020, 10, 6, 4, 35, 0, 0);
var pb = new PublicHoliday
{
Title = "Test Holidays",
Date = new DateTime(2020, 10, 5, 0, 0, 0, 0)
};
var publicHolidays = new List<PublicHoliday> {pb};
var expectDays = 2;
var result = DateListMapper.GetListOfWorkingDates(startDate, endDate, publicHolidays);
result.Count.Should().Be(expectDays);
}
}
}
|
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.RightsManagement;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
namespace VNPrototype
{
public class Settings
{
public double MusicVolume { get; set; }
public double SoundEffectsVolume { get; set; }
public int DialogueSpeed { get; set; }
public bool Fullscreen { get; set; }
public int FadeSpeed { get; } = 25;
public Settings(double musicVolume, double soundEffectsVolume, int dialogueSpeed, bool fullscreen)
{
MusicVolume = musicVolume;
SoundEffectsVolume = soundEffectsVolume;
DialogueSpeed = dialogueSpeed;
Fullscreen = fullscreen;
}
public static Settings LoadSettings()
{
return JsonConvert.DeserializeObject<Settings>(File.ReadAllText(@"..\..\resources\settings.json"));
}
public static void SaveSettings(Settings settings)
{
File.WriteAllText(@"..\..\resources\settings.json",JsonConvert.SerializeObject(settings, Formatting.Indented));
}
}
}
|
namespace Sila.Models.Database
{
using System;
/// <summary>
/// Represents an object able to be stored in a database.
/// </summary>
public interface IDatabaseObject
{
/// <summary>
/// The object identifier.
/// </summary>
String Id { get; }
}
} |
namespace WinAppDriver
{
using System;
[System.AttributeUsage(AttributeTargets.Class, AllowMultiple = true)]
internal class RouteAttribute : Attribute
{
public RouteAttribute(string method, string pattern)
{
this.Method = method;
this.Pattern = pattern;
}
public string Method { get; private set; }
public string Pattern { get; private set; }
}
} |
using EmailExtractor.DatabaseModel;
using MailKit;
using System.Collections.Generic;
namespace EmailExtractor.ImapConnector
{
interface IConnector
{
string ServerKey { get; }
IEnumerable<IMailFolder> Folders(IMailFolder rootFolder, bool recursive);
List<MailItem> ExtractMailItems(IMailFolder folder, int pageSize, int page, List<uint> existingUids);
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;
using UnityEngine.SceneManagement;
using System.IO;
using Michsky.UI.ModernUIPack;
public class Utils : MonoBehaviour
{
public static Map<int, string> interactionMap;
public static Dictionary<int, float[]> animationRequirements;
public static Dictionary<string, string> sceneNames;
public static string[] animations;
public static UnityEngine.KeyCode[] animationEnums;
public void MoveToRoom(string roomName)
{
Loading.sceneString = roomName;
SceneManager.LoadScene("Loading");
}
public void ChangeGlobalVolume(float f){
AudioListener.volume = f;
}
private void Awake()
{
sceneNames = new Dictionary<string, string>();
animationRequirements = new Dictionary<int, float[]>();
Physics.IgnoreLayerCollision(9, 10);
interactionMap = new Map<int, string>();
interactionMap.Add(1, "ShakeHand");
interactionMap.Add(2, "Diploma");
//interactionMap.Add(2, "TriggerShakeHand");
if (!animationRequirements.ContainsKey(1))
animationRequirements.Add(1, new[]{1.0f, 0.55f});
if (!animationRequirements.ContainsKey(2))
animationRequirements.Add(2, new[]{0.6f, 0.45f});
animations = new[]
{
"OnGround",
"Sit",
"Crouch",
"Clap",
"Wave",
"Samba",
"HipHop",
"Cheer",
//"IndividualShakeHand",
};
animationEnums = new[]
{
KeyCode.C,
KeyCode.Alpha1,
KeyCode.Alpha2,
KeyCode.Alpha3,
KeyCode.Alpha4,
KeyCode.Alpha5,
//KeyCode.H
};
if (!sceneNames.ContainsKey("1"))
sceneNames.Add("1", "The Lobby");
if (!sceneNames.ContainsKey("2"))
sceneNames.Add("2", "The Circle");
}
}
public class Map<T1, T2>
{
private Dictionary<T1, T2> _forward = new Dictionary<T1, T2>();
private Dictionary<T2, T1> _reverse = new Dictionary<T2, T1>();
public Map()
{
this.Forward = new Indexer<T1, T2>(_forward);
this.Reverse = new Indexer<T2, T1>(_reverse);
}
public class Indexer<T3, T4>
{
private Dictionary<T3, T4> _dictionary;
public Indexer(Dictionary<T3, T4> dictionary)
{
_dictionary = dictionary;
}
public T4 this[T3 index]
{
get { return _dictionary[index]; }
set { _dictionary[index] = value; }
}
}
public void Add(T1 t1, T2 t2)
{
_forward.Add(t1, t2);
_reverse.Add(t2, t1);
}
public Indexer<T1, T2> Forward { get; private set; }
public Indexer<T2, T1> Reverse { get; private set; }
}
|
using CESI_Afficheur.BDD;
using MySql.Data.MySqlClient;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
namespace CESI_Afficheur.Model
{
public class Message
{
public static MyDatabase MyDatabase { get; set; }
public int Message_Id { get; set; }
public string Libelle { get; set; }
public string HeureD { get; set; }
public string HeureF { get; set; }
public bool Important { get; set; }
public static void AddMessage(string message, string heured, string heuref, bool important)
{
if (checkIfMessageExist(message, heured, heuref,important))
{
string query = "INSERT INTO message (libelle,heured,heuref,important) VALUES ('" + message.Replace("'","''") + "', '" + heured + "', '" + heuref +"', " + important + "); ";
MyDatabase = new MyDatabase();
if (MyDatabase.OpenConnection() == true)
{
MySqlConnection connection = MyDatabase.getCon();
connection.Open();
//Create Command
MySqlCommand cmd = new MySqlCommand(query, connection);
//Execute command
cmd.ExecuteNonQuery();
MyDatabase.CloseConnection();
App.Server.NeddUpdate = true;
}
}
else
{
MessageBox.Show("Ce message existe déjà !");
}
}
public static void EditMessage(int Id, string message, string heured, string heuref, bool important)
{
string query = "UPDATE message SET libelle = '" + message.Replace("'","''") + "', heured = ' " + heured + " ', heuref = '" + heuref + "', important = " + important + " WHERE message_id= " + Id + ";";
MyDatabase = new MyDatabase();
if (MyDatabase.OpenConnection() == true)
{
MySqlConnection connection = MyDatabase.getCon();
connection.Open();
//Create Command
MySqlCommand cmd = new MySqlCommand(query, connection);
//Execute command
cmd.ExecuteNonQuery();
MyDatabase.CloseConnection();
App.Server.NeddUpdate = true;
}
}
public static void DeleteMessage(int Id)
{
string query = "DELETE FROM message WHERE message_id = " + Id + ";";
MyDatabase = new MyDatabase();
if (MyDatabase.OpenConnection() == true)
{
MySqlConnection connection = MyDatabase.getCon();
connection.Open();
//Create Command
MySqlCommand cmd = new MySqlCommand(query, connection);
//Execute command
cmd.ExecuteNonQuery();
MyDatabase.CloseConnection();
App.Server.NeddUpdate = true;
}
}
public static List<Message> GetMessage()
{
string query = "SELECT * FROM message";
MyDatabase = new MyDatabase();
//Create a list to store the result
List<Message> list = new List<Message>();
//Open connection
if (MyDatabase.OpenConnection() == true)
{
MySqlConnection connection = MyDatabase.getCon();
connection.Open();
//Create Command
MySqlCommand cmd = new MySqlCommand(query, connection);
//Create a data reader and Execute the command
MySqlDataReader dataReader = cmd.ExecuteReader();
//Read the data and store them in the list
while (dataReader.Read())
{
Message message = new Message();
message.Message_Id = (int)dataReader["message_Id"];
message.Libelle = (string)dataReader["libelle"];
message.HeureD = (string)dataReader["heured"];
message.HeureF = (string)dataReader["heuref"];
message.Important = (bool)dataReader["important"];
list.Add(message);
}
//close Data Reader
dataReader.Close();
//close Connection
MyDatabase.CloseConnection();
//return list to be displayed
return list;
}
else
{
return list;
}
}
public static bool checkIfMessageExist(string message, string heured, string heuref, bool important)
{
string query = "SELECT * FROM message WHERE libelle = '" + message.Replace("'","''") + "' AND heured = '"+ heured+ "' AND heuref = '" + heuref + "' ";
MyDatabase = new MyDatabase();
if (MyDatabase.OpenConnection() == true)
{
MySqlConnection connection = MyDatabase.getCon();
connection.Open();
//Create Command
MySqlCommand cmd = new MySqlCommand(query, connection);
//Create a data reader and Execute the command
MySqlDataReader dataReader = cmd.ExecuteReader();
//Read the data and store them in the list
while (dataReader.Read())
{
return false;
}
//close Data Reader
dataReader.Close();
//close Connection
MyDatabase.CloseConnection();
return true;
}
return false;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Threading.Tasks;
using System.Windows.Forms;
using UseFul.ClientApi;
using UseFul.ClientApi.Dtos;
using UseFul.Forms.Welic;
using UseFul.Uteis;
using UseFul.Uteis.UI;
namespace Welic.WinForm.Cadastros.Pessoas
{
public partial class FrmCadastroPessoas : FormCadastro
{
private PessoaDto _pessoaDto;
public FrmCadastroPessoas()
{
InitializeComponent();
//Inicialização dos Eventos.
this.Load += new EventHandler(LoadFormulario);
this.toolStripBtnNovo.Visible = true;
this.toolStripBtnNovo.Click += new EventHandler(ClickNovo);
this.toolStripBtnEditar.Visible = true;
this.toolStripBtnEditar.Click += new EventHandler(ClickEditar);
this.toolStripBtnExcluir.Visible = true;
this.toolStripBtnExcluir.Click += new EventHandler(ClickExcluir);
this.toolStripBtnGravar.Visible = true;
this.toolStripBtnGravar.Click += new EventHandler(ClickGravar);
this.toolStripBtnVoltar.Visible = true;
this.toolStripBtnVoltar.Click += new EventHandler(ClickVoltar);
this.toolStripBtnLocalizar.Visible = false;
//this.toolStripBtnLocalizar.Click += new EventHandler(ClickLocalizar);
this.toolStripBtnImprimir.Visible = false;
//this.toolStripBtnImprimir.Click += new EventHandler(ClickImprimir);
this.toolStripBtnAuditoria.Visible = false;
this.toolStripBtnAjuda.Visible = false;
//this.toolStripBtnAjuda.Click += new EventHandler(ClickAjuda);
this.toolStripSeparatorAcoes.Visible = true;
this.toolStripSeparatorOutros.Visible = false;
this.KeyUp += new KeyEventHandler(KeyUpFechar);
}
private void LimpaCamposNaoChave()
{
LimpaCamposNaoChave(this.Controls);
cboSexo.SelectedIndex = 0;
if (cboUfEndereco.Items.Count > 0)
cboUfEndereco.SelectedIndex = 0;
if (cboUfNaturalidade.Items.Count > 0)
cboUfNaturalidade.SelectedIndex = 0;
if (cboUfOrgaoExpedidor.Items.Count > 0)
cboUfOrgaoExpedidor.SelectedIndex = 0;
}
/// <summary>
/// Código Padrão - Load do Formulário - Tela de Cadastro
/// Versão 0.1 - 13/08/2010
/// </summary>
private void LoadFormulario(object sender, EventArgs e)
{
LiberaChaveBloqueiaCampos(this.Controls);
LimpaCampos(this.Controls);
ModoOpcoes();
AcaoFormulario = CAcaoFormulario.Nenhum;
}
/// <summary>
/// Código Padrão - Ação Botão Novo - Tela de Cadastro
/// Versão 0.1 - 13/08/2010
/// </summary>
private void ClickNovo(object sender, EventArgs e)
{
LimpaCamposBloqueiaAutoIncremento(this.Controls);
LimpaCamposNaoChave();
ModoGravacao();
AcaoFormulario = CAcaoFormulario.Novo;
}
/// <summary>
/// Código Padrão - Ação Botão Editar - Tela de Cadastro
/// Versão 0.1 - 23/08/2010
/// </summary>
private void ClickEditar(object sender, EventArgs e)
{
if (!ValidaCamposObrigatorios(this.Controls))
MessageBox.Show("Por favor, preencha os campos que identificam o registro a ser alterado.", "Atenção", MessageBoxButtons.OK, MessageBoxIcon.Information);
else
{
BloqueiaChaveLiberaCampos(this.Controls);
ModoGravacao();
AcaoFormulario = CAcaoFormulario.Editar;
}
}
/// <summary>
/// Código Padrão - Ação Botão Excluir - Tela de Cadastro
/// Versão 0.1 - 23/08/2010
/// </summary>
private void ClickExcluir(object sender, EventArgs e)
{
if (!ValidaCamposObrigatorios(this.Controls))
MessageBox.Show("Por favor, preencha os campos que identificam o registro a ser excluído.", "Atenção", MessageBoxButtons.OK, MessageBoxIcon.Information);
else
{
if (MessageBox.Show("Confirma a exclusão do registro?", "Atenção", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) == DialogResult.Yes)
{
try
{
_pessoaDto = (PessoaDto) BindingPessoa.DataSource;
HttpResponseMessage
response = ClienteApi.Instance.RequisicaoPost($"pessoa/delete/{_pessoaDto.IdPessoa}");
ClienteApi.Instance.ObterResposta(response);
MensagemStatusBar("Excluído com sucesso.");
LiberaChaveBloqueiaCampos(this.Controls);
LimpaCampos(this.Controls);
AcaoFormulario = CAcaoFormulario.Excluir;
}
catch (CustomException ex)
{
ProcessMessage(ex.Message, MessageType.Error);
}
catch (Exception exception)
{
ProcessException(exception);
}
}
}
}
/// <summary>
/// Código Padrão - Ação Botão Gravar - Tela de Cadastro
/// Versão 0.1 - 23/08/2010
/// </summary>
private void ClickGravar(object sender, EventArgs e)
{
if (!ValidaCamposObrigatorios(this.Controls))
MessageBox.Show("Por favor, preencha os campos que identificam o registro.", "Atenção", MessageBoxButtons.OK, MessageBoxIcon.Information);
else
{
try
{
_pessoaDto = new PessoaDto()
{
NomePai = txtNomePai.Text,
Celular = txtTelCelular.MaskFull ? txtTelCelular.Text.Replace("(", "").Replace(")", "").Replace("-", "") : "",
Bairro = txtBairro.Text,
Cep = int.Parse(txtCEP.Text.Replace(".", "").Replace("-", "").Trim()),
Cidade = txtCidadeEndereco.Text,
Complemento = txtComplemento.Text,
Cpf = long.Parse(txtCPF.Text.Replace(".", "").Replace("-", "").Trim()),
DataExpedicao = DateTime.Parse(txtDtExpedicaoRG.Text.Trim()),
DataNascimeto = DateTime.Parse(txtDtNascimento.Text.Trim()),
Email = txtEmail.Text,
EmailCorporativo = txtEmailCorporativo.Text,
Endereco = txtEndereco.Text,
EstadoCivil = txtEstadoCivilDesc.Text,
Identidade = txtRG.Text,
OrgaoExpeditor = cboUfOrgaoExpedidor.SelectedItem.ToString(),
Nacionalidade = txtNacionalidadeDesc.Text,
Naturalidade = txtCidadeNaturalidade.Text,
Nome = txtNome.Text,
NomeMae = txtNomeMae.Text,
Numero = txtNumero.Text,
Secao = int.Parse(txtSecao.Text),
Zona = int.Parse(txtZona.Text),
Sexo = cboSexo.SelectedIndex,//1-masculino; 2-feminino
Telefone = txtTelResidencial.MaskFull ? txtTelResidencial.Text.Replace("(", "").Replace(")", "").Replace("-", "") : "",
TelComercial = txtTelComercial.MaskFull ? txtTelComercial.Text.Replace("(", "").Replace(")", "").Replace("-", "") : "",
TituloEleitor = txtTituloEleitor.Text,
UfExpeditor = cboUfOrgaoExpedidor.SelectedIndex,
};
#region campos
//int? cidadeNaturalidade = null;
//if (!string.IsNullOrEmpty(txtCidadeNaturalidade.Text.Trim()))
// cidadeNaturalidade = int.Parse(txtCidadeNaturalidade.Text);
//int? nacionalidade = null;
//if (!string.IsNullOrEmpty(txtNacionalidade.Text.Trim()))
// nacionalidade = int.Parse(txtNacionalidade.Text);
//string rg = txtRG.Text;
//int? cidadeEndereco = null;
//if (!string.IsNullOrEmpty(txtCidadeEndereco.Text.Trim()))
// cidadeEndereco = int.Parse(txtCidadeEndereco.Text);
#endregion
if (AcaoFormulario == CAcaoFormulario.Novo)
{
HttpResponseMessage
response = ClienteApi.Instance.RequisicaoPost("pessoa/save", _pessoaDto);
_pessoaDto =
ClienteApi.Instance.ObterResposta<PessoaDto>(response);
txtPessoa.Text = _pessoaDto.IdPessoa.ToString();
MensagemInsertUpdate("Salvo com sucesso.");
}
else if (AcaoFormulario == CAcaoFormulario.Editar)
{
//Busca Entidade pelas chaves
_pessoaDto.IdPessoa = int.Parse(txtPessoa.Text);
HttpResponseMessage
response = ClienteApi.Instance.RequisicaoPost("pessoa/update", _pessoaDto);
MensagemInsertUpdate("Alterado com sucesso.");
}
LiberaChaveBloqueiaCampos(this.Controls);
ModoOpcoes();
AcaoFormulario = CAcaoFormulario.Gravar;
}
catch (CustomException ex)
{
ProcessMessage(ex.Message, MessageType.Error);
}
catch (Exception exception)
{
ProcessException(exception);
}
}
}
private void MensagemInsertUpdate(string mensagem)
{
MensagemStatusBar(mensagem);
}
/// <summary>
/// Código Padrão - Ação Botão Voltar - Tela de Cadastro
/// Versão 0.1 - 23/08/2010
/// </summary>
private void ClickVoltar(object sender, EventArgs e)
{
LiberaChaveBloqueiaCampos(this.Controls);
LimpaCamposNaoChave();
ModoOpcoes();
AcaoFormulario = CAcaoFormulario.Voltar;
}
/// <summary>
/// Código Padrão - Ação KeyUp Fechar(Esc) - Tela de Cadastro
/// Versão 0.1 - 23/08/2010
/// </summary>
private void KeyUpFechar(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Escape)
{
if (AcaoFormulario == CAcaoFormulario.Novo || AcaoFormulario == CAcaoFormulario.Editar)
LoadFormulario(sender, new EventArgs());
else
this.Close();
}
}
private async void txtPessoa_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
txtPessoa_Leave(sender, new EventArgs());
}
else if (e.KeyCode == Keys.F3)
{
Task<HttpResponseMessage> response =
ClienteApi.Instance.RequisicaoGetAsync("pessoa/get");
Task<List<PessoaDto>> retorno =
ClienteApi.Instance.ObterRespostaAsync<List<PessoaDto>>(await response);
if (retorno.Result.Count > 0 && retorno != null)
{
var Fb = new FormBuscaPaginacao();
Fb.SetListAsync<PessoaDto>(retorno.Result, "Nome");
Fb.ShowDialog();
BindingPessoa.DataSource = Fb.RetornoList<PessoaDto>();
}
}
}
private async void txtPessoa_Leave(object sender, EventArgs e)
{
if (!string.IsNullOrEmpty(txtPessoa.Text.Trim()))
{
Task<HttpResponseMessage> response =
ClienteApi.Instance.RequisicaoGetAsync($"pessoa/getbyid/{int.Parse(txtPessoa.Text)}");
Task<PessoaDto> retorno =
ClienteApi.Instance.ObterRespostaAsync<PessoaDto>(await response);
if (retorno.Result != null)
{
BindingPessoa.DataSource = retorno.Result;
}
else
{
LimpaCamposNaoChave();
}
}
else
{
LimpaCamposNaoChave();
}
}
private void cboNaturalidadeUF_SelectedIndexChanged(object sender, EventArgs e)
{
if (cboUfNaturalidade.SelectedIndex > 0)
{
txtCidadeNaturalidade.Enabled = true;
txtCidadeNaturalidade.ReadOnly = false;
}
else
{
txtCidadeNaturalidade.Enabled = false;
txtCidadeNaturalidade.ReadOnly = true;
}
}
private async void txtCidadeNaturalidade_KeyDown(object sender, KeyEventArgs e)
{
if (cboUfNaturalidade.SelectedIndex > 0)
{
Task<HttpResponseMessage> response =
ClienteApi.Instance.RequisicaoGetAsync("city/get");
Task<List<CityDto>> retorno =
ClienteApi.Instance.ObterRespostaAsync<List<CityDto>>(await response);
if (retorno != null)
{
var Fb = new FormBuscaPaginacao();
Fb.SetListAsync<CityDto>(retorno.Result, "Cep");
Fb.ShowDialog();
BindingPessoa.DataSource = Fb.RetornoList<CityDto>();
}
else
{
MessageBox.Show("Não foi encontrado nenhuma cidade");
}
}
}
private async void txtCidadeNaturalidade_Leave(object sender, EventArgs e)
{
Task<HttpResponseMessage> response =
ClienteApi.Instance.RequisicaoGetAsync($"city/getbyid/{int.Parse(txtCidadeNaturalidade.Text)}");
Task<CityDto> retorno =
ClienteApi.Instance.ObterRespostaAsync<CityDto>(await response);
txtCidadeNaturalidadeDesc.Text = retorno.Result.Nome;
if (string.IsNullOrEmpty(txtCidadeNaturalidadeDesc.Text))
txtCidadeNaturalidade.Text = "";
}
private void cboEstadoEndereco_SelectedIndexChanged(object sender, EventArgs e)
{
if (cboUfNaturalidade.SelectedIndex > 0)
{
txtCidadeEndereco.Enabled = true;
txtCidadeEndereco.ReadOnly = false;
}
else
{
txtCidadeEndereco.Enabled = false;
txtCidadeEndereco.ReadOnly = true;
}
}
private async void txtCidadeEndereco_KeyDown(object sender, KeyEventArgs e)
{
if (cboUfEndereco.SelectedIndex > 0)
{
Task<HttpResponseMessage> response =
ClienteApi.Instance.RequisicaoGetAsync("city/get");
Task<List<CityDto>> retorno =
ClienteApi.Instance.ObterRespostaAsync<List<CityDto>>(await response);
var Fb = new FormBuscaPaginacao();
Fb.SetListAsync<CityDto>(retorno.Result, "Cep");
Fb.ShowDialog();
BindingPessoa.DataSource = Fb.RetornoList<CityDto>();
}
}
private async void txtCidadeEndereco_Leave(object sender, EventArgs e)
{
Task<HttpResponseMessage> response =
ClienteApi.Instance.RequisicaoGetAsync($"city/getbyid/{int.Parse(txtCidadeNaturalidade.Text)}");
Task<CityDto> retorno =
ClienteApi.Instance.ObterRespostaAsync<CityDto>(await response);
txtCidadeEnderecoDesc.Text = retorno.Result.Nome;
if (string.IsNullOrEmpty(txtCidadeEnderecoDesc.Text))
txtCidadeEndereco.Text = "";
}
private void txtTelCelular_TextChanged(object sender, EventArgs e)
{
if (txtTelCelular.Text.Trim().Length > 2)
txtTelCelular.Mask = Validacao.verificaCelular(txtTelCelular.Text.Replace("-", "").Replace("(","").Replace(")",""));
}
}
}
|
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using AutoMapper;
using Castle.Services.Transaction;
using com.Sconit.Entity;
using com.Sconit.Entity.Exception;
using com.Sconit.Entity.ORD;
namespace com.Sconit.Service.Impl
{
[Transactional]
public class ShipmentMgrImpl : BaseMgr, IShipmentMgr
{
public IGenericMgr genericMgr { get; set; }
[Transaction(TransactionMode.Requires)]
public void CreateBillofLadingMaster(ShipmentMaster shipmentMaster)
{
genericMgr.Create(shipmentMaster);
foreach (var shipmentDetail in shipmentMaster.ShipmentDetails)
{
genericMgr.Create(shipmentDetail);
}
}
[Transaction(TransactionMode.Requires)]
public void DeleteBillofLadingMaster(ShipmentMaster billofLadingMaster)
{
genericMgr.Delete(billofLadingMaster.ShipmentDetails);
genericMgr.Delete(billofLadingMaster);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using PiwoBack.Data.ViewModels;
using PiwoBack.Services.Interfaces;
namespace PiwoBack.API.Controllers
{
[Produces("application/json")]
[Route("api/[controller]")]
public class BeerController : Controller
{
private readonly IBeerService _beerService;
public BeerController(IBeerService beerService)
{
_beerService = beerService;
}
[HttpGet]
public IActionResult GetBeers()
{
var beers = _beerService.GetAll();
return Ok(beers);
}
[HttpGet("best")]
public IActionResult GetTop7()
{
var top7beers = _beerService.GetTop7Beers(); // Top powinno być konfigurowalne( Top{liczba})
return Ok(top7beers);
}
[HttpGet("{id}")]
public IActionResult GetBeer(int id)
{
var beer = _beerService.GetBeer(id);
if(beer == null)
{
return NotFound();
}
return Ok(beer);
}
[HttpPost("add")]
public IActionResult AddBeer([FromBody]BeerViewModel beerViewModel)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
var result = _beerService.AddBeer(beerViewModel);
if(result.IsError)
{
return BadRequest(result.Errors);
}
return Ok(result);
}
[HttpPost("edit/{id}")]
public IActionResult EditBeer(int? id, [FromBody] BeerViewModel beerViewModel)
{
if (id == null)
{
return NotFound();
}
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
var result = _beerService.EditBeer(id.Value, beerViewModel);
return Ok(result);
}
[HttpDelete("delete/{id}")]
public IActionResult DeleteBeer(int? id)
{
if (id == null)
{
return NotFound();
}
var result = _beerService.DeleteBeer(id.Value);
return Ok(result);
}
[HttpGet("random")]
public IActionResult GetRandom()
{
var result = _beerService.GetRandom();
return Ok(result);
}
[HttpPost("addpicture")]
public IActionResult AddBeerPicture(IFormFile beerPicture, int beerId)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
var result = _beerService.AddBeerPicture(beerPicture, beerId);
if (result.IsError)
{
return BadRequest(result);
}
return Ok(result);
}
}
} |
using gView.Framework.FDB;
using gView.Framework.Geometry;
using System;
using System.Text;
namespace gView.Framework.Data
{
public class gViewSpatialIndexDef : ISpatialIndexDef
{
private IEnvelope _bounds = new Envelope();
private double _spatialRatio = 0.55;
private int _maxPerNode = 200;
private int _levels = 30;
private ISpatialReference _sRef = null;
public gViewSpatialIndexDef()
{
}
public gViewSpatialIndexDef(IEnvelope bounds, int levels)
{
if (bounds != null)
{
_bounds = bounds;
}
if (_levels > 0 && _levels < 62)
{
_levels = levels;
}
}
public gViewSpatialIndexDef(IEnvelope bounds, int levels, int maxPerNode, double spatialRatio)
: this(bounds, levels)
{
if (_maxPerNode > 0)
{
_maxPerNode = maxPerNode;
}
_spatialRatio = spatialRatio;
}
#region ISpatialIndexDef Member
public GeometryFieldType GeometryType
{
get { return GeometryFieldType.Default; }
}
public IEnvelope SpatialIndexBounds
{
get { return _bounds; }
set { _bounds = value; }
}
public double SplitRatio
{
get { return _spatialRatio; }
set { _spatialRatio = value; }
}
public int MaxPerNode
{
get { return _maxPerNode; }
set { _maxPerNode = value; }
}
public int Levels
{
get { return _levels; }
set { _levels = value; }
}
public ISpatialReference SpatialReference
{
get { return _sRef; }
set { _sRef = value; }
}
public bool ProjectTo(ISpatialReference sRef)
{
if (_bounds == null)
{
return false;
}
if (_sRef != null && !_sRef.Equals(sRef))
{
IGeometry result = GeometricTransformerFactory.Transform2D(_bounds, _sRef, sRef);
if (result != null && result.Envelope != null)
{
_bounds = result.Envelope;
_sRef = sRef;
return true;
}
}
return true;
}
#endregion
}
public enum MSSpatialIndexLevelSize
{
NO = 0,
LOW = 1,
MEDIUM = 2,
HIGH = 3
}
public class MSSpatialIndex : ISpatialIndexDef
{
private IFormatProvider _nhi = System.Globalization.CultureInfo.InvariantCulture.NumberFormat;
private GeometryFieldType _fieldType = GeometryFieldType.MsGeometry;
private IEnvelope _extent;
private int _cellsPerObject = 256;
private MSSpatialIndexLevelSize _level1 = MSSpatialIndexLevelSize.NO;
private MSSpatialIndexLevelSize _level2 = MSSpatialIndexLevelSize.NO;
private MSSpatialIndexLevelSize _level3 = MSSpatialIndexLevelSize.NO;
private MSSpatialIndexLevelSize _level4 = MSSpatialIndexLevelSize.NO;
private ISpatialReference _sRef = null;
public MSSpatialIndex()
{
IEnvelope _extent = new Envelope();
}
#region Properties
public int CellsPerObject
{
get { return this.MaxPerNode; }
set { this.MaxPerNode = value; }
}
public MSSpatialIndexLevelSize Level1
{
get { return _level1; }
set { _level1 = value; }
}
public MSSpatialIndexLevelSize Level2
{
get { return _level2; }
set { _level2 = value; }
}
public MSSpatialIndexLevelSize Level3
{
get { return _level3; }
set { _level3 = value; }
}
public MSSpatialIndexLevelSize Level4
{
get { return _level4; }
set { _level4 = value; }
}
#endregion
public string ToSql(string indexName, string tableName, string colName)
{
StringBuilder sb = new StringBuilder();
if (_fieldType == GeometryFieldType.MsGeography)
{
sb.Append("CREATE SPATIAL INDEX " + indexName);
sb.Append(" ON " + tableName + "(" + colName + ")");
sb.Append(" USING GEOGRAPHY_GRID WITH (");
sb.Append("GRIDS = (LEVEL_1 = " + _level1.ToString() + ", LEVEL_2 = " + _level2.ToString() + ", LEVEL_3 = " + _level3.ToString() + ", LEVEL_4 = " + _level4.ToString() + ")");
sb.Append(",CELLS_PER_OBJECT = " + _cellsPerObject.ToString());
sb.Append(")");
}
else if (_fieldType == GeometryFieldType.MsGeometry)
{
sb.Append("CREATE SPATIAL INDEX " + indexName);
sb.Append(" ON " + tableName + "(" + colName + ")");
sb.Append(" USING GEOMETRY_GRID WITH (");
if (_extent != null)
{
sb.Append("BOUNDING_BOX = (");
sb.Append("xmin=" + _extent.minx.ToString(_nhi) + ",");
sb.Append("ymin=" + _extent.miny.ToString(_nhi) + ",");
sb.Append("xmax=" + _extent.maxx.ToString(_nhi) + ",");
sb.Append("ymax=" + _extent.maxy.ToString(_nhi) + "),");
}
sb.Append("GRIDS = (LEVEL_1 = " + _level1.ToString() + ", LEVEL_2 = " + _level2.ToString() + ", LEVEL_3 = " + _level3.ToString() + ", LEVEL_4 = " + _level4.ToString() + ")");
sb.Append(",CELLS_PER_OBJECT = " + _cellsPerObject.ToString());
sb.Append(")");
}
return sb.ToString();
}
#region ISpatialIndexDef Member
public GeometryFieldType GeometryType
{
get { return _fieldType; }
set
{
if (value == GeometryFieldType.MsGeography ||
value == GeometryFieldType.MsGeometry)
{
_fieldType = value;
}
}
}
public IEnvelope SpatialIndexBounds
{
get { return _extent; }
set { _extent = value; }
}
public double SplitRatio
{
get { return 0.0; }
}
public int MaxPerNode
{
get { return _cellsPerObject; }
set { _cellsPerObject = value; }
}
public int Levels
{
get
{
return (int)_level1 +
((int)_level2 << 4) +
((int)_level3 << 8) +
((int)_level4 << 12);
}
set
{
_level1 = (MSSpatialIndexLevelSize)(value & 0xf);
_level2 = (MSSpatialIndexLevelSize)((value >> 4) & 0xf);
_level3 = (MSSpatialIndexLevelSize)((value >> 8) & 0xf);
_level4 = (MSSpatialIndexLevelSize)((value >> 12) & 0xf);
}
}
public ISpatialReference SpatialReference
{
get { return _sRef; }
set { _sRef = value; }
}
public bool ProjectTo(ISpatialReference sRef)
{
if (_extent == null)
{
return false;
}
if (_sRef != null && !_sRef.Equals(sRef))
{
IGeometry result = GeometricTransformerFactory.Transform2D(_extent, _sRef, sRef);
if (result != null && result.Envelope != null)
{
_extent = result.Envelope;
_sRef = sRef;
return true;
}
}
return true;
}
#endregion
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Airelax.Application.Messages.Request;
using Airelax.Application.Messages.Response;
using Airelax.Domain.Messages;
using Airelax.Domain.RepositoryInterface;
using Airelax.EntityFramework.Repositories;
using Lazcat.Infrastructure.DependencyInjection;
namespace Airelax.Application.Messages
{
[DependencyInjection(typeof(IMessageService))]
public class MessageService : IMessageService
{
private readonly IMessageRepository _messageRepository;
private readonly IHouseRepository _houseRepository;
private readonly IMemberRepository _memberRepository;
public MessageService(IMessageRepository messageRepository, IHouseRepository houseRepository, IMemberRepository memberRepository)
{
_messageRepository = messageRepository;
_houseRepository = houseRepository;
_memberRepository = memberRepository;
}
public async Task<List<MessageDto>> GetMessage(string memberId)
{
var messages = _messageRepository.GetMessage(memberId);
List<MessageDto> result = new List<MessageDto>();
foreach (var item in messages)
{
var house = await _houseRepository.GetAsync(x => x.Id == item.HouseId);
//兩種情況 - 查詢人是房東或房客
var member = _memberRepository
.GetMemberInfoSearchObject(memberId == house.OwnerId ? (item.MemberOneId == memberId ? item.MemberTwoId : item.MemberOneId) : memberId);
var owner = _memberRepository.GetMemberInfoSearchObject(house.OwnerId);
result.Add(new MessageDto
{
Id = item.Id,
ConnectString = $"{item.MemberOneId}-{item.MemberTwoId}",
MemberId = memberId,
GusetId = memberId == house.OwnerId ? item.MemberTwoId : item.MemberOneId,
Name = member.First().MemberName,
Portrait = member.First().Cover,
Pictures = house.Photos?.Select(x => x.Image) ?? new List<string>(),
MemberOneStatus = item.MemberOneStatus,
MemberTwoStatus = item.MemberTwoStatus,
Landlord = new LandlordDto
{
Id = house.OwnerId,
HouseId = house.Id,
Cover = owner.First().Cover,
Name = owner.First().MemberName
},
TourDetail = new TourDetailDto
{
StartDate = item.StartDate,
EndDate = item.EndDate,
Title = house.Title,
City = house.HouseLocation?.City,
Country = house.HouseLocation?.Country,
Town = house.HouseLocation?.Town
},
Communications = item.Contents.Select(x =>
new CommunicationDto
{
SenderId = x.SenderId,
ReceiverId = x.ReceiverId,
Content = x.Content,
Time = x.Time
}).ToList()
,
Origin = house.HousePrice?.PerNight ?? 0,
PaymentDetail = new PaymentDetail
{
CleanFee = house.HousePrice?.Fee?.CleanFee??0,
ServiceFee = house.HousePrice?.Fee?.ServiceFee??0,
TaxFee = house.HousePrice?.Fee?.TaxFee??0,
}
});
}
return result;
}
public bool UpdateContent(string id, MessageInupt input)
{
var message = _messageRepository.UpdateMessage(input.senderId, input.receiverId);
//重要 signalR有時候會重複寫入資料
if(message.Contents.Last().SenderId == input.senderId && message.Contents.Last().ReceiverId == input.receiverId && message.Contents.Last().Time == input.time && message.Contents.Last().Content == input.content) return true;
message.Contents.Add(new MessageContent()
{
Content = input.content,
SenderId = input.senderId,
ReceiverId = input .receiverId,
Time = input.time
});
Update(message);
return true;
}
public bool UpdateStatus(string id, UpdateStatusInput input)
{
var message = _messageRepository.UpdateMessage(input.MemberId, input.OtherId);
if (message.MemberOneId == input.MemberId) message.MemberOneStatus = 0;
else message.MemberTwoStatus = 0;
Update(message);
return true;
}
public bool UpdateOnTime(string id, UpdateStatusInput input)
{
var message = _messageRepository.UpdateMessage(input.MemberId, input.OtherId);
if (message.MemberOneId == input.MemberId) message.MemberTwoStatus += 1;
else message.MemberOneStatus += 1;
Update(message);
return true;
}
public bool CreateContent(string id, CreateMessageInput input)
{
var message = _messageRepository.UpdateMessage(input.MemberOneId, input.MemberTwoId);
if (message == null)
{
var createItem = new Message()
{
MemberOneId = input.MemberOneId,
MemberTwoId = input.MemberTwoId,
EndDate = input.EndDate,
StartDate = input.StartDate,
HouseId = input.HouseId,
Contents = input.Contents,
MemberOneStatus = input.MemberOneStatus,
MemberTwoStatus = input.MemberTwoStatus
};
_messageRepository.CreateMessage().Add(createItem);
_messageRepository.Create(createItem);
_messageRepository.SaveChange();
}
else
{
var updateItem = new MessageInupt()
{
content = input.Contents.FirstOrDefault().Content,
senderId = input.Contents.FirstOrDefault().SenderId,
receiverId = input.Contents.FirstOrDefault().ReceiverId,
time = input.Contents.FirstOrDefault().Time
};
var mes = _messageRepository.UpdateMessage(updateItem.senderId, updateItem.receiverId);
mes.MemberOneStatus += input.MemberOneStatus;
mes.Contents.Add(new MessageContent()
{
Content = updateItem.content,
SenderId = updateItem.senderId,
ReceiverId = updateItem.receiverId,
Time = updateItem.time
});
Update(mes);
}
return true;
}
public void Update(Message message)
{
_messageRepository.Update(message);
_messageRepository.SaveChange();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace EmrEditor
{
class TempletManagement
{
}
}
|
using Xunit;
namespace AplicacaoDemo.Tests.TestesFeatures
{
[Collection(nameof(ClienteCollection))]
public class ClientTestsFakeWithFixture
{
private readonly ClienteTestsFixture _clienteTestsFixture;
public ClientTestsFakeWithFixture(ClienteTestsFixture clienteTestsFixture)
{
_clienteTestsFixture = clienteTestsFixture;
}
[Fact(DisplayName = "Novo Cliente deve ser válido")]
[Trait("Categoria", "2 - Fixture")]
public void Cliente_NovoCliente_DeveSerValido()
{
// Arrange
var cliente = _clienteTestsFixture.GerarClienteValido();
// Act
var resultado = cliente.EhValido();
// Assert
Assert.True(resultado);
Assert.Equal(0, cliente.ValidationResult.Errors.Count);
}
[Fact(DisplayName = "Novo Cliente deve ser inválido")]
[Trait("Categoria", "2 - Fixture")]
public void Cliente_NovoCliente_DeveSerInvalido()
{
// Arrange
var cliente = _clienteTestsFixture.GerarClienteInvalido();
// Act
var resultado = cliente.EhValido();
// Assert
Assert.False(resultado);
Assert.NotEqual(0, cliente.ValidationResult.Errors.Count);
}
}
}
|
using UnityEngine;
[System.Serializable]
public class BeatAspect {
public string nickname;
public AudioClip clip;
public int beatStart;
public int beatsPer;
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Hover : MonoBehaviour
{
public float amplitude;
float originY;
void Start()
{
originY = transform.position.y;
}
void Update()
{
float y = originY + (amplitude * Mathf.Sin(Time.time));
transform.position = new Vector3(transform.position.x, y, transform.position.z);
}
}
|
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Windows.Forms;
using System.Windows.Media;
using CS_2_HomeWork.Object;
namespace CS_2_HomeWork
{
/// <summary>
/// Делегат для логера
/// </summary>
/// <param name="msg"></param>
public delegate void ToLog(string msg);
/// <summary>
/// Делегат для пуль
/// </summary>
/// <returns></returns>
public delegate bool DelBull();
class Game
{
private static Timer timer = new Timer();
public static Random rnd = new Random();
private static BufferedGraphicsContext _context;
public static BufferedGraphics Buffer;
/// <summary>
/// Событие для логера
/// </summary>
public static event ToLog Write;
/// <summary>
/// Корабль
/// </summary>
private static Ship ship;
/// <summary>
/// Установка ширины игрового поля
/// </summary>
public static int Width
{
get => width;
set
{
if (value > 1001 || value < 0) throw new ArgumentOutOfRangeException("Недопустимая ширина игрового поля");
width = value;
}
}
/// <summary>
/// Ширина игрового поля
/// </summary>
private static int width;
/// <summary>
/// Установка высоты игрового поля
/// </summary>
public static int Height
{
get => height;
set
{
if (value > 1001 || value < 0) throw new ArgumentOutOfRangeException("Недопустимая высота игрового поля");
height = value;
}
}
/// <summary>
/// Выоста игрового поля
/// </summary>
private static int height;
static Game()
{
}
/// <summary>
/// Обработчик нажатия клавиш
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private static void GameForm_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Up) Game.IsShipUpKeyPress = true;
if (e.KeyCode == Keys.Down) Game.IsShipDownKeyPress = true;
if (e.KeyCode == Keys.Space) Game.IsShootKeyPress = true;
}
/// <summary>
/// Обработчик отпускания клавиш
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private static void GameForm_KeyUp(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Up) Game.IsShipUpKeyPress = false;
if (e.KeyCode == Keys.Down) Game.IsShipDownKeyPress = false;
if (e.KeyCode == Keys.Space) Game.IsShootKeyPress = false;
}
/// <summary>
/// Флаг клавиши выстрела
/// </summary>
public static bool IsShootKeyPress { get; set; } = false;
/// <summary>
/// Флаг клавиши вверх
/// </summary>
public static bool IsShipUpKeyPress { get; set; } = false;
/// <summary>
/// Флаг клавиши вниз
/// </summary>
public static bool IsShipDownKeyPress { get; set; } = false;
/// <summary>
/// Графическое устройство для вывода графики
/// </summary>
/// <param name="form"></param>
public static void Init(Form form)
{
Graphics g;
// Предоставляет доступ к главному буферу гарфического контекста
// для текущего приложения
_context = BufferedGraphicsManager.Current;
g = form.CreateGraphics();
// Обработчики событий
form.KeyDown += GameForm_KeyDown;
form.KeyUp += GameForm_KeyUp;
// Создание объекта, связывание его с формой
// Сохранение размера формы
form.Width = width;
form.Height = height;
// Связывание буфера в памяти с графическим объектом, чтобы рисовать в буфере
Buffer = _context.Allocate(g, new Rectangle(0, 0, Width, Height));
Load();
Timer timer = new Timer { Interval = 60 };
timer.Start();
timer.Tick += Timer_Tick;
}
/// <summary>
/// Коллеция объектов
/// </summary>
public static List<BaseObject> objs;
/// <summary>
/// Коллекция астероидов
/// </summary>
private static List<Asteroid> asteroids;
/// <summary>
/// Максимальное кол-во астероидов
/// </summary>
public static int MaxAsteroids { get; set; } = 8;
/// <summary>
/// Коллекция аптечек
/// </summary>
private static List<Kit> kit;
/// <summary>
/// Объект пули
/// </summary>
public static List<Bullet> bullets;
/// <summary>
/// Фоновая музыка
/// </summary>
private static MediaPlayer foneM = new MediaPlayer
{
};
/// <summary>
/// Музыка проигрыша
/// </summary>
private static MediaPlayer loseM = new MediaPlayer
{
};
/// <summary>
/// Метод для воспроизведения фоновой музыки
/// </summary>
private static void PlayLoseMusic()
{
foneM.Open(new Uri(System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "../../Resources/Sanctuary_Guardian.wav")));
foneM.Volume = 0.1;
foneM.Play();
}
/// <summary>
/// Метод для воспроизведения фоновой музыки
/// </summary>
private static void PlayFoneMusic()
{
foneM.Open(new Uri(System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "../../Resources/PigStep.wav")));
foneM.Volume = 0.2;
foneM.Play();
}
/// <summary>
/// Создание астероидов
/// </summary>
public static void AsterCrt()
{
asteroids = new List<Asteroid>(MaxAsteroids);
Bitmap img_ast = new Bitmap("../../Resources/ceres.png");
for (int i = 0; i < MaxAsteroids; i++)
{
int r = rnd.Next(50, 80);
asteroids.Add(new Asteroid(img_ast, new Point((Game.Width + rnd.Next(700)), rnd.Next(81, Game.Height)), new Point(5), new Size(r, r)));
}
}
/// <summary>
/// Метод создания объектов
/// </summary>
public static void Load()
{
Write?.Invoke($"Начало игры");
objs = new List<BaseObject>();
kit = new List<Kit>();
bullets = new List<Bullet>();
Random rnd = new Random();
// Создание фонового рисунка
Bitmap img_background = new Bitmap("../../Resources/background.png"); // Да... это не красиво. Как сделать лучше?
objs.Add(new Planet(img_background, new Point(0, 0), new Point(0), new Size(Width, Height)));
// Старт фоновой музыки
PlayFoneMusic();
// Создание звёзд
for (int i = 1; i < 40; i++) // Звезды побольше (ближние)
objs.Add(new Star(new Point(rnd.Next(1, Width), rnd.Next(1, Height)), new Point(3), new Size(3, 3)));
for (int i = 1; i < 200; i++) // Средние
objs.Add(new Star(new Point(rnd.Next(1, Width), rnd.Next(1, Height)), new Point(2), new Size(2, 2)));
for (int i = 1; i < 600; i++) // Маленькие (дальние)
objs.Add(new Star(new Point(rnd.Next(1, Width), rnd.Next(1, Height)), new Point(1), new Size(1, 1)));
// Создание корабля
Bitmap img_ship = new Bitmap("../../Resources/bunny_ship.png");
ship = new Ship(img_ship, new Point(10, 400), new Point(10, 10), new Size(100, 100));
// Создание астероидов
AsterCrt();
// Создание аптечек
Bitmap img_kit = new Bitmap("../../Resources/kit.png");
for (int i = 0; i < 50; i++)
{
kit.Add(new Kit(img_kit, new Point(Game.Width + (i * rnd.Next(800, 1000)), rnd.Next(10, (Game.Height - 10))), new Point(2), new Size(50, 50)));
}
// Создание планет
Bitmap img_earth = new Bitmap("../../Resources/earth.png");
objs.Add(new Planet(img_earth, new Point(550, 500), new Point(0), new Size(800, 700)));
Bitmap img_saturn = new Bitmap("../../Resources/saturn.png");
objs.Add(new Planet(img_saturn, new Point(200, 150), new Point(0), new Size(70, 70)));
}
/// <summary>
/// Отрисовка графики
/// </summary>
public static void Draw()
{
// Проверяем вывод графики
Buffer.Graphics.Clear(System.Drawing.Color.Black);
// Звезды и планеты
foreach (BaseObject obj in objs)
obj.Draw();
// Астероиды
foreach (Asteroid ast in asteroids)
ast.Draw();
// Пули
foreach (Bullet bul in bullets)
bul.Draw();
// Корабль
ship?.Draw();
//Аптечки
foreach (Kit k in kit)
k.Draw();
// Энергия корабля
if (ship != null)
Buffer.Graphics.DrawString("Energy:" + ship.Energy, SystemFonts.DefaultFont, System.Drawing.Brushes.White, 0, 0);
Buffer.Render();
}
/// <summary>
/// Метод обновляющий состояние объектов
/// </summary>
public static void Update()
{
// Энергия корабля
if (ship.Energy > 0) Buffer.Graphics.DrawString("Energy:" + ship.Energy, SystemFonts.DefaultFont, System.Drawing.Brushes.White, 0, 0);
else Buffer.Graphics.Clear(System.Drawing.Color.Black);
// Звезды и планеты
foreach (BaseObject obj in objs)
obj.Update();
// Увелечение коллекции астероидов
if (asteroids.Count == 0)
{
MaxAsteroids++;
AsterCrt();
}
// Астероиды
foreach (Asteroid ast in asteroids)
ast.Update();
// Пули
foreach (Bullet bul in bullets)
bul.Update();
// Аптечки
foreach (Kit k in kit)
k.Update();
// Корабль
ship.Update();
Random rnd = new Random();
// Ох, господь... что же это
for (int j = 0; j < bullets.Count; j++)
{
// Столкновение пули с астероидом
for (var i = 0; i < asteroids.Count; i++)
{
if (bullets[j].Collision(asteroids[i]))
{
asteroids.RemoveAt(i);
bullets.RemoveAt(j);
ship.EnergyAdd(5);
}
}
// Удаление пуль вылетевших за пределы поля
if (bullets[j].DelBull()) bullets.RemoveAt(j);
}
// Столкновение астероида с кораблем
for(var i = 0; i < asteroids.Count; i++)
{
if (ship.Collision(asteroids[i]))
{
ship.EnergyLow(20);
asteroids.RemoveAt(i);
}
// Удаление астероидов вылетевших за пределы поля
if (asteroids[i].DelAst())
{
asteroids.RemoveAt(i);
ship.EnergyLow(20);
}
}
// Столкновение пули с аптечкой
if (kit.Count > 0)
{
for (int i = 0; i < kit.Count; i++)
{
for (int j = 0; j < bullets.Count; j++)
{
if (bullets[j].Collision(kit[i]))
{
ship.EnergyAdd(50);
kit.RemoveAt(i);
bullets.RemoveAt(j);
}
}
}
}
// Здесь прокидываеться событие конца игры
if (ship.Energy < 0)
{
ship.EventDie += Finish;
}
}
/// <summary>
/// Обработчик таймера
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private static void Timer_Tick(object sender, EventArgs e)
{
Draw();
Update();
}
/// <summary>
/// Конец игры
/// </summary>
public static void Finish()
{
timer.Stop();
Buffer.Graphics.DrawString("Конец игры", new Font(System.Drawing.FontFamily.GenericMonospace, 70, FontStyle.Underline), System.Drawing.Brushes.White, 200, 100);
Buffer.Render();
System.Threading.Thread.Sleep(3000);
Application.Exit();
}
}
}
|
using System.Collections.Concurrent;
namespace Sentry.Samples.GraphQL.Server.Notes;
public class NotesData
{
private static int NextId = 0;
private readonly ICollection<Note> _notes = new List<Note> ()
{
new() { Id = NextId++, Message = "Hello World!" },
new() { Id = NextId++, Message = "Hello World! How are you?" }
};
public ICollection<Note> GetAll() => _notes;
public Task<Note?> GetNoteByIdAsync(int id)
{
return Task.FromResult(_notes.FirstOrDefault(n => n.Id == id));
}
public Note AddNote(Note note)
{
note.Id = NextId++;
_notes.Add(note);
return note;
}
}
|
namespace PokemonDontGo
{
using System;
using System.Linq;
public class StartUp
{
public static void Main()
{
var sequence = Console.ReadLine()
.Split(new char[] { ' ', '\t' }, StringSplitOptions.RemoveEmptyEntries)
.Select(long.Parse)
.ToList();
var counter = 0L;
while (sequence.Count > 0)
{
var index = int.Parse(Console.ReadLine());
var tempNumber = 0L;
if (index < 0)
{
tempNumber = sequence[0];
sequence[0] = sequence[sequence.Count - 1];
}
else if (index > sequence.Count - 1)
{
tempNumber = sequence[sequence.Count - 1];
sequence[sequence.Count - 1] = sequence[0];
}
else
{
tempNumber = sequence[index];
sequence.RemoveAt(index);
}
counter += tempNumber;
for (int i = 0; i < sequence.Count; i++)
{
if (sequence[i] <= tempNumber)
{
sequence[i] += tempNumber;
}
else
{
sequence[i] -= tempNumber;
}
}
}
Console.WriteLine(counter);
}
}
}
|
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 Автошкола
{
public partial class JournalUsesForm : Form
{
public JournalUsesForm()
{
InitializeComponent();
}
public BusinessLogic BusinessLogic = new BusinessLogic();
AutoschoolDataSet dataSetForCarriers, dataSetForPracticeLessons;
string LastSearchingCarrierText = "";
int LastFoundCarrierRow = -1;
string LastSearchingUsageText = "";
int LastFoundUsageRow = -1;
bool FormLoad = false;
bool FirstLoad = true;
void ReloadCarriers()
{
dataSetForCarriers = BusinessLogic.ReadCarriers();
Carriers_dataGridView.DataSource = dataSetForCarriers;
Carriers_dataGridView.DataMember = "Carriers";
Carriers_dataGridView.Columns["ID"].Visible = false;
Carriers_dataGridView.Columns["Brand"].Visible = false;
Carriers_dataGridView.Columns["Model"].Visible = false;
Carriers_dataGridView.Columns["StateNumber"].Visible = false;
Carriers_dataGridView.Columns["Color"].Visible = false;
Carriers_dataGridView.Columns["Transmission"].Visible = false;
Carriers_dataGridView.Columns["Category"].Visible = false;
Carriers_dataGridView.Columns["Status"].Visible = false;
Carriers_dataGridView.Columns["FinalName"].Visible = false;
IDColumn.DataPropertyName = "ID";
BrandColumn.DataPropertyName = "Brand";
ModelColumn.DataPropertyName = "Model";
StateNumberColumn.DataPropertyName = "StateNumber";
ColorColumn.DataPropertyName = "Color";
TransmissionColumn.DataSource = dataSetForCarriers.Transmissions;
TransmissionColumn.DisplayMember = "Transmission";
TransmissionColumn.ValueMember = "ID";
TransmissionColumn.DataPropertyName = "Transmission";
CategoryColumn.DataSource = dataSetForCarriers.Categories;
CategoryColumn.DisplayMember = "Name";
CategoryColumn.ValueMember = "ID";
CategoryColumn.DataPropertyName = "Category";
StatusColumn.DataSource = dataSetForCarriers.CarriersStatuses;
StatusColumn.DisplayMember = "Name";
StatusColumn.ValueMember = "ID";
StatusColumn.DataPropertyName = "Status";
}
void ReloadPracticeLessons(int CarrierID)
{
PracticeLessons_dGV.Rows.Clear();
DateTime BeginDate = Convert.ToDateTime(DateBegin_dateTimePicker.Text).Date;
DateTime EndDate = Convert.ToDateTime(DateEnd_dateTimePicker.Text).Date;
if (Carriers_dataGridView.SelectedRows[0].Cells["StatusColumn"].FormattedValue.ToString() == "Используется")
{
// берем все практические занятия за нужный период
dataSetForPracticeLessons = BusinessLogic.ReadPracticeLessonsByCarrierID_AND_BeginEndDates(CarrierID, BeginDate, EndDate);
// для каждого практического занятия ищем замены ТС по дате
// сначала смотрим фактическую дату, если она пустая - то назначенную
// если замены есть - эта машина не использовалась, т.е. запись не добавляем
for (int i = 0; i < dataSetForPracticeLessons.PracticeLessons.Rows.Count; i++)
{
DateTime LessonTime = Convert.ToDateTime((dataSetForPracticeLessons.PracticeLessons.Rows[i]["FactDate"].ToString() != "01.01.0001 0:00:00") ?
dataSetForPracticeLessons.PracticeLessons.Rows[i]["FactDate"].ToString() :
dataSetForPracticeLessons.PracticeLessons.Rows[i]["AppointedDate"].ToString()).Date;
int CarrierUseID = Convert.ToInt32(dataSetForPracticeLessons.Students.Rows.Find(dataSetForPracticeLessons.PracticeLessons.Rows[i]["Student"].ToString())["CarrierUse"].ToString());
AutoschoolDataSet TempDS = BusinessLogic.ReadReplacementsCarriersByLessonDateANDCarrierUseID(LessonTime, CarrierUseID);
if (TempDS.ReplacementsCarriers.Rows.Count == 0)
{
PracticeLessons_dGV.Rows.Add(
dataSetForPracticeLessons.PracticeLessons.Rows[i]["ID"],
Convert.ToDateTime(dataSetForPracticeLessons.PracticeLessons.Rows[i]["AppointedDate"]).ToShortDateString(),
dataSetForPracticeLessons.PracticeLessons.Rows[i]["AppointedTime"],
dataSetForPracticeLessons.Students.Rows.Find(dataSetForPracticeLessons.PracticeLessons.Rows[i]["Student"].ToString())["InstructorName"],
dataSetForPracticeLessons.PracticeLessons.Rows[i]["StudentFIO"],
(dataSetForPracticeLessons.PracticeLessons.Rows[i]["FactDate"].ToString() != "01.01.0001 0:00:00"
? Convert.ToDateTime(dataSetForPracticeLessons.PracticeLessons.Rows[i]["FactDate"].ToString()).ToShortDateString() : ""),
(dataSetForPracticeLessons.PracticeLessons.Rows[i]["FactDate"].ToString() != "01.01.0001 0:00:00"
? dataSetForPracticeLessons.PracticeLessons.Rows[i]["FactTime"] : "")
);
}
}
}
else if (Carriers_dataGridView.SelectedRows[0].Cells["StatusColumn"].FormattedValue.ToString() == "Резерв")
{
// берем замены ТС за нужный период, где заменяющей ТС было выбранное ТС
// для каждой замены ТС
// по CarrierUseID получаем практические занятия в этот период
// выводим эти занятия
AutoschoolDataSet TempDS = BusinessLogic.ReadByCarrierReplacementID_AND_BeginEndDates(CarrierID, BeginDate, EndDate);
for (int i = 0; i < TempDS.ReplacementsCarriers.Rows.Count; i++)
{
dataSetForPracticeLessons = BusinessLogic.ReadPracticeLessonsByCarrierUseID_AND_DatesBeginEnd(
Convert.ToInt32(TempDS.ReplacementsCarriers.Rows[i]["CarrierUse"].ToString()),
Convert.ToDateTime(TempDS.ReplacementsCarriers.Rows[i]["DateBeginReplacement"].ToString()).Date,
Convert.ToDateTime(TempDS.ReplacementsCarriers.Rows[i]["DateEndReplacement"].ToString()).Date);
for (int j = 0; j < dataSetForPracticeLessons.PracticeLessons.Rows.Count; j++)
{
PracticeLessons_dGV.Rows.Add(
dataSetForPracticeLessons.PracticeLessons.Rows[j]["ID"],
Convert.ToDateTime(dataSetForPracticeLessons.PracticeLessons.Rows[i]["AppointedDate"]).ToShortDateString(),
dataSetForPracticeLessons.PracticeLessons.Rows[j]["AppointedTime"],
dataSetForPracticeLessons.Students.Rows.Find(dataSetForPracticeLessons.PracticeLessons.Rows[0]["Student"].ToString())["InstructorName"],
dataSetForPracticeLessons.PracticeLessons.Rows[j]["StudentFIO"],
(dataSetForPracticeLessons.PracticeLessons.Rows[i]["FactDate"].ToString() != "01.01.0001 0:00:00"
? Convert.ToDateTime(dataSetForPracticeLessons.PracticeLessons.Rows[i]["FactDate"].ToString()).ToShortDateString() : ""),
(dataSetForPracticeLessons.PracticeLessons.Rows[i]["FactDate"].ToString() != "01.01.0001 0:00:00"
? dataSetForPracticeLessons.PracticeLessons.Rows[i]["FactTime"] : "")
);
}
}
}
/*PracticeLessons_dGV.DataSource = dataSetForPracticeLessons;
PracticeLessons_dGV.DataMember = "PracticeLessons";
PracticeLessons_dGV.Columns["ID"].Visible = false;
PracticeLessons_dGV.Columns["Student"].Visible = false;
PracticeLessons_dGV.Columns["AppointedDate"].Visible = false;
PracticeLessons_dGV.Columns["AppointedTime"].Visible = false;
PracticeLessons_dGV.Columns["FactDate"].Visible = false;
PracticeLessons_dGV.Columns["FactTime"].Visible = false;
PracticeLessons_dGV.Columns["StudentFIO"].Visible = false;
PracticeLessons_dGV.Columns["CarrierName"].Visible = false;
IDPLColumn.DataPropertyName = "ID";
AppointedDateColumn.DataPropertyName = "AppointedDate";
AppointedTimeColumn.DataPropertyName = "AppointedTime";
FactDateColumn.DataPropertyName = "FactDate";
FactTimeColumn.DataPropertyName = "FactTime";
StudentColumn.DataPropertyName = "StudentFIO";
InstructorColumn.DataSource = dataSetForPracticeLessons.Students;
InstructorColumn.DisplayMember = "InstructorName";
InstructorColumn.ValueMember = "ID";
InstructorColumn.DataPropertyName = "Student";*/
}
private void Carriers_dataGridView_SelectionChanged(object sender, EventArgs e)
{
if (FormLoad && Carriers_dataGridView.SelectedRows.Count > 0)
ReloadPracticeLessons(Convert.ToInt32(Carriers_dataGridView.SelectedRows[0].Cells["ID"].Value));
}
private void SearchCarrier_button_Click(object sender, EventArgs e)
{
SearchingInDataGridViewClass.Search(SearchCarrier_textBox, ref Carriers_dataGridView, DirectionCarrier_checkBox,
ref LastSearchingCarrierText, ref LastFoundCarrierRow, "BrandColumn", "ModelColumn", "StateNumberColumn");
}
private void SearchCarrier_textBox_KeyPress(object sender, KeyPressEventArgs e)
{
if ((char)e.KeyChar == (Char)Keys.Enter)
{
SearchCarrier_button_Click(sender, e);
}
if ((char)e.KeyChar == (Char)Keys.Back)
{
LastSearchingCarrierText = "";
}
}
private void SearchInUsage_button_Click(object sender, EventArgs e)
{
SearchingInDataGridViewClass.Search(SearchInUsage_textBox, ref PracticeLessons_dGV, DirectionInUsage_checkBox,
ref LastSearchingUsageText, ref LastFoundUsageRow, "InstructorColumn", "StudentColumn");
}
private void SearchInUsage_textBox_KeyPress(object sender, KeyPressEventArgs e)
{
if ((char)e.KeyChar == (Char)Keys.Enter)
{
SearchInUsage_button_Click(sender, e);
}
if ((char)e.KeyChar == (Char)Keys.Back)
{
LastSearchingUsageText = "";
}
}
private void ReloadCarriers_button_Click(object sender, EventArgs e)
{
FormLoad = false;
ReloadCarriers();
FormLoad = true;
Carriers_dataGridView_SelectionChanged(sender, e);
}
private void ReloadPracticeLessons_button_Click(object sender, EventArgs e)
{
Carriers_dataGridView_SelectionChanged(sender, e);
}
private void CarriersUseJournalForm_FormClosing(object sender, FormClosingEventArgs e)
{
MainForm.Perem(MainForm.FormsNames[11], false);
}
private void Close_button_Click(object sender, EventArgs e)
{
Close();
}
private void JournalUsesForm_VisibleChanged(object sender, EventArgs e)
{
if (Visible)
{
if (!FirstLoad)
ReloadCarriers_button_Click(sender, e);
else
FirstLoad = false;
}
}
private void DateBegin_dateTimePicker_ValueChanged(object sender, EventArgs e)
{
DateEnd_dateTimePicker.MinDate = DateBegin_dateTimePicker.Value;
}
private void NewDates_button_Click(object sender, EventArgs e)
{
Carriers_dataGridView_SelectionChanged(sender, e);
}
private void CarriersUseJournalForm_Load(object sender, EventArgs e)
{
ReloadCarriers();
FormLoad = true;
Carriers_dataGridView_SelectionChanged(sender, e);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
using DBDiff.Schema.MySQL.Model;
namespace DBDiff.Schema.MySQL.Compare
{
internal static class CompareColumns
{
public static Columns GenerateDiferences(Columns CamposOrigen, Columns CamposDestino)
{
foreach (Column node in CamposDestino)
{
if (!CamposOrigen.Find(node.Name))
{
node.Status = StatusEnum.ObjectStatusType.CreateStatus;
CamposOrigen.Parent.Status = StatusEnum.ObjectStatusType.AlterStatus;
CamposOrigen.Add(node);
}
else
{
if (!Column.Compare(CamposOrigen[node.Name],node))
{
node.Status = StatusEnum.ObjectStatusType.AlterRebuildStatus;
CamposOrigen[node.Name].Parent.Status = StatusEnum.ObjectStatusType.AlterRebuildStatus;
CamposOrigen[node.Name] = node.Clone((Table)CamposOrigen[node.Name].Parent);
}
}
}
foreach (Column node in CamposOrigen)
{
if (!CamposDestino.Find(node.Name))
{
node.Status = StatusEnum.ObjectStatusType.DropStatus;
CamposOrigen.Parent.Status = StatusEnum.ObjectStatusType.AlterStatus;
}
}
return CamposOrigen;
}
}
}
|
using Alabo.Test.Base.Core.Model;
namespace Alabo.Test.Cms.Articles.Domain.Services
{
public class ISinglePageServiceTests : CoreTest
{
/*end*/
}
} |
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Arduino_Alarm.SetAlarm.GetSchedule;
namespace UnitTestProject1
{
[TestClass]
public class Settings_Tests
{
[TestMethod]
public void Subgroup_IsNot_Over_2()
{
Settings set = new Settings();
int sub = set.Subgroup;
if (sub > 2)
Assert.Fail("Error");
}
}
}
|
using Cs_Notas.Dominio.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Cs_Notas.Dominio.Interfaces.Repositorios
{
public interface IRepositorioCadProcuracao: IRepositorioBase<CadProcuracao>
{
CadProcuracao SalvarAlteracaoProcuracao(CadProcuracao alterar);
CadProcuracao ObterProcuracaoPorSeloLivroFolhaAto(string selo, string aleatorio, string livro, int folhainicio, int folhaFim, int ato);
List<CadProcuracao> ObterProcuracaoPorPeriodo(DateTime dataInicio, DateTime dataFim);
List<CadProcuracao> ObterProcuracaoPorLivro(string livro);
List<CadProcuracao> ObterProcuracaoPorAto(int numeroAto);
List<CadProcuracao> ObterProcuracaoPorSelo(string selo);
List<CadProcuracao> ObterProcuracaoPorParticipante(List<int> idsAto);
}
}
|
using Assets.Scripts.Mathx;
using UnityEngine;
using UnityEngine.EventSystems;
namespace Assets.Scripts.Buildings.Controller
{
public class MovableObject : MonoBehaviour
{
private SpriteRenderer backSpriteRenderer;//Çarpştığında oluşacak renk efekti için
private bool isCollided;//Çarpıştımı?
private bool isDrag;//Sürüklenebilirmi
private bool isJustInstianitate;//Şimdi oluşturuluyorsa ve uygunsuz bir yerdeyse gameobjeyi destroy etmek için
private Vector3 resetPosition;//Uygunsuz bir yere yerleştirmeye çalışıldığında geri dönebilmek için
private void Awake()
{
backSpriteRenderer = transform.Find("bg").GetComponent<SpriteRenderer>();//Childrendan backgroundu bulmak için
}
private void Update()
{
if (Input.GetMouseButtonDown(0))//Mouse sol tıkına ilk basılma anı
{
//On mouse down methodu sıkıntı çıkardığı için bunu kullanıyoruz
//Mouse un deydiği tüm colliderleri topla
var hits =
Physics2D.RaycastAll(Camera.main.ScreenToWorldPoint(Input.mousePosition), Vector2.zero);
//Eğer UI üzerindeysem return
if (EventSystem.current.IsPointerOverGameObject()) return;
//Hits döngü
foreach (var hit in hits)
if (hit.collider != null)
if (hit.transform == transform)
{
//sürükleme değişkeni true
isDrag = true;
resetPosition = transform.position;
}
}
//sürükleme aktif değilse geri dön
if (!isDrag) return;
if (Input.GetMouseButton(0))//Sol tıka basılı tutuluyorsa taşıma işlemlerini bitir
{
Vector2 pos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
//Gridde hareket ediyomuş hissi için değere yuvarlama işlemi kullan
transform.position = new Vector2(Mathematic.RoundToMultiple(pos.x, 0.32f)+0.16f,
Mathematic.RoundToMultiple(pos.y, 0.32f)+0.16f);
}
//Sol tık tan parmak kalkmadığı sürece buradan devam etme
if (!Input.GetMouseButtonUp(0)) return;
//sol tık a basıldıysa isDrag false yap
isDrag = false;
//
if (isCollided)
{
//collided true ise ve yeni oluşturulan bir drag objeyse objeyi yoket
if (isJustInstianitate)
Destroy(gameObject);
transform.position = resetPosition;
}
else
{
isJustInstianitate = false;
}
}
private void OnCollisionStay2D(Collision2D collision)
{
//Collision oyun tahtamız veya Asker değilse
if (collision.gameObject.name != "Board" && collision.gameObject.layer != 9)
{
//Kırmızı renk
backSpriteRenderer.color = new Color(0.5f, 0, 0, 0.6f);
isCollided = true;
}
}
private void OnCollisionExit2D(Collision2D collision)
{
//Collision oyun tahtamız veya Asker değilse
if (collision.gameObject.name != "Board" && collision.gameObject.layer != 9)
{
//Beyaz renk
backSpriteRenderer.color = new Color(1, 1, 1, 0.3f);
isCollided = false;
}
}
/// <summary>
/// Yeni oluşturma için ayarlama yapar
/// </summary>
public void SetForCreating()
{
isDrag = true;
isJustInstianitate = true;
}
}
} |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Reflection;
using System.Threading;
using DevExpress.XtraEditors;
using IRAP.Global;
using IRAP.Client.User;
using IRAP.Entity.Kanban;
using IRAP.Entity.MDM;
using IRAP.WCF.Client.Method;
namespace IRAP.Client.GUI.MDM
{
public partial class frmEnvParamStandardProperties : IRAP.Client.GUI.MDM.frmCustomProperites
{
private string className =
MethodBase.GetCurrentMethod().DeclaringType.FullName;
private DataTable dtStandards = null;
public frmEnvParamStandardProperties()
{
InitializeComponent();
dtStandards = new DataTable();
dtStandards.Columns.Add("Level", typeof(int));
dtStandards.Columns.Add("T20LeafID", typeof(int));
dtStandards.Columns.Add("LowLimit", typeof(int));
dtStandards.Columns.Add("Criterion", typeof(string));
dtStandards.Columns.Add("HighLimit", typeof(int));
dtStandards.Columns.Add("Scale", typeof(int));
dtStandards.Columns.Add("UnitOfMeasure", typeof(string));
dtStandards.Columns.Add("RecordingMode", typeof(int));
dtStandards.Columns.Add("SamplingCycle", typeof(int));
dtStandards.Columns.Add("Reference", typeof(bool));
grdStandards.DataSource = dtStandards;
GetStandardList();
GetCriterionList();
}
private void GetCriterionList()
{
string strProcedureName =
string.Format(
"{0}.{1}",
className,
MethodBase.GetCurrentMethod().Name);
WriteLog.Instance.WriteBeginSplitter(strProcedureName);
try
{
int errCode = 0;
string errText = "";
List<ScopeCriterionType> criterionItems = new List<ScopeCriterionType>();
WriteLog.Instance.Write("获取比较标准项列表", strProcedureName);
IRAPKBClient.Instance.sfn_GetList_ScopeCriterionType(
IRAPUser.Instance.SysLogID,
ref criterionItems,
out errCode,
out errText);
WriteLog.Instance.Write(string.Format("({0}){1}", errCode, errText), strProcedureName);
if (errCode == 0)
{
riluCriterion.DataSource = criterionItems;
}
riluCriterion.DisplayMember = "TypeHint";
riluCriterion.ValueMember = "TypeCode";
riluCriterion.NullText = "";
}
catch (Exception error)
{
WriteLog.Instance.Write(error.Message, strProcedureName);
}
finally
{
WriteLog.Instance.WriteEndSplitter(strProcedureName);
}
}
/// <summary>
/// 获取标准项列表
/// </summary>
private void GetStandardList()
{
string strProcedureName =
string.Format(
"{0}.{1}",
className,
MethodBase.GetCurrentMethod().Name);
WriteLog.Instance.WriteBeginSplitter(strProcedureName);
try
{
int errCode = 0;
string errText = "";
List<SubTreeLeaf> standardItems = new List<SubTreeLeaf>();
WriteLog.Instance.Write("获取生产环境项列表", strProcedureName);
IRAPKBClient.Instance.sfn_AccessibleSubtreeLeaves(
IRAPUser.Instance.CommunityID,
20,
5418, // 生产环境节点标识
IRAPUser.Instance.ScenarioIndex,
IRAPUser.Instance.SysLogID,
ref standardItems,
out errCode,
out errText);
WriteLog.Instance.Write(
string.Format("({0}){1}", errCode, errText),
strProcedureName);
if (errCode == 0)
{
for (int i = standardItems.Count - 1; i >= 0; i--)
if (standardItems[i].LeafStatus != 0)
standardItems.Remove(standardItems[i]);
riluParameterName.DataSource = standardItems;
}
riluParameterName.DisplayMember = "NodeName";
riluParameterName.ValueMember = "LeafID";
riluParameterName.NullText = "";
}
catch (Exception error)
{
WriteLog.Instance.Write(error.Message, strProcedureName);
}
finally
{
WriteLog.Instance.WriteEndSplitter(strProcedureName);
}
}
public override void GetProperties(int t102LeafID, int t216LeafID)
{
string strProcedureName =
string.Format(
"{0}.{1}",
className,
MethodBase.GetCurrentMethod().Name);
WriteLog.Instance.WriteBeginSplitter(strProcedureName);
try
{
int errCode = 0;
string errText = "";
#region 获取产品与工序的关联ID
IRAPMDMClient.Instance.ufn_GetMethodID(
IRAPUser.Instance.CommunityID,
t102LeafID,
216,
t216LeafID,
IRAPUser.Instance.SysLogID,
ref c64ID,
out errCode,
out errText);
WriteLog.Instance.Write(
string.Format("({0}){1}", errCode, errText),
strProcedureName);
if (errCode != 0)
{
XtraMessageBox.Show(
errText,
Text,
MessageBoxButtons.OK,
MessageBoxIcon.Error);
return;
}
#endregion
if (c64ID == 0)
{
string msgText = "";
if (Thread.CurrentThread.CurrentUICulture.Name.Substring(0, 2) == "en")
msgText = "The relationship of current product and process are not generated!";
else
msgText = "当前产品和工序的关联未生成!";
XtraMessageBox.Show(
msgText,
Text,
MessageBoxButtons.OK,
MessageBoxIcon.Error);
return;
}
else
{
List<EnvParamStandard> standards = new List<EnvParamStandard>();
#region 获取指定产品和工序所对应的生产环境参数
IRAPMDMClient.Instance.ufn_GetList_EnvParamStandard(
IRAPUser.Instance.CommunityID,
t102LeafID,
t216LeafID,
"",
IRAPUser.Instance.SysLogID,
ref standards,
out errCode,
out errText);
WriteLog.Instance.Write(string.Format("({0}){1}", errCode, errText), strProcedureName);
if (dtStandards != null)
{
foreach (EnvParamStandard standard in standards)
{
dtStandards.Rows.Add(new object[]
{
standard.Ordinal,
standard.T20LeafID,
standard.ParameterName,
standard.LowLimit,
standard.Criterion,
standard.HighLimit,
standard.Scale,
standard.UnitOfMeasure,
standard.CollectingMode,
standard.CollectingCycle,
standard.Reference,
});
}
}
//for (int i = 0; i < grdvMethodStandards.Columns.Count; i++)
// grdvMethodStandards.Columns[i].BestFit();
grdvStandards.BestFitColumns();
grdvStandards.LayoutChanged();
grdvStandards.OptionsBehavior.Editable = true;
grdvStandards.OptionsView.NewItemRowPosition = DevExpress.XtraGrid.Views.Grid.NewItemRowPosition.Bottom;
grdStandards.UseEmbeddedNavigator = true;
#endregion
#region 如果当前显示的数据是模板数据
if (standards.Count > 0 && standards[0].Reference)
{
if (Thread.CurrentThread.CurrentUICulture.Name.Substring(0, 2) == "en")
lblTitle.Text += "(Template)";
else
lblTitle.Text += "(模板数据)";
btnSave.Enabled = true;
}
else
{
btnSave.Enabled = false;
}
#endregion
}
}
finally
{
WriteLog.Instance.WriteEndSplitter(strProcedureName);
}
}
protected override string GenerateRSAttrXML()
{
string strStandardXML = "";
int i = 1;
dtStandards.DefaultView.Sort = "Level asc";
DataTable dt = dtStandards.Copy();
dt = dtStandards.DefaultView.ToTable();
foreach (DataRow dr in dt.Rows)
{
strStandardXML = strStandardXML +
string.Format("<Row RealOrdinal=\"{0}\" T20LeafID=\"{1}\" LowLimit=\"{2}\" " +
"Criterion=\"{3}\" HighLimit=\"{4}\" Scale=\"{5}\" UnitOfMeasure=\"{6}\" " +
"RecordingMode=\"{7}\" SamplingCycle=\"{8}\" RTDBDSLinkID=\"{9}\" " +
"RTDBTagName=\"{10}\" />",
i++,
dr["T20LeafID"].ToString(),
dr["LowLimit"].ToString(),
dr["Criterion"].ToString(),
dr["HighLimit"].ToString(),
dr["Scale"].ToString(),
dr["UnitOfMeasure"].ToString(),
dr["RecordingMode"].ToString(),
dr["SamplingCycle"].ToString(),
0,
"");
}
return string.Format("<RSAttr>{0}</RSAttr>", strStandardXML);
}
private void grdvEnvParamStandards_InitNewRow(object sender, DevExpress.XtraGrid.Views.Grid.InitNewRowEventArgs e)
{
DataRow dr = grdvStandards.GetDataRow(e.RowHandle);
dr["Level"] = dtStandards.Rows.Count + 1;
dr["T20LeafID"] = 0;
dr["ParameterName"] = "";
dr["LowLimit"] = 0;
dr["Criterion"] = "GELE";
dr["HighLimit"] = 0;
dr["Scale"] = 0;
dr["UnitOfMeasure"] = "";
dr["RecordingMode"] = 0;
dr["SamplingCycle"] = 0;
dr["Reference"] = false;
SetEditorMode(true);
}
private void grdvEnvParamStandards_RowDeleted(object sender, DevExpress.Data.RowDeletedEventArgs e)
{
grdvStandards.BestFitColumns();
SetEditorMode(true);
}
private void grdvEnvParamStandards_RowUpdated(object sender, DevExpress.XtraGrid.Views.Base.RowObjectEventArgs e)
{
grdvStandards.BestFitColumns();
SetEditorMode(true);
}
}
}
|
namespace JhinBot
{
public class Program
{
public static void Main(string[] args) =>
new JhinBotInstance().RunAndBlockAsync(args).GetAwaiter().GetResult();
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.