text stringlengths 13 6.01M |
|---|
using UnityEngine;
using UnityEditor;
namespace Motion.Tools
{
[CanEditMultipleObjects]
[CustomEditor(typeof(BrownianMotion))]
public class BrownianMotionEditor : Editor
{
static readonly GUIContent textPositionNoise = new GUIContent("Position Noise");
static readonly GUIContent textRotationNoise = new GUIContent("Rotation Noise");
static readonly GUIContent textFrequency = new GUIContent("Frequency");
static readonly GUIContent textAmplitude = new GUIContent("Amplitude");
static readonly GUIContent textScale = new GUIContent("Scale");
static readonly GUIContent textFractal = new GUIContent("Fractal");
private SerializedProperty enablePositionNoise = default;
private SerializedProperty enableRotationNoise = default;
private SerializedProperty positionFrequency = default;
private SerializedProperty rotationFrequency = default;
private SerializedProperty positionAmplitude = default;
private SerializedProperty rotationAmplitude = default;
private SerializedProperty positionScale = default;
private SerializedProperty rotationScale = default;
private SerializedProperty positionFractalLevel = default;
private SerializedProperty rotationFractalLevel = default;
private void OnEnable()
{
enablePositionNoise = serializedObject.FindProperty("_enablePositionNoise");
enableRotationNoise = serializedObject.FindProperty("_enableRotationNoise");
positionFrequency = serializedObject.FindProperty("_positionFrequency");
rotationFrequency = serializedObject.FindProperty("_rotationFrequency");
positionAmplitude = serializedObject.FindProperty("_positionAmplitude");
rotationAmplitude = serializedObject.FindProperty("_rotationAmplitude");
positionScale = serializedObject.FindProperty("_positionScale");
rotationScale = serializedObject.FindProperty("_rotationScale");
positionFractalLevel = serializedObject.FindProperty("_positionFractalLevel");
rotationFractalLevel = serializedObject.FindProperty("_rotationFractalLevel");
}
public override void OnInspectorGUI()
{
serializedObject.Update();
EditorGUILayout.PropertyField(enablePositionNoise, textPositionNoise);
if (enablePositionNoise.hasMultipleDifferentValues || enablePositionNoise.boolValue)
{
EditorGUI.indentLevel++;
EditorGUILayout.PropertyField(positionFrequency, textFrequency);
EditorGUILayout.PropertyField(positionAmplitude, textAmplitude);
EditorGUILayout.PropertyField(positionScale, textScale);
EditorGUILayout.PropertyField(positionFractalLevel, textFractal);
EditorGUI.indentLevel--;
}
EditorGUILayout.PropertyField(enableRotationNoise, textRotationNoise);
if (enableRotationNoise.hasMultipleDifferentValues || enableRotationNoise.boolValue)
{
EditorGUI.indentLevel++;
EditorGUILayout.PropertyField(rotationFrequency, textFrequency);
EditorGUILayout.PropertyField(rotationAmplitude, textAmplitude);
EditorGUILayout.PropertyField(rotationScale, textScale);
EditorGUILayout.PropertyField(rotationFractalLevel, textFractal);
EditorGUI.indentLevel--;
}
serializedObject.ApplyModifiedProperties();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Runtime.CompilerServices;
using Logic.PlayerClasses;
using Logic.Resource;
using Logic.SupportClasses;
using Logic.Buildings;
using Logic.PopulationClasses;
namespace Logic.SpaceObjects {
/// <summary>
/// Представляет звездную систему
/// </summary>
[Serializable]
public class StarSystem : INotifyPropertyChanged {
private string name;
private readonly List<Star> systemStars;
private readonly List<Planet> systemPlanets;
private MinerFleet systemMiners;
public SystemBuildings Buildings { get; }
/// <summary>
/// Возвращает ресурсы системы
/// </summary>
public IMutableResources SystemResources { get; private set; }
private byte colonizedCount;
private long population;
[field: NonSerialized]
public event PropertyChangedEventHandler PropertyChanged;
/// <summary>
/// Инициализирует экземпляр класса с значениями по умолчанию
/// </summary>
public StarSystem() {
}
/// <summary>
/// Инициализирует экземпляр класса звездной системы
/// </summary>
/// <param name="name"></param>
/// <param name="systemStars"></param>
/// <param name="planets"></param>
public StarSystem(string name, IList<Star> stars, IList<Planet> planets) {
this.Name = name ?? throw new ArgumentNullException(nameof(name));
this.systemStars = new List<Star>(stars) ?? throw new ArgumentNullException(nameof(stars));
if (planets.Count > 255) {
throw new ArgumentOutOfRangeException(nameof(planets), "Count can't be greater than 255");
}
this.systemPlanets = new List<Planet>(planets) ?? throw new ArgumentNullException(nameof(planets));
this.Buildings = new SystemBuildings();
this.systemMiners = new MinerFleet();
foreach (var planet in this.SystemPlanets) {
planet.PropertyChanged += this.Planet_PropertyChanged;
}
this.SetSystemPopulation();
this.ColonizedCount = this.SetColonizedPlantes();
SetMiners();
this.SystemResources = new StarSystemResourceGenerator().GenerateResources();
}
/// <summary>
/// Возвращает ссылку на коллекцию объектов <see cref="Star"/> системы
/// </summary>
public ReadOnlyCollection<Star> SystemStars { get => new ReadOnlyCollection<Star>(this.systemStars); }
/// <summary>
/// Возвращает ссылку на коллекцию объектов <see cref="Planet"/> системы
/// </summary>
public ReadOnlyCollection<Planet> SystemPlanets { get => new ReadOnlyCollection<Planet>(this.systemPlanets); }
/// <summary>
/// Возвращает ссылку на коллекцию объектов <see cref="HabitablePlanet"/> системы
/// </summary>
public ReadOnlyCollection<HabitablePlanet> SystemHabitablePlanets {
get {
List<HabitablePlanet> habitablePlanets = new List<HabitablePlanet>();
foreach (var planet in this.SystemPlanets) {
if(planet is HabitablePlanet habitablePlanet) {
habitablePlanets.Add(habitablePlanet);
}
}
return new ReadOnlyCollection<HabitablePlanet>(habitablePlanets);
}
}
/// <summary>
/// Возвращает количество планет в системе
/// </summary>
public int PlanetsCount { get => this.SystemPlanets.Count; }
/// <summary>
/// Возвращает количество колонизируемых планет в системе
/// </summary>
public int HabitablePlanetsCount { get => this.SystemHabitablePlanets.Count; }
/// <summary>
/// Возвращает количество звезд в системе
/// </summary>
public int StarsCount { get => this.SystemStars.Count; }
/// <summary>
/// Возвращает имя звездной системы
/// </summary>
public string Name {
get => this.name;
set {
if (this.name != value) {
this.name = value;
OnPropertyChanged();
}
}
}
/// <summary>
/// Возвращает количество колонизированных планет в системе
/// </summary>
public byte ColonizedCount {
get => colonizedCount;
private set {
if (this.colonizedCount != value) {
this.colonizedCount = value;
OnPropertyChanged();
}
}
}
/// <summary>
/// Возвращает количество обитателей системы
/// </summary>
public long Population {
get => population;
private set {
if (this.population != value) {
this.population = value;
}
}
}
/// <summary>
/// Возвращает количество добывающих кораблей системы
/// </summary>
public int MinersCount {
get => this.systemMiners.MinersCount;
}
//TODO: переработать этот костыль
public void SetMiners() {
if (this.Population > 0) {
int minersToAdd = 50;
this.systemMiners = new MinerFleet(minersToAdd);
}
}
/// <summary>
/// Выполняет все операции для перехода на следующий ход
/// </summary>
/// <param name="player">
/// Игрок, которому принадлежит система
/// </param>
public void NextTurn(Player player) {
this.PlanetsNextTurn(player);
this.StarsNextTurn();
this.systemMiners.Mine(this.SystemResources, player.OwnedResources);
this.Buildings.NextTurn(player.OwnedResources);
this.SetSystemPopulation();
}
private void PlanetsNextTurn(Player player) {
foreach (Planet planet in this.SystemPlanets) {
planet.NextTurn(player);
}
}
private void StarsNextTurn() {
foreach (Star star in this.SystemStars) {
star.NextTurn();
}
}
private void SetSystemPopulation() {
long population = 0;
foreach (var planet in this.SystemHabitablePlanets) {
population += planet.PopulationValue;
}
population += this.Buildings.Population;
this.Population = population;
}
public void UpdatePopulation() {
OnPropertyChanged(nameof(StarSystem.Population));
}
private byte SetColonizedPlantes() {
byte colonized = 0;
foreach (var planet in this.SystemHabitablePlanets) {
if (planet.IsColonized) {
colonized++;
}
}
return colonized;
}
protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = "") {
var handler = PropertyChanged;
handler?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
private void Planet_PropertyChanged(object sender, PropertyChangedEventArgs e) {
if (sender is HabitablePlanet planet) {
if (e.PropertyName == nameof(HabitablePlanet.IsColonized)) {
this.ColonizedCount += (byte)((planet.IsColonized) ? 1 : -1);
}
else if (e.PropertyName == nameof(HabitablePlanet.Population.Value)) {
this.SetSystemPopulation();
}
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;
using EkspozitaPikturave.Models;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.AspNetCore.Hosting;
using System.IO;
namespace EkspozitaPikturave.Areas.Identity.Pages.Account.Manage
{
public partial class IndexModel : PageModel
{
private readonly UserManager<ApplicationUser> _userManager;
private readonly SignInManager<ApplicationUser> _signInManager;
[Obsolete]
IHostingEnvironment _env;
[Obsolete]
public IndexModel(
UserManager<ApplicationUser> userManager,
SignInManager<ApplicationUser> signInManager,
IHostingEnvironment environment
)
{
_userManager = userManager;
_signInManager = signInManager;
_env = environment;
}
[Display(Name = "Useri")]
public string Username { get; set; }
[TempData]
public string StatusMessage { get; set; }
[BindProperty]
public InputModel Input { get; set; }
public class InputModel
{
[Phone]
[Display(Name = "Numri telefonit")]
public string PhoneNumber { get; set; }
}
[BindProperty]
public InputRolesModel InputRoles { get; set; }
public class InputRolesModel
{
[Display(Name = "Roli")]
public string Roles { get; set; }
}
public string profilePhoto = "/Upload/Images/withoutProfilPhoto.jpg";
private async Task LoadAsync(ApplicationUser user)
{
var userName = await _userManager.GetUserNameAsync(user);
var phoneNumber = await _userManager.GetPhoneNumberAsync(user);
var roleU = await _userManager.GetRolesAsync(user);
if(user.PhotoPath != null)
{
profilePhoto = user.PhotoPath.Substring(2);
}
Username = userName;
Input = new InputModel
{
PhoneNumber = phoneNumber
};
if (roleU.Any()) {
InputRoles = new InputRolesModel
{
Roles = roleU[0]
};
}
}
public async Task<IActionResult> OnGetAsync()
{
var user = await _userManager.GetUserAsync(User);
if (user == null)
{
return NotFound($"Unable to load user with ID '{_userManager.GetUserId(User)}'.");
}
await LoadAsync(user);
return Page();
}
[Obsolete]
public async Task<IActionResult> OnPostAsync(IFormFile file)
{
var user = await _userManager.GetUserAsync(User);
if (user == null)
{
return NotFound($"Unable to load user with ID '{_userManager.GetUserId(User)}'.");
}
if (!ModelState.IsValid)
{
await LoadAsync(user);
return Page();
}
var phoneNumber = await _userManager.GetPhoneNumberAsync(user);
if (Input.PhoneNumber != phoneNumber)
{
var setPhoneResult = await _userManager.SetPhoneNumberAsync(user, Input.PhoneNumber);
if (!setPhoneResult.Succeeded)
{
var userId = await _userManager.GetUserIdAsync(user);
throw new InvalidOperationException($"Unexpected error occurred setting phone number for user with ID '{userId}'.");
}
}
//-------------------
var roleU = await _userManager.GetRolesAsync(user);
if(roleU.Count > 0)
{
for (int i = 0; i < roleU.Count; i++)
{
await _userManager.RemoveFromRoleAsync(user, roleU[i]);
}
}
string varIR = InputRoles.Roles;
await _userManager.AddToRoleAsync(user, varIR);
//-------------------
//FileUpload
if (file != null && file.Length > 0)
{
var imagePath = @"\Upload\Images\ProfilPics\";
var uploadPath = _env.WebRootPath + imagePath;
//Create Directory
if (!Directory.Exists(uploadPath))
{
Directory.CreateDirectory(uploadPath);
}
//Create Uniq file name
var uniqFileName = Guid.NewGuid().ToString();
var filename = Path.GetFileName(uniqFileName + "." + file.FileName.Split(".")[1].ToLower());
string fullPath = uploadPath + filename;
var filePath = @".." + Path.Combine(imagePath, filename);
using (var fileStream = new FileStream(fullPath, FileMode.Create))
{
await file.CopyToAsync(fileStream);
}
var app_user = await _userManager.GetUserAsync(User);
app_user.PhotoPath = filePath;
await _userManager.UpdateAsync(app_user);
}
await _signInManager.RefreshSignInAsync(user);
StatusMessage = "Profili juaj u perditesua me sukses";
return RedirectToPage();
}
}
}
|
using Prism.Commands;
using Prism.Mvvm;
using System;
using System.Collections.Generic;
using System.Linq;
namespace LogUrFace.Reporting.ViewModels
{
public class DTRReportViewModel : BindableBase
{
private DelegateCommand<DateTime> _viewLogCommand;
public DelegateCommand<DateTime> ViewLogCommand
{
get { return _viewLogCommand; }
set
{
SetProperty(ref _viewLogCommand, value);
}
}
public DTRReportViewModel()
{
ViewLogCommand = new DelegateCommand<DateTime>((logDate) =>
{
var s = "";
});
}
}
}
|
using System;
using System.Collections.Generic;
using System.Reactive.Linq;
using Prism.Windows.Mvvm;
using Prism.Windows.Navigation;
using System.Threading;
using SoSmartTv.VideoService;
using SoSmartTv.VideoService.Dto;
using SoSmartTv.VideoService.Services;
namespace SoSmartTv.VideoPlayer.ViewModels
{
public class VideoDetailsViewModel : ViewModelBase, IVideoDetailsViewModel
{
private VideoItem _details;
private readonly IVideoItemsProvider _videoItemsProvider;
public VideoDetailsViewModel(IVideoItemsProvider videoItemsProvider)
{
_videoItemsProvider = videoItemsProvider;
}
public override void OnNavigatedTo(NavigatedToEventArgs e, Dictionary<string, object> viewModelState)
{
var context = SynchronizationContext.Current;
_videoItemsProvider.GetVideoItem((int) e.Parameter)
.ObserveOn(context)
.Subscribe(x => Details = x);
base.OnNavigatedTo(e, viewModelState);
}
public VideoItem Details
{
get { return _details; }
private set
{
_details = value;
OnPropertyChanged();
}
}
}
} |
using System;
using System.Collections.Generic;
using System.Data.OleDb;
using System.Text;
using System.Threading.Tasks;
using dk.via.businesslayer.Data.Services;
using dk.via.ftc.businesslayer.Data.Services;
using dk.via.ftc.businesslayer.Models;
using dk.via.ftc.businesslayer.Persistence;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
namespace dk.via.ftc.businesslayer.Controllers
{
[Route("api/[controller]")]
[ApiController]
[ApiExplorerSettings(IgnoreApi = true)]
public class DispensaryController : ControllerBase
{
private DispensaryLicencesContext context;
private IDispensaryService _dispensaryService;
// GET
public DispensaryController(DispensaryLicencesContext context1, IDispensaryService _dispensaryService
)
{
context = context1;
this._dispensaryService = _dispensaryService;
}
[HttpGet, HttpPost]
[Route("License/{license}")]
public async Task<ActionResult<bool>>
CheckLicense([FromRoute]string license)
{
try
{
Console.WriteLine(license);
DispensaryLicense retrieved = context.GetLicense(license);
Console.WriteLine(retrieved.active);
if (retrieved.active == false)
{
return Ok(true);
}
return Ok(false);
}
catch (Exception e)
{
Console.WriteLine(e.Message);
return StatusCode(500, false);
}
}
[HttpGet, HttpPost]
[Route("DispensaryLic/{license}")]
public async Task<ActionResult<string>>
GetDispensary([FromRoute]string license)
{
try
{
Console.WriteLine(license + " Is the retrieved license");
IList<Dispensary> dispensaries = await _dispensaryService.GetDispensariesAsync();
Console.WriteLine(dispensaries.Count+" Retrieved Dispensaries");
foreach (Dispensary disp in dispensaries)
{
string s = JsonConvert.SerializeObject(disp);
Console.WriteLine(s);
if (disp.DispensaryLicense.Equals(license))
{
Console.WriteLine(disp.DispensaryId + " is the found ID");
return Ok(disp.DispensaryId);
}
}
return Ok("NotFound");
}
catch (Exception e)
{
Console.WriteLine(e.Message);
return StatusCode(500, false);
}
}
[HttpPut]
public async Task RegisterDispensary([FromBody]Dispensary dispensary)
{
string s = JsonConvert.SerializeObject(dispensary);
Console.WriteLine(s);
await _dispensaryService.AddDispensaryAsync(dispensary);
}
[HttpPut]
[Route("DispensaryAdmin")]
public async Task RegisterDispensaryAdmin([FromBody]DispensaryAdmin dispensaryAdmin)
{
string s = JsonConvert.SerializeObject(dispensaryAdmin);
Console.WriteLine(s);
await _dispensaryService.AddDispensaryAdminAsync(dispensaryAdmin);
}
[HttpGet]
[Route("Dispensary/{username}")]
public async Task<ActionResult<DispensaryAdmin>> GetDispensaryAdmin([FromRoute] string username)
{
try
{
DispensaryAdmin dispensaryAdmin = await _dispensaryService.GetDispensaryByUsername(username);
string s = JsonConvert.SerializeObject(dispensaryAdmin);
Console.WriteLine(s);
return Ok(s);
}
catch (Exception e)
{
Console.WriteLine(e);
return StatusCode(200, e.Message);
}
}
[HttpGet]
[Route("DAValidate/{username}/{password}")]
public async Task<ActionResult<bool>> ValidateDispensaryAdmin([FromRoute] string username, [FromRoute] string password)
{
try
{
bool validation = await _dispensaryService.ValidateDispensaryAdmin(username,password);
Console.WriteLine("Login Validation: "+ validation);
return Ok(validation);
}
catch (Exception e)
{
Console.WriteLine(e);
return StatusCode(200, e.Message);
}
}
}
} |
namespace Promact.Oauth.Server.StringLiterals
{
public class ConsumerApp
{
public string AlphaNumericString { get; set; }
public string CapitalAlphaNumericString { get; set; }
}
}
|
using System;
[CustomLuaClass]
public class VerificationOfLogin : Singleton<VerificationOfLogin>
{
private string m_cachedAccessToken;
private string m_cachedAnyDataForAnySDKLogin;
public static VerificationOfLogin Instance
{
get
{
return Singleton<VerificationOfLogin>.ins;
}
}
public string CachedAccessToken
{
get
{
return this.m_cachedAccessToken;
}
set
{
this.m_cachedAccessToken = value;
}
}
public string CachedAnyDataForAnySDKLogin
{
get
{
return this.m_cachedAnyDataForAnySDKLogin;
}
set
{
this.m_cachedAnyDataForAnySDKLogin = value;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Sock5Example
{
class Program
{
static void Main(string[] args)
{
var sock = SocksProxy.ConnectToSocks5Proxy();
}
}
}
|
// --------------------------------------------------------------------------------------------------------------
// <copyright file="TinyResult.cs" company="Tiny开源团队">
// Copyright (c) 2017-2018 Tiny. All rights reserved.
// </copyright>
// <site>http://www.lxking.cn</site>
// <last-editor>ArcherTrister</last-editor>
// <last-date>2019/3/13 21:42:26</last-date>
// --------------------------------------------------------------------------------------------------------------
using System;
using Tiny.Extensions;
namespace Tiny.Data
{
/// <summary>
/// Tiny结果基类
/// </summary>
/// <typeparam name="TResultType"></typeparam>
public abstract class TinyResult<TResultType> : TinyResult<TResultType, object>, ITinyResult<TResultType>
{
/// <summary>
/// 初始化一个<see cref="TinyResult{TResultType}"/>类型的新实例
/// </summary>
protected TinyResult()
: this(default(TResultType))
{ }
/// <summary>
/// 初始化一个<see cref="TinyResult{TResultType}"/>类型的新实例
/// </summary>
protected TinyResult(TResultType type)
: this(type, null, null)
{ }
/// <summary>
/// 初始化一个<see cref="TinyResult{TResultType}"/>类型的新实例
/// </summary>
protected TinyResult(TResultType type, string message)
: this(type, message, null)
{ }
/// <summary>
/// 初始化一个<see cref="TinyResult{TResultType}"/>类型的新实例
/// </summary>
protected TinyResult(TResultType type, string message, object data)
: base(type, message, data)
{ }
}
/// <summary>
/// Tiny结果基类
/// </summary>
/// <typeparam name="TResultType">结果类型</typeparam>
/// <typeparam name="TData">结果数据类型</typeparam>
public abstract class TinyResult<TResultType, TData> : ITinyResult<TResultType, TData>
{
/// <summary>
/// 内部消息
/// </summary>
protected string _message;
/// <summary>
/// 初始化一个<see cref="TinyResult{TResultType,TData}"/>类型的新实例
/// </summary>
protected TinyResult()
: this(default(TResultType))
{ }
/// <summary>
/// 初始化一个<see cref="TinyResult{TResultType,TData}"/>类型的新实例
/// </summary>
protected TinyResult(TResultType type)
: this(type, null, default(TData))
{ }
/// <summary>
/// 初始化一个<see cref="TinyResult{TResultType,TData}"/>类型的新实例
/// </summary>
protected TinyResult(TResultType type, string message)
: this(type, message, default(TData))
{ }
/// <summary>
/// 初始化一个<see cref="TinyResult{TResultType,TData}"/>类型的新实例
/// </summary>
protected TinyResult(TResultType type, string message, TData data)
{
if (message == null && typeof(TResultType).IsEnum)
{
message = (type as Enum)?.ToDescription();
}
ResultType = type;
_message = message;
Data = data;
}
/// <summary>
/// 获取或设置 结果类型
/// </summary>
public TResultType ResultType { get; set; }
/// <summary>
/// 获取或设置 返回消息
/// </summary>
public virtual string Message
{
get { return _message; }
set { _message = value; }
}
/// <summary>
/// 获取或设置 结果数据
/// </summary>
public TData Data { get; set; }
}
}
|
public static class GameTags
{
public const string Ball = "Ball";
public const string Ship = "Ship";
public const string Enemy = "Enemy";
public const string Frame = "Frame";
public const string EnemyProjectile = "EnemyProjectile";
public const string Striker = "Striker";
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
/**
* Copyright (c) blueback
* Released under the MIT License
* https://github.com/bluebackblue/fee/blob/master/LICENSE.txt
* http://bbbproject.sakura.ne.jp/wordpress/mitlicense
* @brief イベントプレート。ブロックアイテム。
*/
/** NEventPlate
*/
namespace NEventPlate
{
/** BlockItem
*/
public class BlockItem : NDeleter.DeleteItem_Base
{
/** deleter
*/
NDeleter.Deleter deleter;
/** eventplate
*/
private Item eventplate_button;
private Item eventplate_viewitem;
private Item eventplate_view;
/** constructor
*/
public BlockItem(NDeleter.Deleter a_deleter,long a_priority)
{
//deleter
this.deleter = new NDeleter.Deleter();
this.eventplate_button = new Item(this.deleter,EventType.Button,a_priority);
this.eventplate_viewitem = new Item(this.deleter,EventType.ViewItem,a_priority);
this.eventplate_view = new Item(this.deleter,EventType.View,a_priority);
this.eventplate_button.SetRect(0,0,NRender2D.Render2D.VIRTUAL_W,NRender2D.Render2D.VIRTUAL_H);
this.eventplate_viewitem.SetRect(0,0,NRender2D.Render2D.VIRTUAL_W,NRender2D.Render2D.VIRTUAL_H);
this.eventplate_view.SetRect(0,0,NRender2D.Render2D.VIRTUAL_W,NRender2D.Render2D.VIRTUAL_H);
//削除管理。
if(a_deleter != null){
a_deleter.Register(this);
}
}
/** 削除。
*/
public void Delete()
{
this.deleter.DeleteAll();
}
/** 有効。設定。
*/
public void SetEnable(bool a_flag)
{
this.eventplate_button.SetEnable(a_flag);
this.eventplate_viewitem.SetEnable(a_flag);
this.eventplate_view.SetEnable(a_flag);
}
/** プライオリティ。設定。
*/
public void SetPriority(long a_priority)
{
this.eventplate_button.SetPriority(a_priority);
this.eventplate_viewitem.SetPriority(a_priority);
this.eventplate_view.SetPriority(a_priority);
}
}
}
|
using MrHai.Application;
using MrHai.BMS.Controllers.Base;
using MrHai.BMS.Models.Work;
using MrHai.Core.Models;
using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.Linq;
using System.Web;
namespace MrHai.BMS.Controllers.Common.Funtion
{
[Export]
public class AddEWC
{
[Import]
public IMrHaiApplication MrHaiApplication { get; set; }
public AddEWC(IMrHaiApplication haiApplication)
{
if (haiApplication!=null)
{
MrHaiApplication = haiApplication;
}
}
/// <summary>
/// 新增
/// </summary>
/// <param name="data"></param>
/// <returns></returns>
public ResponseMessage CommonAdd(viewAddModel data)
{
ResponseMessage responseMessage = new ResponseMessage();
if (string.IsNullOrEmpty(data.workId) || string.IsNullOrEmpty(data.title) || string.IsNullOrEmpty(data.content))
{
responseMessage.result.errcode = -1;
responseMessage.result.msg = "信息不完整,新增失败";
return responseMessage;
}
if (!string.IsNullOrEmpty(MrHaiApplication.GetModelByTitle(data.title, data.workId, data.infoType)))
{
responseMessage.result.errcode = 1;
responseMessage.result.msg = "信息存在";
return responseMessage;
}
Infomation exhibition = new Infomation()
{
Title = data.title,
CategoryId = data.workId,
Content = data.content,
CreateUserId = data.userID,
CreateTime = DateTime.Now,
InfoType = data.infoType,
IsDeleted = false
};
int count = MrHaiApplication.SaveInfomation(new List<Infomation> { exhibition });
if (count > 0)
{
responseMessage.result.errcode = 0;
responseMessage.result.msg = "新增成功";
}
else
{
responseMessage.result.errcode = 2;
responseMessage.result.msg = "新增失败";
}
return responseMessage;
}
/// <summary>
/// 更新
/// </summary>
/// <param name="data"></param>
/// <returns></returns>
public ResponseMessage CommonUpdate(viewAddModel data)
{
ResponseMessage responseMessage = new ResponseMessage();
if (string.IsNullOrEmpty(data.workId) || string.IsNullOrEmpty(data.title) || string.IsNullOrEmpty(data.content))
{
responseMessage.result.errcode = -1;
responseMessage.result.msg = "信息不完整,更新失败";
return responseMessage;
}
var dbModel = MrHaiApplication.GetInfo(data.infoID).AppendData as Infomation;
dbModel.CategoryId = data.workId;
dbModel.Title = data.title;
dbModel.Content = data.content;
int count = MrHaiApplication.UpdateinfomationChanges(new List<Infomation> { dbModel });
if (count > 0)
{
responseMessage.result.errcode = 0;
responseMessage.result.msg = "更新成功";
}
else
{
responseMessage.result.errcode = 2;
responseMessage.result.msg = "更新失败";
}
return responseMessage;
}
/// <summary>
/// 删除
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
public ResponseMessage CommonDelete(string id)
{
ResponseMessage responseMessage = new ResponseMessage();
if (string.IsNullOrEmpty(id))
{
responseMessage.result.errcode = -1;
responseMessage.result.msg = "确少必要参数";
return responseMessage;
}
var dbModel = MrHaiApplication.GetInfo(id).AppendData as Infomation;
if (dbModel==null)
{
responseMessage.result.errcode = -1;
responseMessage.result.msg = "该条信息不存在";
return responseMessage;
}
dbModel.IsDeleted = true;
dbModel.DeletedTime = DateTime.Now;
int count = MrHaiApplication.UpdateinfomationChanges(new List<Infomation> { dbModel });
if (count > 0)
{
responseMessage.result.errcode = 0;
responseMessage.result.msg = "删除成功";
}
else
{
responseMessage.result.errcode = 2;
responseMessage.result.msg = "删除失败";
}
return responseMessage;
}
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class HealthRegen : MonoBehaviour
{
//==========================| Variables |===============================================
const float duration_untilStart = 2.0f;
const float duration_fullRegen = 20.0f;
const float duration_interval = 0.2f;
public static HealthRegen Instance;
//==========================| Awake() |===============================================
private void Awake()
{
Instance = this;
}
//==========================| JustGotHit() |===============================================
public void JustGotHit()
{
StopAllCoroutines();
StartCoroutine(Regen());
}
//==========================| IEnumerator - Regen() |===============================================
private IEnumerator Regen()
{
yield return new WaitForSeconds(duration_untilStart);
float perSecond = HitPoints.hp_player / duration_fullRegen;
float timeLast = Time.time;
while (HitPoints.Instance_Player.hitPoints < HitPoints.hp_player)
{
HitPoints.Instance_Player.hitPoints += perSecond * (Time.time - timeLast);
timeLast = Time.time;
Healthbar.Instance.ShowPercentage(HitPoints.Instance_Player.hitPoints / HitPoints.hp_player);
yield return new WaitForSeconds(duration_interval);
}
HitPoints.Instance_Player.hitPoints = HitPoints.hp_player;
Healthbar.Instance.ShowPercentage(1.0f);
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Dentist.Models;
using Kendo.Mvc.UI;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
namespace Dentist.Controllers
{
public class TryController : Controller
{
// GET: Try
public ActionResult Index()
{
return View();
}
public JsonResult DateTime()
{
var obj = new SomeObject();
obj.DateTimeLocal = System.DateTime.Now;
obj.DateTimeUtc = System.DateTime.UtcNow;
obj.DateTimeLocalSerilized = JsonConvert.SerializeObject(obj.DateTimeLocal);
obj.DateTimeLocalISOSerilized = JsonConvert.SerializeObject(obj.DateTimeLocal, new IsoDateTimeConverter());
obj.DateTimeLocalJavaScriptSerilized = JsonConvert.SerializeObject(obj.DateTimeLocal, new JavaScriptDateTimeConverter());
return Json(obj, JsonRequestBehavior.AllowGet);
}
}
public class SomeObject
{
public DateTime DateTimeLocal { get; set; }
public DateTime DateTimeUtc { get; set; }
public string DateTimeLocalSerilized { get; set; }
public string DateTimeLocalISOSerilized { get; set; }
public string DateTimeLocalJavaScriptSerilized { get; set; }
}
} |
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;
using System.Net;
using System.IO;
using Jil;
using System.Security.Cryptography;
using System.Runtime.Serialization.Formatters.Binary;
using HtmlAgilityPack;
using System.Threading;
namespace WinYatang
{
public partial class frm_Login : Form
{
public const string PageURL_Base = "https://jr.yatang.cn";
public const string PageURL_Login = "https://yztapi.yatang.cn/loginM.jsp?origin=1&source=1&synUrl=https://jr.yatang.cn/index.php?s=/index/index/*type:1&findPwdUrl=https://jr.yatang.cn/index.php?s=/new_login/lookpassword/*type:3®Url=https://jr.yatang.cn/NewRegister/*type:2";
public const string PageURL_LoginPost = "https://yztapi.yatang.cn/yluser";
private const string PageURL_InvestDetail = "https://jr.yatang.cn/Invest/ViewBorrow/ibid/";
private const string PageURL_GetUserCoupon = "https://jr.yatang.cn/Ajax/getUserCoupon";
private const string PageURL_InvestCheckPPay = "https://jr.yatang.cn/Invest/checkppay";
public const string PageURL_Index = "/index.php?s=/index/index";
private const string cookiesDir = "Cookies";
public frm_Login()
{
InitializeComponent();
}
private CookieContainer cookie = null;
private Dictionary<string, CookieContainer> CookiesDict = null;
private void frm_Login_Load(object sender, EventArgs e)
{
//var ppay = Encrypt("fmy712", "15f6c805ba51da28a6350de6a2720f12"); //支付密码
//var pppay = Decrypt(ppay, "15f6c805ba51da28a6350de6a2720f12");
//ppay = XXTEA.Code(, "15f6c805ba51da28a6350de6a2720f12", XXTEAMode.Encrypt);
PnOptor.Hide();
PnLogin.Show();
}
private void ReLoadCookieUsers()
{
CookiesDict = new Dictionary<string, CookieContainer>();
cboSelectUser.Items.Clear();
if (Directory.Exists(cookiesDir))
{
string[] files = Directory.GetFiles(cookiesDir);
foreach (var file in files.OrderBy(t => new FileInfo(t).Name))
{
FileInfo f = new FileInfo(file);
CookiesDict.Add(f.Name, ReadCookiesFromDisk(file));
cboSelectUser.Items.Add(f.Name);
}
if (files.Length > 0)
cboSelectUser.SelectedIndex = 0;
}
}
private void btn_Login_Click(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(txtPayPWD.Text))
{
txtLogs.AppendText("请输入支付密码!!!!\r\n");
return;
}
try
{
string file = null;
if (rdoNewUser.Checked)
{
string userName = txt_UserName.Text.Trim();
string pwd = txt_Password.Text.Trim();
string dateStr = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
string encryptPWD = Encrypt(dateStr + pwd, "oZ3qvmx4BTATvbI7", "oZ3qvmx4BTATvbI7");
var param = string.Format(@"format=json&appKey=00001&v=1.0×tamp={0}&method=sso.login&origin=1&source=1&vcode=''&cookieAge=7200&u={1}&p={2}&synUrl=https://jr.yatang.cn/index.php?s=/index/index/*type:1", dateStr, userName, encryptPWD);
string res = WebHttpHeper.PostFormRequest(param, PageURL_Login, PageURL_LoginPost, ref cookie);
dynamic data = null;
data = JSON.DeserializeDynamic(res);
if (data.code == "0")
{
lblUserName.Text = txt_UserName.Text;
PnOptor.Show();
PnLogin.Hide();
if (!Directory.Exists(cookiesDir))
{
Directory.CreateDirectory(cookiesDir);
}
file = cookiesDir + "/" + lblUserName.Text;
WriteCookiesToDisk(file, cookie);
if (data.isRedirect)
{
SetUserCookieAnUserLoginStatus(data.redirectUrl.ToString().Trim('"'));
return;
}
//其他处理
return;
}
txtLogs.AppendText(data.message.ToString() + data.data + "\r\n");
}
else
{
lblUserName.Text = cboSelectUser.SelectedItem.ToString();
cookie = CookiesDict[lblUserName.Text];
SetUserCookieAnUserLoginStatus("https://jr.yatang.cn/index.php?s=/index/index/*type:1");
PnLogin.Hide();
PnOptor.Show();
}
CookieCollection collection = cookie.GetCookies(new Uri(PageURL_Base, UriKind.Absolute));
Cookie ckItem = collection["PayPWD"];
if (ckItem == null)
{
cookie.SetCookies(new Uri(PageURL_Base, UriKind.Absolute), "PayPWD=" + txtPayPWD.Text);
file = cookiesDir + "/" + lblUserName.Text;
WriteCookiesToDisk(file, cookie);
}
lblPayPWD.Text = txtPayPWD.Text;
}
catch (Exception ex)
{
txtLogs.AppendText("系统异常:" + ex.Message + "\r\n");
}
}
public void SetUserCookieAnUserLoginStatus(string url)
{
Uri uri = new Uri(url);
var loginRedirectURL = uri.Scheme + "://" + uri.Host + "/ytRedirect.html#" + url;
//var ret = WebHttpHeper.GetRequest(loginRedirectURL, ref cookie);
//txtLogs.AppendText("------登录跳转------\r\n");
var setCookieUrl = uri.Scheme + "://" + uri.Host + "/Ajax/setUserCookie";
//var rets = WebHttpHeper.PostJSONRequest(JSON.Serialize(new { url = url }), loginRedirectURL, setCookieUrl, ref cookie);
var rets = WebHttpHeper.PostFormRequest("url=" + url, loginRedirectURL, setCookieUrl, ref cookie);
txtLogs.AppendText("------登录成功-------\r\n");
}
Random r = new Random();
// 融资标列表
private void StartAutoInvest()
{
tmrRandFloat.Stop();
//用户是否有红包
bool luckMoneyDataIsNotNull = true;
bool isInvestIng = false;
try
{
//var result = WebHttpHeper.PostFormRequest("aprrange=1&selectdate=2&repaystyle=1&page_href=", "https://jr.yatang.cn/Financial/asset", "https://jr.yatang.cn/Financial/getAssetList", ref cookie);
var result = WebHttpHeper.PostFormRequest("aprrange=0&selectdate=0&repaystyle=0&page_href=", "https://jr.yatang.cn/Financial/asset", "https://jr.yatang.cn/Financial/getAssetList", ref cookie);
var financeData = JSON.DeserializeDynamic(result);
txtLogs.AppendText(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + financeData.ToString() + "\r\n");
if (financeData.status == 1 && financeData.list.Count > 0)
{
dynamic maxRemain = null;
List<dynamic> financeList = new List<dynamic>();
//抓取剩余金额最大的一个
foreach (var item in financeData.list)
{
if (maxRemain == null)
{
maxRemain = item;
}
else if (item.remain > maxRemain.remain)
{
maxRemain = item;
}
financeList.Add(item);
}
//投标 URL
string investDetailURL = PageURL_InvestDetail + maxRemain.id.ToString().Trim('"');
//请求页面,解析 html {hash,uniqKey}
var retHTML = WebHttpHeper.GetRequest(investDetailURL, ref cookie);
//获取用户红包
var data = GetUserLuckMoney(investDetailURL, maxRemain, out luckMoneyDataIsNotNull);
//没有可用红包继续轮询
if (data != null)
{
//自动投资
string name = maxRemain.name.ToString().Trim('"');
string ibnum = "121" + name.Substring(name.IndexOf('_') + 1);
InvestToRemote(investDetailURL, retHTML, ibnum, Convert.ToInt32(data.id.ToString().Trim('"')), Convert.ToInt32(data.user_constraint.ToString()));
}
//不使用红包
if (!chkUseLuckMoney.Checked)
{
//自动投资
string name = maxRemain.name.ToString().Trim('"');
string ibnum = "121" + name.Substring(name.IndexOf('_') + 1);
InvestToRemote(investDetailURL, retHTML, ibnum, 0, Convert.ToInt32(txtInvestValue.Text));
isInvestIng = true;
}
}
}
catch (Exception ex)
{
txtLogs.AppendText("系统异常:" + ex.Message + "\r\n");
}
finally
{
//使用红包,不适用红包投资中
if ((chkUseLuckMoney.Checked && luckMoneyDataIsNotNull) ||
(!chkUseLuckMoney.Checked && !isInvestIng))
tmrAutoInvest.Start();
}
}
int luckMoneyRate = 50;
// 用户数据,红包列表
private dynamic GetUserLuckMoney(string headerURL, dynamic invest, out bool luckMoneyDataIsNotNull)
{
luckMoneyRate = Convert.ToInt32(txtLuckMoneyRate.Text);
string name = invest.name.ToString().Trim('"');
var retLuckMoney = WebHttpHeper.PostFormRequest("investMoney=&borrowNum=121" + name.Substring(name.IndexOf('_') + 1) + "&pageNum=1", headerURL, PageURL_GetUserCoupon, ref cookie);
var data = JSON.DeserializeDynamic(retLuckMoney);
luckMoneyDataIsNotNull = true;
if (data.status == 0)
{
txtLogs.AppendText("---拉取红包" + Convert.ToString(data.info) + "\r\n");
txtLogs.AppendText("---" + data.ToString() + "\r\n");
string info = data.info.ToString().Trim('"');
//判断是否登录过期
if (info == "请先登陆")
{
luckMoneyDataIsNotNull = false;
PnLogin.Visible = true;
PnOptor.Visible = false;
}
else luckMoneyDataIsNotNull = info != "暂无适合使用的红包";
}
if (data.data != null)
{
double withDrawal_Cash = Convert.ToDouble(data.withdrawal_cash.ToString().Trim('"'));
dynamic luckMoney = null;
foreach (var item in data.data)
{
if (invest.remain < item.user_constraint) continue;//剩余金额小于红包金额
//红包比例
int currRate = (int)(item.user_constraint / item.value);
if (currRate <= luckMoneyRate)
{
double userConstraint = Convert.ToDouble(item.user_constraint.ToString());
//剩余可用红包金额大于,红包金额时
if (withDrawal_Cash > userConstraint)
{
//如果使用
if (luckMoney == null)
{
luckMoney = item;
}
else
{
int luckRate = (int)(luckMoney.user_constraint / luckMoney.value);
//红包比例更小
if (currRate < luckRate)
{
//红包比例更小优先
luckMoney = item;
continue;
}
else if (currRate == luckRate)//红包比例相等,优先大额
{
if (item.user_constraint > luckMoney.user_constraint)
{
luckMoney = item;
}
//红包比例相等,额度相等,优先快过期
else if (item.user_constraint == luckMoney.user_constraint)
{
if (item.nearExpire == 1)
{
luckMoney = item;
}
}
}
}
}
}
}
return luckMoney;
}
return null;
}
/// <summary>
///
/// </summary>
/// <param name="url">标链接</param>
/// <param name="ibnum">标号</param>
/// <param name="lunchId">红包ID</param>
/// <param name="amount">投资金额</param>
private void InvestToRemote(string url, string retHTML, string ibnum, int lunchId, int amount)//红包ID,投资金额(根据红包来)
{
//html 解析值
var userID = ""; //用户ID; CUID
var uniqKey = ""; //唯一key
var _hash = ""; //hash 值
HtmlAgilityPack.HtmlDocument document = new HtmlAgilityPack.HtmlDocument();
document.LoadHtml(retHTML);
HtmlNode cuidNode = document.GetElementbyId("cuid");
userID = cuidNode.Attributes["value"].Value;
HtmlNode uniqKeyNode = document.GetElementbyId("uniqKey");
uniqKey = uniqKeyNode.Attributes["value"].Value;
HtmlNode _hashNode = document.GetElementbyId("J_form_msg2").SelectSingleNode("//input[@name='__hash__']");
_hash = _hashNode.Attributes["value"].Value;
//密码加密
//var ppay = Encrypt(txtPayPWD.Text, uniqKey); //支付密码
Thread.Sleep(3000);
string utf8Str = (string)webBrowser1.Document.InvokeScript("utf16to8", new string[] { txtPayPWD.Text });
string xxteaEncryptStr = (string)webBrowser1.Document.InvokeScript("xxtea_encrypt", new string[] { utf8Str, uniqKey });
string ppay = (string)webBrowser1.Document.InvokeScript("encode64", new string[] { xxteaEncryptStr });
//encode64(xxtea_encrypt(utf16to8(ppay), $("#uniqKey").val()))
//txtLogs.AppendText("utf8Str:" + utf8Str);
//txtLogs.AppendText("xxteaEncryptStr:" + xxteaEncryptStr);
txtLogs.AppendText("ppay:" + ppay);
string paramStr = string.Format("p_pay={0}&user_id={1}&ibnum={2}&lunchId={3}&amount={4}&__hash__={5}&vcode=", ppay, userID, ibnum, lunchId, amount, _hash);
txtLogs.AppendText(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + paramStr + "\r\n");
var result = WebHttpHeper.PostFormRequest(paramStr, url, PageURL_InvestCheckPPay, ref cookie);
var resultText = JSON.DeserializeDynamic(result).ToString();
txtLogs.AppendText(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + resultText + "\r\n");
}
private static string Encrypt(string toEncrypt, string key, string iv)
{
byte[] keyArray = UTF8Encoding.UTF8.GetBytes(key);
byte[] ivArray = UTF8Encoding.UTF8.GetBytes(iv);
byte[] toEncryptArray = UTF8Encoding.UTF8.GetBytes(toEncrypt);
RijndaelManaged rDel = new RijndaelManaged();
rDel.Key = keyArray;
rDel.IV = ivArray;
rDel.Mode = CipherMode.CBC;
rDel.Padding = PaddingMode.PKCS7;
ICryptoTransform cTransform = rDel.CreateEncryptor();
byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);
return Convert.ToBase64String(resultArray, 0, resultArray.Length);
}
private static void WriteCookiesToDisk(string file, CookieContainer cookieJar)
{
using (Stream stream = File.Create(file))
{
try
{
Console.Out.Write("Writing cookies to disk... ");
BinaryFormatter formatter = new BinaryFormatter();
formatter.Serialize(stream, cookieJar);
Console.Out.WriteLine("Done.");
}
catch (Exception e)
{
Console.Out.WriteLine("Problem writing cookies to disk: " + e.GetType());
}
}
}
private static CookieContainer ReadCookiesFromDisk(string file)
{
try
{
using (Stream stream = File.Open(file, FileMode.Open))
{
Console.Out.Write("Reading cookies from disk... ");
BinaryFormatter formatter = new BinaryFormatter();
Console.Out.WriteLine("Done.");
return (CookieContainer)formatter.Deserialize(stream);
}
}
catch (Exception e)
{
Console.Out.WriteLine("Problem reading cookies from disk: " + e.GetType());
return new CookieContainer();
}
}
private void btnLoginOut_Click(object sender, EventArgs e)
{
tmrRandFloat.Stop();
tmrAutoInvest.Stop();
cookie = null;
//File.Delete(cookiesDir + "/" + lblUserName.Text);
PnOptor.Hide();
PnLogin.Show();
}
/// <summary>
/// 浮动timer
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void tmrRandFloat_Tick(object sender, EventArgs e)
{
StartAutoInvest();
}
private void tmrAutoInvest_Tick(object sender, EventArgs e)
{
//停止固定计时器
tmrAutoInvest.Stop();
//开启随机计时器
tmrRandFloat.Interval = r.Next(1, 3) * 1000;
tmrRandFloat.Start();
}
private void btnStart_Click(object sender, EventArgs e)
{
tmrRandFloat.Start();
}
private void btnStop_Click(object sender, EventArgs e)
{
tmrRandFloat.Stop();
tmrAutoInvest.Stop();
}
private void chkUseLuckMoney_CheckedChanged(object sender, EventArgs e)
{
txtInvestValue.Enabled = !chkUseLuckMoney.Checked;
}
private void rdoUser_CheckedChanged(object sender, EventArgs e)
{
var isNewUser = ((RadioButton)sender) == rdoNewUser;
txt_UserName.Enabled = isNewUser;
txt_Password.Enabled = isNewUser;
cboSelectUser.Enabled = !isNewUser;
if (!isNewUser) ReLoadCookieUsers();
}
private void cboSelectUser_SelectedIndexChanged(object sender, EventArgs e)
{
txtPayPWD.Text = string.Empty;
string userName = ((ComboBox)sender).SelectedItem.ToString();
CookieCollection collection = CookiesDict[userName].GetCookies(new Uri(PageURL_Base, UriKind.Absolute));
Cookie ckItem = collection["PayPWD"];
if (ckItem != null)
{
txtPayPWD.Text = ckItem.Value;
}
}
}
public enum XXTEAMode
{
Encrypt,
Decrypt
}
static public class XXTEA
{
static public byte[] Code(byte[] data, uint[] k, XXTEAMode mode)
{
uint[] v = new uint[(int)Math.Ceiling((float)data.Length / 4)];
Buffer.BlockCopy(data, 0, v, 0, data.Length);
unchecked
{
const uint DELTA = 0x9e3779b9;
uint y = 0, z = 0, sum = 0, p = 0, rounds = 0, e = 0;
int n = v.Length;
Func<uint> MX = () => (((z >> 5 ^ y << 2) + (y >> 3 ^ z << 4)) ^ ((sum ^ y) + (k[(p & 3) ^ e] ^ z)));
if (mode == XXTEAMode.Encrypt)
{
rounds = (uint)(6 + 52 / n);
z = v[n - 1];
do
{
sum += DELTA;
e = (sum >> 2) & 3;
for (p = 0; p < n - 1; p++)
{
y = v[p + 1];
z = v[p] += MX();
}
y = v[0];
z = v[n - 1] += MX();
} while (--rounds > 0);
}
else
{
rounds = (uint)(6 + 52 / n);
sum = rounds * DELTA;
y = v[0];
do
{
e = (sum >> 2) & 3;
for (p = (uint)(n - 1); p > 0; p--)
{
z = v[p - 1];
y = v[p] -= MX();
}
z = v[n - 1];
y = v[0] -= MX();
} while ((sum -= DELTA) != 0);
}
}
byte[] rvl = new byte[v.Length * 4];
Buffer.BlockCopy(v, 0, rvl, 0, rvl.Length);
return rvl;
}
}
}
|
using DevExpress.Office.Utils;
using MetroFramework;
using MetroFramework.Forms;
using PDV.CONTROLER.Funcoes;
using PDV.DAO.Entidades;
using PDV.UTIL;
using PDV.VIEW.Forms.Cadastro;
using PDV.VIEW.Forms.Util;
using System;
using System.Collections.Generic;
using System.Data;
using System.Windows.Forms;
namespace PDV.VIEW.Forms.Consultas
{
public partial class FCO_FluxoCaixa : DevExpress.XtraEditors.XtraForm
{
private string NOME_TELA = "CONSULTA DE FLUXO DE CAIXA";
public FCO_FluxoCaixa()
{
InitializeComponent();
Atualizar();
dateEdit1.DateTime = dateEdit2.DateTime = DateTime.Today;
}
private void Atualizar()
{
gridControl1.DataSource = FuncoesFluxoCaixa.GetFluxosCaixa(dateEdit1.DateTime, dateEdit2.DateTime.AddDays(1));
Grids.FormatGrid(ref gridView1);
Grids.FormatColumnType(ref gridView1, new List<string>
{
"valorfechamentocaixa",
"valorcaixa"
}, GridFormats.Finance);
}
private void ovBTN_Editar_Click(object sender, EventArgs e)
{
Editar();
}
private void imprimriMetroButton_Click(object sender, EventArgs e)
{
gridControl1.ShowPrintPreview();
}
private void atualizarMetroButton_Click(object sender, EventArgs e)
{
Atualizar();
}
private void dateEdit1_EditValueChanged(object sender, EventArgs e)
{
if (dateEdit1.DateTime > dateEdit2.DateTime)
dateEdit2.DateTime = dateEdit1.DateTime;
}
private void dateEdit2_EditValueChanged(object sender, EventArgs e)
{
if (dateEdit1.DateTime > dateEdit2.DateTime)
dateEdit1.DateTime = dateEdit2.DateTime;
}
private void gridControl1_DoubleClick(object sender, EventArgs e)
{
Editar();
}
private void Editar()
{
try
{
new FCA_FluxoCaixa(Grids.GetValorDec(gridView1, "idfluxocaixa")).ShowDialog();
Atualizar();
}
catch (Exception exception)
{
Alert(exception.Message);
}
}
private void Alert(string message)
{
MessageBox.Show(message, NOME_TELA, MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
|
using CleanArch.Application.ViewModels;
using CleanArch.Domain.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CleanArch.Application.Interfaces
{
public interface IProductService
{
//IEnumerable<ProductViewModel> GetProducts();
ProductViewModel GetProducts();
public Product GetProductDetails(int id);
void Create(ProductViewModel productViewModel);
void Update(ProductViewModel productViewModel, int id);
void Delete(int id);
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Azure.WebJobs.Extensions.OpenApi.Core.Abstractions;
using Microsoft.Azure.WebJobs.Extensions.OpenApi.Core.Enums;
using Microsoft.Azure.WebJobs.Extensions.OpenApi.Core.Extensions;
using Microsoft.OpenApi.Models;
namespace Microsoft.Azure.WebJobs.Extensions.OpenApi.Core.Configurations
{
/// <summary>
/// This represents the options entity for OpenAPI metadata configuration.
/// </summary>
public class DefaultOpenApiConfigurationOptions : IOpenApiConfigurationOptions
{
/// <inheritdoc />
public virtual OpenApiInfo Info { get; set; } = new OpenApiInfo()
{
Version = "1.0.0",
Title = "Azure Functions OpenAPI Extension",
};
/// <inheritdoc />
public virtual List<OpenApiServer> Servers { get; set; } = GetHostNames();
/// <inheritdoc />
public virtual OpenApiVersionType OpenApiVersion { get; set; } = OpenApiVersionType.V2;
/// <inheritdoc />
public virtual bool IncludeRequestingHostName { get; set; } = Environment.GetEnvironmentVariable("AZURE_FUNCTIONS_ENVIRONMENT") == "Development";
/// <summary>
/// Gets the list of hostnames.
/// </summary>
/// <returns>Returns the list of hostnames.</returns>
protected static List<OpenApiServer> GetHostNames()
{
var servers = new List<OpenApiServer>();
var collection = Environment.GetEnvironmentVariable("OpenApi__HostNames");
if (collection.IsNullOrWhiteSpace())
{
return servers;
}
var hostnames = collection.Split(new[] { "," }, StringSplitOptions.RemoveEmptyEntries)
.Select(p => new OpenApiServer() { Url = p });
servers.AddRange(hostnames);
return servers;
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Rotater : MonoBehaviour
{
private void Update()
{
this.transform.Rotate(new Vector3(0, Time.deltaTime * 5, 0));
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ORI_uvod
{
public class FizzBuzz
{
public static string GetFizzBuzz()
{
string fbString = "";
// TODO 4: -Implementirati FizzBuzz algoritam
return fbString;
}
}
}
|
using JigneshPractical.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace JigneshPractical.Repository
{
public interface IUser_Repository : IDisposable
{
List<MST_City_List_Get_Result> GetCityList();
int GetUserCode();
List<MST_User_Register_Result> MST_User_Register(string UserName, string EmailId, string Passwod, int CityId, out int ReturnValue, out string RetuenMsg);
List<User_Login_Result> User_Login(string UserName, string Passwod, out int ReturnValue, out string RetuenMsg);
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
namespace System.IO.Compression
{
public class HttpZipStream : IDisposable
{
string httpUrl { get; set; }
HttpClient httpClient { get; set; }
bool LeaveHttpClientOpen { get; set; }
public HttpZipStream(string httpUrl) : this(httpUrl, new HttpClient()) { this.LeaveHttpClientOpen = true; }
public HttpZipStream(string httpUrl, HttpClient httpClient)
{
this.httpUrl = httpUrl;
this.httpClient = httpClient;
this.httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/octet-stream"));
}
public long ContentLength { get; private set; } = -1;
/// <summary>
/// Manually setting the content length is only recommended if you truly know what your doing. This may increase loading time but could also invalidate the requests.
/// </summary>
public void SetContentLength(long value) { this.ContentLength = value; }
public async Task<long> GetContentLengthAsync()
{
try
{
if (this.ContentLength != -1) { return this.ContentLength; }
using (var httpMessage = await this.httpClient.GetAsync(this.httpUrl, HttpCompletionOption.ResponseHeadersRead))
{
if (!httpMessage.IsSuccessStatusCode) { return -1; }
this.ContentLength = httpMessage.Content.Headers
.GetValues("Content-Length")
.Select(x => long.Parse(x))
.FirstOrDefault();
return this.ContentLength;
}
}
catch (Exception) { throw; }
}
HttpZipDirectory directoryData { get; set; }
private async Task<bool> LocateDirectoryAsync()
{
try
{
// INITIALIZE
this.directoryData = new HttpZipDirectory { Offset = -1 };
var secureMargin = 22;
var chunkSize = 256;
var rangeStart = this.ContentLength - secureMargin;
var rangeFinish = this.ContentLength;
// TRY TO FOUND THE CENTRAL DIRECTORY FOUR TIMES SLOWLY INCREASING THE CHUNK SIZE
short tries = 1;
while (this.directoryData.Offset == -1 && tries <= 4)
{
// MAKE A HTTP CALL USING THE RANGE HEADER
rangeStart -= (chunkSize * tries);
this.httpClient.DefaultRequestHeaders.Range = new RangeHeaderValue(rangeStart, rangeFinish);
var byteArray = await httpClient.GetByteArrayAsync(this.httpUrl);
// TRY TO LOCATE THE END OF CENTRAL DIRECTORY DEFINED BY
// 50 4B 05 06
// https://en.wikipedia.org/wiki/Zip_(file_format)#End_of_central_directory_record_(EOCD)
int pos = (byteArray.Length - secureMargin);
while (pos >= 0)
{
// FOUND CENTRAL DIRECTORY
if (byteArray[pos + 0] == 0x50 &&
byteArray[pos + 1] == 0x4b &&
byteArray[pos + 2] == 0x05 &&
byteArray[pos + 3] == 0x06)
{
this.directoryData.Size = BitConverter.ToInt32(byteArray, pos + 12);
this.directoryData.Offset = BitConverter.ToInt32(byteArray, pos + 16);
this.directoryData.Entries = BitConverter.ToInt16(byteArray, pos + 10);
return true;
}
else { pos--; }
}
tries++;
}
return false;
}
catch (Exception) { throw; }
}
public async Task<List<HttpZipEntry>> GetEntriesAsync()
{
try
{
// INITIALIZE
var entryList = new List<HttpZipEntry>();
if (await this.GetContentLengthAsync() == -1) { return null; }
if (await this.LocateDirectoryAsync() == false) { return null; }
// MAKE A HTTP CALL USING THE RANGE HEADER
var rangeStart = this.directoryData.Offset;
var rangeFinish = this.directoryData.Offset + this.directoryData.Size;
this.httpClient.DefaultRequestHeaders.Range = new RangeHeaderValue(rangeStart, rangeFinish);
var byteArray = await httpClient.GetByteArrayAsync(this.httpUrl);
// LOOP THROUGH ENTRIES
var entriesOffset = 0;
for (int entryIndex = 0; entryIndex < this.directoryData.Entries; entryIndex++)
{
var entry = new HttpZipEntry(entryIndex);
// https://en.wikipedia.org/wiki/Zip_(file_format)#Local_file_header
entry.Signature = BitConverter.ToInt32(byteArray, entriesOffset + 0); // 0x04034b50
entry.VersionMadeBy = BitConverter.ToInt16(byteArray, entriesOffset + 4);
entry.MinimumVersionNeededToExtract = BitConverter.ToInt16(byteArray, entriesOffset + 6);
entry.GeneralPurposeBitFlag = BitConverter.ToInt16(byteArray, entriesOffset + 8);
entry.CompressionMethod = BitConverter.ToInt16(byteArray, entriesOffset + 10);
entry.FileLastModification = BitConverter.ToInt32(byteArray, entriesOffset + 12);
entry.CRC32 = BitConverter.ToInt32(byteArray, entriesOffset + 16);
entry.CompressedSize = BitConverter.ToInt32(byteArray, entriesOffset + 20);
entry.UncompressedSize = BitConverter.ToInt32(byteArray, entriesOffset + 24);
entry.FileNameLength = BitConverter.ToInt16(byteArray, entriesOffset + 28); // (n)
entry.ExtraFieldLength = BitConverter.ToInt16(byteArray, entriesOffset + 30); // (m)
entry.FileCommentLength = BitConverter.ToInt16(byteArray, entriesOffset + 32); // (k)
entry.DiskNumberWhereFileStarts = BitConverter.ToInt16(byteArray, entriesOffset + 34);
entry.InternalFileAttributes = BitConverter.ToInt16(byteArray, entriesOffset + 36);
entry.ExternalFileAttributes = BitConverter.ToInt32(byteArray, entriesOffset + 38);
entry.FileOffset = BitConverter.ToInt32(byteArray, entriesOffset + 42);
var fileNameStart = entriesOffset + 46;
var fileNameBuffer = new byte[entry.FileNameLength];
Array.Copy(byteArray, fileNameStart, fileNameBuffer, 0, entry.FileNameLength);
entry.FileName = System.Text.Encoding.Default.GetString(fileNameBuffer);
var extraFieldStart = fileNameStart + entry.FileNameLength;
var extraFieldBuffer = new byte[entry.ExtraFieldLength];
Array.Copy(byteArray, extraFieldStart, extraFieldBuffer, 0, entry.ExtraFieldLength);
entry.ExtraField = System.Text.Encoding.Default.GetString(extraFieldBuffer);
var fileCommentStart = extraFieldStart + entry.ExtraFieldLength;
var fileCommentBuffer = new byte[entry.FileCommentLength];
Array.Copy(byteArray, fileCommentStart, fileCommentBuffer, 0, entry.FileCommentLength);
entry.FileComment = System.Text.Encoding.Default.GetString(fileCommentBuffer);
entryList.Add(entry);
entriesOffset = fileCommentStart + entry.FileCommentLength;
}
// RESULT
return entryList;
}
catch (Exception) { throw; }
}
[Obsolete]
public async Task ExtractAsync(List<HttpZipEntry> entryList, Action<MemoryStream> resultCallback)
{
try
{
foreach (var entry in entryList)
{ await this.ExtractAsync(entry, resultCallback); }
}
catch (Exception) { throw; }
}
public async Task ExtractAsync(HttpZipEntry entry, Action<MemoryStream> resultCallback)
{
try
{
var fileDataBuffer = await this.ExtractAsync(entry);
var resultStream = new MemoryStream(fileDataBuffer);
resultStream.Position = 0;
resultCallback.Invoke(resultStream);
return;
}
catch (Exception) { throw; }
}
public async Task<byte[]> ExtractAsync(HttpZipEntry entry)
{
try
{
// MAKE A HTTP CALL USING THE RANGE HEADER
var fileHeaderLength = 30 + entry.FileNameLength + entry.ExtraFieldLength;
var rangeStart = entry.FileOffset;
var rangeFinish = entry.FileOffset + fileHeaderLength + entry.CompressedSize;
this.httpClient.DefaultRequestHeaders.Range = new RangeHeaderValue(rangeStart, rangeFinish);
var byteArray = await httpClient.GetByteArrayAsync(this.httpUrl);
// LOCATE DATA BOUNDS
// https://en.wikipedia.org/wiki/Zip_(file_format)#Local_file_header
var fileSignature = BitConverter.ToInt32(byteArray, 0);
var bitFlag = BitConverter.ToInt16(byteArray, 6);
var compressionMethod = BitConverter.ToInt16(byteArray, 8);
var crc = BitConverter.ToInt32(byteArray, 14);
var compressedSize = BitConverter.ToInt32(byteArray, 18);
var uncompressedSize = BitConverter.ToInt32(byteArray, 22);
var fileNameLength = BitConverter.ToInt16(byteArray, 26); // (n)
var extraFieldLength = BitConverter.ToInt16(byteArray, 28); // (m)
var fileDataOffset = 30 + fileNameLength + extraFieldLength;
var fileDataSize = entry.CompressedSize;
// EXTRACT DATA BUFFER
var fileDataBuffer = new byte[fileDataSize];
Array.Copy(byteArray, fileDataOffset, fileDataBuffer, 0, fileDataSize);
Array.Clear(byteArray, 0, byteArray.Length);
byteArray = null;
/* STORED */
if (entry.CompressionMethod == 0)
{ return fileDataBuffer; }
/* DEFLATED */
if (entry.CompressionMethod == 8)
{
var deflatedArray = new byte[entry.UncompressedSize];
using (var compressedStream = new MemoryStream(fileDataBuffer))
{
using (var deflateStream = new System.IO.Compression.DeflateStream(compressedStream, CompressionMode.Decompress))
{
await deflateStream.ReadAsync(deflatedArray, 0, deflatedArray.Length);
}
/*
using (var deflatedStream = new MemoryStream())
{
var deflater = new System.IO.Compression.DeflateStream(compressedStream, CompressionMode.Decompress, true);
byte[] buffer = new byte[1024];
var bytesPending = entry.UncompressedSize;
while (bytesPending > 0)
{
var bytesRead = deflater.Read(buffer, 0, (int)Math.Min(bytesPending, buffer.Length));
deflatedStream.Write(buffer, 0, bytesRead);
bytesPending -= (uint)bytesRead;
if (bytesRead == 0) { break; }
}
deflatedArray = deflatedStream.ToArray();
}
*/
}
return deflatedArray;
}
// NOT SUPPORTED COMPRESSION METHOD
throw new NotSupportedException($"The compression method [{entry.CompressionMethod}] is not supported");
}
catch (Exception) { throw; }
}
public void Dispose()
{
if (!this.LeaveHttpClientOpen) { this.httpClient.Dispose(); this.httpClient = null; }
this.directoryData = null;
this.ContentLength = -1;
}
}
} |
using UnityEngine;
using System.Collections;
public class P0_Basic_Particle : MonoBehaviour {
public float period = 5;
public float speed = 5;
public float distance = 5;
public float swell_amt = 1;
public float rotation_amt = 20;
public bool visible;
protected Messenger messenger;
protected int vertices = 6;
void Start(){
if (transform.parent == null){
transform.parent = GameObject.Find("Collision_Manager").transform;
}
}
void OnTriggerExit(){
collider.enabled = true;
}
// Audio & Particle System triggering.
void OnBecameVisible()
{
audio.Play();
transform.particleSystem.Play();
}
// We clear the ParticleSystem to remove the particles still in the player's view
void OnBecameInvisible()
{
audio.Pause();
transform.particleSystem.Clear();
transform.particleSystem.Stop();
}
}
|
using System;
using System.Threading.Tasks;
namespace Caliburn.Light
{
/// <summary>
/// Provides data for <see cref="Task"/> events.
/// </summary>
public sealed class TaskEventArgs : EventArgs
{
/// <summary>
/// Initializes a new instance of the <see cref="TaskEventArgs"/> class.
/// </summary>
/// <param name="task">The supplied Task.</param>
public TaskEventArgs(Task task)
{
if (task is null)
throw new ArgumentNullException(nameof(task));
Task = task;
}
/// <summary>
/// The supplied task.
/// </summary>
public Task Task { get; }
}
}
|
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class Splitter : MonoBehaviour
{
public float coeff;
public float Coeff
{
get
{
return coeff;
}
set
{
if(Activate)
{
foreach(var c in collided)
{
CircleCollider2D cc = c.gameObject.GetComponent<CircleCollider2D>();
if(cc != null)
{
cc.radius /= coeff*value;
}
BoxCollider2D bc = c.gameObject.GetComponent<BoxCollider2D>();
if(bc != null)
{
bc.size /= coeff*value;
}
}
}
coeff = value;
}
}
public bool activate;
private List<Collider2D> collided = new List<Collider2D>();
public bool Activate
{
get
{
return activate;
}
set
{
if(activate != value)
{
if(activate)
{
foreach(var c in collided)
{
CircleCollider2D cc = c.gameObject.GetComponent<CircleCollider2D>();
if(cc != null)
{
cc.radius /= coeff;
}
BoxCollider2D bc = c.gameObject.GetComponent<BoxCollider2D>();
if(bc != null)
{
bc.size /= coeff;
}
}
}
else
{
foreach(var c in collided)
{
CircleCollider2D cc = c.gameObject.GetComponent<CircleCollider2D>();
if(cc != null)
{
cc.radius *= coeff;
}
BoxCollider2D bc = c.gameObject.GetComponent<BoxCollider2D>();
if(bc != null)
{
bc.size *= coeff;
}
}
}
}
activate = value;
}
}
void OnTriggerEnter2D(Collider2D other)
{
if(other.gameObject.GetComponent<Splitable>() != null)
{
if(Activate)
{
CircleCollider2D cc = other.gameObject.GetComponent<CircleCollider2D>();
if(cc != null)
{
cc.radius *= coeff;
}
BoxCollider2D bc = other.gameObject.GetComponent<BoxCollider2D>();
if(bc != null)
{
bc.size *= coeff;
}
}
if(!collided.Contains(other))
{
collided.Add(other);
}
}
}
void OnTriggerExit2D(Collider2D other)
{
if(collided.Contains(other))
{
if(Activate)
{
CircleCollider2D cc = other.gameObject.GetComponent<CircleCollider2D>();
if(cc != null)
{
cc.radius /= Coeff;
}
BoxCollider2D bc = other.gameObject.GetComponent<BoxCollider2D>();
if(bc != null)
{
bc.size /= Coeff;
}
}
collided.Remove(other);
}
}
}
|
using Newtonsoft.Json;
namespace GaleService.DomainLayer.Managers.Services.Fitbit.ResourceModels
{
public class FitbitHeartRateResource : FitbitResourceBase
{
[JsonProperty("activities-heart-intraday")]
public ActivitiesHeartIntraday ActivitiesHeartIntraday { get; set; }
}
public class ActivitiesHeartIntraday
{
public Dataset[] Dataset { get; set; }
}
public class Dataset
{
public string Time { get; set; }
public string Value { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Sokoban
{
public class MapObject
{
public PictureBox picturebox;
protected Point point;
public virtual void setPosition(int x, int y)
{
}
public int getX()
{
return point.X;
}
public int getY()
{
return point.Y;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework;
namespace CyberPunkRPG.Guns
{
class Pistol : InteractiveObject
{
Rectangle sourceRect;
public Pistol(Vector2 pos) : base(pos)
{
sourceRect = new Rectangle(30, 228, 32, 12);
interactHitBox = new Rectangle((int)pos.X - 6, (int)pos.Y - 6, sourceRect.Width + 12, sourceRect.Height + 12);
weaponID = 3;
}
public override void Update(GameTime gameTime)
{
}
public override void Draw(SpriteBatch sb)
{
sb.Draw(AssetManager.pistolTex, pos, sourceRect, Color.White);
}
}
}
|
using System;
namespace ConstructorInheritance
{
public class Car:Vehicle
{
private readonly string registrationNumber;
/// <summary>
/// to demonstrate hierachy of implementation
/// </summary>
//public Car()
//{
// Console.WriteLine("Car is being initialized");
//}
public Car(string registrationNumber):base(registrationNumber)
{
this.registrationNumber = registrationNumber;
Console.WriteLine($"Car is being initialized {registrationNumber}");
}
}
}
|
using System.Web.Mvc;
namespace Psub.DataAccess.Attributes
{
public class TransactionPerRequest : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
NHibernateHelper.GetCurrentSession().BeginTransaction();
}
public override void OnActionExecuted(ActionExecutedContext filterContext)
{
// use this method instead of OnResultExecuted if the transaction / session
// does not need be open for the view rendering.
}
public override void OnResultExecuted(ResultExecutedContext filterContext)
{
if (filterContext.Exception == null)
NHibernateHelper.GetCurrentSession().Transaction.Commit();
else
NHibernateHelper.GetCurrentSession().Transaction.Rollback();
NHibernateHelper.DisposeSession();
}
}
} |
using System.Collections.Generic;
namespace backendapi
{
public class Item
{
public int Id { get; set; }
public string Title { get; set; }
public List<ItemChild> Children { get; set; }
}
} |
using System;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
namespace Crt.Model.Utils
{
public static class CsvUtils
{
public static string ConvertToCsv<T>(T entity, string[] wholeNumberFields)
{
var csvValue = new StringBuilder();
var fields = typeof(T).GetProperties();
foreach (var field in fields)
{
var val = field.GetValue(entity);
if (val == null)
{
csvValue.Append($",");
continue;
}
if (field.PropertyType == typeof(DateTime))
{
csvValue.Append($"{DateUtils.CovertToString((DateTime)val)},");
}
else if(wholeNumberFields.Contains(field.Name, StringComparer.InvariantCultureIgnoreCase))
{
var valule = Regex.Replace(val.ToString(), @"\.0+$", "");
csvValue.Append($"{valule},");
}
else
{
csvValue.Append($"{val.ToString()},");
}
}
return csvValue.ToString().Trim(',');
}
public static string GetCsvHeader<T>()
{
var csvValue = new StringBuilder();
var fields = typeof(T).GetProperties();
foreach (var field in fields)
{
var val = field.Name.WordToWords();
csvValue.Append($"{val},");
}
return csvValue.ToString().Trim(',');
}
public static string[] GetLowercaseFieldsFromCsvHeaders(string[] headers)
{
var fields = new string[headers.Length];
var i = 0;
foreach(var header in headers)
{
fields[i] = Regex.Replace(header.ToLower(), @"[\s|\/]", string.Empty);
i++;
}
return fields;
}
}
}
|
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="NullOrDefaultToVisibilityConverter.cs" company="Soloplan GmbH">
// Copyright (c) Soloplan GmbH. All rights reserved.
// Licensed under the MIT License. See License-file in the project root for license information.
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
namespace Soloplan.WhatsON.GUI.Common.Converters
{
using System;
using System.Globalization;
using System.Windows.Data;
using System.Windows.Media;
/// <summary>
/// Converts given value from rgba to rgb.
/// </summary>
public class RGBToRGBAConverter : IValueConverter
{
/// <summary>Converts SolidColorBrush from RGBA to RGB, if RGB given it returns RGB. F ex, when given "#FFDDFFDD" returns "#DDFFDD".</summary>
/// <param name="value">SolidColorBrush is the given brush to convert from rgba to rgb.</param>
/// <param name="targetType">This parameter is not used.</param>
/// <param name="parameter">This parameter is not used.</param>
/// <param name="culture">This parameter is not used.</param>
/// <returns>
/// String with rgb />.</returns>
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if (value is SolidColorBrush)
{
string input = ((SolidColorBrush)value).ToString();
if (input.Length == 7)
{
return input;
}
string output=string.Empty;
for (int i = 0; i < input.Length; i++)
{
if (i == 1) { i = 3; }
output += input[i];
}
return output;
}
return null;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
return value;
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Net.NetworkInformation;
using System.Runtime.InteropServices;//for StructLayoutAttribute
namespace winClient2
{
[Serializable]
[StructLayoutAttribute(LayoutKind.Sequential,CharSet=CharSet.Unicode,Pack=1)]
public struct Test {
public int first;
public int second;
//字符串
//[MarshalAs(UnmanagedType.ByValArray,SizeConst=10)]
//public char [] msg;
/**public Test(int one, int two, string str) {
this.first = one;
this.second = two;
this.msg = str.PadRight(10, '\0').ToCharArray();
//this.msg = str.ToCharArray();
}*/
//[MarshalAs(UnmanagedType.ByValTStr,SizeConst=256)]
public string msg ;
public Test(int f, int s, string str) {
this.first = f;
this.second = s;
this.msg = str;
}
}
class Program
{
private static byte[] result = new byte[1024];
static void Main(string[] args)
{
IPAddress ip = IPAddress.Parse("182.254.233.115");
Random rd=new Random();
int mPort = 9201;
Socket clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
try
{
clientSocket.Connect(new IPEndPoint(ip, mPort)); //配置服务器IP与端口
//clientSocket.Connect(new IPEndPoint(ip,9201)); //配置服务器IP与端口
Console.WriteLine("连接服务器成功");
}
catch
{
Console.WriteLine("连接服务器失败,请按回车键退出!");
//return;
}
Test tst=new Test(11,18,"hello\r\n");
/**
tst.first=9;
tst.second=13;
string m = "he";
tst.msg =m.ToCharArray();*/
//tst.msg = "ha";
int counts = 0;
int MAXTIME = 1;
byte[] msg = Transform.StructToBytes(tst);
while (counts < MAXTIME)
{
Thread.Sleep(2000);
try
{
//string sendMessage = " hello guang server ,I come in at " + DateTime.Now + " with times:" + counts;
clientSocket.Send(msg);
Console.WriteLine("send success at " + counts);
}
catch (Exception e)
{
Console.WriteLine("At times " + counts + " send error!" + e.Message);
break;
}
try
{
Console.WriteLine("wait for receive");
byte[] result=new byte[1024];
int receiveLength = clientSocket.Receive(result);
Type type=typeof(Test);
Test rr = (Test)Transform.BytesToStruct(result,type);
Console.WriteLine("接收服务器消息:result.first={0},result.second={1},msg={2}",rr.first,rr.second,rr.msg );
}
catch {
Console.WriteLine("接收失败!");
break;
}
counts++;
}
Console.ReadKey();
}
}
}
|
using System.Reflection;
using System.Runtime.InteropServices;
[assembly: AssemblyTitle("KazakhSupportPlugin")]
[assembly: AssemblyProduct("KazakhSupportPlugin")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyCompany("NPO Computer")]
[assembly: AssemblyCopyright("Copyright © NPO Computer 2018")]
[assembly: AssemblyTrademark("")]
[assembly: ComVisible(false)]
[assembly: AssemblyVersion("2.9.0.0")]
[assembly: AssemblyFileVersion("2.9.0.0")] |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Exercice_6
{
class Program
{
static void Main(string[] args)
{
string saisie;
int h;
int m;
int s;
Console.Write("****conversion d'une duree h,m,s en heure (V1.0, 07 / 07 / 2016) ****");
Console.WriteLine();
Console.WriteLine("Entrez un nombre de secondes");
saisie = Console.ReadLine();
s = Convert.ToInt32(saisie);
h = s / 3600;
s = s % 3600;
m = s / 60;
s = s % 60;
Console.Write("voici la decomposition : " + saisie + "en secondes est "+ h + "H" + m + "M" + s + "S");
Console.ReadLine();
}
}
}
|
namespace TrafficControl.DAL.RestSharp.Types
{
public class Installation
{
public long Id { get; set; }
public string Name { get; set; }
public Position Position { get; set; }
public int Status { get; set; }
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;
namespace ItemEdit.Models.profiles
{
public class Character
{
public string _id { get; set; }
public string aid { get; set; }
public string savage { get; set; }
public Info Info { get; set; }
public Customization Customization { get; set; }
public Health Health { get; set; }
public Inventory Inventory { get; set; }
public Skills Skills { get; set; }
public Stats Stats { get; set; }
public Dictionary<string,bool> Encyclopedia { get; set; }
public Conditioncounters ConditionCounters { get; set; }
public Dictionary<string, BackendCounter> BackendCounters { get; set; }
public Insureditem[] InsuredItems { get; set; }
public Hideout Hideout { get; set; }
public Bonus[] Bonuses { get; set; }
public Notes Notes { get; set; }
public Quest[] Quests { get; set; }
public Dictionary<string, Ragfair> TraderStandings { get; set; }
public Ragfairinfo RagfairInfo { get; set; }
public string[] WishList { get; set; }
}
public class Info
{
public string Nickname { get; set; }
public string LowerNickname { get; set; }
public string Side { get; set; }
public string Voice { get; set; }
public int Level { get; set; }
public int Experience { get; set; }
public int RegistrationDate { get; set; }
public string GameVersion { get; set; }
public int AccountType { get; set; }
public string MemberCategory { get; set; }
public bool lockedMoveCommands { get; set; }
public int SavageLockTime { get; set; }
public int LastTimePlayedAsSavage { get; set; }
public Settings Settings { get; set; }
public bool NeedWipe { get; set; }
public bool GlobalWipe { get; set; }
public int NicknameChangeDate { get; set; }
public object[] Bans { get; set; }
}
public class Settings
{
public string Role { get; set; }
public string BotDifficulty { get; set; }
public int Experience { get; set; }
}
public class Customization
{
public string Head { get; set; }
public string Body { get; set; }
public string Feet { get; set; }
public string Hands { get; set; }
}
public class Health
{
public Hydration Hydration { get; set; }
public Energy Energy { get; set; }
public Bodyparts BodyParts { get; set; }
public int UpdateTime { get; set; }
}
public class Hydration
{
public int Current { get; set; }
public int Maximum { get; set; }
}
public class Energy
{
public int Current { get; set; }
public int Maximum { get; set; }
}
public class Bodyparts
{
public Head Head { get; set; }
public Chest Chest { get; set; }
public Stomach Stomach { get; set; }
public Leftarm LeftArm { get; set; }
public Rightarm RightArm { get; set; }
public Leftleg LeftLeg { get; set; }
public Rightleg RightLeg { get; set; }
}
public class Head
{
public Health1 Health { get; set; }
}
public class Health1
{
public float Current { get; set; }
public int Maximum { get; set; }
}
public class Chest
{
public Health2 Health { get; set; }
}
public class Health2
{
public float Current { get; set; }
public int Maximum { get; set; }
}
public class Stomach
{
public Health3 Health { get; set; }
}
public class Health3
{
public float Current { get; set; }
public int Maximum { get; set; }
}
public class Leftarm
{
public Health4 Health { get; set; }
}
public class Health4
{
public float Current { get; set; }
public int Maximum { get; set; }
}
public class Rightarm
{
public Health5 Health { get; set; }
}
public class Health5
{
public float Current { get; set; }
public int Maximum { get; set; }
}
public class Leftleg
{
public Health6 Health { get; set; }
}
public class Health6
{
public float Current { get; set; }
public int Maximum { get; set; }
}
public class Rightleg
{
public Health7 Health { get; set; }
}
public class Health7
{
public float Current { get; set; }
public int Maximum { get; set; }
}
public class Inventory
{
public Item[] items { get; set; }
public string equipment { get; set; }
public string stash { get; set; }
public string questRaidItems { get; set; }
public string questStashItems { get; set; }
public Fastpanel fastPanel { get; set; }
}
public class Fastpanel
{
}
public class Item
{
public string _id { get; set; }
public string _tpl { get; set; }
public string parentId { get; set; }
public string slotId { get; set; }
public object location { get; set; }
public Upd upd { get; set; }
}
public class Upd
{
public float? StackObjectsCount { get; set; }
public Tag Tag { get; set; }
public Repairable Repairable { get; set; }
public Firemode FireMode { get; set; }
public bool? SpawnedInSession { get; set; }
public Fooddrink FoodDrink { get; set; }
public Medkit MedKit { get; set; }
public Sight Sight { get; set; }
public Resource Resource { get; set; }
public Light Light { get; set; }
public Key Key { get; set; }
public Foldable Foldable { get; set; }
public Togglable Togglable { get; set; }
public Faceshield FaceShield { get; set; }
public Dogtag Dogtag { get; set; }
public Map Map { get; set; }
}
public class Tag
{
public int Color { get; set; }
public string Name { get; set; }
}
public class Repairable
{
public float MaxDurability { get; set; }
public float Durability { get; set; }
}
public class Firemode
{
public string FireMode { get; set; }
}
public class Fooddrink
{
public int HpPercent { get; set; }
}
public class Medkit
{
public int HpResource { get; set; }
}
public class Sight
{
public int SelectedSightMode { get; set; }
}
public class Resource
{
public int Value { get; set; }
}
public class Light
{
public bool IsActive { get; set; }
public int SelectedMode { get; set; }
}
public class Key
{
public int NumberOfUsages { get; set; }
}
public class Foldable
{
public bool Folded { get; set; }
}
public class Togglable
{
public bool On { get; set; }
}
public class Faceshield
{
public int Hits { get; set; }
public int HitSeed { get; set; }
}
public class Dogtag
{
public string Nickname { get; set; }
public string Side { get; set; }
public int Level { get; set; }
public DateTime Time { get; set; }
public string Status { get; set; }
public string KillerName { get; set; }
public string WeaponName { get; set; }
}
public class Map
{
public object[] Markers { get; set; }
}
public class Skills
{
public Common[] Common { get; set; }
public Mastering[] Mastering { get; set; }
public object Bonuses { get; set; }
public int Points { get; set; }
}
public class Common
{
public string Id { get; set; }
public double Progress { get; set; }
public double PointsEarnedDuringSession { get; set; }
public int LastAccess { get; set; }
}
public class Mastering
{
public string Id { get; set; }
public int Progress { get; set; }
}
public class Stats
{
public Sessioncounters SessionCounters { get; set; }
public Overallcounters OverallCounters { get; set; }
public float SessionExperienceMult { get; set; }
public double ExperienceBonusMult { get; set; }
public int TotalSessionExperience { get; set; }
public int LastSessionDate { get; set; }
public Aggressor Aggressor { get; set; }
public Droppeditem[] DroppedItems { get; set; }
public object[] FoundInRaidItems { get; set; }
public Victim[] Victims { get; set; }
public string[] CarriedQuestItems { get; set; }
public int TotalInGameTime { get; set; }
public string SurvivorClass { get; set; }
}
public class Sessioncounters
{
public Item1[] Items { get; set; }
}
public class Item1
{
public string[] Key { get; set; }
public int Value { get; set; }
}
public class Overallcounters
{
public Item2[] Items { get; set; }
}
public class Item2
{
public string[] Key { get; set; }
public int Value { get; set; }
}
public class Aggressor
{
public string Name { get; set; }
public string Side { get; set; }
public string BodyPart { get; set; }
public string HeadSegment { get; set; }
public string WeaponName { get; set; }
public string Category { get; set; }
}
public class Droppeditem
{
public string QuestId { get; set; }
public string ItemId { get; set; }
public string ZoneId { get; set; }
}
public class Victim
{
public string Name { get; set; }
public string Side { get; set; }
public string Time { get; set; }
public int Level { get; set; }
public string BodyPart { get; set; }
public string Weapon { get; set; }
}
public class Conditioncounters
{
public Counter[] Counters { get; set; }
}
public class Counter
{
public string id { get; set; }
public int value { get; set; }
}
public class BackendCounter
{
public string id { get; set; }
public string qid { get; set; }
public int value { get; set; }
}
public class Hideout
{
public Dictionary<string, Production> Production { get; set; }
public Area[] Areas { get; set; }
}
public class Production
{
public int Progress { get; set; }
public bool inProgress { get; set; }
public string RecipeId { get; set; }
public object[] Products { get; set; }
public int SkipTime { get; set; }
public int StartTime { get; set; }
}
public class Area
{
public int type { get; set; }
public int level { get; set; }
public bool active { get; set; }
public bool passiveBonusesEnabled { get; set; }
public int completeTime { get; set; }
public bool constructing { get; set; }
public Slot[] slots { get; set; }
}
public class Slot
{
public Item3[] item { get; set; }
}
public class Item3
{
public string _id { get; set; }
public string _tpl { get; set; }
public Upd1 upd { get; set; }
}
public class Upd1
{
public int StackObjectsCount { get; set; }
public Resource1 Resource { get; set; }
}
public class Resource1
{
public float Value { get; set; }
}
public class Notes
{
[JsonProperty("Notes")]
public object[] Sub_Notes { get; set; }
}
public class Ragfair
{
public int currentLevel { get; set; }
public int currentSalesSum { get; set; }
public float currentStanding { get; set; }
public object NextLoyalty { get; set; }
public Dictionary<string, loyaltyLevel> loyaltyLevels { get; set; }
}
public class loyaltyLevel
{
public int minLevel { get; set; }
public int minSalesSum { get; set; }
public float minStanding { get; set; }
}
public class Ragfairinfo
{
public float rating { get; set; }
public bool isRatingGrowing { get; set; }
public object[] offers { get; set; }
}
public class Insureditem
{
public string tid { get; set; }
public string itemId { get; set; }
}
public class Bonus
{
public string type { get; set; }
public string templateId { get; set; }
}
public class Quest
{
public string qid { get; set; }
public int startTime { get; set; }
public string[] completedConditions { get; set; }
public Dictionary<string, double> statusTimers { get; set; }
public string status { get; set; }
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Bot.Builder;
using Microsoft.Bot.Builder.Integration.AspNet.Core;
using Microsoft.Bot.Configuration;
using Microsoft.Bot.Connector.Authentication;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using JIoffe.BIAD.Bots;
using Microsoft.Bot.Builder.AI.QnA;
namespace JIoffe.BIAD.QnABot
{
public class Startup
{
private ILoggerFactory _loggerFactory;
public IConfiguration Configuration { get; }
private IHostingEnvironment Environment { get; }
public Startup(IHostingEnvironment env)
{
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
.AddEnvironmentVariables();
Configuration = builder.Build();
Environment = env;
}
// This method gets called by the runtime. Use this method to add services to the container.
// For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
public void ConfigureServices(IServiceCollection services)
{
//Instantiate the bot configuration for use in the bot
//Traffic coming through to your app is protected by the app ID and app secret
//credentials applied to your Bot Registration on Azure.
//If you are running locally, these can be blank.
var secretKey = Configuration.GetSection("botFileSecret")?.Value;
var botFilePath = Configuration.GetSection("botFilePath")?.Value;
var botConfig = BotConfiguration.Load(botFilePath ?? @".\BotConfiguration.bot", secretKey);
if (botConfig == null)
throw new InvalidOperationException($"The .bot config file could not be loaded from [{botFilePath}]");
//Add the bot configuration as something we can retrieve through DI
services.AddSingleton(botConfig);
//Step X) Retrieve the service from botConfig that is of type QnA;
// - (Optional) Throw an exception if the service is null or if any required fields are empty
var qnaService = botConfig.Services.FirstOrDefault(s => s.Type == ServiceTypes.QnA) as QnAMakerService;
if (qnaService == null)
throw new InvalidOperationException($"The QnA Service is not configured correctly in {botFilePath}");
//Step X) Create a new instance of QnAMaker and add it to the services container as a singleton
var qnaMaker = new QnAMaker(qnaService);
services.AddSingleton(qnaMaker);
//The extension to add a bot to our services container
//can be found in Microsoft.Bot.Builder.Integration.AspNet.Core
//Whichever type is passed will be the bot that is created
services.AddBot<QnAMakerBot>(options =>
{
//The bot configuration can map different endpoints for different environments
var serviceName = Environment.EnvironmentName.ToLowerInvariant();
var service = botConfig.FindServiceByNameOrId(serviceName) as EndpointService;
if(service == null)
throw new InvalidOperationException($"The .bot file does not contain an endpoint with name '{serviceName}'.");
options.CredentialProvider = new SimpleCredentialProvider(service.AppId, service.AppPassword);
//Memory storage is only used for this example.
//In a production application, you should always rely on
//a more persistant storage mechanism, such as CosmosDB
IStorage dataStore = new MemoryStorage();
//Whichever datastore we're working with, we will need to use it
//to actually store the conversation state.
var conversationState = new ConversationState(dataStore);
options.State.Add(conversationState);
//Step x) Add a callback for "OnTurnError" that logs any bot or middleware errors to the console
// - (Optional) Send a message to the user indicating there was a problem
ILogger logger = _loggerFactory.CreateLogger<QnAMakerBot>();
options.OnTurnError = async (context, e) =>
{
//Ideally you do not want to get here - you want to handle business logic errors more gracefully.
//But if we're here, we can do any housekeeping such as logging and letting the know something went wrong.
logger.LogError(e, "Unhandled exception on bot turn - incoming input was {0}", context.Activity.Text);
//Since we have the context, we can send (helpful) messagse to the user
await context.SendActivityAsync($"Something went wrong. Please forgive me. Exception: {e.Message}");
};
});
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
_loggerFactory = loggerFactory;
app.UseDefaultFiles()
.UseStaticFiles()
.UseBotFramework(); //Automatically maps endpoint handlers related to bots
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Accounting.Entity
{
public class LCAcceptance
{
public LCAcceptance() { }
#region Fields
private int numSlNo;
private int numLCID;
private DateTime dtacceptDate;
private double dblacceptQty;
private double dblacceptValue;
private DateTime dtActualShipmentDate;
private DateTime dtMaturityDate;
private DateTime dtPaidDate;
private string strremarks;
#endregion
#region Properties
public int SlNo
{
get { return numSlNo; }
set { numSlNo = value; }
}
public int LCID
{
get { return numLCID; }
set { numLCID = value; }
}
public DateTime acceptDate
{
get { return dtacceptDate; }
set { dtacceptDate = value; }
}
public double acceptQty
{
get { return dblacceptQty; }
set { dblacceptQty = value; }
}
public double acceptValue
{
get { return dblacceptValue; }
set { dblacceptValue = value; }
}
public DateTime ActualShipmentDate
{
get { return dtActualShipmentDate; }
set { dtActualShipmentDate = value; }
}
public DateTime MaturityDate
{
get { return dtMaturityDate; }
set { dtMaturityDate = value; }
}
public DateTime PaidDate
{
get { return dtPaidDate; }
set { dtPaidDate = value; }
}
public string remarks
{
get { return strremarks; }
set { strremarks = value; }
}
#endregion
}
}
|
//-------------------------------------------------------------------
//版权所有:版权所有(C) 2010,Wakaoyun
//系统名称:
//作 者:dengqibin
//邮箱地址:wakaoyun@gmail.com
//创建日期:9/8/2010 11:24:41 AM
//功能说明:Sql数据库执行帮助类
//-------------------------------------------------------------------
//修改 人:
//修改时间:
//修改内容:
//-------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Wakaoyun.DQB.DataAccess.Interface;
using System.Data.SqlClient;
using System.Data;
using Wakaoyun.DQB.DataAccess.Enum;
using System.Xml;
using Wakaoyun.DQB.Framework;
using Wakaoyun.DQB.DataAccess.Entity;
namespace Wakaoyun.DQB.DataAccess.DbHelper
{
/// <summary>
/// Sql数据库执行帮助类
/// </summary>
public sealed class SqlHelper : DbHelperBase, IDbHelper
{
private string _ConnectionString;
private IExceptionHandler _ExceptionHandler;
//private static IDbCacheDependencyHelper Current;
private bool LogDBException;
private const string ParameterChar = "@";
private bool TrackSql;
private SqlHelper()
{
this._ConnectionString = string.Empty;
this._ExceptionHandler = null;
}
private SqlHelper(string connectionString)
{
this._ExceptionHandler = null;
this.ConnectionString = connectionString;
}
private static void AssignParameterValues(SqlParameter[] commandParameters, DataRow dataRow)
{
if ((commandParameters != null) && (dataRow != null))
{
int i = 0;
foreach (SqlParameter commandParameter in commandParameters)
{
if ((commandParameter.ParameterName == null) || (commandParameter.ParameterName.Length <= 1))
{
throw new Exception(string.Format("Please provide a valid parameter name on the parameter #{0}, the ParameterName property has the following value: '{1}'.", i, commandParameter.ParameterName));
}
if (dataRow.Table.Columns.IndexOf(commandParameter.ParameterName.Substring(1)) != -1)
{
commandParameter.Value = dataRow[commandParameter.ParameterName.Substring(1)];
}
i++;
}
}
}
private static void AssignParameterValues(SqlParameter[] commandParameters, object[] parameterValues)
{
if ((commandParameters != null) && (parameterValues != null))
{
if (commandParameters.Length != parameterValues.Length)
{
throw new ArgumentException("Parameter count does not match Parameter Value count.");
}
int i = 0;
int j = commandParameters.Length;
while (i < j)
{
if (parameterValues[i] is IDbDataParameter)
{
IDbDataParameter paramInstance = (IDbDataParameter) parameterValues[i];
if (paramInstance.Value == null)
{
commandParameters[i].Value = DBNull.Value;
}
else
{
commandParameters[i].Value = paramInstance.Value;
}
}
else if (parameterValues[i] == null)
{
commandParameters[i].Value = DBNull.Value;
}
else
{
commandParameters[i].Value = parameterValues[i];
}
i++;
}
}
}
private static void AttachParameters(SqlCommand command, SqlParameter[] commandParameters)
{
if (command == null)
{
throw new ArgumentNullException("command");
}
if (commandParameters != null)
{
foreach (SqlParameter p in commandParameters)
{
if (p != null)
{
if (((p.Direction == ParameterDirection.InputOutput) || (p.Direction == ParameterDirection.Input)) && (p.Value == null))
{
p.Value = DBNull.Value;
}
command.Parameters.Add(p);
}
}
}
}
public SqlCommand CreateCommand(SqlConnection connection, string spName, params string[] sourceColumns)
{
if (connection == null)
{
throw new ArgumentNullException("connection");
}
if ((spName == null) || (spName.Length == 0))
{
throw new ArgumentNullException("spName");
}
SqlCommand cmd = new SqlCommand(spName, connection);
cmd.CommandType = CommandType.StoredProcedure;
if ((sourceColumns != null) && (sourceColumns.Length > 0))
{
SqlParameter[] commandParameters = SqlParameterCacheHelper.GetSpParameterSet(connection.ConnectionString, spName);
for (int index = 0; index < sourceColumns.Length; index++)
{
commandParameters[index].SourceColumn = sourceColumns[index];
}
AttachParameters(cmd, commandParameters);
}
return cmd;
}
//public static IDbCacheDependencyHelper CreateInstance(string connectionString)
//{
// Current = DbHelperCache.Get(connectionString);
// if (Current == null)
// {
// Current = new MySqlHelper1(connectionString);
// DbHelperCache.Add(connectionString, Current);
// }
// return Current;
//}
public DataSet ExecuteDataset(IDbConnection connection, CommandType commandType, string commandText)
{
return this.ExecuteDataset(connection, commandType, commandText, null);
}
public DataSet ExecuteDataset(IDbConnection connection, string spName, params object[] parameterValues)
{
if (connection == null)
{
throw new ArgumentNullException("connection");
}
if ((spName == null) || (spName.Length == 0))
{
throw new ArgumentNullException("spName");
}
if ((parameterValues != null) && (parameterValues.Length > 0))
{
SqlParameter[] commandParameters = SqlParameterCacheHelper.GetSpParameterSet(connection.ConnectionString, spName);
AssignParameterValues(commandParameters, parameterValues);
return this.ExecuteDataset(connection, CommandType.StoredProcedure, spName, commandParameters);
}
return this.ExecuteDataset(connection, CommandType.StoredProcedure, spName);
}
public DataSet ExecuteDataset(IDbTransaction transaction, CommandType commandType, string commandText)
{
return this.ExecuteDataset(transaction, commandType, commandText, null);
}
public DataSet ExecuteDataset(IDbTransaction transaction, string spName, params object[] parameterValues)
{
if (transaction == null)
{
throw new ArgumentNullException("transaction");
}
if ((transaction != null) && (transaction.Connection == null))
{
throw new ArgumentException("The transaction was rollbacked or commited, please provide an open transaction.", "transaction");
}
if ((spName == null) || (spName.Length == 0))
{
throw new ArgumentNullException("spName");
}
if ((parameterValues != null) && (parameterValues.Length > 0))
{
SqlParameter[] commandParameters = SqlParameterCacheHelper.GetSpParameterSet(transaction.Connection.ConnectionString, spName);
AssignParameterValues(commandParameters, parameterValues);
return this.ExecuteDataset(transaction, CommandType.StoredProcedure, spName, commandParameters);
}
return this.ExecuteDataset(transaction, CommandType.StoredProcedure, spName);
}
public DataSet ExecuteDataset(string connectionString, CommandType commandType, string commandText)
{
return this.ExecuteDataset(connectionString, commandType, commandText, null);
}
public DataSet ExecuteDataset(string connectionString, string spName, params object[] parameterValues)
{
if ((connectionString == null) || (connectionString.Length == 0))
{
throw new ArgumentNullException("connectionString");
}
if ((spName == null) || (spName.Length == 0))
{
throw new ArgumentNullException("spName");
}
if ((parameterValues != null) && (parameterValues.Length > 0))
{
SqlParameter[] commandParameters = SqlParameterCacheHelper.GetSpParameterSet(connectionString, spName);
AssignParameterValues(commandParameters, parameterValues);
return this.ExecuteDataset(connectionString, CommandType.StoredProcedure, spName, commandParameters);
}
return this.ExecuteDataset(connectionString, CommandType.StoredProcedure, spName);
}
public DataSet ExecuteDataset(IDbConnection connection, CommandType commandType, string commandText, params IDbDataParameter[] commandParameters)
{
if (connection == null)
{
throw new ArgumentNullException("connection");
}
SqlCommand cmd = new SqlCommand();
bool mustCloseConnection = false;
PrepareCommand(cmd, (SqlConnection) connection, null, commandType, commandText, (SqlParameter[]) commandParameters, out mustCloseConnection);
using (SqlDataAdapter da = new SqlDataAdapter(cmd))
{
DataSet ds = new DataSet();
da.Fill(ds);
cmd.Parameters.Clear();
if (mustCloseConnection)
{
connection.Close();
}
return ds;
}
}
public DataSet ExecuteDataset(IDbTransaction transaction, CommandType commandType, string commandText, params IDbDataParameter[] commandParameters)
{
if (transaction == null)
{
throw new ArgumentNullException("transaction");
}
if ((transaction != null) && (transaction.Connection == null))
{
throw new ArgumentException("The transaction was rollbacked or commited, please provide an open transaction.", "transaction");
}
SqlCommand cmd = new SqlCommand();
bool mustCloseConnection = false;
PrepareCommand(cmd, (SqlConnection) transaction.Connection, (SqlTransaction) transaction, commandType, commandText, (SqlParameter[]) commandParameters, out mustCloseConnection);
using (SqlDataAdapter da = new SqlDataAdapter(cmd))
{
DataSet ds = new DataSet();
da.Fill(ds);
cmd.Parameters.Clear();
return ds;
}
}
public DataSet ExecuteDataset(string connectionString, CommandType commandType, string commandText, params IDbDataParameter[] commandParameters)
{
if ((connectionString == null) || (connectionString.Length == 0))
{
throw new ArgumentNullException("connectionString");
}
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
return this.ExecuteDataset(connection, commandType, commandText, commandParameters);
}
}
public DataSet ExecuteDatasetTypedParams(SqlConnection connection, string spName, DataRow dataRow)
{
if (connection == null)
{
throw new ArgumentNullException("connection");
}
if ((spName == null) || (spName.Length == 0))
{
throw new ArgumentNullException("spName");
}
if ((dataRow != null) && (dataRow.ItemArray.Length > 0))
{
SqlParameter[] commandParameters = SqlParameterCacheHelper.GetSpParameterSet(connection.ConnectionString, spName);
AssignParameterValues(commandParameters, dataRow);
return ExecuteDataset(connection, CommandType.StoredProcedure, spName, commandParameters);
}
return ExecuteDataset(connection, CommandType.StoredProcedure, spName);
}
public DataSet ExecuteDatasetTypedParams(SqlTransaction transaction, string spName, DataRow dataRow)
{
if (transaction == null)
{
throw new ArgumentNullException("transaction");
}
if ((transaction != null) && (transaction.Connection == null))
{
throw new ArgumentException("The transaction was rollbacked or commited, please provide an open transaction.", "transaction");
}
if ((spName == null) || (spName.Length == 0))
{
throw new ArgumentNullException("spName");
}
if ((dataRow != null) && (dataRow.ItemArray.Length > 0))
{
SqlParameter[] commandParameters = SqlParameterCacheHelper.GetSpParameterSet(transaction.Connection.ConnectionString, spName);
AssignParameterValues(commandParameters, dataRow);
return ExecuteDataset(transaction, CommandType.StoredProcedure, spName, commandParameters);
}
return ExecuteDataset(transaction, CommandType.StoredProcedure, spName);
}
public DataSet ExecuteDatasetTypedParams(string connectionString, string spName, DataRow dataRow)
{
if ((connectionString == null) || (connectionString.Length == 0))
{
throw new ArgumentNullException("connectionString");
}
if ((spName == null) || (spName.Length == 0))
{
throw new ArgumentNullException("spName");
}
if ((dataRow != null) && (dataRow.ItemArray.Length > 0))
{
SqlParameter[] commandParameters = SqlParameterCacheHelper.GetSpParameterSet(connectionString, spName);
AssignParameterValues(commandParameters, dataRow);
return ExecuteDataset(connectionString, CommandType.StoredProcedure, spName, commandParameters);
}
return ExecuteDataset(connectionString, CommandType.StoredProcedure, spName);
}
public int ExecuteNonQuery(CommandType commandType, string commandText)
{
return this.ExecuteNonQuery(this.ConnectionString, commandType, commandText, null);
}
public int ExecuteNonQuery(string spName, params object[] parameterValues)
{
string connectionString = this.ConnectionString;
if ((connectionString == null) || (connectionString.Length == 0))
{
throw new ArgumentNullException("connectionString");
}
if ((spName == null) || (spName.Length == 0))
{
throw new ArgumentNullException("spName");
}
if ((parameterValues != null) && (parameterValues.Length > 0))
{
SqlParameter[] commandParameters = SqlParameterCacheHelper.GetSpParameterSet(connectionString, spName);
AssignParameterValues(commandParameters, parameterValues);
return this.ExecuteNonQuery(connectionString, CommandType.StoredProcedure, spName, commandParameters);
}
return this.ExecuteNonQuery(connectionString, CommandType.StoredProcedure, spName);
}
public int ExecuteNonQuery(CommandType commandType, string commandText, params IDbDataParameter[] commandParameters)
{
if ((this.ConnectionString == null) || (this.ConnectionString.Length == 0))
{
throw new ArgumentNullException("ConnectionString");
}
using (SqlConnection connection = new SqlConnection(this.ConnectionString))
{
connection.Open();
return this.ExecuteNonQuery(connection, commandType, commandText, commandParameters);
}
}
public int ExecuteNonQuery(IDbConnection connection, CommandType commandType, string commandText)
{
return this.ExecuteNonQuery(connection, commandType, commandText, null);
}
public int ExecuteNonQuery(IDbConnection connection, string spName, params object[] parameterValues)
{
if (connection == null)
{
throw new ArgumentNullException("connection");
}
if ((spName == null) || (spName.Length == 0))
{
throw new ArgumentNullException("spName");
}
if ((parameterValues != null) && (parameterValues.Length > 0))
{
SqlParameter[] commandParameters = SqlParameterCacheHelper.GetSpParameterSet(connection.ConnectionString, spName);
AssignParameterValues(commandParameters, parameterValues);
return this.ExecuteNonQuery(connection, CommandType.StoredProcedure, spName, commandParameters);
}
return this.ExecuteNonQuery(connection, CommandType.StoredProcedure, spName);
}
public int ExecuteNonQuery(IDbTransaction transaction, CommandType commandType, string commandText)
{
return this.ExecuteNonQuery(transaction, commandType, commandText, null);
}
public int ExecuteNonQuery(IDbTransaction transaction, string spName, params object[] parameterValues)
{
if (transaction == null)
{
throw new ArgumentNullException("transaction");
}
if ((transaction != null) && (transaction.Connection == null))
{
throw new ArgumentException("The transaction was rollbacked or commited, please provide an open transaction.", "transaction");
}
if ((spName == null) || (spName.Length == 0))
{
throw new ArgumentNullException("spName");
}
if ((parameterValues != null) && (parameterValues.Length > 0))
{
SqlParameter[] commandParameters = SqlParameterCacheHelper.GetSpParameterSet(transaction.Connection.ConnectionString, spName);
AssignParameterValues(commandParameters, parameterValues);
return this.ExecuteNonQuery(transaction, CommandType.StoredProcedure, spName, commandParameters);
}
return this.ExecuteNonQuery(transaction, CommandType.StoredProcedure, spName);
}
public int ExecuteNonQuery(string connectionString, CommandType commandType, string commandText)
{
return this.ExecuteNonQuery(connectionString, commandType, commandText, null);
}
public int ExecuteNonQuery(string connectionString, string spName, params object[] parameterValues)
{
if ((connectionString == null) || (connectionString.Length == 0))
{
throw new ArgumentNullException("connectionString");
}
if ((spName == null) || (spName.Length == 0))
{
throw new ArgumentNullException("spName");
}
if ((parameterValues != null) && (parameterValues.Length > 0))
{
SqlParameter[] commandParameters = SqlParameterCacheHelper.GetSpParameterSet(connectionString, spName);
AssignParameterValues(commandParameters, parameterValues);
return this.ExecuteNonQuery(connectionString, CommandType.StoredProcedure, spName, commandParameters);
}
return this.ExecuteNonQuery(connectionString, CommandType.StoredProcedure, spName);
}
public int ExecuteNonQuery(IDbConnection connection, CommandType commandType, string commandText, params IDbDataParameter[] commandParameters)
{
if (connection == null)
{
throw new ArgumentNullException("connection");
}
SqlCommand cmd = new SqlCommand();
bool mustCloseConnection = false;
PrepareCommand(cmd, (SqlConnection) connection, null, commandType, commandText, (SqlParameter[]) commandParameters, out mustCloseConnection);
int retval = cmd.ExecuteNonQuery();
cmd.Parameters.Clear();
if (mustCloseConnection)
{
connection.Close();
}
return retval;
}
public int ExecuteNonQuery(IDbTransaction transaction, CommandType commandType, string commandText, params IDbDataParameter[] commandParameters)
{
if (transaction == null)
{
throw new ArgumentNullException("transaction");
}
if ((transaction != null) && (transaction.Connection == null))
{
throw new ArgumentException("The transaction was rollbacked or commited, please provide an open transaction.", "transaction");
}
SqlCommand cmd = new SqlCommand();
bool mustCloseConnection = false;
PrepareCommand(cmd, (SqlConnection) transaction.Connection, (SqlTransaction) transaction, commandType, commandText, (SqlParameter[]) commandParameters, out mustCloseConnection);
int retval = cmd.ExecuteNonQuery();
cmd.Parameters.Clear();
return retval;
}
public int ExecuteNonQuery(string connectionString, CommandType commandType, string commandText, params IDbDataParameter[] commandParameters)
{
if ((connectionString == null) || (connectionString.Length == 0))
{
throw new ArgumentNullException("connectionString");
}
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
return this.ExecuteNonQuery(connection, commandType, commandText, commandParameters);
}
}
public int ExecuteNonQueryTypedParams(SqlConnection connection, string spName, DataRow dataRow)
{
if (connection == null)
{
throw new ArgumentNullException("connection");
}
if ((spName == null) || (spName.Length == 0))
{
throw new ArgumentNullException("spName");
}
if ((dataRow != null) && (dataRow.ItemArray.Length > 0))
{
SqlParameter[] commandParameters = SqlParameterCacheHelper.GetSpParameterSet(connection.ConnectionString, spName);
AssignParameterValues(commandParameters, dataRow);
return ExecuteNonQuery(connection, CommandType.StoredProcedure, spName, commandParameters);
}
return ExecuteNonQuery(connection, CommandType.StoredProcedure, spName);
}
public int ExecuteNonQueryTypedParams(SqlTransaction transaction, string spName, DataRow dataRow)
{
if (transaction == null)
{
throw new ArgumentNullException("transaction");
}
if ((transaction != null) && (transaction.Connection == null))
{
throw new ArgumentException("The transaction was rollbacked or commited, please provide an open transaction.", "transaction");
}
if ((spName == null) || (spName.Length == 0))
{
throw new ArgumentNullException("spName");
}
if ((dataRow != null) && (dataRow.ItemArray.Length > 0))
{
SqlParameter[] commandParameters = SqlParameterCacheHelper.GetSpParameterSet(transaction.Connection.ConnectionString, spName);
AssignParameterValues(commandParameters, dataRow);
return ExecuteNonQuery(transaction, CommandType.StoredProcedure, spName, commandParameters);
}
return ExecuteNonQuery(transaction, CommandType.StoredProcedure, spName);
}
public int ExecuteNonQueryTypedParams(string connectionString, string spName, DataRow dataRow)
{
if ((connectionString == null) || (connectionString.Length == 0))
{
throw new ArgumentNullException("connectionString");
}
if ((spName == null) || (spName.Length == 0))
{
throw new ArgumentNullException("spName");
}
if ((dataRow != null) && (dataRow.ItemArray.Length > 0))
{
SqlParameter[] commandParameters = SqlParameterCacheHelper.GetSpParameterSet(connectionString, spName);
AssignParameterValues(commandParameters, dataRow);
return ExecuteNonQuery(connectionString, CommandType.StoredProcedure, spName, commandParameters);
}
return ExecuteNonQuery(connectionString, CommandType.StoredProcedure, spName);
}
public IDataReader ExecuteReader(string spName, params object[] parameterValues)
{
if ((this.ConnectionString == null) || (this.ConnectionString.Length == 0))
{
throw new ArgumentNullException("ConnectionString");
}
if ((spName == null) || (spName.Length == 0))
{
throw new ArgumentNullException("spName");
}
if ((parameterValues != null) && (parameterValues.Length > 0))
{
SqlParameter[] commandParameters = SqlParameterCacheHelper.GetSpParameterSet(this.ConnectionString, spName);
AssignParameterValues(commandParameters, parameterValues);
return this.ExecuteReader(this.ConnectionString, CommandType.StoredProcedure, spName, commandParameters);
}
return this.ExecuteReader(this.ConnectionString, CommandType.StoredProcedure, spName);
}
public IDataReader ExecuteReader(CommandType commandType, string commandText, params IDbDataParameter[] commandParameters)
{
IDataReader dr;
if ((this.ConnectionString == null) || (this.ConnectionString.Length == 0))
{
throw new ArgumentNullException("ConnectionString");
}
SqlConnection connection = null;
try
{
connection = new SqlConnection(this.ConnectionString);
connection.Open();
dr = this.ExecuteReader(connection, null, commandType, commandText, commandParameters, DbConnectionOwnership.Internal);
}
catch (Exception)
{
if (connection != null)
{
connection.Close();
}
throw;
}
return dr;
}
public IDataReader ExecuteReader(IDbConnection connection, CommandType commandType, string commandText)
{
return this.ExecuteReader(connection, commandType, commandText, null);
}
public IDataReader ExecuteReader(IDbConnection connection, string spName, params object[] parameterValues)
{
if (connection == null)
{
throw new ArgumentNullException("connection");
}
if ((spName == null) || (spName.Length == 0))
{
throw new ArgumentNullException("spName");
}
if ((parameterValues != null) && (parameterValues.Length > 0))
{
SqlParameter[] commandParameters = SqlParameterCacheHelper.GetSpParameterSet(connection.ConnectionString, spName);
AssignParameterValues(commandParameters, parameterValues);
return this.ExecuteReader(connection, CommandType.StoredProcedure, spName, commandParameters);
}
return this.ExecuteReader(connection, CommandType.StoredProcedure, spName);
}
public IDataReader ExecuteReader(IDbTransaction transaction, CommandType commandType, string commandText)
{
return this.ExecuteReader(transaction, commandType, commandText, null);
}
public IDataReader ExecuteReader(IDbTransaction transaction, string spName, params object[] parameterValues)
{
if (transaction == null)
{
throw new ArgumentNullException("transaction");
}
if ((transaction != null) && (transaction.Connection == null))
{
throw new ArgumentException("The transaction was rollbacked or commited, please provide an open transaction.", "transaction");
}
if ((spName == null) || (spName.Length == 0))
{
throw new ArgumentNullException("spName");
}
if ((parameterValues != null) && (parameterValues.Length > 0))
{
SqlParameter[] commandParameters = SqlParameterCacheHelper.GetSpParameterSet(transaction.Connection.ConnectionString, spName);
AssignParameterValues(commandParameters, parameterValues);
return this.ExecuteReader(transaction, CommandType.StoredProcedure, spName, commandParameters);
}
return this.ExecuteReader(transaction, CommandType.StoredProcedure, spName);
}
public IDataReader ExecuteReader(string connectionString, CommandType commandType, string commandText)
{
return this.ExecuteReader(connectionString, commandType, commandText, null);
}
public IDataReader ExecuteReader(string connectionString, string spName, params object[] parameterValues)
{
if ((connectionString == null) || (connectionString.Length == 0))
{
throw new ArgumentNullException("connectionString");
}
if ((spName == null) || (spName.Length == 0))
{
throw new ArgumentNullException("spName");
}
if ((parameterValues != null) && (parameterValues.Length > 0))
{
SqlParameter[] commandParameters = SqlParameterCacheHelper.GetSpParameterSet(connectionString, spName);
AssignParameterValues(commandParameters, parameterValues);
return this.ExecuteReader(connectionString, CommandType.StoredProcedure, spName, commandParameters);
}
return this.ExecuteReader(connectionString, CommandType.StoredProcedure, spName);
}
public IDataReader ExecuteReader(IDbConnection connection, CommandType commandType, string commandText, params IDbDataParameter[] commandParameters)
{
return this.ExecuteReader(connection, null, commandType, commandText, commandParameters, DbConnectionOwnership.External);
}
public IDataReader ExecuteReader(IDbTransaction transaction, CommandType commandType, string commandText, params IDbDataParameter[] commandParameters)
{
if (transaction == null)
{
throw new ArgumentNullException("transaction");
}
if ((transaction != null) && (transaction.Connection == null))
{
throw new ArgumentException("The transaction was rollbacked or commited, please provide an open transaction.", "transaction");
}
return this.ExecuteReader(transaction.Connection, transaction, commandType, commandText, commandParameters, DbConnectionOwnership.External);
}
public IDataReader ExecuteReader(string connectionString, CommandType commandType, string commandText, params IDbDataParameter[] commandParameters)
{
IDataReader dr;
if ((connectionString == null) || (connectionString.Length == 0))
{
throw new ArgumentNullException("connectionString");
}
SqlConnection connection = null;
try
{
connection = new SqlConnection(connectionString);
connection.Open();
dr = this.ExecuteReader(connection, null, commandType, commandText, commandParameters, DbConnectionOwnership.Internal);
}
catch (Exception)
{
if (connection != null)
{
connection.Close();
}
throw;
}
return dr;
}
public IDataReader ExecuteReader(IDbConnection connection, IDbTransaction transaction, CommandType commandType, string commandText, IDbDataParameter[] commandParameters, DbConnectionOwnership connectionOwnership)
{
IDataReader dr;
if (connection == null)
{
throw new ArgumentNullException("connection");
}
bool mustCloseConnection = false;
SqlCommand cmd = new SqlCommand();
try
{
SqlDataReader dataReader;
PrepareCommand(cmd, (SqlConnection) connection, (SqlTransaction) transaction, commandType, commandText, (SqlParameter[]) commandParameters, out mustCloseConnection);
if (connectionOwnership == DbConnectionOwnership.External)
{
dataReader = cmd.ExecuteReader();
}
else
{
dataReader = cmd.ExecuteReader(CommandBehavior.CloseConnection);
}
bool canClear = true;
foreach (SqlParameter commandParameter in cmd.Parameters)
{
if (commandParameter.Direction != ParameterDirection.Input)
{
canClear = false;
}
}
if (canClear)
{
cmd.Parameters.Clear();
}
dr = dataReader;
}
catch (Exception)
{
if (mustCloseConnection)
{
connection.Close();
}
throw;
}
finally
{
if (mustCloseConnection && (connection.State != ConnectionState.Closed))
{
connection.Close();
}
connection.Dispose();
}
return dr;
}
public SqlDataReader ExecuteReaderTypedParams(SqlConnection connection, string spName, DataRow dataRow)
{
if (connection == null)
{
throw new ArgumentNullException("connection");
}
if ((spName == null) || (spName.Length == 0))
{
throw new ArgumentNullException("spName");
}
if ((dataRow != null) && (dataRow.ItemArray.Length > 0))
{
SqlParameter[] commandParameters = SqlParameterCacheHelper.GetSpParameterSet(connection.ConnectionString, spName);
AssignParameterValues(commandParameters, dataRow);
return (SqlDataReader)ExecuteReader(connection, CommandType.StoredProcedure, spName, commandParameters);
}
return (SqlDataReader)ExecuteReader(connection, CommandType.StoredProcedure, spName);
}
public SqlDataReader ExecuteReaderTypedParams(SqlTransaction transaction, string spName, DataRow dataRow)
{
if (transaction == null)
{
throw new ArgumentNullException("transaction");
}
if ((transaction != null) && (transaction.Connection == null))
{
throw new ArgumentException("The transaction was rollbacked or commited, please provide an open transaction.", "transaction");
}
if ((spName == null) || (spName.Length == 0))
{
throw new ArgumentNullException("spName");
}
if ((dataRow != null) && (dataRow.ItemArray.Length > 0))
{
SqlParameter[] commandParameters = SqlParameterCacheHelper.GetSpParameterSet(transaction.Connection.ConnectionString, spName);
AssignParameterValues(commandParameters, dataRow);
return (SqlDataReader)ExecuteReader(transaction, CommandType.StoredProcedure, spName, commandParameters);
}
return (SqlDataReader)ExecuteReader(transaction, CommandType.StoredProcedure, spName);
}
public SqlDataReader ExecuteReaderTypedParams(string connectionString, string spName, DataRow dataRow)
{
if ((connectionString == null) || (connectionString.Length == 0))
{
throw new ArgumentNullException("connectionString");
}
if ((spName == null) || (spName.Length == 0))
{
throw new ArgumentNullException("spName");
}
if ((dataRow != null) && (dataRow.ItemArray.Length > 0))
{
SqlParameter[] commandParameters = SqlParameterCacheHelper.GetSpParameterSet(connectionString, spName);
AssignParameterValues(commandParameters, dataRow);
return (SqlDataReader)ExecuteReader(connectionString, CommandType.StoredProcedure, spName, commandParameters);
}
return (SqlDataReader)ExecuteReader(connectionString, CommandType.StoredProcedure, spName);
}
//public Hashtable ExecuteReturnCacheTransation(IList<TransationParam> paramList, string conString, IExceptionHandler exceptionHandler)
//{
// SqlConnection transationConn = new SqlConnection(conString);
// SqlTransaction tran = null;
// SqlCommand sqlCmd = null;
// object execResult = null;
// Hashtable newTempHashCahe = null;
// int itemIndex = 0;
// try
// {
// transationConn.Open();
// tran = transationConn.BeginTransaction(IsolationLevel.Serializable);
// sqlCmd = new SqlCommand();
// sqlCmd.Connection = transationConn;
// sqlCmd.Transaction = tran;
// int reuslt = 0;
// newTempHashCahe = new Hashtable();
// foreach (TransationParam transationParam in paramList)
// {
// itemIndex++;
// sqlCmd.CommandText = transationParam.CommandText;
// sqlCmd.CommandType = transationParam.CommandType;
// sqlCmd.Parameters.Clear();
// if (transationParam.SqlParameterList.Length > 0)
// {
// AttachParameters(sqlCmd, (SqlParameter[]) transationParam.SqlParameterList);
// if ((transationParam.FieldHashKey != null) && (transationParam.FieldHashKey.Count > 0))
// {
// foreach (string fieldName in transationParam.FieldHashKey.Keys)
// {
// sqlCmd.Parameters["@" + fieldName].Value = newTempHashCahe[transationParam.FieldHashKey[fieldName]];
// }
// }
// }
// reuslt = sqlCmd.ExecuteNonQuery();
// if ((itemIndex == paramList.Count) || transationParam.IsNeedTransfer)
// {
// if (transationParam.CommandType == CommandType.StoredProcedure)
// {
// execResult = transationParam.SqlParameterList[0].Value;
// }
// if (transationParam.TempCacheKey != null)
// {
// newTempHashCahe.Add(transationParam.TempCacheKey, execResult);
// }
// else
// {
// newTempHashCahe.Add(transationParam.SqlParameterList[0].ParameterName, execResult);
// }
// }
// }
// tran.Commit();
// }
// catch (Exception ex)
// {
// execResult = null;
// try
// {
// tran.Rollback();
// }
// catch (MySqlException e)
// {
// if ((tran.Connection != null) && (exceptionHandler != null))
// {
// exceptionHandler.WriteLog(e);
// }
// }
// if (exceptionHandler != null)
// {
// exceptionHandler.WriteLog(ex);
// }
// }
// finally
// {
// if (transationConn.State != ConnectionState.Closed)
// {
// transationConn.Close();
// transationConn.Dispose();
// }
// }
// return newTempHashCahe;
//}
//public object ExecuteReturnTransation(IList<TransationParam> paramList, string conString, IExceptionHandler exceptionHandler)
//{
// SqlConnection transationConn = new SqlConnection(conString);
// SqlTransaction tran = null;
// SqlCommand sqlCmd = null;
// object execResult = null;
// Hashtable newTempHashCahe = null;
// int itemIndex = 0;
// try
// {
// transationConn.Open();
// tran = transationConn.BeginTransaction(IsolationLevel.Serializable);
// sqlCmd = new SqlCommand();
// sqlCmd.Connection = transationConn;
// sqlCmd.Transaction = tran;
// int reuslt = 0;
// newTempHashCahe = new Hashtable();
// foreach (TransationParam transationParam in paramList)
// {
// itemIndex++;
// sqlCmd.CommandText = transationParam.CommandText;
// sqlCmd.CommandType = transationParam.CommandType;
// sqlCmd.Parameters.Clear();
// if (transationParam.SqlParameterList.Length > 0)
// {
// AttachParameters(sqlCmd, (SqlParameter[]) transationParam.SqlParameterList);
// if ((transationParam.FieldHashKey != null) && (transationParam.FieldHashKey.Count > 0))
// {
// foreach (string fieldName in transationParam.FieldHashKey.Keys)
// {
// sqlCmd.Parameters["@" + fieldName].Value = newTempHashCahe[transationParam.FieldHashKey[fieldName]];
// }
// }
// }
// reuslt = sqlCmd.ExecuteNonQuery();
// if ((itemIndex == paramList.Count) || transationParam.IsNeedTransfer)
// {
// if (transationParam.CommandType == CommandType.StoredProcedure)
// {
// execResult = transationParam.SqlParameterList[0].Value;
// }
// if (transationParam.TempCacheKey != null)
// {
// newTempHashCahe.Add(transationParam.TempCacheKey, execResult);
// }
// else
// {
// newTempHashCahe.Add(transationParam.SqlParameterList[0].ParameterName, execResult);
// }
// }
// }
// tran.Commit();
// }
// catch (Exception ex)
// {
// execResult = null;
// try
// {
// tran.Rollback();
// }
// catch (MySqlException e)
// {
// if ((tran.Connection != null) && (exceptionHandler != null))
// {
// exceptionHandler.WriteLog(e);
// }
// }
// if (exceptionHandler != null)
// {
// exceptionHandler.WriteLog(ex);
// }
// }
// finally
// {
// if (transationConn.State != ConnectionState.Closed)
// {
// transationConn.Close();
// transationConn.Dispose();
// }
// }
// return execResult;
//}
public object ExecuteScalar(IDbConnection connection, CommandType commandType, string commandText)
{
return this.ExecuteScalar(connection, commandType, commandText, null);
}
public object ExecuteScalar(IDbConnection connection, string spName, params object[] parameterValues)
{
if (connection == null)
{
throw new ArgumentNullException("connection");
}
if ((spName == null) || (spName.Length == 0))
{
throw new ArgumentNullException("spName");
}
if ((parameterValues != null) && (parameterValues.Length > 0))
{
SqlParameter[] commandParameters = SqlParameterCacheHelper.GetSpParameterSet(connection.ConnectionString, spName);
AssignParameterValues(commandParameters, parameterValues);
return this.ExecuteScalar(connection, CommandType.StoredProcedure, spName, commandParameters);
}
return this.ExecuteScalar(connection, CommandType.StoredProcedure, spName);
}
public object ExecuteScalar(IDbTransaction transaction, CommandType commandType, string commandText)
{
return this.ExecuteScalar(transaction, commandType, commandText, null);
}
public object ExecuteScalar(IDbTransaction transaction, string spName, params object[] parameterValues)
{
if (transaction == null)
{
throw new ArgumentNullException("transaction");
}
if ((transaction != null) && (transaction.Connection == null))
{
throw new ArgumentException("The transaction was rollbacked or commited, please provide an open transaction.", "transaction");
}
if ((spName == null) || (spName.Length == 0))
{
throw new ArgumentNullException("spName");
}
if ((parameterValues != null) && (parameterValues.Length > 0))
{
SqlParameter[] commandParameters = SqlParameterCacheHelper.GetSpParameterSet(transaction.Connection.ConnectionString, spName);
AssignParameterValues(commandParameters, parameterValues);
return this.ExecuteScalar(transaction, CommandType.StoredProcedure, spName, commandParameters);
}
return this.ExecuteScalar(transaction, CommandType.StoredProcedure, spName);
}
public object ExecuteScalar(string connectionString, CommandType commandType, string commandText)
{
return this.ExecuteScalar(connectionString, commandType, commandText, null);
}
public object ExecuteScalar(string connectionString, string spName, params object[] parameterValues)
{
if ((connectionString == null) || (connectionString.Length == 0))
{
throw new ArgumentNullException("connectionString");
}
if ((spName == null) || (spName.Length == 0))
{
throw new ArgumentNullException("spName");
}
if ((parameterValues != null) && (parameterValues.Length > 0))
{
SqlParameter[] commandParameters = SqlParameterCacheHelper.GetSpParameterSet(connectionString, spName);
AssignParameterValues(commandParameters, parameterValues);
return this.ExecuteScalar(connectionString, CommandType.StoredProcedure, spName, commandParameters);
}
return this.ExecuteScalar(connectionString, CommandType.StoredProcedure, spName);
}
public object ExecuteScalar(IDbConnection connection, CommandType commandType, string commandText, params IDbDataParameter[] commandParameters)
{
if (connection == null)
{
throw new ArgumentNullException("connection");
}
SqlCommand cmd = new SqlCommand();
bool mustCloseConnection = false;
PrepareCommand(cmd, (SqlConnection) connection, null, commandType, commandText, (SqlParameter[]) commandParameters, out mustCloseConnection);
object retval = cmd.ExecuteScalar();
cmd.Parameters.Clear();
if (mustCloseConnection)
{
connection.Close();
}
return retval;
}
public object ExecuteScalar(IDbTransaction transaction, CommandType commandType, string commandText, params IDbDataParameter[] commandParameters)
{
if (transaction == null)
{
throw new ArgumentNullException("transaction");
}
if ((transaction != null) && (transaction.Connection == null))
{
throw new ArgumentException("The transaction was rollbacked or commited, please provide an open transaction.", "transaction");
}
SqlCommand cmd = new SqlCommand();
bool mustCloseConnection = false;
PrepareCommand(cmd, (SqlConnection) transaction.Connection, (SqlTransaction) transaction, commandType, commandText, (SqlParameter[]) commandParameters, out mustCloseConnection);
object retval = cmd.ExecuteScalar();
cmd.Parameters.Clear();
return retval;
}
public object ExecuteScalar(string connectionString, CommandType commandType, string commandText, params IDbDataParameter[] commandParameters)
{
if ((connectionString == null) || (connectionString.Length == 0))
{
throw new ArgumentNullException("connectionString");
}
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
return this.ExecuteScalar(connection, commandType, commandText, commandParameters);
}
}
public object ExecuteScalarTypedParams(SqlConnection connection, string spName, DataRow dataRow)
{
if (connection == null)
{
throw new ArgumentNullException("connection");
}
if ((spName == null) || (spName.Length == 0))
{
throw new ArgumentNullException("spName");
}
if ((dataRow != null) && (dataRow.ItemArray.Length > 0))
{
SqlParameter[] commandParameters = SqlParameterCacheHelper.GetSpParameterSet(connection.ConnectionString, spName);
AssignParameterValues(commandParameters, dataRow);
return ExecuteScalar(connection, CommandType.StoredProcedure, spName, commandParameters);
}
return ExecuteScalar(connection, CommandType.StoredProcedure, spName);
}
public object ExecuteScalarTypedParams(SqlTransaction transaction, string spName, DataRow dataRow)
{
if (transaction == null)
{
throw new ArgumentNullException("transaction");
}
if ((transaction != null) && (transaction.Connection == null))
{
throw new ArgumentException("The transaction was rollbacked or commited, please provide an open transaction.", "transaction");
}
if ((spName == null) || (spName.Length == 0))
{
throw new ArgumentNullException("spName");
}
if ((dataRow != null) && (dataRow.ItemArray.Length > 0))
{
SqlParameter[] commandParameters = SqlParameterCacheHelper.GetSpParameterSet(transaction.Connection.ConnectionString, spName);
AssignParameterValues(commandParameters, dataRow);
return ExecuteScalar(transaction, CommandType.StoredProcedure, spName, (IDbDataParameter[]) commandParameters);
}
return ExecuteScalar(transaction, CommandType.StoredProcedure, spName);
}
public object ExecuteScalarTypedParams(string connectionString, string spName, DataRow dataRow)
{
if ((connectionString == null) || (connectionString.Length == 0))
{
throw new ArgumentNullException("connectionString");
}
if ((spName == null) || (spName.Length == 0))
{
throw new ArgumentNullException("spName");
}
if ((dataRow != null) && (dataRow.ItemArray.Length > 0))
{
SqlParameter[] commandParameters = SqlParameterCacheHelper.GetSpParameterSet(connectionString, spName);
AssignParameterValues(commandParameters, dataRow);
return ExecuteScalar(connectionString, CommandType.StoredProcedure, spName, commandParameters);
}
return ExecuteScalar(connectionString, CommandType.StoredProcedure, spName);
}
//public bool ExecuteTransation(IList<TransationParam> paramList, string conString, IExceptionHandler exceptionHandler)
//{
// SqlConnection transationConn = new SqlConnection(conString);
// SqlTransaction tran = null;
// SqlCommand sqlCmd = null;
// bool execResult = false;
// try
// {
// transationConn.Open();
// tran = transationConn.BeginTransaction();
// sqlCmd = new SqlCommand();
// sqlCmd.Connection = transationConn;
// sqlCmd.Transaction = tran;
// foreach (TransationParam transationParam in paramList)
// {
// sqlCmd.CommandText = transationParam.CommandText;
// sqlCmd.CommandType = transationParam.CommandType;
// sqlCmd.Parameters.Clear();
// if (transationParam.SqlParameterList.Length > 0)
// {
// AttachParameters(sqlCmd, (SqlParameter[]) transationParam.SqlParameterList);
// }
// int reuslt = 0;
// reuslt = sqlCmd.ExecuteNonQuery();
// }
// tran.Commit();
// execResult = true;
// }
// catch (Exception ex)
// {
// try
// {
// tran.Rollback();
// }
// catch (MySqlException e)
// {
// if ((tran.Connection != null) && (exceptionHandler != null))
// {
// exceptionHandler.WriteLog(e);
// }
// }
// if (exceptionHandler != null)
// {
// exceptionHandler.WriteLog(ex);
// }
// }
// finally
// {
// if (transationConn.State != ConnectionState.Closed)
// {
// transationConn.Close();
// transationConn.Dispose();
// }
// }
// return execResult;
//}
public void FillDataset(SqlConnection connection, CommandType commandType, string commandText, DataSet dataSet, string[] tableNames)
{
this.FillDataset(connection, commandType, commandText, dataSet, tableNames, null);
}
public void FillDataset(SqlConnection connection, string spName, DataSet dataSet, string[] tableNames, params object[] parameterValues)
{
if (connection == null)
{
throw new ArgumentNullException("connection");
}
if (dataSet == null)
{
throw new ArgumentNullException("dataSet");
}
if ((spName == null) || (spName.Length == 0))
{
throw new ArgumentNullException("spName");
}
if ((parameterValues != null) && (parameterValues.Length > 0))
{
SqlParameter[] commandParameters = SqlParameterCacheHelper.GetSpParameterSet(connection.ConnectionString, spName);
AssignParameterValues(commandParameters, parameterValues);
this.FillDataset(connection, CommandType.StoredProcedure, spName, dataSet, tableNames, commandParameters);
}
else
{
this.FillDataset(connection, CommandType.StoredProcedure, spName, dataSet, tableNames);
}
}
public void FillDataset(SqlTransaction transaction, CommandType commandType, string commandText, DataSet dataSet, string[] tableNames)
{
this.FillDataset(transaction, commandType, commandText, dataSet, tableNames, null);
}
public void FillDataset(SqlTransaction transaction, string spName, DataSet dataSet, string[] tableNames, params object[] parameterValues)
{
if (transaction == null)
{
throw new ArgumentNullException("transaction");
}
if ((transaction != null) && (transaction.Connection == null))
{
throw new ArgumentException("The transaction was rollbacked or commited, please provide an open transaction.", "transaction");
}
if (dataSet == null)
{
throw new ArgumentNullException("dataSet");
}
if ((spName == null) || (spName.Length == 0))
{
throw new ArgumentNullException("spName");
}
if ((parameterValues != null) && (parameterValues.Length > 0))
{
SqlParameter[] commandParameters = SqlParameterCacheHelper.GetSpParameterSet(transaction.Connection.ConnectionString, spName);
AssignParameterValues(commandParameters, parameterValues);
this.FillDataset(transaction, CommandType.StoredProcedure, spName, dataSet, tableNames, commandParameters);
}
else
{
this.FillDataset(transaction, CommandType.StoredProcedure, spName, dataSet, tableNames);
}
}
public void FillDataset(string connectionString, CommandType commandType, string commandText, DataSet dataSet, string[] tableNames)
{
if ((connectionString == null) || (connectionString.Length == 0))
{
throw new ArgumentNullException("connectionString");
}
if (dataSet == null)
{
throw new ArgumentNullException("dataSet");
}
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
this.FillDataset(connection, commandType, commandText, dataSet, tableNames);
}
}
public void FillDataset(string connectionString, string spName, DataSet dataSet, string[] tableNames, params object[] parameterValues)
{
if ((connectionString == null) || (connectionString.Length == 0))
{
throw new ArgumentNullException("connectionString");
}
if (dataSet == null)
{
throw new ArgumentNullException("dataSet");
}
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
this.FillDataset(connection, spName, dataSet, tableNames, parameterValues);
}
}
public void FillDataset(SqlConnection connection, CommandType commandType, string commandText, DataSet dataSet, string[] tableNames, params SqlParameter[] commandParameters)
{
this.FillDataset(connection, null, commandType, commandText, dataSet, tableNames, commandParameters);
}
public void FillDataset(SqlTransaction transaction, CommandType commandType, string commandText, DataSet dataSet, string[] tableNames, params SqlParameter[] commandParameters)
{
this.FillDataset(transaction.Connection, transaction, commandType, commandText, dataSet, tableNames, commandParameters);
}
public void FillDataset(string connectionString, CommandType commandType, string commandText, DataSet dataSet, string[] tableNames, params SqlParameter[] commandParameters)
{
if ((connectionString == null) || (connectionString.Length == 0))
{
throw new ArgumentNullException("connectionString");
}
if (dataSet == null)
{
throw new ArgumentNullException("dataSet");
}
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
this.FillDataset(connection, commandType, commandText, dataSet, tableNames, commandParameters);
}
}
private void FillDataset(SqlConnection connection, SqlTransaction transaction, CommandType commandType, string commandText, DataSet dataSet, string[] tableNames, params SqlParameter[] commandParameters)
{
if (connection == null)
{
throw new ArgumentNullException("connection");
}
if (dataSet == null)
{
throw new ArgumentNullException("dataSet");
}
SqlCommand command = new SqlCommand();
bool mustCloseConnection = false;
PrepareCommand(command, connection, transaction, commandType, commandText, commandParameters, out mustCloseConnection);
using (SqlDataAdapter dataAdapter = new SqlDataAdapter(command))
{
if ((tableNames != null) && (tableNames.Length > 0))
{
string tableName = "Table";
for (int index = 0; index < tableNames.Length; index++)
{
if ((tableNames[index] == null) || (tableNames[index].Length == 0))
{
throw new ArgumentException("The tableNames parameter must contain a list of tables, a value was provided as null or empty string.", "tableNames");
}
dataAdapter.TableMappings.Add(tableName, tableNames[index]);
tableName = tableName + ((index + 1)).ToString();
}
}
dataAdapter.Fill(dataSet);
command.Parameters.Clear();
}
if (mustCloseConnection)
{
connection.Close();
}
}
public int GetCount(string tblName, string condition)
{
StringBuilder sql = new StringBuilder("select count(*) from " + tblName);
if (!string.IsNullOrEmpty(condition))
{
sql.Append(" where " + condition);
}
return ConvertHelper.ToInt(this.ExecuteScalar(this.ConnectionString, CommandType.Text, sql.ToString(), null).ToString());
}
public T GetEntity<T>(string spName, params object[] parameterValues) where T: class, new()
{
if ((this.ConnectionString == null) || (this.ConnectionString.Length == 0))
{
throw new ArgumentNullException("connectionString");
}
if ((spName == null) || (spName.Length == 0))
{
throw new ArgumentNullException("spName");
}
if ((parameterValues != null) && (parameterValues.Length > 0))
{
SqlParameter[] commandParameters = SqlParameterCacheHelper.GetSpParameterSet(this.ConnectionString, spName);
AssignParameterValues(commandParameters, parameterValues);
return this.GetEntity<T>(this.ConnectionString, CommandType.StoredProcedure, spName, commandParameters);
}
return this.GetEntity<T>(this.ConnectionString, CommandType.StoredProcedure, spName);
}
public T GetEntity<T>(CommandType commandType, string commandText, params IDbDataParameter[] commandParameters) where T: class, new()
{
T t;
if ((this.ConnectionString == null) || (this.ConnectionString.Length == 0))
{
throw new ArgumentNullException("connectionString");
}
SqlConnection connection = null;
try
{
connection = new SqlConnection(this.ConnectionString);
connection.Open();
t = this.GetEntity<T>(connection, null, commandType, commandText, commandParameters, DbConnectionOwnership.Internal);
}
catch (Exception)
{
if (connection != null)
{
connection.Close();
}
throw;
}
return t;
}
public T GetEntity<T>(IDbConnection connection, CommandType commandType, string commandText) where T: class, new()
{
return this.GetEntity<T>(connection, commandType, commandText, null);
}
public T GetEntity<T>(IDbConnection connection, string spName, params object[] parameterValues) where T: class, new()
{
if (connection == null)
{
throw new ArgumentNullException("connection");
}
if ((spName == null) || (spName.Length == 0))
{
throw new ArgumentNullException("spName");
}
if ((parameterValues != null) && (parameterValues.Length > 0))
{
SqlParameter[] commandParameters = SqlParameterCacheHelper.GetSpParameterSet(connection.ConnectionString, spName);
AssignParameterValues(commandParameters, parameterValues);
return this.GetEntity<T>(connection, CommandType.StoredProcedure, spName, commandParameters);
}
return this.GetEntity<T>(connection, CommandType.StoredProcedure, spName);
}
public T GetEntity<T>(IDbTransaction transaction, CommandType commandType, string commandText) where T: class, new()
{
return this.GetEntity<T>(transaction, commandType, commandText, null);
}
public T GetEntity<T>(IDbTransaction transaction, string spName, params object[] parameterValues) where T: class, new()
{
if (transaction == null)
{
throw new ArgumentNullException("transaction");
}
if ((transaction != null) && (transaction.Connection == null))
{
throw new ArgumentException("The transaction was rollbacked or commited, please provide an open transaction.", "transaction");
}
if ((spName == null) || (spName.Length == 0))
{
throw new ArgumentNullException("spName");
}
if ((parameterValues != null) && (parameterValues.Length > 0))
{
SqlParameter[] commandParameters = SqlParameterCacheHelper.GetSpParameterSet(transaction.Connection.ConnectionString, spName);
AssignParameterValues(commandParameters, parameterValues);
return this.GetEntity<T>(transaction, CommandType.StoredProcedure, spName, commandParameters);
}
return this.GetEntity<T>(transaction, CommandType.StoredProcedure, spName);
}
public T GetEntity<T>(string connectionString, CommandType commandType, string commandText) where T: class, new()
{
return this.GetEntity<T>(connectionString, commandType, commandText, null);
}
public T GetEntity<T>(string connectionString, string spName, params object[] parameterValues) where T: class, new()
{
if ((connectionString == null) || (connectionString.Length == 0))
{
throw new ArgumentNullException("connectionString");
}
if ((spName == null) || (spName.Length == 0))
{
throw new ArgumentNullException("spName");
}
if ((parameterValues != null) && (parameterValues.Length > 0))
{
SqlParameter[] commandParameters = SqlParameterCacheHelper.GetSpParameterSet(connectionString, spName);
AssignParameterValues(commandParameters, parameterValues);
return this.GetEntity<T>(connectionString, CommandType.StoredProcedure, spName, commandParameters);
}
return this.GetEntity<T>(connectionString, CommandType.StoredProcedure, spName);
}
public T GetEntity<T>(IDbConnection connection, CommandType commandType, string commandText, params IDbDataParameter[] commandParameters) where T: class, new()
{
return this.GetEntity<T>(connection, null, commandType, commandText, commandParameters, DbConnectionOwnership.External);
}
public T GetEntity<T>(IDbTransaction transaction, CommandType commandType, string commandText, params IDbDataParameter[] commandParameters) where T: class, new()
{
if (transaction == null)
{
throw new ArgumentNullException("transaction");
}
if ((transaction != null) && (transaction.Connection == null))
{
throw new ArgumentException("The transaction was rollbacked or commited, please provide an open transaction.", "transaction");
}
return this.GetEntity<T>(transaction.Connection, transaction, commandType, commandText, commandParameters, DbConnectionOwnership.External);
}
public T GetEntity<T>(string connectionString, CommandType commandType, string commandText, params IDbDataParameter[] commandParameters) where T: class, new()
{
T t;
if ((connectionString == null) || (connectionString.Length == 0))
{
throw new ArgumentNullException("connectionString");
}
SqlConnection connection = null;
try
{
connection = new SqlConnection(connectionString);
connection.Open();
t = this.GetEntity<T>(connection, null, commandType, commandText, commandParameters, DbConnectionOwnership.Internal);
}
catch (Exception)
{
if (connection != null)
{
connection.Close();
}
throw;
}
return t;
}
public T GetEntity<T>(IDbConnection connection, IDbTransaction transaction, CommandType commandType, string commandText, IDbDataParameter[] commandParameters, DbConnectionOwnership connectionOwnership) where T: class, new()
{
T returnEntity = default(T);
if (connection == null)
{
throw new ArgumentNullException("connection");
}
bool mustCloseConnection = false;
SqlCommand cmd = new SqlCommand();
try
{
SqlDataReader dataReader;
PrepareCommand(cmd, (SqlConnection) connection, (SqlTransaction) transaction, commandType, commandText, (SqlParameter[]) commandParameters, out mustCloseConnection);
if (connectionOwnership == DbConnectionOwnership.External)
{
dataReader = cmd.ExecuteReader();
}
else
{
dataReader = cmd.ExecuteReader(CommandBehavior.CloseConnection);
}
bool canClear = true;
foreach (SqlParameter commandParameter in cmd.Parameters)
{
if (commandParameter.Direction != ParameterDirection.Input)
{
canClear = false;
}
}
if (canClear)
{
cmd.Parameters.Clear();
}
returnEntity = default(T);
returnEntity = EntityFactory.CreateInstance().FillEntity<T>(dataReader);
}
catch (Exception)
{
if (mustCloseConnection)
{
connection.Close();
}
throw;
}
finally
{
if (mustCloseConnection && (connection.State != ConnectionState.Closed))
{
connection.Close();
}
connection.Dispose();
}
return returnEntity;
}
public List<T> GetList<T>(string spName, params object[] parameterValues) where T: class, new()
{
if ((this.ConnectionString == null) || (this.ConnectionString.Length == 0))
{
throw new ArgumentNullException("connectionString");
}
if ((spName == null) || (spName.Length == 0))
{
throw new ArgumentNullException("spName");
}
if ((parameterValues != null) && (parameterValues.Length > 0))
{
SqlParameter[] commandParameters = SqlParameterCacheHelper.GetSpParameterSet(this.ConnectionString, spName);
AssignParameterValues(commandParameters, parameterValues);
return this.GetList<T>(this.ConnectionString, CommandType.StoredProcedure, spName, commandParameters);
}
return this.GetList<T>(this.ConnectionString, CommandType.StoredProcedure, spName);
}
public List<T> GetList<T>(CommandType commandType, string commandText, params IDbDataParameter[] commandParameters) where T: class, new()
{
List<T> list;
if ((this.ConnectionString == null) || (this.ConnectionString.Length == 0))
{
throw new ArgumentNullException("connectionString");
}
SqlConnection connection = null;
try
{
connection = new SqlConnection(this.ConnectionString);
connection.Open();
base.CommandTrackLog(commandText);
list = this.GetList<T>(connection, null, commandType, commandText, commandParameters, DbConnectionOwnership.Internal);
}
catch (Exception ex)
{
if (connection != null)
{
connection.Close();
}
throw ex;
}
return list;
}
public List<T> GetList<T>(IDbConnection connection, CommandType commandType, string commandText) where T: class, new()
{
return this.GetList<T>(connection, commandType, commandText, (IDbDataParameter[]) null);
}
public List<T> GetList<T>(IDbConnection connection, string spName, params object[] parameterValues) where T: class, new()
{
if (connection == null)
{
throw new ArgumentNullException("connection");
}
if ((spName == null) || (spName.Length == 0))
{
throw new ArgumentNullException("spName");
}
if ((parameterValues != null) && (parameterValues.Length > 0))
{
SqlParameter[] commandParameters = SqlParameterCacheHelper.GetSpParameterSet(connection.ConnectionString, spName);
AssignParameterValues(commandParameters, parameterValues);
return this.GetList<T>(connection, CommandType.StoredProcedure, spName, commandParameters);
}
return this.GetList<T>(connection, CommandType.StoredProcedure, spName);
}
public List<T> GetList<T>(IDbTransaction transaction, CommandType commandType, string commandText) where T: class, new()
{
return this.GetList<T>(transaction, commandType, commandText, (IDbDataParameter[]) null);
}
public List<T> GetList<T>(IDbTransaction transaction, string spName, params object[] parameterValues) where T: class, new()
{
if (transaction == null)
{
throw new ArgumentNullException("transaction");
}
if ((transaction != null) && (transaction.Connection == null))
{
throw new ArgumentException("The transaction was rollbacked or commited, please provide an open transaction.", "transaction");
}
if ((spName == null) || (spName.Length == 0))
{
throw new ArgumentNullException("spName");
}
if ((parameterValues != null) && (parameterValues.Length > 0))
{
SqlParameter[] commandParameters = SqlParameterCacheHelper.GetSpParameterSet(transaction.Connection.ConnectionString, spName);
AssignParameterValues(commandParameters, parameterValues);
return this.GetList<T>(transaction, CommandType.StoredProcedure, spName, commandParameters);
}
return this.GetList<T>(transaction, CommandType.StoredProcedure, spName);
}
public List<T> GetList<T>(string connectionString, CommandType commandType, string commandText) where T: class, new()
{
return this.GetList<T>(connectionString, commandType, commandText, (IDbDataParameter[]) null);
}
public List<T> GetList<T>(string connectionString, string spName, params object[] parameterValues) where T: class, new()
{
if ((connectionString == null) || (connectionString.Length == 0))
{
throw new ArgumentNullException("connectionString");
}
if ((spName == null) || (spName.Length == 0))
{
throw new ArgumentNullException("spName");
}
if ((parameterValues != null) && (parameterValues.Length > 0))
{
SqlParameter[] commandParameters = SqlParameterCacheHelper.GetSpParameterSet(connectionString, spName);
AssignParameterValues(commandParameters, parameterValues);
return this.GetList<T>(connectionString, CommandType.StoredProcedure, spName, commandParameters);
}
return this.GetList<T>(connectionString, CommandType.StoredProcedure, spName);
}
//public List<T> GetList<T>(string spName, ref CacheDependency cacheDependency, params object[] parameterValues) where T: class, new()
//{
// if ((this.ConnectionString == null) || (this.ConnectionString.Length == 0))
// {
// throw new ArgumentNullException("connectionString");
// }
// if ((spName == null) || (spName.Length == 0))
// {
// throw new ArgumentNullException("spName");
// }
// if ((parameterValues != null) && (parameterValues.Length > 0))
// {
// SqlParameter[] commandParameters = SqlParameterCacheHelper.GetSpParameterSet(this.ConnectionString, spName);
// AssignParameterValues(commandParameters, parameterValues);
// return this.GetList<T>(this.ConnectionString, CommandType.StoredProcedure, spName, ref cacheDependency, commandParameters);
// }
// return this.GetList<T>(this.ConnectionString, CommandType.StoredProcedure, spName);
//}
//public List<T> GetList<T>(CommandType commandType, string commandText, ref CacheDependency cacheDependency, params IDbDataParameter[] commandParameters) where T: class, new()
//{
// List<T> list;
// if ((this.ConnectionString == null) || (this.ConnectionString.Length == 0))
// {
// throw new ArgumentNullException("connectionString");
// }
// SqlConnection connection = null;
// try
// {
// connection = new SqlConnection(this.ConnectionString);
// connection.Open();
// base.LogSql(commandText);
// list = this.GetList<T>(connection, null, commandType, commandText, commandParameters, DbConnectionOwnership.Internal, ref cacheDependency);
// }
// catch (Exception ex)
// {
// if (connection != null)
// {
// connection.Close();
// }
// throw ex;
// }
// return list;
//}
//public List<T> GetList<T>(IDbConnection connection, CommandType commandType, string commandText, ref CacheDependency cacheDependency) where T: class, new()
//{
// return this.GetList<T>(connection, commandType, commandText, ref cacheDependency, null);
//}
public List<T> GetList<T>(IDbConnection connection, CommandType commandType, string commandText, params IDbDataParameter[] commandParameters) where T: class, new()
{
return this.GetList<T>(connection, null, commandType, commandText, commandParameters, DbConnectionOwnership.External);
}
//public List<T> GetList<T>(IDbConnection connection, string spName, ref CacheDependency cacheDependency, params object[] parameterValues) where T: class, new()
//{
// if (connection == null)
// {
// throw new ArgumentNullException("connection");
// }
// if ((spName == null) || (spName.Length == 0))
// {
// throw new ArgumentNullException("spName");
// }
// if ((parameterValues != null) && (parameterValues.Length > 0))
// {
// SqlParameter[] commandParameters = SqlParameterCacheHelper.GetSpParameterSet(connection.ConnectionString, spName);
// AssignParameterValues(commandParameters, parameterValues);
// return this.GetList<T>(connection, CommandType.StoredProcedure, spName, ref cacheDependency, commandParameters);
// }
// return this.GetList<T>(connection, CommandType.StoredProcedure, spName, ref cacheDependency);
//}
//public List<T> GetList<T>(IDbTransaction transaction, CommandType commandType, string commandText, ref CacheDependency cacheDependency) where T: class, new()
//{
// return this.GetList<T>(transaction, commandType, commandText, ref cacheDependency, null);
//}
public List<T> GetList<T>(IDbTransaction transaction, CommandType commandType, string commandText, params IDbDataParameter[] commandParameters) where T: class, new()
{
if (transaction == null)
{
throw new ArgumentNullException("transaction");
}
if ((transaction != null) && (transaction.Connection == null))
{
throw new ArgumentException("The transaction was rollbacked or commited, please provide an open transaction.", "transaction");
}
return this.GetList<T>(transaction.Connection, transaction, commandType, commandText, commandParameters, DbConnectionOwnership.External);
}
//public List<T> GetList<T>(IDbTransaction transaction, string spName, ref CacheDependency cacheDependency, params object[] parameterValues) where T: class, new()
//{
// if (transaction == null)
// {
// throw new ArgumentNullException("transaction");
// }
// if ((transaction != null) && (transaction.Connection == null))
// {
// throw new ArgumentException("The transaction was rollbacked or commited, please provide an open transaction.", "transaction");
// }
// if ((spName == null) || (spName.Length == 0))
// {
// throw new ArgumentNullException("spName");
// }
// if ((parameterValues != null) && (parameterValues.Length > 0))
// {
// SqlParameter[] commandParameters = SqlParameterCacheHelper.GetSpParameterSet(transaction.Connection.ConnectionString, spName);
// AssignParameterValues(commandParameters, parameterValues);
// return this.GetList<T>(transaction, CommandType.StoredProcedure, spName, ref cacheDependency, commandParameters);
// }
// return this.GetList<T>(transaction, CommandType.StoredProcedure, spName, ref cacheDependency);
//}
public List<T> GetList<T>(string connectionString, CommandType commandType, string commandText, params IDbDataParameter[] commandParameters) where T: class, new()
{
List<T> list;
if ((connectionString == null) || (connectionString.Length == 0))
{
throw new ArgumentNullException("connectionString");
}
SqlConnection connection = null;
try
{
connection = new SqlConnection(connectionString);
connection.Open();
base.CommandTrackLog(commandText);
list = this.GetList<T>(connection, null, commandType, commandText, commandParameters, DbConnectionOwnership.Internal);
}
catch (Exception ex)
{
if (connection != null)
{
connection.Close();
}
throw ex;
}
return list;
}
//public List<T> GetList<T>(string connectionString, CommandType commandType, string commandText, ref CacheDependency cacheDependency) where T: class, new()
//{
// return this.GetList<T>(connectionString, commandType, commandText, ref cacheDependency, null);
//}
//public List<T> GetList<T>(string connectionString, string spName, ref CacheDependency cacheDependency, params object[] parameterValues) where T: class, new()
//{
// if ((connectionString == null) || (connectionString.Length == 0))
// {
// throw new ArgumentNullException("connectionString");
// }
// if ((spName == null) || (spName.Length == 0))
// {
// throw new ArgumentNullException("spName");
// }
// if ((parameterValues != null) && (parameterValues.Length > 0))
// {
// SqlParameter[] commandParameters = SqlParameterCacheHelper.GetSpParameterSet(connectionString, spName);
// AssignParameterValues(commandParameters, parameterValues);
// return this.GetList<T>(connectionString, CommandType.StoredProcedure, spName, ref cacheDependency, commandParameters);
// }
// return this.GetList<T>(connectionString, CommandType.StoredProcedure, spName, ref cacheDependency);
//}
//public List<T> GetList<T>(IDbConnection connection, CommandType commandType, string commandText, ref CacheDependency cacheDependency, params IDbDataParameter[] commandParameters) where T: class, new()
//{
// return this.GetList<T>(connection, null, commandType, commandText, commandParameters, DbConnectionOwnership.External, ref cacheDependency);
//}
//public List<T> GetList<T>(IDbTransaction transaction, CommandType commandType, string commandText, ref CacheDependency cacheDependency, params IDbDataParameter[] commandParameters) where T: class, new()
//{
// if (transaction == null)
// {
// throw new ArgumentNullException("transaction");
// }
// if ((transaction != null) && (transaction.Connection == null))
// {
// throw new ArgumentException("The transaction was rollbacked or commited, please provide an open transaction.", "transaction");
// }
// return this.GetList<T>(transaction.Connection, transaction, commandType, commandText, commandParameters, DbConnectionOwnership.External, ref cacheDependency);
//}
//public List<T> GetList<T>(string connectionString, CommandType commandType, string commandText, ref CacheDependency cacheDependency, params IDbDataParameter[] commandParameters) where T: class, new()
//{
// List<T> list;
// if ((connectionString == null) || (connectionString.Length == 0))
// {
// throw new ArgumentNullException("connectionString");
// }
// SqlConnection connection = null;
// try
// {
// connection = new SqlConnection(connectionString);
// connection.Open();
// base.LogSql(commandText);
// list = this.GetList<T>(connection, null, commandType, commandText, commandParameters, DbConnectionOwnership.Internal, ref cacheDependency);
// }
// catch (Exception ex)
// {
// if (connection != null)
// {
// connection.Close();
// }
// throw ex;
// }
// return list;
//}
public List<T> GetList<T>(IDbConnection connection, IDbTransaction transaction, CommandType commandType, string commandText, IDbDataParameter[] commandParameters, DbConnectionOwnership connectionOwnership) where T: class, new()
{
List<T> returnList = null;
if (connection == null)
{
throw new ArgumentNullException("connection");
}
bool mustCloseConnection = false;
SqlCommand cmd = new SqlCommand();
try
{
SqlDataReader dataReader;
PrepareCommand(cmd, (SqlConnection) connection, (SqlTransaction) transaction, commandType, commandText, (SqlParameter[]) commandParameters, out mustCloseConnection);
base.CommandTrackLog(cmd.CommandText);
if (connectionOwnership == DbConnectionOwnership.External)
{
dataReader = cmd.ExecuteReader();
}
else
{
dataReader = cmd.ExecuteReader(CommandBehavior.CloseConnection);
}
bool canClear = true;
foreach (SqlParameter commandParameter in cmd.Parameters)
{
if (commandParameter.Direction != ParameterDirection.Input)
{
canClear = false;
}
}
if (canClear)
{
cmd.Parameters.Clear();
}
returnList = new List<T>();
returnList = EntityFactory.CreateInstance().FillEntityList<T>(dataReader);
}
catch (Exception ex)
{
base.ExceptionLog(ex, cmd.CommandText);
if (mustCloseConnection)
{
connection.Close();
}
throw ex;
}
finally
{
if (mustCloseConnection && (connection.State != ConnectionState.Closed))
{
connection.Close();
}
connection.Dispose();
}
return returnList;
}
//public List<T> GetList<T>(IDbConnection connection, IDbTransaction transaction, CommandType commandType, string commandText, IDbDataParameter[] commandParameters, DbConnectionOwnership connectionOwnership, ref CacheDependency cacheDependency) where T: class, new()
//{
// List<T> returnList = null;
// if (connection == null)
// {
// throw new ArgumentNullException("connection");
// }
// bool mustCloseConnection = false;
// SqlCommand cmd = new SqlCommand();
// try
// {
// SqlDataReader dataReader;
// PrepareCommand(cmd, (SqlConnection) connection, (SqlTransaction) transaction, commandType, commandText, (SqlParameter[]) commandParameters, out mustCloseConnection);
// base.LogSql(cmd.CommandText);
// if (connectionOwnership == DbConnectionOwnership.External)
// {
// dataReader = cmd.ExecuteReader();
// }
// else
// {
// dataReader = cmd.ExecuteReader(CommandBehavior.CloseConnection);
// }
// bool canClear = true;
// foreach (SqlParameter commandParameter in cmd.Parameters)
// {
// if (commandParameter.Direction != ParameterDirection.Input)
// {
// canClear = false;
// }
// }
// if (canClear)
// {
// cmd.Parameters.Clear();
// }
// cacheDependency = null;
// returnList = new List<T>();
// returnList = EntityHelper.FillList<T>(dataReader, this.GetListExceptionHandler);
// }
// catch (Exception ex)
// {
// base.LogException(ex, cmd.CommandText);
// if (mustCloseConnection)
// {
// connection.Close();
// }
// throw new DataBaseException("数据库操作异常", cmd.CommandText, ex);
// }
// finally
// {
// if (mustCloseConnection && (connection.State != ConnectionState.Closed))
// {
// connection.Close();
// }
// connection.Dispose();
// }
// return returnList;
//}
public IDataReader GetPageList(string tblName, int pageSize, int pageIndex, string fldSort, bool sort, string condition)
{
string sql = this.GetPagerSQL(condition, pageSize, pageIndex, fldSort, tblName, sort);
return this.ExecuteReader(this.ConnectionString, CommandType.Text, sql, null);
}
private string GetPagerSQL(string condition, int pageSize, int pageIndex, string fldSort, string tblName, bool sort)
{
string strSort = sort ? " DESC" : " ASC";
StringBuilder strSql = new StringBuilder("select * from " + tblName);
if (!string.IsNullOrEmpty(condition))
{
strSql.AppendFormat(" where {0} order by {1}{2}", condition, fldSort, strSort);
}
else
{
strSql.AppendFormat(" order by {0}{1}", fldSort, strSort);
}
strSql.AppendFormat(" limit {0},{1}", pageSize * (pageIndex - 1), pageSize);
return strSql.ToString();
}
private static void PrepareCommand(SqlCommand command, SqlConnection connection, SqlTransaction transaction, CommandType commandType, string commandText, SqlParameter[] commandParameters, out bool mustCloseConnection)
{
if (command == null)
{
throw new ArgumentNullException("command");
}
if ((commandText == null) || (commandText.Length == 0))
{
throw new ArgumentNullException("commandText");
}
if (connection.State != ConnectionState.Open)
{
mustCloseConnection = true;
connection.Open();
}
else
{
mustCloseConnection = false;
}
command.Connection = connection;
command.CommandText = commandText;
if (transaction != null)
{
if (transaction.Connection == null)
{
throw new ArgumentException("The transaction was rollbacked or commited, please provide an open transaction.", "transaction");
}
command.Transaction = transaction;
}
command.CommandType = commandType;
if (commandParameters != null)
{
AttachParameters(command, commandParameters);
}
}
public void UpdateDataset(SqlCommand insertCommand, SqlCommand deleteCommand, SqlCommand updateCommand, DataSet dataSet, string tableName)
{
if (insertCommand == null)
{
throw new ArgumentNullException("insertCommand");
}
if (deleteCommand == null)
{
throw new ArgumentNullException("deleteCommand");
}
if (updateCommand == null)
{
throw new ArgumentNullException("updateCommand");
}
if ((tableName == null) || (tableName.Length == 0))
{
throw new ArgumentNullException("tableName");
}
using (SqlDataAdapter dataAdapter = new SqlDataAdapter())
{
dataAdapter.UpdateCommand = updateCommand;
dataAdapter.InsertCommand = insertCommand;
dataAdapter.DeleteCommand = deleteCommand;
dataAdapter.Update(dataSet, tableName);
dataSet.AcceptChanges();
}
}
public string ConnectionString
{
get
{
return this._ConnectionString;
}
set
{
this._ConnectionString = value;
}
}
public IExceptionHandler GetListExceptionHandler
{
get
{
return this._ExceptionHandler;
}
set
{
this._ExceptionHandler = value;
}
}
}
}
|
namespace PICSimulator.Model.Commands
{
public abstract class PICCommand
{
public readonly string SourceCodeText; // Line in the src file
public readonly uint SourceCodeLine; // LineNmbr in the src file
public readonly uint Position;
public readonly uint Command;
protected readonly BinaryFormatParser Parameter;
public PICCommand(string sct, uint scl, uint pos, uint cmd)
{
SourceCodeText = sct;
SourceCodeLine = scl;
Position = pos;
Command = cmd;
Parameter = BinaryFormatParser.Parse(GetCommandCodeFormat(), cmd);
}
public override string ToString()
{
return string.Format("[{0:X04}] {1}:<{2:X04}> ({3}: {4})", Position, this.GetType().Name, Command, SourceCodeLine, SourceCodeText);
}
public abstract void Execute(PICController controller);
public abstract string GetCommandCodeFormat();
public abstract uint GetCycleCount(PICController controller);
}
}
|
#region 版本说明
/*****************************************************************************
*
* 项 目 :
* 作 者 : 李金坪
* 创建时间 : 2014/11/18 13:18:33
*
* Copyright (C) 2008 - 鹏业软件公司
*
*****************************************************************************/
#endregion
/*
<!--模块管理-->
<component id="ModelInfoServerSvr" type="PengeSoft.CMS.BaseDatum.ModelInfoServerSvr, PengeSoft.CMS.BaseDatum" service="PengeSoft.CMS.BaseDatum.IModelInfoServerSvr, PengeSoft.CMS.BaseDatum" lifestyle="Singleton">
<parameters>
</parameters>
</component>
*/
using System;
using System.Collections;
using System.Text;
using Castle.Windsor;
using PengeSoft.Data;
using PengeSoft.Enterprise.Appication;
using PengeSoft.WorkZoneData;
using PengeSoft.Common.Exceptions;
using PengeSoft.Auther.RightCheck;
using PengeSoft.Service;
using IBatisNet.DataAccess;
using PengeSoft.db.IBatis;
namespace PengeSoft.CMS.BaseDatum
{
/// <summary>
/// ModelInfoServerSvr实现。
/// </summary>
[PublishName("ModelInfoServer")]
public class ModelInfoServerSvr : PengeSoft.Service.Auther.UserAutherImp, IModelInfoServerSvr
{
protected IDaoManager _daoManager = null;
private IModelInfoDao _modelinfodao;
#region 服务描述
public override void FormActionList(AppActionList Acts)
{
base.FormActionList(Acts);
// 添加需发布的功能信息
}
public ModelInfoServerSvr()
{
_daoManager = ServiceConfig.GetInstance().DaoManager;
_modelinfodao = (IModelInfoDao)_daoManager.GetDao(typeof(IModelInfoDao));
}
public override void FormAttribsRec(PengeSoft.WorkZoneData.AppAttribBaseRec attr)
{
base.FormAttribsRec(attr);
attr.Detail = "模块管理";
}
#endregion
#region IModelInfoServerSvr 函数
/// <summary>
/// 获取模块总数
/// </summary>
/// <param name="uTag">登录标识</param>
/// <returns></returns>
[PublishMethod]
public int GetModelCount(string uTag)
{
if (CheckRight(uTag, "") == AutherCheckResult.OP_SUCESS)
{
return _modelinfodao.GetCount();
}
return 0;
}
/// <summary>
/// 获取模块列表
/// </summary>
/// <param name="uTag">登录标识</param>
/// <param name="currentPage">当前页</param>
/// <param name="PageSize">页大小</param>
/// <returns></returns>
[PublishMethod]
public ModelInfoList GetModelList(string uTag, int currentPage, int PageSize)
{
if (CheckRight(uTag, "") == AutherCheckResult.OP_SUCESS)
{
int start = 0;
start = (currentPage - 1) * PageSize;
DataList dlist = _modelinfodao.GetList(start, PageSize, null);
ModelInfoList result = new ModelInfoList();
result.AssignFrom(dlist);
return result;
}
return null;
}
/// <summary>
/// 新增模块
/// </summary>
/// <param name="uTag"></param>
/// <param name="modelInfo"></param>
/// <returns></returns>
[PublishMethod]
public int AddModelInfo(string uTag, ModelInfo modelInfo)
{
if (CheckRight(uTag, "") == AutherCheckResult.OP_SUCESS)
{
_modelinfodao.Insert(modelInfo);
return 0;
}
return -1;
}
/// <summary>
/// 删除模块
/// </summary>
/// <param name="uTag"></param>
/// <param name="mId"></param>
/// <returns></returns>
[PublishMethod]
public void DelModelInfo(string uTag, int mId)
{
if (CheckRight(uTag, "") == AutherCheckResult.OP_SUCESS)
{
ModelInfo model = new ModelInfo();
model.MId = mId;
_modelinfodao.Delete(model);
}
}
#endregion
}
} |
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace IBApi {
partial class ContractDetails {
static readonly ConcurrentDictionary<string, ContractDetails> ContractDetailsCache = new ConcurrentDictionary<string, ContractDetails>(StringComparer.OrdinalIgnoreCase);
public static void ClearCache() { ContractDetailsCache.Clear(); }
public ContractDetails AddToCache() { ContractDetailsCache.TryAdd(summary.AddToCache().Key, this); return this; }
public IEnumerable<ContractDetails> FromCache() => FromCache(summary);
public static IEnumerable<ContractDetails> FromCache(Contract contract) => FromCache(contract.Key);
public static IEnumerable<ContractDetails> FromCache(string instrument) {
if(ContractDetailsCache.TryGetValue(instrument, out var contract))
yield return contract;
}
public static IEnumerable<T> FromCache<T>(string instrument, Func<ContractDetails, T> map) {
if(ContractDetailsCache.TryGetValue(instrument, out var contract))
yield return map(contract);
}
public override string ToString() =>
base.ToString();
}
}
|
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using SGDE.Domain.Supervisor;
using SGDE.Domain.ViewModels;
using System;
namespace SGDE.API.Controllers
{
[Route("api/[controller]")]
[ApiController]
[Authorize]
public class AdvancesController : ControllerBase
{
private readonly ISupervisor _supervisor;
private readonly ILogger<AdvancesController> _logger;
public AdvancesController(ILogger<AdvancesController> logger, ISupervisor supervisor)
{
_logger = logger;
_supervisor = supervisor;
}
// GET api/advances/5
[HttpGet("{id}")]
public object Get(int id)
{
try
{
return _supervisor.GetAdvanceById(id);
}
catch (Exception ex)
{
_logger.LogError(ex, "Exception: ");
return StatusCode(500, ex);
}
}
[HttpGet]
public object Get()
{
try
{
var queryString = Request.Query;
var skip = Convert.ToInt32(queryString["$skip"]);
var take = Convert.ToInt32(queryString["$top"]);
var userId = Convert.ToInt32(queryString["userId"]);
var queryResult = _supervisor.GetAllAdvance(skip, take, userId);
return new { Items = queryResult.Data, Count = queryResult.Count };
}
catch (Exception ex)
{
_logger.LogError(ex, "Exception: ");
return StatusCode(500, ex);
}
}
[HttpPost]
public object Post([FromBody] AdvanceViewModel advanceViewModel)
{
try
{
var result = _supervisor.AddAdvance(advanceViewModel);
return result;
}
catch (Exception ex)
{
_logger.LogError(ex, "Exception: ");
return StatusCode(500, ex);
}
}
[HttpPut]
public object Put([FromBody] AdvanceViewModel advanceViewModel)
{
try
{
if (_supervisor.UpdateAdvance(advanceViewModel) && advanceViewModel.id != null)
{
return _supervisor.GetAdvanceById((int)advanceViewModel.id);
}
return null;
}
catch (Exception ex)
{
_logger.LogError(ex, "Exception: ");
return StatusCode(500, ex);
}
}
// DELETE: api/advances/5
[HttpDelete("{id:int}")]
//[Route("userdocument/{id:int}")]
public object Delete(int id)
{
try
{
return _supervisor.DeleteAdvance(id);
}
catch (Exception ex)
{
_logger.LogError(ex, "Exception: ");
return StatusCode(500, ex);
}
}
}
}
|
using ProBuilder2.Math;
using System;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
namespace ProBuilder2.Common
{
[Serializable]
public class pb_Edge : IEquatable<pb_Edge>
{
private struct pb_Range
{
public int min;
public int max;
public pb_Range(int min, int max)
{
this.min = min;
this.max = max;
}
public bool Contains(int x)
{
return x >= this.min && x <= this.max;
}
public override string ToString()
{
return string.Concat(new object[]
{
"(",
this.min,
", ",
this.max,
")"
});
}
}
public int x;
public int y;
public pb_Edge()
{
}
public pb_Edge(int _x, int _y)
{
this.x = _x;
this.y = _y;
}
public pb_Edge(pb_Edge edge)
{
this.x = edge.x;
this.y = edge.y;
}
public bool IsValid()
{
return this.x > -1 && this.y > -1 && this.x != this.y;
}
public override string ToString()
{
return string.Concat(new object[]
{
"[",
this.x,
", ",
this.y,
"]"
});
}
public bool Equals(pb_Edge edge)
{
return (this.x == edge.x && this.y == edge.y) || (this.x == edge.y && this.y == edge.x);
}
public override bool Equals(object b)
{
return b is pb_Edge && (this.x == ((pb_Edge)b).x || this.x == ((pb_Edge)b).y) && (this.y == ((pb_Edge)b).x || this.y == ((pb_Edge)b).y);
}
public override int GetHashCode()
{
int hashCode;
int hashCode2;
if (this.x < this.y)
{
hashCode = this.x.GetHashCode();
hashCode2 = this.y.GetHashCode();
}
else
{
hashCode = this.y.GetHashCode();
hashCode2 = this.x.GetHashCode();
}
return hashCode ^ hashCode2;
}
public int[] ToArray()
{
return new int[]
{
this.x,
this.y
};
}
public bool Equals(pb_Edge b, pb_IntArray[] sharedIndices)
{
int num = sharedIndices.IndexOf(this.x);
int[] arg_32_0;
if (num > -1)
{
arg_32_0 = sharedIndices[num].array;
}
else
{
(arg_32_0 = new int[1])[0] = this.x;
}
int[] a = arg_32_0;
num = sharedIndices.IndexOf(this.y);
int[] arg_63_0;
if (num > -1)
{
arg_63_0 = sharedIndices[num].array;
}
else
{
(arg_63_0 = new int[1])[0] = this.y;
}
int[] a2 = arg_63_0;
num = sharedIndices.IndexOf(b.x);
int[] arg_94_0;
if (num > -1)
{
arg_94_0 = sharedIndices[num].array;
}
else
{
(arg_94_0 = new int[1])[0] = b.x;
}
int[] b2 = arg_94_0;
num = sharedIndices.IndexOf(b.y);
int[] arg_C5_0;
if (num > -1)
{
arg_C5_0 = sharedIndices[num].array;
}
else
{
(arg_C5_0 = new int[1])[0] = b.y;
}
int[] b3 = arg_C5_0;
return (a.ContainsMatch(b2) || a.ContainsMatch(b3)) && (a2.ContainsMatch(b2) || a2.ContainsMatch(b3));
}
public bool Equals(pb_Edge b, Dictionary<int, int> lookup)
{
int num = lookup.get_Item(this.x);
int num2 = lookup.get_Item(this.y);
int num3 = lookup.get_Item(b.x);
int num4 = lookup.get_Item(b.y);
return (num == num3 && num2 == num4) || (num == num4 && num2 == num3);
}
public bool Contains(int a)
{
return this.x == a || this.y == a;
}
public bool Contains(int a, pb_IntArray[] sharedIndices)
{
int num = sharedIndices.IndexOf(a);
return Array.IndexOf<int>(sharedIndices[num], this.x) > -1 || Array.IndexOf<int>(sharedIndices[num], this.y) > -1;
}
public static pb_Edge[] GetUniversalEdges(pb_Edge[] edges, Dictionary<int, int> sharedIndicesLookup)
{
pb_Edge[] array = new pb_Edge[edges.Length];
for (int i = 0; i < edges.Length; i++)
{
array[i] = new pb_Edge(sharedIndicesLookup.get_Item(edges[i].x), sharedIndicesLookup.get_Item(edges[i].y));
}
return array;
}
public static pb_Edge[] GetUniversalEdges(pb_Edge[] edges, pb_IntArray[] sharedIndices)
{
int num = edges.Length;
int num2 = sharedIndices.Length;
pb_Edge.pb_Range[] array = new pb_Edge.pb_Range[sharedIndices.Length];
for (int i = 0; i < num2; i++)
{
array[i] = new pb_Edge.pb_Range(pb_Math.Min<int>(sharedIndices[i].array), pb_Math.Max<int>(sharedIndices[i].array));
}
pb_Edge[] array2 = new pb_Edge[num];
for (int j = 0; j < num; j++)
{
int num3 = -1;
int num4 = -1;
for (int k = 0; k < num2; k++)
{
if (array[k].Contains(edges[j].x))
{
for (int l = 0; l < sharedIndices[k].Length; l++)
{
if (sharedIndices[k][l] == edges[j].x)
{
num3 = k;
break;
}
}
if (num3 > -1)
{
break;
}
}
}
for (int m = 0; m < num2; m++)
{
if (array[m].Contains(edges[j].y))
{
for (int n = 0; n < sharedIndices[m].Length; n++)
{
if (sharedIndices[m][n] == edges[j].y)
{
num4 = m;
break;
}
}
if (num4 > -1)
{
break;
}
}
}
array2[j] = new pb_Edge(num3, num4);
}
return array2;
}
public static pb_Edge GetUniversalEdge(pb_Edge edge, pb_IntArray[] sharedIndices)
{
return new pb_Edge(sharedIndices.IndexOf(edge.x), sharedIndices.IndexOf(edge.y));
}
public static pb_Edge GetLocalEdge(pb_Object pb, pb_Edge edge)
{
pb_Face[] faces = pb.faces;
pb_IntArray[] sharedIndices = pb.sharedIndices;
int num = -1;
int num2 = -1;
int num3 = -1;
int num4 = -1;
for (int i = 0; i < faces.Length; i++)
{
if (faces[i].distinctIndices.ContainsMatch(sharedIndices[edge.x].array, out num, out num3) && faces[i].distinctIndices.ContainsMatch(sharedIndices[edge.y].array, out num2, out num4))
{
int num5 = faces[i].distinctIndices[num];
int num6 = faces[i].distinctIndices[num2];
return new pb_Edge(num5, num6);
}
}
return null;
}
public static bool ValidateEdge(pb_Object pb, pb_Edge edge, out pb_Edge validEdge)
{
pb_Face[] faces = pb.faces;
pb_IntArray[] sharedIndices = pb.sharedIndices;
pb_Edge universalEdge = pb_Edge.GetUniversalEdge(edge, sharedIndices);
int num = -1;
int num2 = -1;
int num3 = -1;
int num4 = -1;
for (int i = 0; i < faces.Length; i++)
{
if (faces[i].distinctIndices.ContainsMatch(sharedIndices[universalEdge.x].array, out num, out num3) && faces[i].distinctIndices.ContainsMatch(sharedIndices[universalEdge.y].array, out num2, out num4))
{
int num5 = faces[i].distinctIndices[num];
int num6 = faces[i].distinctIndices[num2];
validEdge = new pb_Edge(num5, num6);
return true;
}
}
validEdge = edge;
return false;
}
public static pb_Edge[] GetLocalEdges_Fast(pb_Edge[] edges, pb_IntArray[] sharedIndices)
{
pb_Edge[] array = new pb_Edge[edges.Length];
for (int i = 0; i < array.Length; i++)
{
array[i] = new pb_Edge(sharedIndices[edges[i].x][0], sharedIndices[edges[i].y][0]);
}
return array;
}
public static pb_Edge[] AllEdges(pb_Face[] faces)
{
List<pb_Edge> list = new List<pb_Edge>();
for (int i = 0; i < faces.Length; i++)
{
pb_Face pb_Face = faces[i];
list.AddRange(pb_Face.edges);
}
return list.ToArray();
}
public static bool ContainsDuplicateFast(pb_Edge[] edges, pb_Edge edge)
{
int num = 0;
for (int i = 0; i < edges.Length; i++)
{
if (edges[i].Equals(edge))
{
num++;
}
}
return num > 1;
}
public static Vector3[] VerticesWithEdges(pb_Edge[] edges, Vector3[] vertices)
{
Vector3[] array = new Vector3[edges.Length * 2];
int num = 0;
for (int i = 0; i < edges.Length; i++)
{
array[num++] = vertices[edges[i].x];
array[num++] = vertices[edges[i].y];
}
return array;
}
public static pb_Edge[] GetPerimeterEdges(pb_Edge[] edges)
{
int[] count = pbUtil.FilledArray<int>(0, edges.Length);
for (int i = 0; i < edges.Length - 1; i++)
{
for (int j = i + 1; j < edges.Length; j++)
{
if (edges[i].Equals(edges[j]))
{
count[i]++;
count[j]++;
}
}
}
return Enumerable.ToArray<pb_Edge>(Enumerable.Where<pb_Edge>(edges, (pb_Edge val, int index) => count[index] < 1));
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Sample_Reflection
{
class Program
{
static void Main(string[] args)
{
//使用者輸入
System.Console.Write("請輸入您的交通工具類型(1.摩托車;2.汽車):");
int iMachineType = System.Convert.ToInt32(System.Console.ReadLine());
System.Console.Write("請輸入您的交通工具匿稱:");
string cTargetName = System.Console.ReadLine();
string cTargetClassName = "Sample_Reflection.Program+Transportation";
string cTargetProperty = "Name";
string cTargetMethodName = "Wheels";
System.Object oTemp = System.Activator.CreateInstance(System.Type.GetType(cTargetClassName));
System.Type oTypeBase = System.Type.GetType(cTargetClassName);
//設定與展示物件的名稱屬性
System.Reflection.PropertyInfo oProperty = oTypeBase.GetProperty(cTargetProperty);
oProperty.SetValue(oTemp, cTargetName);
System.Console.Write("您的愛車{0}", oProperty.GetValue(oTemp));
//依使用者選擇的「字串」,動態轉換物件去調用介面成員
System.Object oEntity;
switch (iMachineType)
{
case 2:
oTypeBase = System.Type.GetType("Sample_Reflection.Program+ICar");
oEntity = (ICar)oTemp;
break;
default:
oTypeBase = System.Type.GetType("Sample_Reflection.Program+IBike");
oEntity = (IBike)oTemp;
break;
}
System.Reflection.MethodInfo oMethod = oTypeBase.GetMethod(cTargetMethodName);
System.Console.WriteLine("擁有{0}顆輪子。", oMethod.Invoke(oEntity, null));
System.Console.Read();
}
class Transportation : ICar, IBike
{
public string Name { get; set; }
int ICar.Wheels() { return 4; }
int IBike.Wheels() { return 2; }
}
//小客車介面
interface ICar
{
int Wheels();
}
//機踏車介面
interface IBike
{
int Wheels();
}
}
} |
using Cappta.Gp.Api.Com.Model;
using PDV.VIEW.FRENTECAIXA;
using System;
using System.Windows.Forms;
namespace Cappta.Gp.Api.Com.Sample.Model
{
public class Notificable
{
public void CriarMensagemErroJanela(string mensagem)
{
MessageBox.Show(mensagem, "Erro");
}
public string ExibirMensagem(IMensagem mensagem)
{
return mensagem.Descricao;
}
public string GerarMensagemTransacaoAprovada()
{
string mensagem = String.Format("Transaç Aprovada!!! Clique em \"OK\" para confirmar a transaç e \"Cancelar\" para desfaze-la.",
Environment.NewLine);
return mensagem;
}
public string CriarMensagemErroPainel(int resultado)
{
String mensagem = Mensagens.ResourceManager.GetString(String.Format("RESULTADO_CAPPTA_{0}", resultado));
if (String.IsNullOrEmpty(mensagem)) { mensagem = "Não foi possível executar a operação."; }
return String.Format("{0}. Código de erro {1}", mensagem, resultado);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using WebBanHang_FoodHub.Model;
namespace WebBanHang_FoodHub.DataUtil
{
public class DataCategory
{
SqlConnection conn = null;
SqlCommand cmd = null;
SqlDataReader dr = null;
public DataCategory()
{
conn = Connection.Connect();
}
public List<Category> ListCategory()
{
conn.Open();
List<Category> listProducts = new List<Category>();
String sql = "SELECT CategoryId,CategoryName FROM Category";
cmd = new SqlCommand(sql, conn);
dr = cmd.ExecuteReader();
while (dr.Read())
{
Category dv = new Category();
dv.CategoryId = int.Parse(dr["CategoryId"].ToString());
dv.CategoryName = dr["CategoryName"].ToString();
listProducts.Add(dv);
}
conn.Close();
return listProducts;
}
public Category FindByProductId(int productId)
{
conn.Open();
string sql = "select Product.CategoryId, CategoryName, Origin, Manufacturer, Active, Description from Category inner join Product on Category.CategoryId = Product.CategoryId where Product.ProductId = @ProductId";
cmd = new SqlCommand(sql, conn);
cmd.Parameters.AddWithValue("ProductId", productId);
dr = cmd.ExecuteReader();
Category dv = null;
while (dr.Read())
{
dv = new Category();
dv.CategoryId = int.Parse(dr["CategoryId"].ToString());
dv.CategoryName = dr["CategoryName"].ToString();
dv.Origin = dr["Origin"].ToString();
dv.Manufacturer = dr["Manufacturer"].ToString();
dv.Active = int.Parse(dr["Active"].ToString());
dv.Description = dr["Description"].ToString();
}
conn.Close();
return dv;
}
}
} |
using App.Entity;
namespace App.Data
{
/// <seealso cref="App.Data.BasicDAC{App.Entity.UserBE, App.Data.UserDAC}" />
public class UserDAC : BasicDAC<UserBE, UserDAC>
{
/// <summary>
/// Initializes a new instance of the <see cref="UserDAC"/> class.
/// </summary>
public UserDAC() : base(ContextVariables.Source, "User") { }
}
}
|
using MCC.Plugin;
using MCC.Plugin.Win;
using MCC.Utility;
using MCC.Utility.Net;
using MCC.Utility.Text;
using System.Collections;
using System.Collections.Generic;
using System.Threading.Tasks;
using System.Windows;
namespace MCC.Youtube
{
public class Youtube : IPluginSender, ISetting, ILogged
{
private Setting setting = Setting.Instance;
private YoutubeConnector connector = new();
private Hashtable table = new();
public string SiteName => "Youtube";
public string StreamKey { get; set; }
public string Author => "ぽんた";
public string PluginName => "Youtube";
public string Description => "YoutubeLiveのコメントを取得します。";
public string Version => "1.0.0.0";
public string MenuItemName => "設定";
public event CommentReceivedEventHandler OnCommentReceived;
public event LoggedEventHandler OnLogged;
public bool Activate()
{
connector.Resume = true;
Task.Run(() => connector.Connect(setting.APIKey, StreamKey));
return true;
}
public bool Inactivate()
{
connector.Resume = false;
connector.Abort();
return true;
}
public bool IsSupport(string url)
{
StreamKey = url.RegexString(@"https://www.youtube.com/channel/(?<value>[\w\-]+)", "value");
if (!string.IsNullOrEmpty(StreamKey) && !string.IsNullOrEmpty(Http.Get($"https://www.youtube.com/feeds/videos.xml?channel_id={StreamKey}")))
{
return true;
}
return false;
}
public void PluginClose() => Inactivate();
public void PluginLoad()
{
connector.OnLogged += BaseLogged;
connector.OnReceived += OnReceived;
table["Streamer"] = new AdditionalData() { Data = "Streamer", Description = "Streamer" };
table["M"] = new AdditionalData() { Data = "M", Description = "モデレーター" };
table["S"] = new AdditionalData() { Data = "S", Description = "スポンサー" };
}
private void OnReceived(object sender, ChatReceivedEventArgs e)
{
foreach (var item in e.ReceiveData.items)
{
var list = new List<AdditionalData>();
var commentData = new CommentData()
{
LiveName = "Youtube",
PostTime = item.snippet.publishedAt,
Comment = item.snippet.displayMessage,
UserName = item.authorDetails.displayName,
UserID = item.authorDetails.channelId
};
if (item.authorDetails.isChatOwner)
{
list.Add(table["Streamer"] as AdditionalData);
}
if (item.authorDetails.isChatModerator)
{
list.Add(table["M"] as AdditionalData);
}
if (item.authorDetails.isChatSponsor)
{
list.Add(table["S"] as AdditionalData);
}
if (item.snippet.type.Equals("superChatEvent"))
{
list.Add(new AdditionalData() { Data = "$$", Description = $"スパチャ : {item.snippet.superChatDetails.amountDisplayString}", Enable = true });
commentData.Comment = item.snippet.superChatDetails.userComment;
}
commentData.Additional = list.ToArray();
OnCommentReceived?.Invoke(this, new(commentData));
}
}
public void ShowWindow(Window window)
{
window.Title = "Twitch設定";
window.Closed += (_, _) => setting.Save();
window.Content = new SettingPage();
window.SizeToContent = SizeToContent.WidthAndHeight;
window.WindowStartupLocation = WindowStartupLocation.CenterOwner;
window.Show();
}
private void BaseLogged(object sender, LoggedEventArgs e) => OnLogged?.Invoke(this, e);
}
}
|
using Renting.Domain.Apartments;
using Renting.Domain.Drafts;
namespace Renting.Domain.Offers
{
public class Offer
{
public OfferId Id;
private Period _period;
private OwnerId _ownerId;
private Apartment _apartment;
private Price _pricePerDay;
private Price _deposit;
public Offer(Period period, OwnerId ownerId, Apartment apartment, Price pricePerDay, OfferId offerId, Price deposit)
{
Id = offerId;
_period = period;
_ownerId = ownerId;
_apartment = apartment;
_pricePerDay = pricePerDay;
_deposit = deposit;
}
public Draft Choose(TenantId tenantId, Period period, DraftFactory draftFactory)
{
return draftFactory.Create(_ownerId, tenantId, _apartment, period, _pricePerDay, Id, _deposit);
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Core;
namespace Wordlist
{
class UserInterface
{
/*
public static void Main()
{
Console.WriteLine("Input command please(split with space)");
string CommandInput = Console.ReadLine();
Console.WriteLine("Command input: [" + CommandInput + "]");
string[] CommandInputArray = CommandInput.Split(' ');
WordListCommandLineSolver.CoreCommandLineSolver(CommandInputArray);
Console.WriteLine("Output file: solution.txt");
Console.WriteLine("-----------Result-----------------");
var ResultReader = new FileReader("solution.txt");
ResultReader.ReadFile();
string[] result = ResultReader.FileData;
foreach (string word in result)
{
if(word != null)
Console.WriteLine(word);
}
Console.WriteLine("------------------------------");
Console.WriteLine("Press any key to exit");
Console.Read();
}
*/
}
}
|
using System;
using System.Collections.Generic;
using Acr.UserDialogs;
using City_Center.Clases;
using City_Center.Helper;
using Xamarin.Forms;
namespace City_Center.Page
{
public partial class DetallePromocion : ContentPage
{
public DetallePromocion()
{
InitializeComponent();
NavigationPage.SetTitleIcon(this, "logo@2x.png");
App.NavPage.BarBackgroundColor = Color.FromHex("#23144B");
}
protected override void OnAppearing()
{
base.OnAppearing();
App.NavPage.BarBackgroundColor = Color.FromHex("#23144B");
}
protected override void OnDisappearing()
{
base.OnDisappearing();
ActualizaBarra.Cambio(VariablesGlobales.VentanaActual);
GC.Collect();
}
async void Chat_click(object sender, System.EventArgs e)
{
bool isLoggedIn = Application.Current.Properties.ContainsKey("IsLoggedIn") ?
(bool)Application.Current.Properties["IsLoggedIn"] : false;
if (isLoggedIn)
{
await ((MasterPage)Application.Current.MainPage).Detail.Navigation.PushAsync(new SeleccionTipoChat());
}
else
{
await Mensajes.Alerta("Es necesario que te registres para completar esta acción");
}
}
async void FechaSolicitada_Tapped(object sender, System.EventArgs e)
{
#if __IOS__
DependencyService.Get<IForceKeyboardDismissalService>().DismissKeyboard();
#endif
var result = await UserDialogs.Instance.DatePromptAsync(new DatePromptConfig
{
IsCancellable = true,
CancelText = "CANCELAR",
});
if (result.Ok)
{
FechaSolicitada.Text = String.Format("{0:dd/MM/yyyy}", result.SelectedDate);
FechaSolicitada.Unfocus();
DependencyService.Get<IForceKeyboardDismissalService>().DismissKeyboard();
}
else
{
FechaSolicitada.Unfocus();
DependencyService.Get<IForceKeyboardDismissalService>().DismissKeyboard();
}
}
async void Fecha_Tapped(object sender, System.EventArgs e)
{
#if __IOS__
DependencyService.Get<IForceKeyboardDismissalService>().DismissKeyboard();
#endif
var result = await UserDialogs.Instance.DatePromptAsync(new DatePromptConfig
{
IsCancellable = true,
CancelText = "CANCELAR",
});
if (result.Ok)
{
Fecha.Text = String.Format("{0:dd/MM/yyyy}", result.SelectedDate);
Fecha.Unfocus();
DependencyService.Get<IForceKeyboardDismissalService>().DismissKeyboard();
}
else
{
Fecha.Unfocus();
DependencyService.Get<IForceKeyboardDismissalService>().DismissKeyboard();
}
}
async void FechaNacimiento_Tapped(object sender, System.EventArgs e)
{
#if __IOS__
DependencyService.Get<IForceKeyboardDismissalService>().DismissKeyboard();
#endif
var result = await UserDialogs.Instance.DatePromptAsync(new DatePromptConfig
{
IsCancellable = true,
CancelText = "CANCELAR",
});
if (result.Ok)
{
FechaNacimiento.Text = String.Format("{0:dd/MM/yyyy}", result.SelectedDate);
FechaNacimiento.Unfocus();
DependencyService.Get<IForceKeyboardDismissalService>().DismissKeyboard();
}
else
{
FechaNacimiento.Unfocus();
DependencyService.Get<IForceKeyboardDismissalService>().DismissKeyboard();
}
}
}
}
|
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Jieshai
{
public class JsonConvertHelper
{
public static bool TryConvert<T>(string json, out T t)
{
t = default(T);
try
{
t = JsonConvert.DeserializeObject<T>(json);
if (t == null)
{
return false;
}
return true;
}
catch
{
return false;
}
}
public static bool TrySerializeObject(object obj, out string json)
{
json = "";
try
{
json = JsonConvert.SerializeObject(obj);
return true;
}
catch
{
return false;
}
}
public static string SerializeObject(object obj)
{
try
{
return JsonConvert.SerializeObject(obj);
}
catch
{
return "";
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using CsvHelper;
using DevExpress.Mvvm.POCO;
namespace InsightsAnalyser.Models
{
public class QueryDataFactory
{
private readonly string _fileName;
public QueryDataFactory(string fileName)
{
_fileName = fileName;
}
public List<QueryData> Get()
{
using (var reader = new StringReader(File.ReadAllText(_fileName)))
{
var csv = new CsvReader(reader);
var records = csv.GetRecords<QueryData>().ToList();
var grouped =
from r in records
group r by new
{
r.timestamp,
r.name,
r.itemType,
r.operation_Name,
r.operation_Id,
r.operation_ParentId,
r.operation_SyntheticSource,
r.session_Id,
r.user_Id,
r.user_AuthenticatedId,
r.user_AccountId,
r.application_Version,
r.client_Type,
r.client_Model,
r.client_OS,
r.client_IP,
r.client_City,
r.client_StateOrProvince,
r.client_CountryOrRegion,
r.client_Browser,
r.cloud_RoleName,
r.cloud_RoleInstance,
r.appId,
r.appName,
r.iKey,
r.sdkVersion,
r.itemCount,
r.customMeasurements
}
into g
select new QueryData()
{
timestamp = g.Key.timestamp,
name = g.Key.name,
itemType = g.Key.itemType,
operation_Name = g.Key.operation_Name,
operation_Id = g.Key.operation_Id,
operation_ParentId = g.Key.operation_ParentId,
operation_SyntheticSource = g.Key.operation_SyntheticSource,
session_Id = g.Key.session_Id,
user_Id = g.Key.user_Id,
user_AuthenticatedId = g.Key.user_AuthenticatedId,
user_AccountId = g.Key.user_AccountId,
application_Version = g.Key.application_Version,
client_Type = g.Key.client_Type,
client_Model = g.Key.client_Model,
client_OS = g.Key.client_OS,
client_IP = g.Key.client_IP,
client_City = g.Key.client_City,
client_StateOrProvince = g.Key.client_StateOrProvince,
client_CountryOrRegion = g.Key.client_CountryOrRegion,
client_Browser = g.Key.client_Browser,
cloud_RoleName = g.Key.cloud_RoleName,
cloud_RoleInstance = g.Key.cloud_RoleInstance,
appId = g.Key.appId,
appName = g.Key.appName,
iKey = g.Key.iKey,
sdkVersion = g.Key.sdkVersion,
itemCount = g.Key.itemCount,
customMeasurements = g.Key.customMeasurements,
customDimensions = g.Select(x => x.customDimensions).First(),
itemId = g.Select(x => x.itemId).First()
};
var onesILike = grouped.Where(x => x.itemId == new Guid("c5f6fc65-6023-11e8-a6e7-f10671242c42") || x.itemId == new Guid("cc7e6f09-6023-11e8-949c-8b1239809af7")).ToArray();
return grouped.ToList();
}
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Sockets;
namespace cMud2
{
public partial class MudCommunication
{
private static MudCommunication Instance;
public static MudCommunication GetInstance()
{
if (Instance == null)
Instance = new MudCommunication();
return Instance;
}
#region 字段
TcpClient _tcpClient = new TcpClient();
NetworkStream _stream;
byte[] _rcvBuffer = new byte[1024 * 64];
IncomingTextProcessor _textProcessor = IncomingTextProcessor.GetInstance();
TelnetParser _telnetParser;
ANSIColorParser _ansiColorParser = new ANSIColorParser();
Queue<string> _queueCmds = new Queue<string>();//命令队列
int fadai;//发呆时间
#endregion
#region 事件定义
//disconnection callback and handler definition
public event disconnectionEventHandler disconnected;
public delegate void disconnectionEventHandler();
//incoming message callback and handler definition
public event serverMessageEventHandler serverMessage;
public delegate void serverMessageEventHandler(List<MUDTextRun> runs);
//incoming telnet control sequence callback and handler definition
public event serverTelnetEventHandler telnetMessage;
public delegate void serverTelnetEventHandler(string message);
public event FadaiEventHandler FadaiHandler;
public delegate void FadaiEventHandler();
#endregion
#region 构造函数
private MudCommunication()
{
System.Threading.Thread td = new System.Threading.Thread(new System.Threading.ThreadStart(new Action(() =>
{
while (true)
{
System.Threading.Thread.Sleep(100);
CheckFadai();
GlobalVariable.Ticks++;
}
})));
td.IsBackground = true;
td.Start();
}
#endregion
//called when receiving any message
void handleServerMessage(IAsyncResult result)
{
try
{
NetworkStream ns;
//get length of data in buffer
int receivedCount;
try
{
ns = (NetworkStream)result.AsyncState;
receivedCount = ns.EndRead(result);
}
catch
{
//if there was any issue reading the server text, ignore the message (what else can we do?)
return;
}
//0 bytes received means the server disconnected
if (receivedCount == 0)
{
this.Disconnect();
return;
}
//list of bytes which aren't telnet sequences
//ultimately, this will be the original buffer minus any telnet messages from the server
List<string> telnetMessages;
List<byte> contentBytes = this._telnetParser.HandleAndRemoveTelnetBytes(this._rcvBuffer, receivedCount, out telnetMessages);
//report any telnet sequences seen to the caller
App.Current.Dispatcher.BeginInvoke(new Action(delegate
{
foreach (string telnetMessage in telnetMessages)
{
//fire the "received a server message" event
this.telnetMessage(telnetMessage);
}
}));
//now we've filtered-out and responded accordingly to any telnet data.
//next, convert the actual MUD content of the message from ASCII to Unicode
string message = AsciiDecoder.AsciiToUnicode(contentBytes.ToArray(), contentBytes.Count);
_textProcessor.AllText += message;
_textProcessor.CurrentText = message;
_textProcessor.ProcessText();
//run the following on the main thread so that calling code doesn't have to think about threading
if (this.serverMessage != null)
{
App.Current.Dispatcher.BeginInvoke(new Action(delegate
{
//pass the message to the mudTranslator to parse any ANSI control sequences (colors!)
List<MUDTextRun> runs = this._ansiColorParser.Translate(message);
//fire the "received a server message" event with the runs to be displayed
this.serverMessage(runs);
}));
}
//now that we're done with this message, listen for the next message
ns.BeginRead(_rcvBuffer, 0, _rcvBuffer.Length, new AsyncCallback(handleServerMessage), _stream);
}
catch (Exception e)
{
System.Windows.MessageBox.Show(e.Message + "\r\n" + e.StackTrace);
}
}
public void TestMessage(string text)
{
string message = text;
_textProcessor.AllText += message;
_textProcessor.CurrentText = message;
_textProcessor.ProcessText();
//run the following on the main thread so that calling code doesn't have to think about threading
if (this.serverMessage != null)
{
App.Current.Dispatcher.BeginInvoke(new Action(delegate
{
//pass the message to the mudTranslator to parse any ANSI control sequences (colors!)
List<MUDTextRun> runs = this._ansiColorParser.Translate(message);
//fire the "received a server message" event with the runs to be displayed
this.serverMessage(runs);
}));
}
}
public void CheckFadai()
{
fadai++;
if (fadai >= GlobalParams.Fadai)
{
SendText("#test 发呆了~,开始启动发呆处理程序~");
if (FadaiHandler != null)
{
SendText("fd");
FadaiHandler();
}
fadai = 0;
}
if (GlobalVariable.Ticks % 200 == 0 && GlobalVariable.Ticks>500)
{
_alias.SaveAlias();
CustomVariable.SaveVariable();
TestMessage(".......................................");
}
if (GlobalParams.Timer != 0)
{
if (GlobalVariable.Ticks % GlobalParams.Timer == 0)
{
SendText("timer");
}
}
}
private void Send(string cmd)
{
cmd = cmd + "\r\n";
byte[] sndBuffer = Encoding.Default.GetBytes(cmd);
string outText = AsciiDecoder.AsciiToUnicode(sndBuffer, sndBuffer.Length);
_textProcessor.AllText += outText;
List<MUDTextRun> runs = this._ansiColorParser.Translate((char)27 + "[1;33m" + cmd.Replace("\r\n", "") + (char)27 + "[0;66m");
//fire the "received a server message" event with the runs to be displayed
App.Current.Dispatcher.BeginInvoke(new Action(() =>
{
if (serverMessage != null)
this.serverMessage(runs);
}));
try
{
//send to server
_stream.Write(sndBuffer, 0, sndBuffer.Length);
}
catch (Exception e)
{
Disconnect();
Connect("mud.pkuxkx.net", 8080);
}
}
public void SendText(string text)
{
// if (!this._tcpClient.Connected) return;
try
{
fadai = 0;
System.Threading.Thread td = new System.Threading.Thread(new System.Threading.ThreadStart(new Action(() =>
{
ExecuteCommandLine(text);
})));
td.IsBackground = true;
td.Start();
}
catch (Exception e)
{
System.Windows.MessageBox.Show(e.Message + "\r\n" + e.StackTrace);
}
}
internal void Connect(string address, int port)
{
try
{
_tcpClient.Connect(address, port);
}
catch (Exception e)
{
this.Disconnect();
this.Connect("mud.pkuxkx.net", 8080);
}
if (this._tcpClient.Connected)
{
//initialize the telnet parser
this._telnetParser = new TelnetParser(this._tcpClient);
_stream = _tcpClient.GetStream();
_stream.BeginRead(_rcvBuffer, 0, _rcvBuffer.Length, new AsyncCallback(handleServerMessage), _stream);
this._telnetParser.sendTelnetBytes((byte)Telnet.WILL, (byte)Telnet.NAWS);
}
}
internal void Disconnect()
{
//if not connected, do nothing
//close the connection
this._tcpClient.Close();
//initialize a new object
this._tcpClient = new TcpClient();
//fire disconnection notification event on main UI thread
if (this.disconnected != null)
{
App.Current.Dispatcher.BeginInvoke(new Action(delegate
{
this.disconnected.Invoke();
}));
}
}
}
}
|
using System;
using System.Linq;
using MenuSample.Scenes.Core;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Xspace;
namespace MenuSample.Scenes
{
/// <summary>
/// Un écran de chargement
/// </summary>
public class SongInfo : AbstractGameScene
{
private string songname;
private KeyboardState keyboardstate;
private GraphicsDeviceManager graphics;
private LoadSong song;
private bool ready;
/// <summary>
/// Le constructeur est privé: le chargement des scènes
/// doit être lancé via la méthode statique Load.
/// </summary>
private SongInfo(SceneManager sceneMgr, string songname, GraphicsDeviceManager graphics)
: base(sceneMgr)
{
this.songname = songname;
this.graphics = graphics;
ready = false;
song = new LoadSong(songname);
keyboardstate = new KeyboardState();
TransitionOnTime = TimeSpan.FromSeconds(1);
TransitionOffTime = TimeSpan.FromSeconds(2);
}
/// <summary>
/// Active la scène de chargement.
/// </summary>
public static void Load(SceneManager sceneMgr, string songname, GraphicsDeviceManager graphics)
{
new SongInfo(sceneMgr, songname, graphics).Add();
}
public override void Update(GameTime gameTime, bool othersceneHasFocus, bool coveredByOtherscene)
{
base.Update(gameTime, othersceneHasFocus, coveredByOtherscene);
keyboardstate = Keyboard.GetState();
if (keyboardstate.IsKeyUp(Keys.Enter))
ready = true;
if (keyboardstate.IsKeyDown(Keys.Escape))
Remove();
if (ready && keyboardstate.IsKeyDown(Keys.Enter))
{
ready = false;
Remove();
LoadingScene.Load(SceneManager, true, new GameplayScene(SceneManager, graphics, 0, 0, GameplayScene.GAME_MODE.LIBRE, songname));
}
}
public override void Draw(GameTime gameTime)
{
SpriteBatch spriteBatch = SceneManager.SpriteBatch;
SpriteFont font = SceneManager.Font;
string message = "";
message += "Titre : " + song.title + "\n";
if (song.album != "")
message += "Album : " + song.album + "\n";
if (song.singer != "")
message += song.singer;
if (song.singer != "" && song.year != "")
message += " - ";
if (song.year != "")
message += song.year;
message += "\n\n";
Viewport viewport = SceneManager.GraphicsDevice.Viewport;
var viewportSize = new Vector2(viewport.Width, viewport.Height);
Vector2 textSize = font.MeasureString(message);
Vector2 textPosition = (viewportSize - textSize) / 2;
Color color = Color.White * TransitionAlpha;
spriteBatch.Begin();
spriteBatch.DrawString(font, message, textPosition, color);
spriteBatch.End();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Microsoft.SharePoint;
using Waffles;
using Waffles.UserControls;
public partial class admin_modal_tools : AdminModal
{
public override void Build()
{
Modal.Label.Append("<i class='fa fa-wrench'></i> Tools");
Modal.FormAction = "/_admin/tools";
/*
if (REQUEST.Count > 3)
{
DataOutput.Add("tools", (object)true ?? WContext.Current.POST);
if (WContext.Current.POST.ContainsKey("XmlConvert_EncodeName"))
DataOutput.Add("XmlConvert_EncodeName", System.Xml.XmlConvert.EncodeName(WContext.Current.POST["XmlConvert_EncodeName"]));
Redirect = null;
return;
}
*/
WSPEdit.FieldsDelete(WContext.Current.RootWeb.Lists["Navigation"], new string[]{
"URL0","Order00","Menus0","Item_x0020_Guid0","Web_x0020_Guid0","Unpublished0","URL0","Order01","Menus1",
"Item_x0020_Guid1","Web_x0020_Guid1","Unpublished1","URL0","Order02","Menus2","Item_x0020_Guid2",
"Web_x0020_Guid2","Unpublished2","URL0","Order03","Menus3","Item_x0020_Guid3","Web_x0020_Guid3",
"Unpublished3","URL0","Order04","Menus4","Item_x0020_Guid4","Web_x0020_Guid4","Unpublished4"});
Modal.ButtonsRight.Add(new WHTML.Button("Submit", "", "", "btn-primary tools-ajax", ""));
Modal.Body.Append(new WHTML.FieldSet("", "XmlConvert_EncodeName", "XmlConvert.EncodeName", false,
new WInput(WInputType.text, "XmlConvert.EncodeName", "XmlConvert_EncodeName", "", false), "Used in SPField.InternalName creation."));
DataOutput.Add("Server.MapPath", Context.Server.MapPath(""));
}
} |
using HacktoberfestProject.Web.Extensions.Rules;
using Microsoft.AspNetCore.Rewrite;
namespace HacktoberfestProject.Web.Extensions
{
public static class RewriteOptionsExtensions
{
public static RewriteOptions AddRedirectToApex(this RewriteOptions options)
{
options.Rules.Add(new RedirectToApexRule());
return options;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;
namespace Tivo.Hmo
{
public class TivoItem
{
protected TivoItem(XElement element)
{
if (element == null)
throw new ArgumentNullException("element");
if (element.Element(Calypso16.Details) == null)
throw new ArgumentException();
Element = element;
}
public XElement Element { get; private set; }
public string ContentType
{
get { return GetContentType(Element); }
}
public string SourceFormat
{
get { return GetSourceFormat(Element); }
}
public string Name
{
get { return GetName(Element); }
}
protected internal string ContentUrl
{
get { return GetContentUrl(Element); }
}
protected static string GetSourceFormat(XElement tivoItem)
{
return (string)tivoItem.Element(Calypso16.Details).Element(Calypso16.SourceFormat);
}
protected static string GetName(XElement tivoItem)
{
return (string)tivoItem.Element(Calypso16.Details).Element(Calypso16.Title);
}
protected internal static string GetContentUrl(XElement tivoItem)
{
return (string)tivoItem.Element(Calypso16.Links).Element(Calypso16.Content).Element(Calypso16.Url);
}
internal static string GetContentType(XElement tivoItem)
{
return (string)tivoItem.Element(Calypso16.Details).Element(Calypso16.ContentType);
}
}
}
|
namespace Triton.Game.Mapping
{
using ns26;
using System;
[Attribute38("GeneralStoreHeroesSelectorButton")]
public class GeneralStoreHeroesSelectorButton : PegUIElement
{
public GeneralStoreHeroesSelectorButton(IntPtr address) : this(address, "GeneralStoreHeroesSelectorButton")
{
}
public GeneralStoreHeroesSelectorButton(IntPtr address, string className) : base(address, className)
{
}
public void Awake()
{
base.method_8("Awake", Array.Empty<object>());
}
public int GetHeroDbId()
{
return base.method_11<int>("GetHeroDbId", Array.Empty<object>());
}
public string GetHeroId()
{
return base.method_13("GetHeroId", Array.Empty<object>());
}
public bool GetPurchased()
{
return base.method_11<bool>("GetPurchased", Array.Empty<object>());
}
public bool IsAvailable()
{
return base.method_11<bool>("IsAvailable", Array.Empty<object>());
}
public void OnOut(PegUIElement.InteractionState oldState)
{
object[] objArray1 = new object[] { oldState };
base.method_8("OnOut", objArray1);
}
public void OnOver(PegUIElement.InteractionState oldState)
{
object[] objArray1 = new object[] { oldState };
base.method_8("OnOver", objArray1);
}
public void OnPress()
{
base.method_8("OnPress", Array.Empty<object>());
}
public void OnRelease()
{
base.method_8("OnRelease", Array.Empty<object>());
}
public void Select()
{
base.method_8("Select", Array.Empty<object>());
}
public void SetHeroIds(int heroDbId, string heroId)
{
object[] objArray1 = new object[] { heroDbId, heroId };
base.method_8("SetHeroIds", objArray1);
}
public void SetPurchased(bool purchased)
{
object[] objArray1 = new object[] { purchased };
base.method_8("SetPurchased", objArray1);
}
public void Unselect()
{
base.method_8("Unselect", Array.Empty<object>());
}
public void UpdateName(string name)
{
Class272.Enum20[] enumArray1 = new Class272.Enum20[] { Class272.Enum20.String };
object[] objArray1 = new object[] { name };
base.method_9("UpdateName", enumArray1, objArray1);
}
public void UpdateName(GeneralStoreHeroesSelectorButton rhs)
{
Class272.Enum20[] enumArray1 = new Class272.Enum20[] { Class272.Enum20.Class };
object[] objArray1 = new object[] { rhs };
base.method_9("UpdateName", enumArray1, objArray1);
}
public void UpdatePortrait(GeneralStoreHeroesSelectorButton rhs)
{
Class272.Enum20[] enumArray1 = new Class272.Enum20[] { Class272.Enum20.Class };
object[] objArray1 = new object[] { rhs };
base.method_9("UpdatePortrait", enumArray1, objArray1);
}
public void UpdatePortrait(EntityDef entityDef, CardDef cardDef)
{
Class272.Enum20[] enumArray1 = new Class272.Enum20[] { Class272.Enum20.Class, Class272.Enum20.Class };
object[] objArray1 = new object[] { entityDef, cardDef };
base.method_9("UpdatePortrait", enumArray1, objArray1);
}
public CardDef m_currentCardDef
{
get
{
return base.method_3<CardDef>("m_currentCardDef");
}
}
public EntityDef m_currentEntityDef
{
get
{
return base.method_3<EntityDef>("m_currentEntityDef");
}
}
public Actor m_heroActor
{
get
{
return base.method_3<Actor>("m_heroActor");
}
}
public int m_heroDbId
{
get
{
return base.method_2<int>("m_heroDbId");
}
}
public string m_heroId
{
get
{
return base.method_4("m_heroId");
}
}
public UberText m_heroName
{
get
{
return base.method_3<UberText>("m_heroName");
}
}
public HighlightState m_highlight
{
get
{
return base.method_3<HighlightState>("m_highlight");
}
}
public string m_mouseOverSound
{
get
{
return base.method_4("m_mouseOverSound");
}
}
public bool m_purchased
{
get
{
return base.method_2<bool>("m_purchased");
}
}
public bool m_selected
{
get
{
return base.method_2<bool>("m_selected");
}
}
public string m_selectSound
{
get
{
return base.method_4("m_selectSound");
}
}
public string m_unselectSound
{
get
{
return base.method_4("m_unselectSound");
}
}
}
}
|
using System.Collections.Generic;
namespace MonoGame.Extended.Sprites
{
public class SpriteSheetAnimationCycle
{
public SpriteSheetAnimationCycle()
{
Frames = new List<SpriteSheetAnimationFrame>();
}
public float FrameDuration { get; set; } = 0.2f;
public List<SpriteSheetAnimationFrame> Frames { get; set; }
public bool IsLooping { get; set; }
public bool IsReversed { get; set; }
public bool IsPingPong { get; set; }
}
} |
using System.Linq;
using FluentAssertions;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using OmniSharp.Extensions.JsonRpc;
using OmniSharp.Extensions.JsonRpc.Server;
using OmniSharp.Extensions.JsonRpc.Server.Messages;
using Xunit;
namespace JsonRpc.Tests.Server
{
public class SpecificationReceiverTests
{
[Theory]
[ClassData(typeof(SpecificationMessages))]
public void ShouldRespond_AsExpected2(string json, Renor[] request)
{
var receiver = new Receiver();
var (requests, _) = receiver.GetRequests(JToken.Parse(json));
var result = requests.ToArray();
request.Length.Should().Be(result.Length);
for (var i = 0; i < request.Length; i++)
{
var r = request[i];
var response = result[i];
JsonConvert.SerializeObject(response)
.Should().Be(JsonConvert.SerializeObject(r));
}
}
private class SpecificationMessages : TheoryData<string, Renor[]>
{
public SpecificationMessages()
{
Add(
@"{""jsonrpc"": ""2.0"", ""method"": ""subtract"", ""params"": [42, 23], ""id"": 1}",
new Renor[] {
new Request(1, "subtract", new JArray(new[] { 42, 23 }))
}
);
Add(
@"{""jsonrpc"": ""2.0"", ""method"": ""subtract"", ""params"": {""subtrahend"": 23, ""minuend"": 42}, ""id"": 3}",
new Renor[] {
new Request(3, "subtract", JObject.FromObject(new { subtrahend = 23, minuend = 42 }))
}
);
Add(
@"{""jsonrpc"": ""2.0"", ""method"": ""subtract"", ""params"": {""minuend"": 42, ""subtrahend"": 23 }, ""id"": 4}",
new Renor[] {
new Request(4, "subtract", JObject.FromObject(new { minuend = 42, subtrahend = 23 }))
}
);
Add(
@"{""jsonrpc"": ""2.0"", ""method"": ""subtract"", ""id"": 4}",
new Renor[] {
new Request(4, "subtract", null)
}
);
// http://www.jsonrpc.org/specification says:
// If present, parameters for the rpc call MUST be provided as a Structured value.
// Some clients may serialize params as null, instead of omitting it
// We're going to pretend we never got the null in the first place.
Add(
@"{""jsonrpc"": ""2.0"", ""method"": ""subtract"", ""params"": null, ""id"": 4}",
new Renor[] {
new Request(4, "subtract", new JObject())
}
);
Add(
@"{""jsonrpc"": ""2.0"", ""method"": ""update"", ""params"": [1,2,3,4,5]}",
new Renor[] {
new Notification("update", new JArray(new[] { 1, 2, 3, 4, 5 }))
}
);
Add(
@"{""jsonrpc"": ""2.0"", ""method"": ""foobar""}",
new Renor[] {
new Notification("foobar", null)
}
);
// http://www.jsonrpc.org/specification says:
// If present, parameters for the rpc call MUST be provided as a Structured value.
// Some clients may serialize params as null, instead of omitting it
// We're going to pretend we never got the null in the first place.
Add(
@"{""jsonrpc"": ""2.0"", ""method"": ""foobar"", ""params"": null}",
new Renor[] {
new Notification("foobar", new JObject())
}
);
Add(
@"{""jsonrpc"":""2.0"",""method"":""initialized"",""params"":{}}",
new Renor[] {
new Notification("initialized", new JObject()),
}
);
Add(
@"{""jsonrpc"": ""2.0"", ""method"": 1, ""params"": ""bar""}",
new Renor[] {
new InvalidRequest("1", "Invalid params")
}
);
Add(
@"[1]",
new Renor[] {
new InvalidRequest("", "Not an object")
}
);
Add(
@"[1,2,3]",
new Renor[] {
new InvalidRequest("", "Not an object"),
new InvalidRequest("", "Not an object"),
new InvalidRequest("", "Not an object")
}
);
Add(
@"[
{""jsonrpc"": ""2.0"", ""method"": ""sum"", ""params"": [1,2,4], ""id"": ""1""},
{""jsonrpc"": ""2.0"", ""method"": ""notify_hello"", ""params"": [7]},
{""jsonrpc"": ""2.0"", ""method"": ""subtract"", ""params"": [42,23], ""id"": ""2""},
{""foo"": ""boo""},
{""jsonrpc"": ""2.0"", ""method"": ""foo.get"", ""params"": {""name"": ""myself""}, ""id"": ""5""},
{""jsonrpc"": ""2.0"", ""method"": ""get_data"", ""id"": ""9""}
]",
new Renor[] {
new Request("1", "sum", new JArray(new[] { 1, 2, 4 })),
new Notification("notify_hello", new JArray(new[] { 7 })),
new Request("2", "subtract", new JArray(new[] { 42, 23 })),
new InvalidRequest("", "Unexpected protocol"),
new Request("5", "foo.get", JObject.FromObject(new { name = "myself" })),
new Request("9", "get_data", null),
}
);
Add(
@"[
{""jsonrpc"": ""2.0"", ""error"": {""code"": -32600, ""message"": ""Invalid Request"", ""data"": {}}, ""id"": null},
{""jsonrpc"": ""2.0"", ""error"": {""code"": -32600, ""message"": ""Invalid Request"", ""data"": {}}, ""id"": null},
{""jsonrpc"": ""2.0"", ""error"": {""code"": -32600, ""message"": ""Invalid Request"", ""data"": {}}, ""id"": null}
]",
new Renor[] {
new ServerError(new ServerErrorResult(-32600, "Invalid Request")),
new ServerError(new ServerErrorResult(-32600, "Invalid Request")),
new ServerError(new ServerErrorResult(-32600, "Invalid Request")),
}
);
}
}
[Theory]
[ClassData(typeof(InvalidMessages))]
public void Should_ValidateInvalidMessages(string json, bool expected)
{
var receiver = new Receiver();
var result = receiver.IsValid(JToken.Parse(json));
result.Should().Be(expected);
}
private class InvalidMessages : TheoryData<string, bool>
{
public InvalidMessages()
{
Add(@"[]", false);
Add(@"""""", false);
Add(@"1", false);
Add(@"true", false);
Add(@"[{}]", true);
Add(@"{}", true);
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Hwork20
{
class Program
{
delegate double CalcCircle(double r);
static void Main(string[] args)
{
Console.Write("Введите радиус: ");
double r = Convert.ToDouble(Console.ReadLine());
CalcCircle calcCircle1 = Circle.Length;
double length = calcCircle1(r);
Console.WriteLine($"Длина окружности равна {length:f2}");
CalcCircle calcCircle2 = Circle.Square;
double square = calcCircle2(r);
Console.WriteLine($"Площадь круга равна {square:f2}");
CalcCircle calcCircle3 = Circle.Volume;
double volume = calcCircle3(r);
Console.WriteLine($"Объем шара равен {volume:f2}");
Console.ReadKey();
}
static public class Circle
{
static public double Length(double r)
{
return 2 * Math.PI * r;
}
static public double Square(double r)
{
return Math.PI * r * r;
}
static public double Volume(double r)
{
return 4 * Math.PI * Math.Pow(r, 3) / 3;
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Sudoku_Solver;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
private System.Windows.Forms.TextBox[,] textBoxes;
public Form1()
{
InitializeComponent();
this.textBoxes = new System.Windows.Forms.TextBox[9,9];
for (int i = 0; i < 9; i++)
{
for (int a = 0; a < 9; a++)
{
this.textBoxes[i, a] = new TextBox();
this.textBoxes[i, a].Location = new System.Drawing.Point((i*25 +25),(a *25 +25 ));
this.textBoxes[i, a].Name = "textBox" +i.ToString() + a.ToString();
this.textBoxes[i, a].Size = new System.Drawing.Size(25, 25);
this.textBoxes[i, a].Multiline = true;
this.textBoxes[i, a].Font = new System.Drawing.Font("Arial", 10,FontStyle.Bold);
this.textBoxes[i, a].TextAlign = HorizontalAlignment.Center;
this.textBoxes[i, a].MaxLength = 1;
// this.textBoxes[i, a].Text = i.ToString() + a.ToString();
this.textBoxes[i, a].TextChanged += new System.EventHandler(this.textBoxes_TextChanged);
this.Controls.Add(this.textBoxes[i, a]);
}
}
/*
this.textBoxes[0,0].Location = new System.Drawing.Point(20, 20);
this.textBoxes[0,0].Name = "textBox00";
this.textBoxes[0,0].Size = new System.Drawing.Size(25, 25);
*/
}
private int[,] field = new int[10, 10];
private void textBoxes_TextChanged(object sender, EventArgs e)
{
//check if the value is a number
int value;
TextBox box = (TextBox)sender;
if (!Int32.TryParse(box.Text, out value))
box.Text = "";
}
private void button1_Click(object sender, EventArgs e)
{
Sudoku su = new Sudoku(new SudokuField(textBoxes));
su.solve();
su.GetField(ref textBoxes);
}
private void button2_Click(object sender, EventArgs e)
{
Sudoku su = new Sudoku(new SudokuField(textBoxes));
MessageBox.Show(su.GetField().IsValid().ToString());
}
}
}
|
namespace PDV.DAO.Entidades.MDFe
{
public class AverbacaoSeguradoraMDFe
{
public decimal IDAverbacaoSeguradoraMDFe { get; set; }
public decimal IDSeguradoraMDFe { get; set; }
public string NumeroAverbacao { get; set; }
public AverbacaoSeguradoraMDFe() { }
}
}
|
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Currency.Client.Model.Entity;
namespace Currency.Client.Model.Service
{
public interface ICurrencyTableService
{
Task<List<Rate>> FetchRatesForDateAsync(DateTime dateTime);
Task<List<Rate>> FetchRatesForCodeAsync(Rate rate, DateTime startTime, DateTime endTime, Action<double> progressAction);
DownloadList<Rate> FetchFlagsForRates(IEnumerable<Rate> rates);
}
} |
using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Input;
using HandyControl.Data;
using HandyControl.Interactivity;
using HandyControl.Tools;
namespace HandyControl.Controls
{
[TemplatePart(Name = ElementTextBox, Type = typeof(WatermarkTextBox))]
public class SearchBar : Control, IDataInput
{
private const string ElementTextBox = "PART_TextBox";
private WatermarkTextBox _textBox;
public Func<string, OperationResult<bool>> VerifyFunc { get; set; }
public SearchBar()
{
CommandBindings.Add(new CommandBinding(ControlCommands.Clear, (s, e) => _textBox.Text = string.Empty));
CommandBindings.Add(new CommandBinding(ControlCommands.Search, (s, e) => OnSearchStarted()));
}
public static readonly RoutedEvent SearchStartedEvent =
EventManager.RegisterRoutedEvent("SearchStarted", RoutingStrategy.Direct,
typeof(EventHandler<FunctionEventArgs<string>>), typeof(SearchBar));
public event EventHandler<FunctionEventArgs<string>> SearchStarted
{
add => AddHandler(SearchStartedEvent, value);
remove => RemoveHandler(SearchStartedEvent, value);
}
public override void OnApplyTemplate()
{
if (_textBox != null)
{
_textBox.TextChanged -= TextBox_TextChanged;
}
base.OnApplyTemplate();
_textBox = GetTemplateChild(ElementTextBox) as WatermarkTextBox;
if (_textBox != null)
{
SetBinding(TextProperty, new Binding(TextProperty.Name)
{
Source = _textBox,
Mode = BindingMode.TwoWay,
UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged
});
_textBox.TextChanged += TextBox_TextChanged;
_textBox.KeyDown += TextBox_KeyDown;
}
}
private void TextBox_KeyDown(object sender, KeyEventArgs e)
{
if (e.Key == Key.Enter)
{
OnSearchStarted();
}
}
private void TextBox_TextChanged(object sender, TextChangedEventArgs e)
{
if (IsRealTime)
{
OnSearchStarted();
}
VerifyData();
}
private void OnSearchStarted()
{
RaiseEvent(new FunctionEventArgs<string>(SearchStartedEvent, this)
{
Info = Text
});
}
public static readonly DependencyProperty TextProperty = DependencyProperty.Register(
"Text", typeof(string), typeof(SearchBar), new PropertyMetadata(default(string)));
public string Text
{
get => (string)GetValue(TextProperty);
set => SetValue(TextProperty, value);
}
/// <summary>
/// 数据是否错误
/// </summary>
public static readonly DependencyProperty IsErrorProperty = DependencyProperty.Register(
"IsError", typeof(bool), typeof(SearchBar), new PropertyMetadata(ValueBoxes.FalseBox));
public bool IsError
{
get => (bool)GetValue(IsErrorProperty);
set => SetValue(IsErrorProperty, value);
}
/// <summary>
/// 错误提示
/// </summary>
public static readonly DependencyProperty ErrorStrProperty = DependencyProperty.Register(
"ErrorStr", typeof(string), typeof(SearchBar), new PropertyMetadata(default(string)));
public string ErrorStr
{
get => (string)GetValue(ErrorStrProperty);
set => SetValue(ErrorStrProperty, value);
}
/// <summary>
/// 文本类型
/// </summary>
public static readonly DependencyProperty TextTypeProperty = DependencyProperty.Register(
"TextType", typeof(TextType), typeof(SearchBar), new PropertyMetadata(default(TextType)));
public TextType TextType
{
get => (TextType)GetValue(TextTypeProperty);
set => SetValue(TextTypeProperty, value);
}
/// <summary>
/// 是否显示清除按钮
/// </summary>
public static readonly DependencyProperty ShowClearButtonProperty = DependencyProperty.Register(
"ShowClearButton", typeof(bool), typeof(SearchBar), new PropertyMetadata(ValueBoxes.FalseBox));
public bool ShowClearButton
{
get => (bool)GetValue(ShowClearButtonProperty);
set => SetValue(ShowClearButtonProperty, value);
}
/// <summary>
/// 是否实时搜索
/// </summary>
public static readonly DependencyProperty IsRealTimeProperty = DependencyProperty.Register(
"IsRealTime", typeof(bool), typeof(SearchBar), new PropertyMetadata(ValueBoxes.FalseBox));
/// <summary>
/// 是否实时搜索
/// </summary>
public bool IsRealTime
{
get => (bool)GetValue(IsRealTimeProperty);
set => SetValue(IsRealTimeProperty, value);
}
public virtual bool VerifyData()
{
OperationResult<bool> result;
if (VerifyFunc != null)
{
result = VerifyFunc.Invoke(Text);
}
else
{
if (!string.IsNullOrEmpty(Text))
{
if (TextType != TextType.Common)
{
result = Text.IsKindOf(TextType) ? OperationResult.Success() : OperationResult.Failed(Properties.Langs.Lang.FormatError);
}
else
{
result = OperationResult.Success();
}
}
else if (InfoElement.GetNecessary(this))
{
result = OperationResult.Failed(Properties.Langs.Lang.IsNecessary);
}
else
{
result = OperationResult.Success();
}
}
IsError = !result.Data;
ErrorStr = result.Message;
return result.Data;
}
}
} |
namespace FactoryMethodExample
{
public abstract class CarFactory
{
public abstract Car MakeCar();
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class HoverText : MonoBehaviour {
public Transform PlayerTransform;
// Update is called once per frame
void Update () {
transform.localScale = new Vector3(Mathf.Sign(PlayerTransform.localScale.x)*Mathf.Abs(transform.localScale.x),transform.localScale.y,transform.localScale.z);
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AssignLinkedList
{
class Program
{
static void Main(string[] args)
{
LinkedList<string> ls = new LinkedList<string>(new string[] {"quick","fox","the","lazy" });
Console.WriteLine("------------Add First-----------");
ls.AddFirst("the");
foreach (var item in ls)
{
Console.Write(item+" ");
}
Console.WriteLine("");
Console.WriteLine("------------Add Last--------------");
ls.AddLast("dog");
foreach (var item in ls)
{
Console.Write(item + " ");
}
Console.WriteLine("");
// the quick fox the lazy dog
Console.WriteLine("-----------Add After-------------");
ls.AddAfter(ls.Find("quick"), "brown");
foreach (var item in ls)
{
Console.Write(item + " ");
}
Console.WriteLine("");
// the quick brown fox the lazy dog
Console.WriteLine("------------Add Before-----------");
ls.AddBefore(ls.FindLast("the"), "jump over");
foreach (var item in ls)
{
Console.Write(item + " ");
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using JoveZhao.Framework.DDD;
namespace BPiaoBao.DomesticTicket.Domain.Models.Insurance
{
public class InsuranceConfigBuilder : IAggregationBuilder
{
public InsuranceConfig CreateInsuranceConfig()
{
return new InsuranceConfig();
}
}
}
|
using System.Configuration;
using System.Collections.Specialized;
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 OpenSSL_WinGui
{
public partial class SetDefaultsForm : Form
{
public List<string> sslData = new List<string>();
public SetDefaultsForm()
{
InitializeComponent();
}
private void writeDefaultsToFile(object sender, FormClosingEventArgs e)
{
writeTextBoxesToTempList();
}
private void writeTextBoxesToTempList()
{
sslData.Clear();
foreach (TextBox tb in this.Controls.OfType<TextBox>())
{
sslData.Add(tb.Text);
}
}
private void SetDefaultsForm_Load(object sender, EventArgs e)
{
countryTextBox.Text = Properties.Settings.Default.CoutryCode;
stateTextBox.Text = Properties.Settings.Default.StateCode;
cityTextBox.Text = Properties.Settings.Default.City;
companyTextBox.Text = Properties.Settings.Default.CompanyName;
sectionTextBox.Text = Properties.Settings.Default.OrganizationalUnit;
emailTextBox.Text = Properties.Settings.Default.EmailAddress;
}
}
}
|
namespace RefactorTheFolwIfStatements
{
using System;
public class Matrix
{
private const int MinRow = 0;
private const int MaxRow = 10;
private const int MinCol = 0;
private const int MaxCol = 10;
private int currentRow;
private int currentCol;
public Matrix(int currentRow, int currrentCol)
{
this.currentRow = currentRow;
this.currentCol = currrentCol;
}
public bool IsPointIsInMatrix()
{
bool isOutOfRowRange = this.currentRow >= MinRow && this.currentRow <= MaxRow;
bool isOutOfColRange = this.currentCol >= MinCol && this.currentCol <= MaxCol;
bool isInMatrix = isOutOfColRange && isOutOfRowRange;
return isInMatrix;
}
public void VisitCell()
{
Console.WriteLine($"You visit row:{currentRow} col:{currentCol}");
}
}
}
|
using System.Collections.Generic;
using Shakespokemon.Core;
namespace Shakespokemon.Etl.Core
{
public interface IPokemonSourceRepository
{
IEnumerable<Pokemon> GetAll();
}
} |
using WorkerService.Core.Entities.Abstract;
using System;
using System.Collections.Generic;
using System.Text;
namespace WorkerService.Entities.Dtos
{
public class ExamDto : IDto
{
public string Title { get; set; }
public string Information { get; set; }
public int NumberOfQuestions { get; set; }
public string StartTime { get; set; }
public string EndTime { get; set; }
public bool IsFinished { get; set; }
}
}
|
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
namespace VavilichevGD.GameServices.AnalyticService.Example {
public class AnalyticsServiceExample : MonoBehaviour {
[SerializeField] private Button buttonEventNoParameters;
[SerializeField] private Button buttonEventWithParameters;
private AnalyticsService analyticsService;
#region LIFECYCLE
private void OnEnable() {
this.buttonEventNoParameters.onClick.AddListener(this.OnNoParametersButtonClick);
this.buttonEventWithParameters.onClick.AddListener(this.OnWithParametersButtonClick);
}
private void OnDisable() {
this.buttonEventNoParameters.onClick.RemoveListener(this.OnNoParametersButtonClick);
this.buttonEventWithParameters.onClick.RemoveListener(this.OnWithParametersButtonClick);
}
private void Start() {
this.analyticsService = new AnalyticsService();
this.analyticsService.isLoggingEnabled = true;
this.analyticsService.InitializeAsync();
}
#endregion
#region EVENTS
private void OnNoParametersButtonClick() {
const string eventName = "event_no_parameters";
Analytics.Log(eventName);
}
private void OnWithParametersButtonClick() {
const string eventName = "event_with_parameters";
var parameters = new Dictionary<string, object>
{
{ "parameter_1", "parameter_value_1" },
{ "parameter_2", "parameter_value_2" },
{ "parameter_3", "parameter_value_3" },
{ "parameter_4", "parameter_value_4" }
};
Analytics.Log(eventName, parameters);
}
#endregion
}
} |
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;
namespace ConsoleApp1
{
public class Connpass
{
public int results_start { get; set; }
public int results_returned { get; set; }
public int results_available { get; set; }
public List<Event> events { get; set; }
}
public class Event
{
public class Series
{
public int id { get; set; }
public string title { get; set; }
public string url { get; set; }
}
public int event_id { get; set; }
public string title { get; set; }
public string @catch { get; set; }
public string description { get; set; }
public string event_url { get; set; }
public DateTime started_at { get; set; }
public DateTime ended_at { get; set; }
public int limit { get; set; }
public string hash_tag { get; set; }
public string event_type { get; set; }
public int accepted { get; set; }
public int waiting { get; set; }
public DateTime updated_at { get; set; }
public int owner_id { get; set; }
public string owner_nickname { get; set; }
public string owner_display_name { get; set; }
public string place { get; set; }
public string address { get; set; }
public string lat { get; set; }
public string lon { get; set; }
public Series series { get; set; }
}
class Program
{
static async Task Main(string[] args)
{
using (var client = new HttpClient())
{
client.DefaultRequestHeaders.TryAddWithoutValidation("User-Agent", "foo=bar");
var result = await client.GetAsync("https://connpass.com/api/v1/event/?keyword=azure");
var settings = new JsonSerializerSettings
{
NullValueHandling = NullValueHandling.Ignore,
MissingMemberHandling = MissingMemberHandling.Ignore
};
var jsonDes = JsonConvert.DeserializeObject<Connpass>(await result.Content.ReadAsStringAsync(), settings);
var slackUrl = "https://hooks.slack.com/services/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";
foreach (var eventObj in jsonDes.events)
{
var contentJson = $"{{\"text\":\"{eventObj.title}\n{eventObj.event_url}\"}}";
var content = new StringContent(contentJson, Encoding.UTF8, @"application/json");
var result1 = await client.PostAsync(slackUrl, content);
}
}
}
}
}
|
/*
* Copyright (C) 2012 Ricardo Juan Palma Durán
*
* 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.
*/
package jbt.tools.btlibrarygenerator.librarygenerator;
/**
* Exception thrown when there is an error creating an IBTLibrary.
*
* @author Ricardo Juan Palma Durán
*
*/
public class BTLibraryGenerationException extends Exception {
private static final long serialVersionUID = 1L;
public BTLibraryGenerationException(String message) {
super(message);
}
public BTLibraryGenerationException(String message, Throwable cause) {
super(message, cause);
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
//Task 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19
namespace MobilePhone
{
class Program
{
static void Main(string[] args)
{
//run GSMTest class
GSMTest.StartGSMTest();
//run GSMCallHIstoryTest class
GSMCallHistoryTest.StartGSMCallHistoryTest();
}
}
}
|
using GameAnalyticsSDK;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class GameAnalyticsManager_Manual : MonoBehaviour, IGameAnalyticsATTListener
{
public static GameAnalyticsManager_Manual Instance;
private void Start()
{
if (Instance==null)
{
Instance = this;
}
else
{
Destroy(this.gameObject);
}
if (Application.platform == RuntimePlatform.IPhonePlayer)
{
GameAnalytics.RequestTrackingAuthorization(this);
}
else
{
GameAnalytics.Initialize();
}
DontDestroyOnLoad(this.gameObject);
}
public void GameAnalyticsATTListenerNotDetermined()
{
GameAnalytics.Initialize();
}
public void GameAnalyticsATTListenerRestricted()
{
GameAnalytics.Initialize();
}
public void GameAnalyticsATTListenerDenied()
{
GameAnalytics.Initialize();
}
public void GameAnalyticsATTListenerAuthorized()
{
GameAnalytics.Initialize();
}
public void OnGameStart(string levelNumber)
{
GameAnalytics.NewProgressionEvent(GAProgressionStatus.Start, "Level_Num", levelNumber);
}
public void OnGameSucceed(string levelNumber)
{
GameAnalytics.NewProgressionEvent(GAProgressionStatus.Complete, "Level_Num", levelNumber);
}
public void OnGameFailed(string levelNumber)
{
GameAnalytics.NewProgressionEvent(GAProgressionStatus.Fail, "Level_Num", levelNumber);
}
public void OnGameRestart(string levelNumber)
{
GameAnalytics.NewProgressionEvent(GAProgressionStatus.Start, "Level_Num", levelNumber+"Restarted");
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using System;
using UnityEngine.SceneManagement;
public class GetPlayInfo : MonoBehaviour
{
public GameObject GameViewPanel; public Text Time; public Text Score; MoveElement play_info;
List <Vector2> Numbers; List <GameObject> GONumbers = new List<GameObject>(); float anchonum = 0;
int counterR = 11; int countime = 0; GameController gcontroller; int time, score;
void Start() {
time = 50; score = 50; gcontroller = GameObject.FindWithTag("GameController").GetComponent<GameController>();
play_info = GameViewPanel.GetComponent<MoveElement>();
Numbers = play_info.posNumbers;
for (int i = 0; i < Numbers.Count; i++){
GameObject NewObj = new GameObject();
Image NewImage = NewObj.AddComponent<Image>();
RectTransform NewRect = NewObj.GetComponent<RectTransform>();
Vector3 position = new Vector3(Numbers[i].x, Numbers[i].y, 0.0f);
NewRect.SetPositionAndRotation(position, new Quaternion(0, 0, 0, 1));
NewRect.localScale = new Vector3(0.6f,0.6f,0.6f);
anchonum = NewRect.rect.width;
NewRect.SetParent(GetComponent<RectTransform>());
NewObj.SetActive(true);
switch (play_info.valNumbers[i]){
case 1: NewImage.sprite = play_info.Sprites[0]; break;
case 2: NewImage.sprite = play_info.Sprites[1]; break;
case 3: NewImage.sprite = play_info.Sprites[2]; break;
case 4: NewImage.sprite = play_info.Sprites[3]; break;
case 5: NewImage.sprite = play_info.Sprites[4]; break;
case 6: NewImage.sprite = play_info.Sprites[5]; break;
case 7: NewImage.sprite = play_info.Sprites[6]; break;
case 8: NewImage.sprite = play_info.Sprites[7]; break;
case 9: NewImage.sprite = play_info.Sprites[8]; break;
case 10: NewImage.sprite = play_info.Sprites[9]; break;
}
GONumbers.Add(NewObj);
}
}
void Update() {
if (!VerifyGameOver()){
TimeCounter();
if (Input.GetMouseButtonUp(0)) {
for (int i = 0; i < Numbers.Count; i++){
float dist = anchonum/2;
if (Input.mousePosition.x <= Numbers[i].x+dist && Input.mousePosition.x >= Numbers[i].x-dist
&& Input.mousePosition.y <= Numbers[i].y+dist && Input.mousePosition.y >= Numbers[i].y-dist){
if (play_info.valNumbers[i] == MaxNumber(counterR)){
Numbers.Remove(Numbers[i]);
play_info.valNumbers.Remove(play_info.valNumbers[i]);
Destroy(GONumbers[i]);
GONumbers.Remove(GONumbers[i]); score+=5;
}
else{ score-=5; }
Score.text = score.ToString();
}
}
}
} else {
SceneManager.LoadScene("GameOver");
}
}
bool ThisNumberIn(int a){
foreach (int b in play_info.valNumbers){
if (a == b){
return true;
}
}
return false;
}
int MaxNumber(int a){
int max = 0;
foreach (int b in play_info.valNumbers){
if (max < b && max <= a){
max = b;
}
}
return max;
}
bool VerifyGameOver(){
if (time <= 0 || score <= 0 || Numbers.Count == 0){
gcontroller.time = time; gcontroller.score = score;
return true;
}
return false;
}
void TimeCounter(){
if (countime == 50 && time >= 0){
time = time - 1;
Time.text = time.ToString();
countime = 0;
}
else{
countime = countime + 1;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
namespace TopkaE.FPLDataDownloader.Models.InputModels.LeagueDataModel
{
public class GeneralLeagueModel
{
public int Id { get; set; }
public League league { get; set; }
//public NewEntries new_entries { get; set; }
public Standings standings { get; set; }
}
}
|
using System.Threading.Tasks;
using Dating.API.Models;
// repository hi hai but bahar hai ----
namespace Dating.API.Data
{
public interface IAuthRepository
{
Task<User> Register(User user, string password);
//method user passed user and password will return User
Task<User> Login(string username,string password);
Task<bool> UserExists(string username);
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
/**
* Copyright (c) blueback
* Released under the MIT License
* https://github.com/bluebackblue/fee/blob/master/LICENSE.txt
* http://bbbproject.sakura.ne.jp/wordpress/mitlicense
* @brief UI。ツール。
*/
/** NUi
*/
namespace NUi
{
/** Ui
*/
public class Ui : Config
{
/** [シングルトン]s_instance
*/
private static Ui s_instance = null;
/** [シングルトン]インスタンス。作成。
*/
public static void CreateInstance()
{
if(s_instance == null){
s_instance = new Ui();
}
}
/** [シングルトン]インスタンス。チェック。
*/
public static bool IsCreateInstance()
{
if(s_instance != null){
return true;
}
return false;
}
/** [シングルトン]インスタンス。取得。
*/
public static Ui GetInstance()
{
#if(UNITY_EDITOR)
if(s_instance == null){
Tool.Assert(false);
}
#endif
return s_instance;
}
/** [シングルトン]インスタンス。削除。
*/
public static void DeleteInstance()
{
if(s_instance != null){
s_instance.Delete();
s_instance = null;
}
}
//ターゲットリスト。
private List<OnTargetCallBack_Base> target_list;
//追加リスト。
private List<OnTargetCallBack_Base> add_list;
//削除リスト。
private List<OnTargetCallBack_Base> remove_list;
/** [シングルトン]constructor
*/
private Ui()
{
//target_list
this.target_list = new List<OnTargetCallBack_Base>();
//add_list
this.add_list = new List<OnTargetCallBack_Base>();
//remove_list
this.remove_list = new List<OnTargetCallBack_Base>();
}
/** [シングルトン]削除。
*/
private void Delete()
{
}
/** 更新。
*/
public void Main()
{
try{
//追加。
for(int ii=0;ii<this.add_list.Count;ii++){
this.target_list.Add(this.add_list[ii]);
}
this.add_list.Clear();
//削除。
for(int ii=0;ii<this.remove_list.Count;ii++){
this.target_list.Remove(this.remove_list[ii]);
}
this.remove_list.Clear();
//呼び出し。
for(int ii=0;ii<this.target_list.Count;ii++){
this.target_list[ii].OnTarget();
}
}catch(System.Exception t_exception){
Tool.LogError(t_exception);
}
}
/** 追加リクエスト。設定。
*/
public void SetTargetRequest(OnTargetCallBack_Base a_item)
{
this.add_list.Add(a_item);
this.remove_list.Remove(a_item);
}
/** 削除リクエスト。解除。
*/
public void UnSetTargetRequest(OnTargetCallBack_Base a_item)
{
this.remove_list.Add(a_item);
this.add_list.Remove(a_item);
}
}
}
|
using MailKit.Net.Smtp;
using MailKit.Security;
using MimeKit;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
namespace PetSharing.Domain.Services
{
public class EmailService
{
public async Task SendEmailAsync(string email, string subject, string message)
{
var emailMessage = new MimeMessage();
emailMessage.From.Add(new MailboxAddress("Администрация сайта", "petsharing.world@outlook.com"));
emailMessage.To.Add(new MailboxAddress("Dear User", email));
emailMessage.Subject = subject;
emailMessage.Body = new TextPart(MimeKit.Text.TextFormat.Html)
{
Text = message
};
using (var smtp = new SmtpClient())
{
await smtp.ConnectAsync("smtp.office365.com", 587, SecureSocketOptions.StartTls);
await smtp.AuthenticateAsync("petsharing.world@outlook.com", "RUready4SEX");
await smtp.SendAsync(emailMessage);
await smtp.DisconnectAsync(true);
}
}
}
}
|
using System;
using System.Collections;
using System.Net;
using Newtonsoft.Json.Linq;
namespace OCP.AppFramework.Http
{
/**
* A renderer for JSON calls
* @since 6.0.0
*/
class JSONResponse : Response {
/**
* response data
* @var array|object
*/
protected object data;
/**
* constructor of JSONResponse
* @param array|object data the object or array that should be transformed
* @param int statusCode the Http status code, defaults to 200
* @since 6.0.0
*/
public JSONResponse(object data= null, HttpStatusCode statusCode=HttpStatusCode.OK) {
this.data = data;
this.setStatus(statusCode);
this.addHeader("Content-Type", "application/json; charset=utf-8");
}
/**
* Returns the rendered json
* @return string the rendered json
* @since 6.0.0
* @throws \Exception If data could not get encoded
*/
public string render()
{
var response = new JObject();
try
{
response = JObject.Parse(this.data.ToString());
}
catch (Exception e)
{
throw new Exception("Could not json_encode due to invalid " +
"non UTF-8 characters in the array: {this.data}");
}
// response = json_encode(this.data, JSON_HEX_TAG);
// if(response === false) {
//
// }
return response.ToString();
}
/**
* Sets values in the data json array
* @param array|object data an array or object which will be transformed
* to JSON
* @return JSONResponse Reference to this object
* @since 6.0.0 - return value was added in 7.0.0
*/
public JSONResponse setData(object data){
this.data = data;
return this;
}
/**
* Used to get the set parameters
* @return array the data
* @since 6.0.0
*/
public object getData(){
return this.data;
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Sudoku_Designer
{
class Cell
{
protected int value;
public void SetCell(int newValue)
{
value = newValue;
}
public int GetCell()
{
return value;
}
}
}
|
using System;
using SnakeGame;
using NUnit.Framework;
namespace SnakeTest
{
[TestFixture]
public class FruitTest
{
[Test]
public void FruitResetPositionTest()
{
Fruit f = new Fruit(new Point(10, 10), null, false);
f.ResetPosition(new Point(5, 5));
Assert.IsTrue(f.isNetworkDirty());
Assert.AreEqual(new Point(5, 5), f.Position);
}
[Test]
public void FruitSerializeTest()
{
Fruit f = new Fruit(new Point(10, 10), null, false);
var bytes = f.Serialize();
Fruit f2 = new Fruit(new Point(1, 1), null, false);
f2.Deserialize(bytes);
Assert.AreEqual(f.Position, f2.Position);
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using MyDir;
public class ClickOp : MonoBehaviour {
private UserAction action;
CharacterController character_ctrl;
public void setController(CharacterController character){
character_ctrl = character;
}
// Use this for initialization
void Start () {
action = Director.getInstace().current as UserAction;
}
// Update is called once per frame
void Update () {
}
void OnMouseDown(){
if (gameObject.name == "boat") {
action.moveBoat ();
} else {
action.characterIsClicked (character_ctrl);
}
}
}
|
//
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the MIT License. See LICENSE file in the project root for full license information.
//
namespace DotNetNuke.UI.Skins
{
public enum SkinScope
{
All = 0,
Host = 1,
Site = 2
}
}
|
////////////////////////////////////////////////////////////////////////////
// Copyright 2016 : Vladimir Novick https://www.linkedin.com/in/vladimirnovick/
//
// NO WARRANTIES ARE EXTENDED. USE AT YOUR OWN RISK.
//
// To contact the author with suggestions or comments, use :vlad.novick@gmail.com
//
////////////////////////////////////////////////////////////////////////////
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Reflection;
namespace Com.SGcombo.DataSynchronization.Utils
{
public class ComponentLibrary<T>
{
protected string _ComponentFolder;
protected List<T> _Components = new List<T>();
protected bool _LoadRecursive;
#region Properties
public List<T> Components
{
get { return _Components; }
}
public string ComponentFolder
{
get { return _ComponentFolder; }
}
#endregion
public ComponentLibrary() : this(true) { }
public ComponentLibrary(string componentFolder) : this(true, componentFolder) { }
public ComponentLibrary(bool recursive) : this (recursive, AppDomain.CurrentDomain.BaseDirectory) { }
public ComponentLibrary(bool recursive, string componentFolder)
{
_LoadRecursive = recursive;
_ComponentFolder = componentFolder;
LoadComponents(_ComponentFolder);
}
protected void LoadComponents(string folder)
{
if (Directory.Exists(folder) == false) return;
foreach (string str in Directory.GetFiles(folder, "*.dll"))
{
if (GeneralLib.StringCompare(Path.GetExtension(str), ".dll"))
{
LoadComponentsFromAsm(GeneralLib.LoadAssemblyFromFile(str));
}
}
if (_LoadRecursive)
{
foreach (string subfolder in Directory.GetDirectories(folder))
{
LoadComponents(subfolder);
}
}
}
protected void LoadComponentsFromAsm(Assembly asm)
{
if (asm == null) return;
Type[] types = asm.GetTypes();
foreach (Type type in types)
{
object obj = null;
try
{
obj = Activator.CreateInstance(type);
}
catch { }
if (obj != null)
{
T result = default(T);
try
{
result = (T)obj;
_Components.Add(result);
}
catch (Exception ex)
{
Console.Write(ex.Message);
}
}
}
}
}
}
|
using Ninject;
using Services.Interfaces;
using Services.Log;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Threading.Tasks;
using System.Windows;
using UGCS.Example.Enums;
using UGCS.Example.Properties;
namespace UGCS.Example
{
/// <summary>
/// Interaction logic for App.xaml
/// </summary>
public partial class App : Application
{
public static IKernel Kernel { get; set; }
ILogger logger = new Logger(typeof(App));
public App()
{
logger.LogInfoMessage("App init");
AppDomain currentDomain = AppDomain.CurrentDomain;
currentDomain.UnhandledException += new UnhandledExceptionEventHandler(UnmanagedException);
System.Threading.Thread.CurrentThread.CurrentUICulture = new System.Globalization.CultureInfo(Settings.Default.CurrentUICulture);
System.Threading.Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo(Settings.Default.CurrentUICulture);
InitializeComponent();
ShutdownMode = ShutdownMode.OnLastWindowClose;
}
private void UnmanagedException(object sender, UnhandledExceptionEventArgs args)
{
logger.LogError("!!!Unmanaged exception");
Exception e = (Exception)args.ExceptionObject;
logger.LogException(e);
MessageBoxResult result = MessageBox.Show(e.Message + "\n" + args.IsTerminating + "\nApplication will exit", "Unmanaged exception", MessageBoxButton.OK, MessageBoxImage.Error);
if (result == MessageBoxResult.OK)
{
Environment.Exit(0);
}
}
}
}
|
using UnityEngine;
using System.Collections;
public class EnableEvent : ButtonEvent {
public Transform enabledObject;
bool enabled = false;
public override void performEvent() {
enabled = !enabled;
enabledObject.GetComponent<Animator> ().SetBool ("Enabled", enabled);
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
/// <summary>
/// 射击组件
/// </summary>
[DisallowMultipleComponent]
public class CompShooter : Comp
{
public float ammoSpeed { get { return GameSystem.Setter.setting.ammoSpeed; } }
public Transform GunPivot;
private int id;
private void Start()
{
id = AmmoManager.GetId();
}
//接口-----------------------------------
public void Shoot()
{
if (!isWorking) return;
AmmoManager.GenerateAmmo(GunPivot.position, transform.up, ammoSpeed, id, tank.campFlag);
}
/// <summary>
/// 用于暂停
/// </summary>
[HideInInspector]
private bool isWorking = true;
public void Stop()
{
isWorking = false;
}
public void Conti()
{
isWorking = true;
}
}
|
using HangoutsDbLibrary.Data;
using HangoutsDbLibrary.Model;
using HangoutsDbLibrary.Repository;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace WebAPI.Services
{
public class ServiceUserGroup : IServiceUserGroup
{
private HangoutsContext context;
private ServiceGroup serviceGroup;
private ServiceUser serviceUser;
public ServiceUserGroup()
{
serviceUser = new ServiceUser();
serviceGroup = new ServiceGroup();
}
private UnitOfWork CreateUnitOfWork()
{
DesignTimeDbContextFactory designTimeDbContextFactory = new DesignTimeDbContextFactory();
context = designTimeDbContextFactory.CreateDbContext(new string[] { });
return new UnitOfWork(context);
}
public void AddUserToAGroup(int idGroup, int idUser)
{
using (UnitOfWork unitOfWork = CreateUnitOfWork())
{
User user = serviceUser.GetUserById(idUser, unitOfWork);
Group group = serviceGroup.GetGroupById(idGroup, unitOfWork);
unitOfWork.UserGroupRepository.Add(new UserGroup { Group = group, User = user });
unitOfWork.save();
}
}
public List<Group> GetAllGroupsFromAUser(int userId)
{
using (UnitOfWork unitOfWork = CreateUnitOfWork())
{
List<Group> groups = new List<Group>();
foreach (UserGroup ug in unitOfWork.UserGroupRepository.GetAllBy(ug => ug.UserId==userId).ToList())
{
groups.Add(unitOfWork.GroupRepository.FindBy(g => g.Id == ug.GroupId));
}
return groups;
}
}
public List<User> GetAllUsersFromAGroup(int groupId)
{
using (UnitOfWork unitOfWork = CreateUnitOfWork())
{
List<User> users = new List<User>();
foreach(UserGroup ug in unitOfWork.UserGroupRepository.GetAllBy(ug => ug.GroupId == groupId).ToList())
{
users.Add(unitOfWork.UserRepository.FindBy(u => u.Id==ug.UserId));
}
return users;
}
}
public void RemoveUserFromAGroup(int userId, int groupId)
{
using (UnitOfWork unitOfWork = CreateUnitOfWork())
{
User user = serviceUser.GetUserById(userId, unitOfWork);
Group group = serviceGroup.GetGroupById(groupId, unitOfWork);
UserGroup userGroupToDelete = unitOfWork.UserGroupRepository.FindBy(userGroup => userGroup.GroupId == groupId && userGroup.UserId == userId);
unitOfWork.UserGroupRepository.Delete(userGroupToDelete);
unitOfWork.save();
}
}
}
}
|
using System;
using System.Collections.Generic;
using ReactRestChat.Data;
using ReactRestChat.Models;
namespace ReactRestChat.Services
{
public interface IConversationInstanceRepository : IRepository<ConversationInstance>
{
IEnumerable<Guid> GetConversationIds(string userId);
void CreateConversationInstance(Guid conversationId, Guid messageId, string participantId);
void CreateConversationInstances(Guid conversationId, Guid messageId, IEnumerable<string> participantIds);
bool Exists(Guid conversationId, string userId);
bool Delete(Guid conversationId, string participantId, Guid? lastMessageId);
}
} |
using StockData.Contract;
using StockData.Repository;
using System;
using System.Linq;
namespace StockData.ConsoleApp
{
class Program
{
static void Main(string[] args)
{
//source should be set in config files, but i'll simplify this
var stockDS = StockDataSources.Mock;
var stock = new StockRepository(stockDS).GetWarehouseStock();
DisplayData(stock);
Console.ReadKey();
}
private static void DisplayData(WarehouseStockDto[] stock)
{
foreach (var result in stock.OrderByDescending(x=>x.SumOfProducts).OrderByDescending(x=>x.WarehouseId))
{
Console.WriteLine(result.ToString());
}
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.