text stringlengths 13 6.01M |
|---|
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ServiceLayer
{
internal class ValidationService : IValidationService
{
public bool IsValidRequestInformationFormSubmission(
string name,
string emailAddress,
string phoneNumber,
string description)
{
return !string.IsNullOrEmpty(name) && // Name is required
!string.IsNullOrEmpty(emailAddress) && // Email address is required
IsValidEmailAddress(emailAddress) && // Email address is valid
(string.IsNullOrEmpty(phoneNumber) || // Phone number is empty or valid
IsValidPhoneNumber(phoneNumber)) &&
!string.IsNullOrEmpty(description); // Description is required
}
private bool IsValidEmailAddress(string emailAddress)
{
var emailAddressAttribute = new EmailAddressAttribute();
return emailAddressAttribute.IsValid(emailAddress);
}
private bool IsValidPhoneNumber(string phoneNumber)
{
var phoneNumberAttribute = new PhoneAttribute();
return phoneNumberAttribute.IsValid(phoneNumber);
}
}
}
|
namespace RosPurcell.Web.ViewModels.Pages.Interfaces
{
public interface IHeader
{
}
}
|
namespace Assets.Scripts
{
public class ReceiptPayloadData
{
public string json;
public string signature;
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace UseFul.Uteis
{
public class ValidacaoData
{
public static string VerificaData(string Data)
{
string retorno = "";
string mes = Data;
string dia = Data;
string ano = Data;
dia = dia.Substring(0, 2);
mes = mes.Substring(3, 2);
ano = ano.Substring(6, 4);
int day = Convert.ToInt32(dia);
int month = Convert.ToInt32(mes);
int year = Convert.ToInt32(ano);
if (day > 31 || day < 1 || month < 1 || month > 12)
{
retorno = "Data invalida. Favor verificar o valor digitado";
}
else
{
if ((month == 02))
{
if (day >= 29)
{
if (year % 4 == 0 && day == 29)
{
retorno = "";
}
else
{
retorno = "O mês de Fevereiro so tem 28 ou 29 dias";
}
}
}
if ((month == 04))
{
if (day > 30)
{
retorno = "O mês de Abril so tem 30 dias";
}
else
{
retorno = "";
}
}
if ((month == 06))
{
if (day > 30)
{
retorno = "O mês de Junho so tem 30 dias";
}
else
{
retorno = "";
}
}
if ((month == 09))
{
if (day > 30)
{
retorno = "O mês de Setembro so tem 30 dias";
}
else
{
retorno = "";
}
}
if ((month == 11))
{
if (day > 30)
{
retorno = "O mês de Novembro so tem 30 dias";
}
else
{
retorno = "";
}
}
}
return retorno;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
namespace CSharp.Enums.LikeJava
{
/// <summary>
/// https://www.codeproject.com/Articles/38666/Enum-Pattern.aspx
/// https://stackoverflow.com/questions/469287/c-sharp-vs-java-enum-for-those-new-to-c
/// </summary>
public class Planet
{
public static readonly Planet MERCURY = new Planet("Mercury", 3.303e+23, 2.4397e6);
public static readonly Planet VENUS = new Planet("Venus", 4.869e+24, 6.0518e6);
public static readonly Planet EARTH = new Planet("Earth", 5.976e+24, 6.37814e6);
public static readonly Planet MARS = new Planet("Mars", 6.421e+23, 3.3972e6);
public static readonly Planet JUPITER = new Planet("Jupiter", 1.9e+27, 7.1492e7);
public static readonly Planet SATURN = new Planet("Saturn", 5.688e+26, 6.0268e7);
public static readonly Planet URANUS = new Planet("Uranus", 8.686e+25, 2.5559e7);
public static readonly Planet NEPTUNE = new Planet("Neptune", 1.024e+26, 2.4746e7);
public static readonly Planet PLUTO = new Planet("Pluto", 1.27e+22, 1.137e6);
public static IEnumerable<Planet> Values
{
get
{
yield return MERCURY;
yield return VENUS;
yield return EARTH;
yield return MARS;
yield return JUPITER;
yield return SATURN;
yield return URANUS;
yield return NEPTUNE;
yield return PLUTO;
}
}
public string Name { get; private set; }
public double Mass { get; private set; }
public double Radius { get; private set; }
Planet(string name, double mass, double radius) =>
(Name, Mass, Radius) = (name, mass, radius);
// Wniversal gravitational constant (m3 kg-1 s-2)
public const double G = 6.67300E-11;
public double SurfaceGravity() => G * Mass / (Radius * Radius);
public double SurfaceWeight(double other) => other * SurfaceGravity();
public override string ToString() => Name;
}
}
|
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 Hospital_Management_System
{
public partial class Show_User_Info : Form
{
public Show_User_Info()
{
InitializeComponent();
}
private void bttn_Exit_Click(object sender, EventArgs e)
{
if (MessageBox.Show("Are You Sure To Exit Programme ?", "Exit", MessageBoxButtons.OKCancel) == DialogResult.OK)
{
Application.Exit();
}
}
private void Back_Click(object sender, EventArgs e)
{
this.Close();
Patient_Page p1 = new Patient_Page();
p1.Show();
}
}
}
|
using RtsProject.Assets.Scripts.Common.Utility.Touch;
using UnityEngine;
using RtsProject.Assets.Scripts.Data;
namespace RtsProject.Assets.Scripts.Scene.TileMapSample
{
/// <summary>
/// タイルマップサンプルのシーン管理
/// </summary>
public sealed class SceneManager : MonoBehaviour
{
/// <summary>
/// タイルUIパネル
/// </summary>
[SerializeField] private TileUIPanel tileUIPanel;
/// <summary>
/// キャラクター
/// </summary>
[SerializeField] private Character character;
/// <summary>
/// タッチ管理
/// </summary>
[SerializeField] private TouchManager touch;
/// <summary>
/// バトルUIパネル
/// </summary>
[SerializeField] private BattleUIPanel battleUIPanel;
/// <summary>
/// 起動時
/// </summary>
private void Awake ()
{
// TODO:マップ用データを取得する 要修正
var mapData = new MapData(new Vector3Int(0, -2, 0));
// 拡大ボタンを押したとき
battleUIPanel.OnClickScaleUpButtonCallBack = () =>
{
tileUIPanel.ScaleUp();
};
// 縮小ボタンを押したとき
battleUIPanel.OnClickScaleDownButtonCallBack = () =>
{
tileUIPanel.ScaleDown();
};
// キャラクター初期位置の設定
var worldCharacterInitPosition = tileUIPanel.GetInitCharacterWorldPosition(mapData.CharacterInitCellPosition);
// 位置の設定
character.SetPosition(worldCharacterInitPosition);
// タッチ押した時
touch.OnTouchBegan = async () =>
{
// カメラのワールド座標に変換
var touchCameraWorldPosition = touch.GetCameraTouchPosition(Camera.main);
// ワールド座標をタイルマップのセル座標に変換
var touchTileCellPosition = tileUIPanel.GetWorldToCellPosition(touchCameraWorldPosition);
// 当たり判定をタッチした場合、ここで処理終了
if (tileUIPanel.IsCollision(touchTileCellPosition)) return;
// タッチした位置に選択用タイルを配置する
tileUIPanel.SetSelectTile(touchTileCellPosition);
// A-Starアルゴリズム用のクラス生成
var astar = new Astar((Vector2Int)mapData.CharacterInitCellPosition, (Vector2Int)touchTileCellPosition);
// 経路探索処理
await astar.SearchPath((Vector2Int)touchTileCellPosition, tileUIPanel.IsCollision, tileUIPanel.SetRouteSearchTile);
};
}
}
} |
using System.Collections;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using UnityEngine;
using Quark.Targeting;
namespace Quark
{
public class TargetCollection : IEnumerable<TargetUnion>
{
List<Vector3> _points = new List<Vector3>();
List<Targetable> _targetables = new List<Targetable>();
List<Character> _characters = new List<Character>();
public void Add(Vector3 point)
{
_points.Add(point);
}
public void Add(Targetable target)
{
_targetables.Add(target);
}
public void Add(Character target)
{
_characters.Add(target);
}
public void AddRange(TargetCollection targets)
{
foreach (TargetUnion target in targets)
{
switch (target.Type)
{
case TargetType.Point:
Add(target.Point);
break;
case TargetType.Targetable:
Add(target.Targetable);
break;
case TargetType.Character:
Add(target.Character);
break;
}
}
}
public Vector3 FirstPoint
{
get
{
return _points[0];
}
}
public Targetable FirstTargetable
{
get
{
return _targetables[0];
}
}
public Character FirstCharacter
{
get
{
return _characters[0];
}
}
public Vector3[] Points
{
get
{
return _points.ToArray();
}
}
public Targetable[] Targetables
{
get
{
return _targetables.ToArray();
}
}
public Character[] Characters
{
get
{
return _characters.ToArray();
}
}
public int Count
{
get
{
return _points.Count + _targetables.Count + _characters.Count;
}
}
public bool IsEmpty
{
get
{
return Count < 1;
}
}
private TargetUnion[] Targets
{
get
{
TargetUnion[] targets = new TargetUnion[_points.Count + _targetables.Count + _characters.Count];
int i = 0;
foreach (Vector3 point in _points)
targets[i++] = new TargetUnion(point);
foreach (Targetable target in _targetables)
targets[i++] = new TargetUnion(target);
foreach (Character character in _characters)
targets[i++] = new TargetUnion(character);
return targets;
}
}
public IEnumerator<TargetUnion> GetEnumerator()
{
return ((IEnumerable<TargetUnion>)Targets).GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return Targets.GetEnumerator();
}
}
/// <summary>
/// This structure is the generic target type used in Quark framework.
/// </summary>
public struct TargetUnion
{
/// <summary>
/// Type of the target of this union.
/// </summary>
public TargetType Type { get; private set; }
/// <summary>
/// The target Character of this union.
/// </summary>
public Character Character { get; private set; }
/// <summary>
/// The target Targetable of this union.
/// </summary>
public Targetable Targetable { get; private set; }
/// <summary>
/// The target Point of this union.
/// </summary>
public Vector3 Point { get; private set; }
/// <summary>
/// Initializes a TargetUnion instance with a point target.
/// </summary>
/// <param name="point">Target point.</param>
public TargetUnion(Vector3 point)
: this()
{
Point = point;
Type = TargetType.Point;
}
/// <summary>
/// Initializes a TargetUnion instance with a character target.
/// </summary>
/// <param name="character">Target character.</param>
public TargetUnion(Character character)
: this()
{
Character = character;
Type = TargetType.Character;
}
/// <summary>
/// Initializes a TargetUnion instance with a targetable target.
/// </summary>
/// <param name="targetable">Target targetable.</param>
public TargetUnion(Targetable targetable)
: this()
{
Targetable = targetable;
Type = TargetType.Targetable;
}
/// <summary>
/// This method returns appropriate point from its target.
/// </summary>
/// <returns>Position of the target.</returns>
public Vector3 AsPoint()
{
switch (Type)
{
case TargetType.Point:
return Point;
case TargetType.Targetable:
return Targetable.transform.position;
case TargetType.Character:
return Character.transform.position;
}
return Vector3.zero;
}
/// <summary>
/// This method returns appropriate Targetable from its target.
/// </summary>
/// <returns>Targetable.</returns>
public Targetable AsTargetable()
{
switch (Type)
{
case TargetType.Targetable:
return Targetable;
case TargetType.Character:
return Character;
}
return null;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Media;
using System.Text;
namespace RaceManager.UI
{
public class SoundHelper
{
public static void PlaySound(string filePath, SystemSound altSound = null)
{
try
{
if (File.Exists(filePath))
{
var player = new SoundPlayer();
player.SoundLocation = filePath;
player.Play();
}
else
{
altSound?.Play();
}
}
catch (Exception e)
{
Debug.WriteLine(e.Message + e.StackTrace);
}
}
}
}
|
// ScoreHandler script: can save scores onto a binary file to disk.
// Use in conjunction with CntScores which renders scores to screen from file.
using System;
public class ScoreHandler
{
// Initialise the saving process from outside this class here
// E.g. ScoreHandler scoreHandler = new ScoreHandler();
// scoreHandler.Init(0, "Hard", Math.Round(stopWatch.Elapsed.TotalSeconds).ToString())
public void Init(int player, string gameMode, string timeTaken)
{
UpdateScoreList(player, gameMode, timeTaken);
}
private void UpdateScoreList(int player, string gameMode, string timeTaken)
{
string[] scoreStringArr = GetScoreStrings(player, gameMode, timeTaken);
// Make a save file unique to the game mode
string path = "PlayerData/Scores/Scores" + gameMode + ".wpd";
DataBinary scoreData = FileBinary.LoadFromFile(path);
if (scoreData == null)
{
CreateScoreList(scoreStringArr, path);
return;
}
AppendScoreList(scoreStringArr, path, scoreData);
}
private string[] GetScoreStrings(int player, string gameMode, string timeTaken)
{
// We need the date, game mode, player name, and time taken in seconds
string date = DateTime.Now.ToString("d/M/yyyy");
string playerName = player == 0 ? "Bob" : "John"; // placeholder - retrieve player name e.g. GameSettings.Instance.PlayerNames[player];
return new string[4] {date, gameMode, playerName, timeTaken};
}
private void CreateScoreList(string[] scoreStringArr, string path)
{
DataBinary scoreData = new DataBinary();
System.Collections.Generic.List<string[]> scoreList = new System.Collections.Generic.List<string[]>();
scoreList.Add(scoreStringArr);
System.Collections.Generic.Dictionary<string, object> scoreDataDict = new System.Collections.Generic.Dictionary<string, object>()
{
{"scoreList", scoreList}
};
scoreData.SaveBinary(scoreDataDict, path);
}
private void AppendScoreList(string[] scoreStringArr, string path, DataBinary scoreData)
{
System.Collections.Generic.List<string[]> scoreList = (System.Collections.Generic.List<string[]>)scoreData.Data["scoreList"];
if (scoreList.Count >= 12) // Maxlines = 12
scoreList.RemoveAt(11);
scoreList.Insert(0,scoreStringArr);
scoreData.Data["scoreList"] = scoreList;
scoreData.SaveBinary(scoreData.Data, path);
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace IRAP.Entity.Kanban
{
public class TVCtrlParam
{
public int IRAPTreeID { get; set; }
public int TreeViewType { get; set; }
public int EntryNode { get; set; }
public int DefaultWinWidth { get; set; }
public bool WinWidthAdjustable { get; set; }
public string CtrlPrompt { get; set; }
public bool IncludeLeaves { get; set; }
public bool ShowNodeID { get; set; }
public bool ShowNodeCode { get; set; }
public int OrderByMode { get; set; }
public int Accessibility { get; set; }
public int DITVCtrlVar { get; set; }
public string DSTVCtrlBlk { get; set; }
public string FilterClickStream { get; set; }
public string SelectClickStream { get; set; }
public TVCtrlParam Clone()
{
TVCtrlParam rlt = MemberwiseClone() as TVCtrlParam;
return rlt;
}
}
} |
namespace GraphDataStructure.Models
{
public class Edge
{
public long Id { get; set; }
public Vertex VertexA { get; set; }
public Vertex VertexB { get; set; }
}
} |
namespace Shipwreck.TypeScriptModels.Expressions
{
// 4.2
public sealed class ThisExpression : Expression
{
public override ExpressionPrecedence Precedence
=> ExpressionPrecedence.Grouping;
/// <inheritdoc />
/// <summary>
/// This method always calls <see cref="IExpressionVisitor{T}.VisitThis" />.
/// </summary>
public override void Accept<T>(IExpressionVisitor<T> visitor)
=> visitor.VisitThis();
}
} |
using SocialMedia.Data;
using SocialMedia.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SocialMedia.Services
{
//CODING HATES ME
public class PostService
{
private readonly Guid _userId;
public PostService(Guid userId)
{
_userId = userId;
}
public bool CreatePost(PostCreate model)
{
var entity =
new Post()
{
AuthorId = _userId,
Title = model.Title,
Text = model.Text,
};
using (var ctx = new ApplicationDbContext())
{
ctx.Posts.Add(entity);
return ctx.SaveChanges() == 1;
}
}
public IEnumerable<PostListItem> GetPostsById()
{
using (var ctx = new ApplicationDbContext())
{
var query = ctx.Posts.Where(e => e.AuthorId == _userId).Select(e => new PostListItem { Id = e.PostId, Title = e.Title, Text = e.Text });
return query.ToArray();
}
}
public IEnumerable<PostListItem> GetAllPosts()
{
using(var ctx = new ApplicationDbContext())
{
var posts = ctx.Posts.Select(e => new PostListItem { Id = e.PostId, Title = e.Title, Text = e.Text });
return posts.ToArray();
}
}
public bool UpdatePost(PostEdit model)
{
using (var ctx = new ApplicationDbContext())
{
var entity = ctx.Posts.Single(e => e.PostId == model.Id && e.AuthorId == _userId);
entity.Title = model.Title;
entity.Text = model.Text;
return ctx.SaveChanges() == 1;
}
}
public bool DeletePost(int postId)
{
using (var ctx = new ApplicationDbContext())
{
var entity = ctx.Posts.Single(e => e.PostId == postId && e.AuthorId == _userId);
ctx.Posts.Remove(entity);
return ctx.SaveChanges() == 1;
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Diagnostics;
using MakingThings;
namespace CPUMonitor
{
public partial class CPUMonitorWindow : Form
{
public CPUMonitorWindow()
{
InitializeComponent();
cpuCounter = new PerformanceCounter();
cpuCounter.CategoryName = "Processor";
cpuCounter.CounterName = "% Processor Time";
cpuCounter.InstanceName = "_Total";
usbPacket = new UsbPacket();
usbPacket.Open();
osc = new Osc(usbPacket);
// udpPacket = new UdpPacket();
// udpPacket.RemoteHostName = "192.168.0.200";
// udpPacket.RemotePort = 10000;
// udpPacket.LocalPort = 10000;
// udpPacket.Open();
// osc = new Osc(udpPacket);
}
private void timer1_Tick(object sender, EventArgs e)
{
if (!SpeedSet)
{
OscMessage oscMS = new OscMessage();
oscMS.Address = "/servo/0/speed";
oscMS.Values.Add((int)200);
osc.Send(oscMS);
SpeedSet = true;
}
float cpu = getCurrentCpuUsage();
CPU.Text = cpu.ToString();
int cpuSpeed = ((int)cpu) * 10;
if (cpuSpeed != lastCpuSpeed)
{
OscMessage oscM = new OscMessage();
oscM.Address = "/servo/0/position";
oscM.Values.Add(((int)cpu) * 10);
osc.Send(oscM);
lastCpuSpeed = cpuSpeed;
}
}
protected PerformanceCounter cpuCounter;
public float getCurrentCpuUsage()
{
return cpuCounter.NextValue();
}
private UsbPacket usbPacket;
//private UdpPacket udpPacket;
private Osc osc;
private int lastCpuSpeed;
private bool SpeedSet;
}
} |
/**
Copyright (c) 2020, Institut Curie, Institut Pasteur and CNRS
Thomas BLanc, Mohamed El Beheiry, Jean Baptiste Masson, Bassam Hajj and Clement Caporal
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
3. All advertising materials mentioning features or use of this software
must display the following acknowledgement:
This product includes software developed by the Institut Curie, Insitut Pasteur and CNRS.
4. Neither the name of the Institut Curie, Insitut Pasteur and CNRS nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER ''AS IS'' AND ANY
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
**/
using UnityEngine;
using UnityEngine.EventSystems;
using Unity.Collections;
using System.Collections.Generic;
namespace Display
{
/// <summary>
/// Script to put on a camera. Allow user to move the camera using the mouse around a "target" point
/// </summary>
public class DragMouseOrbit : MonoBehaviour
{
public Transform target;
public float distance = 0f;
public float sensitivityDistance = 1.5f;
public float distanceMin = -1f;
public float distanceMax = 10f;
//public float smoothTime = 8f;
bool _pressed;
bool _state;
bool interacting = false;
public bool State
{
get { return _state; }
set
{
if (_state == value) return;
_state = value;
if (OnStateChange != null)
OnStateChange(_state);
}
}
public delegate void OnStateChangeEvent(bool newVal);
public event OnStateChangeEvent OnStateChange;
public Vector3 cameraInitialPosition;
public float timesinceClick;
public float catchtime = 0.25f;
public bool reset = false;
private void OnDisable()
{
State = false;
}
private void OnEnable()
{
State = true;
}
void Start()
{
transform.position = new Vector3(0.0f, 0.0f, -distance);
cameraInitialPosition = transform.position;
Vector3 angles = transform.eulerAngles;
// Make the rigid body not change rotation
if (GetComponent<Rigidbody>())
{
GetComponent<Rigidbody>().freezeRotation = true;
}
_pressed = false;
}
public void Update()
{
if (reset)
{
reset = false;
}
if (Input.GetMouseButtonDown(0))
{
if (Time.time - timesinceClick < catchtime)
{
transform.position = cameraInitialPosition;
distance = 2.0f;
reset = true;
}
else
{
timesinceClick = Time.time;
reset = false;
}
}
}
void LateUpdate()
{
if(reset) { return; }
interacting = false;
if (EventSystem.current.IsPointerOverGameObject())
{
PointerEventData pointer = new PointerEventData(EventSystem.current);
pointer.position = Input.mousePosition;
List<RaycastResult> raycastResults = new List<RaycastResult>();
EventSystem.current.RaycastAll(pointer, raycastResults);
if (raycastResults.Count > 0 && raycastResults[0].gameObject.layer == LayerMask.NameToLayer("UI"))
{
return;
}
}
if (Input.GetMouseButton(0))
{
interacting = true;
if (_pressed || (!(GetComponent<Camera>().ScreenToViewportPoint(Input.mousePosition).y > 1 || GetComponent<Camera>().ScreenToViewportPoint(Input.mousePosition).x > 1)))
{
_pressed = true;
}
}
else
{
_pressed = false;
}
if ((!(GetComponent<Camera>().ScreenToViewportPoint(Input.mousePosition).y > 1 || GetComponent<Camera>().ScreenToViewportPoint(Input.mousePosition).x > 1)))
{
distance -= Input.GetAxis("Mouse ScrollWheel") * sensitivityDistance;
distance = Mathf.Clamp(distance, distanceMin, distanceMax);
}
Vector3 negDistance = new Vector3(0.0f, 0.0f, -distance);
Vector3 position = negDistance;
//GetComponent<Camera>().fieldOfView = Mathf.Lerp(GetComponent<Camera>().fieldOfView, distance, Time.deltaTime * 5f);
transform.position = Vector3.Lerp(transform.position, position, Time.deltaTime * 5f); ;
}
}
} |
using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity.ModelConfiguration;
namespace ServiceDeskSVC.DataAccess.Models.Mapping
{
public class AssetManager_AssetStatusMap : EntityTypeConfiguration<AssetManager_AssetStatus>
{
public AssetManager_AssetStatusMap()
{
// Primary Key
this.HasKey(t => t.Id);
// Properties
this.Property(t => t.Name)
.IsRequired()
.HasMaxLength(50);
// Table & Column Mappings
this.ToTable("AssetManager_AssetStatus");
this.Property(t => t.Id).HasColumnName("Id");
this.Property(t => t.Name).HasColumnName("Name");
this.Property(t => t.CreatedDate).HasColumnName("CreatedDate");
this.Property(t => t.CreatedById).HasColumnName("CreatedById");
this.Property(t => t.ModifiedDate).HasColumnName("ModifiedDate");
this.Property(t => t.ModifiedById).HasColumnName("ModifiedById");
// Relationships
this.HasRequired(t => t.ServiceDesk_Users)
.WithMany(t => t.AssetManager_AssetStatus)
.HasForeignKey(d => d.CreatedById);
this.HasOptional(t => t.ServiceDesk_Users1)
.WithMany(t => t.AssetManager_AssetStatus1)
.HasForeignKey(d => d.ModifiedById);
}
}
}
|
namespace UseFul.ClientApi.Dtos
{
public class DepartamentoUsuario: BaseDto<DepartamentoUsuario>
{
public int IdDepartamento { get; set; }
public string UserId { get; set; }
public DepartamentoUsuario()
{
}
}
}
|
using Autofac;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using NetCoreEntityFramework.Context;
using NetCoreEntityFramework.Repository;
using NetCoreEntityFramework.Services;
using Microsoft.OpenApi.Models;
using Autofac.Extensions.DependencyInjection;
using System;
using NetCoreEntityFramework.Utils;
using System.Reflection;
namespace NetCoreEntityFramework
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public IServiceProvider ConfigureServices(IServiceCollection services)
{
services.AddControllers();
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new OpenApiInfo { Title = "My API", Version = "v1" });
});
services.AddEntityFrameworkNpgsql()
.AddDbContext<UsuarioContext>(options =>
{
options.UseNpgsql("Server=Localhost;Port=5432;Database=instagram;User Id=postgres;Password=123456;",
b =>
{
b.MigrationsAssembly("NetCoreEntityFramework");
});
});
var builder = new ContainerBuilder();
builder.Populate(services);
builder.RegisterType<UsuarioService>().As<IUsuarioService>();
builder.RegisterType<UsuarioRepository>().As<IUsuarioRepository>();
builder.RegisterAssemblyTypes(typeof(RepositoryUsuarioContext<>).GetTypeInfo().Assembly)
.AsClosedTypesOf(typeof(IRepositoryUsuarioContext<>));
var container = builder.Build();
return new AutofacServiceProvider(container);
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseHttpsRedirection();
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
app.UseSwagger();
app.UseSwaggerUI(c =>
{
c.SwaggerEndpoint("/swagger/v1/swagger.json", "Test API V1");
});
}
}
}
|
namespace chat.Models
{
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity.Spatial;
public partial class Conversation
{
[Key]
[Column(Order = 0)]
[DatabaseGenerated(DatabaseGeneratedOption.None)]
public long Profile1_Fk { get; set; }
[Key]
[Column(Order = 1)]
[DatabaseGenerated(DatabaseGeneratedOption.None)]
public long Profile2_Fk { get; set; }
[DataType(DataType.DateTime)]
public DateTime Date { get; set; }
[StringLength(1000)]
public string Message { get; set; }
public bool Seen { get; set; }
[DataType(DataType.DateTime)]
public DateTime SeenDate { get; set; }
public virtual User_Profile Profile { get; set; }
}
}
|
using Parse;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace DoGoService.Models
{
public class DogOwner
{
public int userId { get; set; }
public string address { get; set; }
public string city { get; set; }
public bool isComfortable6To8 { get; set; }
public bool isComfortable8To10 { get; set; }
public bool isComfortable10To12 { get; set; }
public bool isComfortable12To14 { get; set; }
public bool isComfortable14To16 { get; set; }
public bool isComfortable16To18 { get; set; }
public bool isComfortable18To20 { get; set; }
public bool isComfortable20To22 { get; set; }
}
} |
using System;
using System.Runtime.InteropServices;
using System.Windows.Forms;
using NVRCsharpDemo;
using twpx.Model;
using twpx;
using System.IO;
namespace NVRCsharpDemo
{
class Camera
{
private string lid;//设备编号
private string lname;//设备名称
private string ip; //设备IP地址或者域名 Device IP
Int16 port;//设备服务端口号 Device Port
private string username;
private string password;
private bool m_bRecord = false; //录像标志
private Int32 UserID = -1; //-1表示失败,其他值表示返回的用户ID值。该用户ID具有唯一性,后续对设备的操作都需要通过此ID实现。
private Int32 m_lRealHandle=-1;//-1表示失败,其他值作为NET_DVR_StopRealPlay等函数的句柄参数
private Int32 m_lVirtualHandle = -1;//代表无参预览返回的参数
private uint dwAChanTotalNum; //设备模拟通道个数,数字(IP)通道最大个数为byIPChanNum + byHighDChanNum*256
private uint dwDChanTotalNum;//设备最大数字通道个数,低8位,高8位见byHighDChanNum
private uint iLastErr = 0; // 用于接收调用NET_DVR_GetLastError获取的错误码
private int[] iIPDevID = new int[96];
private int[] iChannelNum = new int[96];
public CHCNetSDK.NET_DVR_DEVICEINFO_V40 DeviceInfo;// 设备信息结构体
public CHCNetSDK.NET_DVR_IPPARACFG_V40 m_struIpParaCfgV40; //IP设备资源及IP通道资源配置结构体。
private long iSelIndex = 0;
private Int32 m_lTree = 0;
private string str;
private string str1;
private string str2;
private Int32 i = 0;
public CHCNetSDK.NET_DVR_IPCHANINFO struChanInfo;
public CHCNetSDK.NET_DVR_IPCHANINFO_V40 struChanInfoV40;
private int m_lFindHandle = -1;
private int m_lPlayHandle = -1;
private string strResult; //存储查找路径
private long lHandle;
//监听布防需要的变量
private Int32 m_lAlarmHandle = -1;//布防句柄
private int iPicNumber = 0; //图片序号
private CHCNetSDK.MSGCallBack m_falarmData = null;
public delegate void UpdateListBoxCallback(string strAlarmTime, string strDevIP, string strAlarmMsg);
CHCNetSDK.NET_VCA_TRAVERSE_PLANE m_struTraversePlane = new CHCNetSDK.NET_VCA_TRAVERSE_PLANE();
CHCNetSDK.NET_VCA_AREA m_struVcaArea = new CHCNetSDK.NET_VCA_AREA();
CHCNetSDK.NET_VCA_INTRUSION m_struIntrusion = new CHCNetSDK.NET_VCA_INTRUSION();
CHCNetSDK.UNION_STATFRAME m_struStatFrame = new CHCNetSDK.UNION_STATFRAME();
CHCNetSDK.UNION_STATTIME m_struStatTime = new CHCNetSDK.UNION_STATTIME();
//private CHCNetSDK.MSGCallBack_V31 m_falarmData_V31 = null;
Common Ccommon = new Common();
public Camera(){
lid = "131";
lname = "1教131门口摄像头";
ip = "192.168.1.107";
port = 8000;
username = "admin";
password = "lab12345678";
//login();
}
public Camera(string lid,string lname,string ip,Int16 port,string username,string password)
{
this.lid = lid;
this.lname = lname;
this.ip = ip;
this.port = port;
this.username = username;
this.password = password;
//login();
}
//监听布防初始化
public void initAlam()
{
byte[] strIP = new byte[16 * 16];
uint dwValidNum = 0;
Boolean bEnableBind = false;
//获取本地PC网卡IP信息
if (CHCNetSDK.NET_DVR_GetLocalIP(strIP, ref dwValidNum, ref bEnableBind))
{
if (dwValidNum > 0)
{
//取第一张网卡的IP地址为默认监听端口
CHCNetSDK.NET_DVR_SetValidIP(0, true); //绑定第一张网卡
}
}
//保存SDK日志 To save the SDK log
//CHCNetSDK.NET_DVR_SetLogToFile(3, "C:\\SdkLog\\", true);
/*
for (int i = 0; i < 200; i++)
{
m_lAlarmHandle[i] = -1;
}
//设置报警回调函数
if (m_falarmData_V31 == null)
{
m_falarmData_V31 = new CHCNetSDK.MSGCallBack_V31(MsgCallback_V31);
}
CHCNetSDK.NET_DVR_SetDVRMessageCallBack_V31(m_falarmData_V31, IntPtr.Zero);
*/
}
//设备登录
public bool login()
{
UserID = CHCNetSDK.NET_DVR_Login_V30(ip, port, username, password, ref DeviceInfo);
if (UserID < 0)
{
iLastErr = CHCNetSDK.NET_DVR_GetLastError();
Ccommon.AddLog("iLastErr = " + iLastErr);
return false;
}
else
{
//登录成功
dwAChanTotalNum = DeviceInfo.byChanNum;
dwDChanTotalNum = DeviceInfo.byIPChanNum + 256 * (uint)DeviceInfo.byHighDChanNum;
if (dwDChanTotalNum > 0)
{
deviceInfoIPChannel();
}
else
{
for (i = 0; i < dwAChanTotalNum; i++)
{
deviceListAnalogChannel(i + 1, 1);
iChannelNum[i] = i + DeviceInfo.byStartChan;
}
}
Ccommon.AddLog("登录成功");
return true;
}
}
//设备注销
public bool logout()
{
if (m_bRecord)
{
Ccommon.AddLog("请先停止录像");
return false;
}
if (m_lRealHandle >= 0)
{
CHCNetSDK.NET_DVR_StopRealPlay(m_lRealHandle);
m_lRealHandle = -1;
}
if (UserID >= 0)
{
CHCNetSDK.NET_DVR_Logout(UserID);
UserID = -1;
return true;
}
return false;
}
//ip通道配置
public void deviceInfoIPChannel()
{
uint dwSize = (uint)Marshal.SizeOf(m_struIpParaCfgV40);
IntPtr ptrIpParaCfgV40 = Marshal.AllocHGlobal((Int32)dwSize);
Marshal.StructureToPtr(m_struIpParaCfgV40, ptrIpParaCfgV40, false);
uint dwReturn = 0;
int iGroupNo = 0; //该Demo仅获取第一组64个通道,如果设备IP通道大于64路,需要按组号0~i多次调用NET_DVR_GET_IPPARACFG_V40获取
if (!CHCNetSDK.NET_DVR_GetDVRConfig(UserID, CHCNetSDK.NET_DVR_GET_IPPARACFG_V40, iGroupNo, ptrIpParaCfgV40, dwSize, ref dwReturn))
{
iLastErr = CHCNetSDK.NET_DVR_GetLastError();
/*
str = "NET_DVR_GET_IPPARACFG_V40 failed, error code= " + iLastErr;
获取IP资源配置信息失败,输出错误号 Failed to get configuration of IP channels and output the error code
DebugInfo(str);
*/
}
else
{
m_struIpParaCfgV40 = (CHCNetSDK.NET_DVR_IPPARACFG_V40)Marshal.PtrToStructure(ptrIpParaCfgV40, typeof(CHCNetSDK.NET_DVR_IPPARACFG_V40));
for (i = 0; i < dwAChanTotalNum; i++)
{
deviceListAnalogChannel(i + 1, m_struIpParaCfgV40.byAnalogChanEnable[i]);
iChannelNum[i] = i + (int)DeviceInfo.byStartChan;
}
byte byStreamType = 0;
uint iDChanNum = 64;
if (dwDChanTotalNum < 64)
{
iDChanNum = dwDChanTotalNum; //如果设备IP通道小于64路,按实际路数获取
}
for (i = 0; i < iDChanNum; i++)
{
iChannelNum[i + dwAChanTotalNum] = i + (int)m_struIpParaCfgV40.dwStartDChan;
byStreamType = m_struIpParaCfgV40.struStreamMode[i].byGetStreamType;
dwSize = (uint)Marshal.SizeOf(m_struIpParaCfgV40.struStreamMode[i].uGetStream);
switch (byStreamType)
{
//目前NVR仅支持直接从设备取流 NVR supports only the mode: get stream from device directly
case 0:
IntPtr ptrChanInfo = Marshal.AllocHGlobal((Int32)dwSize);
Marshal.StructureToPtr(m_struIpParaCfgV40.struStreamMode[i].uGetStream, ptrChanInfo, false);
struChanInfo = (CHCNetSDK.NET_DVR_IPCHANINFO)Marshal.PtrToStructure(ptrChanInfo, typeof(CHCNetSDK.NET_DVR_IPCHANINFO));
//列出IP通道 List the IP channel
deviceListIPChannel(i + 1, struChanInfo.byEnable, struChanInfo.byIPID);
iIPDevID[i] = struChanInfo.byIPID + struChanInfo.byIPIDHigh * 256 - iGroupNo * 64 - 1;
Marshal.FreeHGlobal(ptrChanInfo);
break;
case 6:
IntPtr ptrChanInfoV40 = Marshal.AllocHGlobal((Int32)dwSize);
Marshal.StructureToPtr(m_struIpParaCfgV40.struStreamMode[i].uGetStream, ptrChanInfoV40, false);
struChanInfoV40 = (CHCNetSDK.NET_DVR_IPCHANINFO_V40)Marshal.PtrToStructure(ptrChanInfoV40, typeof(CHCNetSDK.NET_DVR_IPCHANINFO_V40));
//列出IP通道 List the IP channel
deviceListIPChannel(i + 1, struChanInfoV40.byEnable, struChanInfoV40.wIPID);
iIPDevID[i] = struChanInfoV40.wIPID - iGroupNo * 64 - 1;
Marshal.FreeHGlobal(ptrChanInfoV40);
break;
default:
break;
}
}
}
Marshal.FreeHGlobal(ptrIpParaCfgV40);
}
//
public void deviceListIPChannel(Int32 iChanNo, byte byOnline, int byIPID)
{
str1 = string.Format("IPCamera {0}", iChanNo);
m_lTree++;
if (byIPID == 0)
{
str2 = "X"; //通道空闲,没有添加前端设备 the channel is idle
}
else
{
if (byOnline == 0)
{
str2 = "offline"; //通道不在线 the channel is off-line
}
else
str2 = "online"; //通道在线 The channel is on-line
}
//listViewIPChannel.Items.Add(new ListViewItem(new string[] { str1, str2 }));将通道添加到列表中 add the channel to the list
}
//
public void deviceListAnalogChannel(Int32 iChanNo, byte byEnable)
{
str1 = string.Format("Camera {0}", iChanNo);
m_lTree++;
if (byEnable == 0)
{
str2 = "Disabled"; //通道已被禁用 This channel has been disabled
}
else
{
str2 = "Enabled"; //通道处于启用状态 This channel has been enabled
}
//将通道添加到列表中 add the channel to the list
//listViewIPChannel.Items.Add(new ListViewItem(new string[] { str1, str2 }));
}
//实时预览
public bool realPlay(PictureBox pictureBox)
{
// 检查设备登录状态
if (UserID < 0)
{
Ccommon.AddLog("请先登录设备!");
return false;
}
// 检查录像状态
if (m_bRecord)
{
Ccommon.AddLog("请先停止录像!");
return false;
}
if (m_lRealHandle < 0)
{
//预览参数结构体。
CHCNetSDK.NET_DVR_PREVIEWINFO lpPreviewInfo = new CHCNetSDK.NET_DVR_PREVIEWINFO();
//播放窗口的句柄,为NULL表示不解码显示
lpPreviewInfo.hPlayWnd = pictureBox.Handle;//预览窗口 live view window
//通道号,目前设备模拟通道号从1开始,数字通道的起始通道号通过NET_DVR_GetDVRConfig(配置命令NET_DVR_GET_IPPARACFG_V40)获取(dwStartDChan)
lpPreviewInfo.lChannel = iChannelNum[(int)iSelIndex];//预览的设备通道 the device channel number
//码流类型:0-主码流,1-子码流,2-三码流,3-虚拟码流,以此类推
lpPreviewInfo.dwStreamType = 0;
//连接方式:0- TCP方式,1- UDP方式,2- 多播方式,3- RTP方式,4- RTP/RTSP,5- RTP/HTTP,6- HRUDP(可靠传输)
lpPreviewInfo.dwLinkMode = 0;
//若设为不阻塞,表示发起与设备的连接就认为连接成功,如果发生码流接收失败、播放失败等情况以预览异常的方式通知上层。在循环播放的时候可以减短停顿的时间,与NET_DVR_RealPlay处理一致。
//若设为阻塞,表示直到播放操作完成才返回成功与否,网络异常时SDK内部connect失败将会有5s的超时才能够返回,不适合于轮询取流操作。
lpPreviewInfo.bBlocked = true; //0- 非阻塞取流,1- 阻塞取流
//播放库播放缓冲区最大缓冲帧数,取值范围:1、6(默认,自适应播放模式)、15,置0时默认为1
lpPreviewInfo.dwDisplayBufNum = 15; //播放库显示缓冲区最大帧数
IntPtr pUser = IntPtr.Zero;//用户数据 user data
//打开预览 Start live view
//[in] NET_DVR_Login_V40等登录接口的返回值 ,[in] 预览参数 ,[in] 码流数据回调函数,[in] 用户数据
m_lRealHandle = CHCNetSDK.NET_DVR_RealPlay_V40(UserID, ref lpPreviewInfo, null/*RealData*/, pUser);
if (m_lRealHandle < 0)
{
iLastErr = CHCNetSDK.NET_DVR_GetLastError();
string str = "预览失败,输出错误号: " + iLastErr; //预览失败,输出错误号 failed to start live view, and output the error code.
Ccommon.AddLog(str);
return false;
}
else
{
Ccommon.AddLog(" " + ip + ": 预览成功");
return true;
}
}
return true;
}
//停止预览
public bool stopPlay()
{
if (m_lRealHandle < 0)
{
return true;
}
if (!CHCNetSDK.NET_DVR_StopRealPlay(m_lRealHandle))
{
iLastErr = CHCNetSDK.NET_DVR_GetLastError();
string str = "NET_DVR_StopRealPlay failed, error code= " + iLastErr + ", IP = " + ip;
Ccommon.AddLog(str);
return false;
}
Ccommon.AddLog("停止预览成功!");
m_lRealHandle = -1;
//pictureBox.Invalidate();//刷新窗口 refresh the window
return true;
}
//无参预览
public bool realVirtualPlay()
{
// 检查设备登录状态
if (UserID < 0)
{
Ccommon.AddLog("请先登录设备!");
return false;
}
// 检查录像状态
if (m_bRecord)
{
Ccommon.AddLog("请先停止录像!");
return false;
}
if (m_lVirtualHandle < 0)
{
//预览参数结构体。
CHCNetSDK.NET_DVR_PREVIEWINFO lpPreviewInfo = new CHCNetSDK.NET_DVR_PREVIEWINFO();
//播放窗口的句柄,为NULL表示不解码显示
//lpPreviewInfo.hPlayWnd = null;//预览窗口 live view window
//通道号,目前设备模拟通道号从1开始,数字通道的起始通道号通过NET_DVR_GetDVRConfig(配置命令NET_DVR_GET_IPPARACFG_V40)获取(dwStartDChan)
lpPreviewInfo.lChannel = 1;//预览的设备通道 the device channel number
//码流类型:0-主码流,1-子码流,2-三码流,3-虚拟码流,以此类推
lpPreviewInfo.dwStreamType = 0;
//连接方式:0- TCP方式,1- UDP方式,2- 多播方式,3- RTP方式,4- RTP/RTSP,5- RTP/HTTP,6- HRUDP(可靠传输)
lpPreviewInfo.dwLinkMode = 0;
//若设为不阻塞,表示发起与设备的连接就认为连接成功,如果发生码流接收失败、播放失败等情况以预览异常的方式通知上层。在循环播放的时候可以减短停顿的时间,与NET_DVR_RealPlay处理一致。
//若设为阻塞,表示直到播放操作完成才返回成功与否,网络异常时SDK内部connect失败将会有5s的超时才能够返回,不适合于轮询取流操作。
lpPreviewInfo.bBlocked = true; //0- 非阻塞取流,1- 阻塞取流
//播放库播放缓冲区最大缓冲帧数,取值范围:1、6(默认,自适应播放模式)、15,置0时默认为1
lpPreviewInfo.dwDisplayBufNum = 15; //播放库显示缓冲区最大帧数
IntPtr pUser = IntPtr.Zero;//用户数据 user data
//打开预览 Start live view
//[in] NET_DVR_Login_V40等登录接口的返回值 ,[in] 预览参数 ,[in] 码流数据回调函数,[in] 用户数据
m_lVirtualHandle = CHCNetSDK.NET_DVR_RealPlay_V40(UserID, ref lpPreviewInfo, null/*RealData*/, pUser);
if (m_lVirtualHandle < 0)
{
iLastErr = CHCNetSDK.NET_DVR_GetLastError();
string str = "预览失败,输出错误号: " + iLastErr; //预览失败,输出错误号 failed to start live view, and output the error code.
Ccommon.AddLog(str);
return false;
}
else
{
Ccommon.AddLog(" " + ip + ": 无参预览成功");
return true;
}
}
return true;
}
//停止无参预览
public bool stopVirtualPlay()
{
if (m_lVirtualHandle < 0)
{
return true;
}
if (!CHCNetSDK.NET_DVR_StopRealPlay(m_lVirtualHandle))
{
iLastErr = CHCNetSDK.NET_DVR_GetLastError();
string str = "NET_DVR_StopRealPlay failed, error code= " + iLastErr + ", IP = " + ip;
Ccommon.AddLog(str);
return false;
}
Ccommon.AddLog("无参预览停止成功");
m_lVirtualHandle = -1;
return true;
}
//录像
public string startRecord(string FileName)
{
//录像保存路径和文件名 the path and file name to save
if (m_bRecord == false)
{
//强制I帧 Make a I frame
int lChannel = 1; //通道号 Channel number
CHCNetSDK.NET_DVR_MakeKeyFrame(UserID, lChannel);
//开始录像 Start recording
if (!CHCNetSDK.NET_DVR_SaveRealData(m_lVirtualHandle, FileName))
{
iLastErr = CHCNetSDK.NET_DVR_GetLastError();
string str = "NET_DVR_SaveRealData failed, error code= " + iLastErr;
Ccommon.AddLog(str);
return null;
}
else
{
Ccommon.AddLog("Succeed to recording...");
m_bRecord = true;
return FileName;
}
}
else
{
//停止录像 Stop recording
if (!CHCNetSDK.NET_DVR_StopSaveRealData(m_lVirtualHandle))
{
iLastErr = CHCNetSDK.NET_DVR_GetLastError();
string str = "NET_DVR_StopSaveRealData failed, error code= " + iLastErr;
Ccommon.AddLog(str);
return null;
}
else
{
string str = "Successful to stop recording and the saved file is " + FileName;
Ccommon.AddLog(str);
m_bRecord = false;
return FileName;
}
}
}
//停止录像
public void stopRecord()
{
}
//无窗口参录像
public string SaveRecord(string saveFile)
{
bool isRecord = m_bRecord;
if (!isRecord)//如果没在录像,启动预览
{
realVirtualPlay();
}
startRecord(saveFile);
if (isRecord)//如果正在录像,不停止无参预览
stopVirtualPlay();
return saveFile;
}
//获取编号
public string getLid()
{
return lid;
}
//获取设备名称
public string getLname()
{
return lname;
}
//获取IP
public string getIp()
{
return ip;
}
//获取端口号
public Int16 getPort()
{
return port;
}
//获取用户名
public string getUserName()
{
return username;
}
//获取用户密码
public string getPassword()
{
return password;
}
//获取userID
public Int32 getUserID()
{
return UserID;
}
//获取m_bRecord
public bool getBRecord()
{
return m_bRecord;
}
//tostring()
public void CameraToString()
{
Console.WriteLine("Lid: " + getLid());
Console.WriteLine("Lname = " + getLname());
Console.WriteLine("IP: " + getIp());
Console.WriteLine("Port: " + getPort());
Console.WriteLine("UserName: " + getUserName());
Console.WriteLine("Password: " + getPassword());
Console.WriteLine("UserID: " + getUserID());
}
//抓图BMP
public string saveBMP()
{
if (m_lRealHandle < 0)
{
MessageBox.Show("Please start live view firstly!"); //BMP抓图需要先打开预览
return null;
}
DateTime date = DateTime.Today;
string sBmpPicFileName;
//图片保存路径和文件名 the path and file name to save
//+ "-" + UserID + "_" + date.ToString("hh:mm:ss")
sBmpPicFileName = "D:\\" + date.ToString("yyyy-MM-dd") + ".bmp";
//BMP抓图 Capture a BMP picture
if (!CHCNetSDK.NET_DVR_CapturePicture(m_lRealHandle, sBmpPicFileName))
{
iLastErr = CHCNetSDK.NET_DVR_GetLastError();
string str = "NET_DVR_CapturePicture failed, error code= " + iLastErr;
MessageBox.Show(str);
return null;
}
else
{
string str = "Successful to capture the BMP file and the saved file is " + sBmpPicFileName;
MessageBox.Show(str);
}
return sBmpPicFileName;
}
//抓图JPEG
public string saveJPEG()
{
DateTime date = DateTime.Today;
string sJpegPicFileName;
//图片保存路径和文件名 the path and file name to save
// + "/" + UserID + "_" + date.ToString("hh:mm:ss")
sJpegPicFileName = "D:\\" + date.ToString("yyyy-MM-dd") + ".jpg";
int lChannel = 1; //通道号 Channel number
CHCNetSDK.NET_DVR_JPEGPARA lpJpegPara = new CHCNetSDK.NET_DVR_JPEGPARA();
lpJpegPara.wPicQuality = 0; //图像质量 Image quality 0-最好
lpJpegPara.wPicSize = 0xff; //抓图分辨率 Picture size: 2- 4CIF,0xff- Auto(使用当前码流分辨率),抓图分辨率需要设备支持,更多取值请参考SDK文档
//JPEG抓图 Capture a JPEG picture
if (!CHCNetSDK.NET_DVR_CaptureJPEGPicture(UserID, lChannel, ref lpJpegPara, sJpegPicFileName))
{
iLastErr = CHCNetSDK.NET_DVR_GetLastError();
str = "NET_DVR_CaptureJPEGPicture failed, error code= " + iLastErr;
MessageBox.Show(str);
return null;
}
else
{
str = "Successful to capture the JPEG file and the saved file is " + sJpegPicFileName;
MessageBox.Show(str);
}
return sJpegPicFileName;
}
//报警回调函数1
public bool MsgCallback_V31(int lCommand, ref CHCNetSDK.NET_DVR_ALARMER pAlarmer, IntPtr pAlarmInfo, uint dwBufLen, IntPtr pUser)
{
//通过lCommand来判断接收到的报警信息类型,不同的lCommand对应不同的pAlarmInfo内容
AlarmMessageHandle(lCommand, ref pAlarmer, pAlarmInfo, dwBufLen, pUser);
return true; //回调函数需要有返回,表示正常接收到数据
}
//报警回调函数2
public void MsgCallback(int lCommand, ref CHCNetSDK.NET_DVR_ALARMER pAlarmer, IntPtr pAlarmInfo, uint dwBufLen, IntPtr pUser)
{
//通过lCommand来判断接收到的报警信息类型,不同的lCommand对应不同的pAlarmInfo内容
AlarmMessageHandle(lCommand, ref pAlarmer, pAlarmInfo, dwBufLen, pUser);
}
//报警回调函数3
public void AlarmMessageHandle(int lCommand, ref CHCNetSDK.NET_DVR_ALARMER pAlarmer, IntPtr pAlarmInfo, uint dwBufLen, IntPtr pUser)
{
//通过lCommand来判断接收到的报警信息类型,不同的lCommand对应不同的pAlarmInfo内容
switch (lCommand)
{
case CHCNetSDK.COMM_UPLOAD_FACESNAP_RESULT://人脸抓拍结果信息
ProcessCommAlarm_FaceSnap(ref pAlarmer, pAlarmInfo, dwBufLen, pUser);
break;
/*
case CHCNetSDK.COMM_SNAP_MATCH_ALARM://人脸比对结果信息
ProcessCommAlarm_FaceMatch(ref pAlarmer, pAlarmInfo, dwBufLen, pUser);
break;
*/
default:
{
/*
//报警设备IP地址
string strIP = ip;
//报警信息类型
string stringAlarm = "报警上传,信息类型:" + lCommand;
if (InvokeRequired)
{
object[] paras = new object[3];
paras[0] = DateTime.Now.ToString(); //当前PC系统时间
paras[1] = strIP;
paras[2] = stringAlarm;
listViewAlarmInfo.BeginInvoke(new UpdateListBoxCallback(UpdateClientList), paras);
}
else
{
//创建该控件的主线程直接更新信息列表
UpdateClientList(DateTime.Now.ToString(), strIP, stringAlarm);
}
*/
}
break;
}
}
//人脸抓拍结果信息
private void ProcessCommAlarm_FaceSnap(ref CHCNetSDK.NET_DVR_ALARMER pAlarmer, IntPtr pAlarmInfo, uint dwBufLen, IntPtr pUser)
{
CHCNetSDK.NET_VCA_FACESNAP_RESULT struFaceSnapInfo = new CHCNetSDK.NET_VCA_FACESNAP_RESULT();
uint dwSize = (uint)Marshal.SizeOf(struFaceSnapInfo);
struFaceSnapInfo = (CHCNetSDK.NET_VCA_FACESNAP_RESULT)Marshal.PtrToStructure(pAlarmInfo, typeof(CHCNetSDK.NET_VCA_FACESNAP_RESULT));
//报警设备IP地址
string strIP = ip;
//保存抓拍图片数据
if ((struFaceSnapInfo.dwBackgroundPicLen != 0) && (struFaceSnapInfo.pBuffer2 != IntPtr.Zero))
{
iPicNumber++;
string str = ".\\picture\\FaceSnap_CapPic_[" + strIP + "]_lUerID_[" + pAlarmer.lUserID + "]_" + iPicNumber + ".jpg";
FileStream fs = new FileStream(str, FileMode.Create);
int iLen = (int)struFaceSnapInfo.dwBackgroundPicLen;
byte[] by = new byte[iLen];
Marshal.Copy(struFaceSnapInfo.pBuffer2, by, 0, iLen);
fs.Write(by, 0, iLen);
fs.Close();
}
//报警时间:年月日时分秒
string strTimeYear = ((struFaceSnapInfo.dwAbsTime >> 26) + 2000).ToString();
string strTimeMonth = ((struFaceSnapInfo.dwAbsTime >> 22) & 15).ToString("d2");
string strTimeDay = ((struFaceSnapInfo.dwAbsTime >> 17) & 31).ToString("d2");
string strTimeHour = ((struFaceSnapInfo.dwAbsTime >> 12) & 31).ToString("d2");
string strTimeMinute = ((struFaceSnapInfo.dwAbsTime >> 6) & 63).ToString("d2");
string strTimeSecond = ((struFaceSnapInfo.dwAbsTime >> 0) & 63).ToString("d2");
string strTime = strTimeYear + "-" + strTimeMonth + "-" + strTimeDay + " " + strTimeHour + ":" + strTimeMinute + ":" + strTimeSecond;
string stringAlarm = "人脸抓拍结果,前端设备IP:" + strIP + ",抓拍时间:" + strTime;
/*
if (InvokeRequired)
{
object[] paras = new object[3];
paras[0] = DateTime.Now.ToString(); //当前PC系统时间
paras[1] = strIP;
paras[2] = stringAlarm;
listViewAlarmInfo.BeginInvoke(new UpdateListBoxCallback(UpdateClientList), paras);
}
else
{
//创建该控件的主线程直接更新信息列表
UpdateClientList(DateTime.Now.ToString(), strIP, stringAlarm);
}
*/
}
//设置布防句柄
public void SetM_lAlarmHandle(Int32 AlarmHandle)
{
m_lAlarmHandle = AlarmHandle;
}
//返回布防句柄
public Int32 GetM_lAlarmHandle()
{
return m_lAlarmHandle;
}
//布防
public void SetAlarm(CHCNetSDK.NET_DVR_SETUPALARM_PARAM struAlarmParam)
{
m_lAlarmHandle = CHCNetSDK.NET_DVR_SetupAlarmChan_V41(UserID, ref struAlarmParam);
}
//撤防
public bool CloseAlarm()
{
if(m_lAlarmHandle >= 0)
{
if (!CHCNetSDK.NET_DVR_CloseAlarmChan_V30(m_lAlarmHandle))
{
return false;
}
else
{
return true;
}
}
return true;
}
/*
//人脸比对结果信息
private void ProcessCommAlarm_FaceMatch(ref CHCNetSDK.NET_DVR_ALARMER pAlarmer, IntPtr pAlarmInfo, uint dwBufLen, IntPtr pUser)
{
CHCNetSDK.NET_VCA_FACESNAP_MATCH_ALARM struFaceMatchAlarm = new CHCNetSDK.NET_VCA_FACESNAP_MATCH_ALARM();
uint dwSize = (uint)Marshal.SizeOf(struFaceMatchAlarm);
struFaceMatchAlarm = (CHCNetSDK.NET_VCA_FACESNAP_MATCH_ALARM)Marshal.PtrToStructure(pAlarmInfo, typeof(CHCNetSDK.NET_VCA_FACESNAP_MATCH_ALARM));
//报警设备IP地址
string strIP = ip;
//保存抓拍人脸子图图片数据
if ((struFaceMatchAlarm.struSnapInfo.dwSnapFacePicLen != 0) && (struFaceMatchAlarm.struSnapInfo.pBuffer1 != IntPtr.Zero))
{
iPicNumber++;
string str = ".\\picture\\FaceMatch_FacePic_[" + strIP + "]_lUerID_[" + pAlarmer.lUserID + "]_" + iPicNumber + ".jpg";
FileStream fs = new FileStream(str, FileMode.Create);
int iLen = (int)struFaceMatchAlarm.struSnapInfo.dwSnapFacePicLen;
byte[] by = new byte[iLen];
Marshal.Copy(struFaceMatchAlarm.struSnapInfo.pBuffer1, by, 0, iLen);
fs.Write(by, 0, iLen);
fs.Close();
}
//保存比对结果人脸库人脸图片数据
if ((struFaceMatchAlarm.struBlackListInfo.dwBlackListPicLen != 0) && (struFaceMatchAlarm.struBlackListInfo.pBuffer1 != IntPtr.Zero))
{
iPicNumber++;
string str = ".\\picture\\FaceMatch_BlackListPic_[" + strIP + "]_lUerID_[" + pAlarmer.lUserID + "]" +
"_fSimilarity[" + struFaceMatchAlarm.fSimilarity + "]_" + iPicNumber + ".jpg";
FileStream fs = new FileStream(str, FileMode.Create);
int iLen = (int)struFaceMatchAlarm.struBlackListInfo.dwBlackListPicLen;
byte[] by = new byte[iLen];
Marshal.Copy(struFaceMatchAlarm.struBlackListInfo.pBuffer1, by, 0, iLen);
fs.Write(by, 0, iLen);
fs.Close();
}
//抓拍时间:年月日时分秒
string strTimeYear = ((struFaceMatchAlarm.struSnapInfo.dwAbsTime >> 26) + 2000).ToString();
string strTimeMonth = ((struFaceMatchAlarm.struSnapInfo.dwAbsTime >> 22) & 15).ToString("d2");
string strTimeDay = ((struFaceMatchAlarm.struSnapInfo.dwAbsTime >> 17) & 31).ToString("d2");
string strTimeHour = ((struFaceMatchAlarm.struSnapInfo.dwAbsTime >> 12) & 31).ToString("d2");
string strTimeMinute = ((struFaceMatchAlarm.struSnapInfo.dwAbsTime >> 6) & 63).ToString("d2");
string strTimeSecond = ((struFaceMatchAlarm.struSnapInfo.dwAbsTime >> 0) & 63).ToString("d2");
string strTime = strTimeYear + "-" + strTimeMonth + "-" + strTimeDay + " " + strTimeHour + ":" + strTimeMinute + ":" + strTimeSecond;
string stringAlarm = "人脸比对报警,抓拍设备:" + System.Text.Encoding.UTF8.GetString(struFaceMatchAlarm.struSnapInfo.struDevInfo.struDevIP.sIpV4).TrimEnd('\0') + ",抓拍时间:"
+ strTime + ",相似度:" + struFaceMatchAlarm.fSimilarity;
if (InvokeRequired)
{
object[] paras = new object[3];
paras[0] = DateTime.Now.ToString(); //当前PC系统时间
paras[1] = strIP;
paras[2] = stringAlarm;
listViewAlarmInfo.BeginInvoke(new UpdateListBoxCallback(UpdateClientList), paras);
}
else
{
//创建该控件的主线程直接更新信息列表
UpdateClientList(DateTime.Now.ToString(), strIP, stringAlarm);
}
}
*/
/*
//启动监听
private void startListen()
{
string sLocalIP = textBoxListenIP.Text;
ushort wLocalPort = ushort.Parse(textBoxListenPort.Text);
if (m_falarmData == null)
{
m_falarmData = new CHCNetSDK.MSGCallBack(MsgCallback);
}
iListenHandle = CHCNetSDK.NET_DVR_StartListen_V30(sLocalIP, wLocalPort, m_falarmData, IntPtr.Zero);
if (iListenHandle < 0)
{
iLastErr = CHCNetSDK.NET_DVR_GetLastError();
strErr = "启动监听失败,错误号:" + iLastErr; //启动监听失败,输出错误号
MessageBox.Show(strErr);
}
else
{
MessageBox.Show("成功启动监听!");
btnStopListen.Enabled = true;
btnStartListen.Enabled = false;
}
}
//关闭监听
private void stopListen()
{
if (!CHCNetSDK.NET_DVR_StopListen_V30(iListenHandle))
{
iLastErr = CHCNetSDK.NET_DVR_GetLastError();
strErr = "停止监听失败,错误号:" + iLastErr; //撤防失败,输出错误号
MessageBox.Show(strErr);
}
else
{
MessageBox.Show("停止监听!");
btnStopListen.Enabled = false;
btnStartListen.Enabled = true;
}
}
*/
}
}
|
using UnityEngine;
using System.IO;
using System.Text;
using System.Collections.Generic;
namespace AssemblyCSharp
{
public class Texto : MonoBehaviour
{
public string nombreFichero;
private const string PATH = "Assets/Textos/";
public List<string> GetTextos ()
{
List<string> textos;
textos = new List<string> ();
string linea;
StreamReader lector = new StreamReader (PATH + nombreFichero + ".txt", Encoding.Default);
using (lector) {
do {
linea = lector.ReadLine ();
if (linea != null) {
textos.Add (linea);
}
} while (linea != null);
}
return textos;
}
}
} |
using Fingo.Auth.DbAccess.Repository.Interfaces;
using Fingo.Auth.Domain.CustomData.Factories.Actions.Implementation;
using Fingo.Auth.Domain.CustomData.Factories.Actions.Interfaces;
using Fingo.Auth.Domain.CustomData.Factories.Implementation;
using Fingo.Auth.Domain.CustomData.Factories.Interfaces;
using Fingo.Auth.Domain.CustomData.Services.Interfaces;
using Moq;
using Xunit;
namespace Fingo.Auth.Domain.CustomData.Tests.Factories.Implementation
{
public class GetCustomDataConfigurationOrDefaultForProjectFactoryTest
{
[Fact]
public void
GetCustomDataConfigurationOrDefaultForProjectFactory_Should_Return_Instance_Of_GetCustomDataConfigurationOrDefaultForProject_Given_By_IGetCustomDataConfigurationOrDefaultForProject
()
{
//Arrange
var customDataJsonConvertServiceMock = new Mock<ICustomDataJsonConvertService>();
var projectMock = new Mock<IProjectRepository>();
//Act
IGetCustomDataConfigurationOrDefaultForProjectFactory target =
new GetCustomDataConfigurationOrDefaultForProjectFactory(projectMock.Object ,
customDataJsonConvertServiceMock.Object);
var result = target.Create();
//Assert
Assert.NotNull(result);
Assert.IsType<GetCustomDataConfigurationOrDefaultForProject>(result);
Assert.IsAssignableFrom<IGetCustomDataConfigurationOrDefaultForProject>(result);
}
}
} |
using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using System.Xml.Serialization;
using KartObjects;
namespace KartLib.Special
{
[Serializable]
public class ImportDocumentFromExlParamSettings : Entity
{
[XmlIgnore]
public override string FriendlyName
{
get { return ""; }
}
[XmlElement("listSettings")]
public List<ExcelImportSettings> ListSettings { get; set; }
}
public class ExcelImportSettings
{
public string Name { get; set; }
public string Table { get; set; }
public int GoodPosition { get; set; }
public int ArticulPosition { get; set; }
public int QuantityPosition { get; set; }
public int PricePosition { get; set; }
public int MeasurePosition { get; set; }
public int BarcodePosition { get; set; }
public bool CreateGood { get; set; }
public int TableYPosition
{
get { return Convert.ToInt32(Regex.Replace(Table, "[^0-9.]", "")); }
}
}
} |
using System;
using System.Collections.Generic;
using System.Text;
using System.Reflection;
using CSConsoleRL.Entities;
using CSConsoleRL.Components;
namespace CSConsoleRL.Helpers
{
public static class DependencyInjectionHelper
{
private static readonly IDictionary<Type, object> _typeInstances = new Dictionary<Type, object>();
public static void Register(object instance)
{
if (_typeInstances.ContainsKey(instance.GetType()))
{
throw new Exception(String.Format("DependencyInjectionHelper already contains type {0}", instance.GetType().ToString()));
}
_typeInstances.Add(instance.GetType(), instance);
}
/// <summary>
/// Returns the specified object type, if it doesn't exist it will be constructed and added to DI helper
/// </summary>
/// <param name="type"></param>
/// <returns></returns>
public static object Resolve(Type type)
{
if (_typeInstances.ContainsKey(type))
{
return _typeInstances[type];
}
else
{
var constructor = type.GetConstructors()[0];
var parameterInfos = constructor.GetParameters();
var parameters = new List<object>();
foreach (var parameterInfo in parameterInfos)
{
if (_typeInstances.ContainsKey(parameterInfo.ParameterType))
{
parameters.Add(_typeInstances[parameterInfo.ParameterType]);
}
else
{
throw new Exception(String.Format(
"DependencyInjectionHelper was called to Resolve type {0}, but is missing type {1} which is required by Constructor",
type.ToString(),
parameterInfo.ParameterType.ToString()
)
);
}
}
var typeInstance = constructor.Invoke(parameters.ToArray());
Register(typeInstance);
return typeInstance;
}
}
}
}
|
using gView.Framework.Sys.UI.Extensions;
using gView.Framework.UI;
using System;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace gView.Plugins.MapTools.Dialogs
{
internal partial class FormLegend : Form
{
private IMapDocument _doc;
public FormLegend(IMapDocument mapDocument)
{
InitializeComponent();
_doc = mapDocument;
if (_doc.Application is IMapApplication)
{
this.ShowInTaskbar = false;
this.TopLevel = true;
this.Owner = ((IMapApplication)_doc.Application).DocumentWindow as Form;
}
}
async private void FormLegend_Load(object sender, EventArgs e)
{
await RefreshLegend();
}
async public Task RefreshLegend()
{
if (!this.Visible)
{
return;
}
if (_doc != null && _doc.FocusMap != null && _doc.FocusMap.TOC != null)
{
pictureBox1.Image = (await _doc.FocusMap.TOC.Legend()).CloneToGdiBitmap();
pictureBox1.Width = pictureBox1.Image.Width;
pictureBox1.Height = pictureBox1.Image.Height;
}
}
}
} |
using System;
using System.Linq;
using SMARTplanner.Data.Contracts;
using SMARTplanner.Entities.Domain;
using SMARTplanner.Entities.Helpers;
using SMARTplanner.Logic.Business;
using SMARTplanner.Logic.Contracts;
namespace SMARTplanner.Logic.Exact
{
public class WorkItemService : IWorkItemService
{
private readonly ISmartPlannerContext _context;
private readonly IAccessService _accessService;
public WorkItemService(ISmartPlannerContext ctx, IAccessService access)
{
_context = ctx;
_accessService = access;
}
public ServiceCollectionResult<WorkItem> GetIssueWorkItems(long issueId, string userId)
{
var result = new ServiceCollectionResult<WorkItem>();
//check can user get access to project
var issue = _context.Issues
.SingleOrDefault(i => i.Id == issueId);
if (issue != null)
{
//does user have any binding with project
var projUserRef = _accessService.GetAccessByIssue(issue, userId);
if (projUserRef == null) result.HandleError(ErrorMessagesDict.AccessDenied);
else result.TargetCollection = issue.WorkItems; //get issue workitems
return result;
}
result.HandleError(ErrorMessagesDict.NotFoundResource);
return result;
}
public ServiceSingleResult<WorkItem> GetWorkItem(long itemId, string userId)
{
var result = new ServiceSingleResult<WorkItem>();
var workItem = GetWorkItemById(itemId);
if (workItem != null)
{
//does user have any binding with project
var projUserRef = _accessService.GetAccessByWorkItem(workItem, userId);
if (projUserRef == null) result.HandleError(ErrorMessagesDict.AccessDenied);
else result.TargetObject = workItem;
return result;
}
result.HandleError(ErrorMessagesDict.NotFoundResource);
return result;
}
public ServiceSingleResult<bool> AddWorkItem(WorkItem item)
{
var result = new ServiceSingleResult<bool>();
if (item != null && item.Issue != null)
{
var projUserRef = _accessService.GetAccessByWorkItem(item, item.CreatorId);
if (projUserRef == null || !Inspector.CanUserUpdateProject(projUserRef))
{
result.HandleError(ErrorMessagesDict.AccessDenied);
return result;
}
if (!Inspector.IsValidWorkItemTime(item))
{
result.HandleError(ErrorMessagesDict.WrongEstimatedTimeFormat);
return result;
}
_context.WorkItems.Add(item);
try
{
_context.SaveChanges();
result.TargetObject = true;
}
catch (Exception exc)
{
result.HandleError(exc.Message);
}
return result;
}
result.HandleError(ErrorMessagesDict.NullInstance);
return result;
}
public ServiceSingleResult<bool> UpdateWorkItem(WorkItem item, string userId)
{
var result = new ServiceSingleResult<bool>();
if (item != null)
{
var itemToUpdate = GetWorkItemById(item.Id);
if (itemToUpdate != null)
{
//check security
var projUserRef = _accessService.GetAccessByWorkItem(itemToUpdate, userId);
if (projUserRef == null || !Inspector.CanUserUpdateProject(projUserRef))
{
result.HandleError(ErrorMessagesDict.AccessDenied);
return result;
}
if (!Inspector.IsValidWorkItemTime(item))
{
result.HandleError(ErrorMessagesDict.WrongEstimatedTimeFormat);
return result;
}
_context.Entry(itemToUpdate).CurrentValues.SetValues(item);
try
{
_context.SaveChanges();
result.TargetObject = true;
}
catch (Exception exc)
{
result.HandleError(exc.Message);
}
return result;
}
result.HandleError(ErrorMessagesDict.NotFoundResource);
return result;
}
result.HandleError(ErrorMessagesDict.NullInstance);
return result;
}
public ServiceSingleResult<bool> DeleteWorkItem(long itemId, string userId)
{
var result = new ServiceSingleResult<bool>();
var item = GetWorkItemById(itemId);
if (item != null)
{
//check security
var projUserRef = _accessService.GetAccessByWorkItem(item, userId);
if (projUserRef == null || !Inspector.CanUserUpdateProject(projUserRef))
{
result.HandleError(ErrorMessagesDict.AccessDenied);
return result;
}
_context.WorkItems.Remove(item);
try
{
_context.SaveChanges();
result.TargetObject = true;
}
catch (Exception exc)
{
result.HandleError(exc.Message);
}
return result;
}
result.HandleError(ErrorMessagesDict.NotFoundResource);
return result;
}
#region Helpers
private WorkItem GetWorkItemById(long itemId)
{
return _context.WorkItems
.SingleOrDefault(w => w.Id == itemId);
}
#endregion
}
}
|
using UnityEngine;
using System.Collections.Generic;
using System;
public delegate void GameEventCallback(GameEventTypes eventType, object[] args);
public class GameEventManager : ManagerTemplateBase<GameEventManager>
{
class GameEvent : IPoolableObject
{
public GameEventTypes eventType;
public object[] args;
public void Reset()
{
eventType = 0;
args = null;
}
}
static Dictionary<GameEventTypes, List<GameEventCallback>> eventMap = new Dictionary<GameEventTypes, List<GameEventCallback>>();
static Queue<GameEvent> eventQueue = new Queue<GameEvent>();
static Queue<GameEvent> eventBackQueue = new Queue<GameEvent>();
static ObjectPool<GameEvent> eventPool = new ObjectPool<GameEvent>(20);
static object eventLock = new object();
public static bool EnableEventFiring = true;
static int mainThreadID;
protected override void InitManager()
{
mainThreadID = System.Threading.Thread.CurrentThread.ManagedThreadId;
}
public void Update()
{
if (!EnableEventFiring)
return;
// 处理上回EnableEventFiring=false引起的未完成任务
while (eventBackQueue.Count > 0)
{
GameEvent ev = eventBackQueue.Dequeue();
RaiseEventNow(ev.eventType, ev.args);
if (!EnableEventFiring)
return;
}
lock (this)
{
if (eventQueue.Count == 0)
return;
var temp = eventQueue;
eventQueue = eventBackQueue;
eventBackQueue = temp;
}
while (eventBackQueue.Count > 0)
{
GameEvent ev = eventBackQueue.Peek();
RaiseEventNow(ev.eventType, ev.args);
eventBackQueue.Dequeue(); // 统计数量需要
if (!EnableEventFiring)
return;
}
}
private static List<GameEventCallback> GetEventCallbackList(GameEventTypes eventType)
{
List<GameEventCallback> callbackList = null;
if (!eventMap.TryGetValue(eventType, out callbackList))
{
callbackList = new List<GameEventCallback>();
eventMap.Add(eventType, callbackList);
}
return callbackList;
}
public static void RegisterEvent(GameEventTypes eventType, GameEventCallback callback)
{
lock (eventLock)
{
List<GameEventCallback> callbackList = GetEventCallbackList(eventType);
callbackList.Add(callback);
}
}
public static void UnregisterEvent(GameEventTypes eventType, GameEventCallback callback)
{
lock (eventLock)
{
List<GameEventCallback> callbackList = GetEventCallbackList(eventType);
for (int i = callbackList.Count - 1; i >= 0; i--)
{
if (callbackList[i] == callback)
{
callbackList.RemoveAt(i);
break;
}
}
}
}
public static void RaiseEvent(GameEventTypes eventType, params object[] args)
{
if (System.Threading.Thread.CurrentThread.ManagedThreadId == mainThreadID && EnableEventFiring)
{
RaiseEventNow(eventType, args);
}
else
{
QueueEvent(eventType, args);
}
}
public static void RaiseEventSync(GameEventTypes eventType, params object[] args)
{
if (System.Threading.Thread.CurrentThread.ManagedThreadId == mainThreadID)
{
RaiseEventNow(eventType, args);
}
else
{
QueueEvent(eventType, args);
WaitQueue();
}
}
private static void RaiseEventNow(GameEventTypes eventType, params object[] args)
{
List<GameEventCallback> callbackList = GetEventCallbackList(eventType);
try
{
for (int i = 0; i < callbackList.Count; i++)
{
callbackList[i].Invoke(eventType, args);
}
}
catch (Exception ex)
{
DebugLogger.LogError(ex);
}
}
private static void QueueEvent(GameEventTypes eventType, params object[] args)
{
lock (eventLock)
{
GameEvent ev = eventPool.Fetch();
ev.eventType = eventType;
ev.args = args;
eventQueue.Enqueue(ev);
}
}
private static void WaitQueue()
{
while (true)
{
lock (eventLock)
{
if (eventQueue.Count + eventBackQueue.Count == 0)
break;
}
System.Threading.Thread.Sleep(0);
}
}
}
|
using System.Collections.Generic;
using System.Linq;
using Uintra.Core.Feed.Models;
namespace Uintra.Features.CentralFeed.Models
{
public class CountableLatestActivities
{
public IEnumerable<IFeedItem> Activities = Enumerable.Empty<IFeedItem>();
public int TotalCount { get; set; }
}
} |
using System;
using System.Collections;
using System.Collections.Generic;
//TODO: Add other using statements here
namespace com.Sconit.Entity.MRP.TRANS
{
[Serializable]
public partial class MrpReceivePlan : EntityBase
{
#region O/R Mapping Properties
public int Id { get; set; }
public string Flow { get; set; }
public string Item { get; set; }
public Double Qty { get; set; }
public string LocationFrom { get; set; }
public Int32 SourceId { get; set; }
public DateTime ReceiveTime { get; set; }
public DateTime StartTime { get; set; }
public com.Sconit.CodeMaster.OrderType OrderType { get; set; }
public com.Sconit.CodeMaster.MrpSourceType SourceType { get; set; }
public DateTime PlanVersion { get; set; }
public string SourceParty { get; set; }
public string SourceFlow { get; set; }
public string ParentItem { get; set; }
public string Bom { get; set; }
public string ExtraLocationFrom { get; set; }
#endregion
public override int GetHashCode()
{
if (Id != 0)
{
return Id.GetHashCode();
}
else
{
return base.GetHashCode();
}
}
public override bool Equals(object obj)
{
MrpShipPlan another = obj as MrpShipPlan;
if (another == null)
{
return false;
}
else
{
return (this.Id == another.Id);
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
namespace Alabo.Helpers {
public static class StringHelper {
#region 截取字符串的后部分
/// <summary>
/// 截取字符串中间的部分
/// </summary>
/// <param name="source">原字符串</param>
/// <param name="beforeValue">开始拆分字符串</param>
/// <param name="afterValue">结束拆分字符串</param>
/// <returns>截取后的字符串</returns>
public static string SubstringBetween(this string source, string beforeValue, string afterValue) {
if (string.IsNullOrEmpty(beforeValue)) {
return source;
}
if (string.IsNullOrEmpty(afterValue)) {
return source;
}
var compareInfo = CultureInfo.InvariantCulture.CompareInfo;
var index = compareInfo.IndexOf(source, beforeValue, CompareOptions.IgnoreCase);
if (index < 0) {
return source;
}
var lastIndex = compareInfo.IndexOf(source, afterValue, index, CompareOptions.IgnoreCase);
if (lastIndex < 0) {
return source;
}
if (lastIndex < index + beforeValue.Length) {
return source;
}
source = source.Substring(index + beforeValue.Length, lastIndex - index - beforeValue.Length);
return source;
}
#endregion 截取字符串的后部分
#region 截取字符串的后部分
/// <summary>
/// 截取字符串的后部分
/// </summary>
/// <param name="source">原字符串</param>
/// <param name="value">拆分字符串</param>
/// <returns>截取后的字符串</returns>
public static string SubstringAfter(this string source, string value) {
if (string.IsNullOrEmpty(value)) {
return source;
}
var compareInfo = CultureInfo.InvariantCulture.CompareInfo;
var index = compareInfo.IndexOf(source, value, CompareOptions.Ordinal);
if (index < 0) {
return string.Empty;
}
return source.Substring(index + value.Length);
}
#endregion 截取字符串的后部分
#region 截取字符串的前部分
/// <summary>
/// 截取字符串的前部分
/// </summary>
/// <param name="source">原字符串</param>
/// <param name="value">拆分字符串</param>
/// <returns>截取后的字符串</returns>
public static string SubstringBefore(this string source, string value) {
if (string.IsNullOrEmpty(value)) {
return value;
}
var compareInfo = CultureInfo.InvariantCulture.CompareInfo;
var index = compareInfo.IndexOf(source, value, CompareOptions.Ordinal);
if (index < 0) {
return string.Empty;
}
return source.Substring(0, index);
}
#endregion 截取字符串的前部分
#region 追加字符串,用分隔符分隔,默认分隔符为“,”
/// <summary>
/// 追加字符串,用分隔符分隔,默认分隔符为“,”
/// </summary>
/// <param name="sb">StringBulider对象</param>
/// <param name="append">要追加的字符串</param>
/// <param name="split">分隔符</param>
public static void AppendString(this StringBuilder sb, string append, string split = ",") {
if (sb.Length == 0) {
sb.Append(append);
return;
}
sb.Append(split);
sb.Append(append);
}
#endregion 追加字符串,用分隔符分隔,默认分隔符为“,”
#region 替换所有HTML标签为空
/// <summary>
/// 替换所有HTML标签为空
/// </summary>
/// <param name="input">The string whose values should be replaced.</param>
/// <returns>A string.</returns>
public static string RemoveHtml(this string input) {
var stripTags = new Regex("</?[a-z][^<>]*>", RegexOptions.IgnoreCase);
return stripTags.Replace(input, string.Empty);
}
#endregion 替换所有HTML标签为空
#region 解码网页参数中的字符串
/// <summary>
/// 解码网页参数中的字符串
/// </summary>
public static string InputTexts(string text) {
if (string.IsNullOrEmpty(text)) {
return string.Empty;
}
text = Regex.Replace(text, @"[\s]{2,}", " ");
text = Regex.Replace(text, @"(<[b|B][r|R]/*>)+|(<[p|P](.|\n)*?>)", "\n");
text = Regex.Replace(text, @"(\s*&[n|N][b|B][s|S][p|P];\s*)+", " ");
text = Regex.Replace(text, @"<(.|\n)*?>", string.Empty);
text = text.Replace("'", "''");
return text;
}
#endregion 解码网页参数中的字符串
#region 把string转换为double
/// <summary>
/// 把string转换为double
/// </summary>
public static double String2Double(string str) {
if (!double.TryParse((str ?? string.Empty).Trim(), out var result)) {
return -1;
}
return result;
}
#endregion 把string转换为double
#region 把string转换为decimal
/// <summary>
/// 把string转换为decimal
/// </summary>
public static decimal StringToDecimal(string str, decimal defaultValue = -1M) {
if (!decimal.TryParse((str ?? string.Empty).Trim(), out var result)) {
return defaultValue;
}
return result;
}
#endregion 把string转换为decimal
#region 把string转换为DateTime
/// <summary>
/// 把string转换为DateTime
/// </summary>
public static DateTime StringToDateTime(string str) {
if (!DateTime.TryParse((str ?? string.Empty).Trim(), out var result)) {
return new DateTime(1970, 1, 1);
}
return result;
}
#endregion 把string转换为DateTime
#region 把string转换为int
/// <summary>
/// 把string转换为int
/// </summary>
public static int StringToInt(string str, int defaultValue = -1) {
if (!int.TryParse((str ?? string.Empty).Trim(), out var result)) {
return defaultValue;
}
return result;
}
#endregion 把string转换为int
#region 把对象转换为字符串,如对象为null则返回空字符串
/// <summary>
/// 把对象转换为字符串,如对象为null则返回空字符串
/// </summary>
public static string ToString(object obj) {
return obj == null ? string.Empty : obj.ToString();
}
#endregion 把对象转换为字符串,如对象为null则返回空字符串
#region 尝试转换为int,如果失败返回null
/// <summary>
/// 尝试转换为int,如果失败返回null
/// </summary>
public static int? TryToInt(object data) {
if (!int.TryParse(data.ToString(), out var v)) {
return null;
}
return v;
}
#endregion 尝试转换为int,如果失败返回null
#region 转换由逗号隔开的数字组字符串到数字列表
/// <summary>
/// 转换由逗号隔开的数字组字符串到数字列表
/// 例
/// "1,2,3" -> List<int>(){1, 2, 3}
/// </summary>
public static List<int> StringToIntList(string data) {
//如果字符串为null则返回空列表
if (data == null) {
return new List<int>();
}
//转换
var result = (from s in data.Split(',')
let v = TryToInt(s)
where v.HasValue // v != null
select v.Value).ToList();
return result;
}
#endregion 转换由逗号隔开的数字组字符串到数字列表
#region 转换数字列表到由逗号隔开的数字组字符串
/// <summary>
/// 转换数字列表到由逗号隔开的数字组字符串
/// 例
/// List<int>(){1, 2, 3} -> "1,2,3"
/// </summary>
public static string IntListToString(IEnumerable<int> intList) {
//如果列表为null则返回空字符串
if (intList == null) {
return string.Empty;
}
//转换
var result = string.Join(",", from v in intList select v.ToString());
return result;
}
#endregion 转换数字列表到由逗号隔开的数字组字符串
#region 尝试转换为uint,如果失败返回null
/// <summary>
/// 尝试转换为uint,如果失败返回null
/// </summary>
public static uint? TryToUInt(object data) {
if (!uint.TryParse(data.ToString(), out var v)) {
return null;
}
return v;
}
#endregion 尝试转换为uint,如果失败返回null
#region 转换由逗号隔开的数字组字符串到无符号数字列表
/// <summary>
/// 转换由逗号隔开的数字组字符串到无符号数字列表
/// 例
/// "1,2,3" -> List uint(){1, 2, 3}
/// </summary>
public static List<uint> StringToUIntList(string data) {
//如果字符串为null则返回空列表
if (data == null) {
return new List<uint>();
}
//转换
var result = (from s in data.Split(',')
let v = TryToUInt(s)
where v.HasValue // v != null
select v.Value).ToList();
return result;
}
#endregion 转换由逗号隔开的数字组字符串到无符号数字列表
#region 转换无符号数字列表到由逗号隔开的数字组字符串
/// <summary>
/// 转换无符号数字列表到由逗号隔开的数字组字符串
/// 例
/// List<uint>(){1, 2, 3} -> "1,2,3"
/// </summary>
public static string UIntListToString(IEnumerable<uint> uintList) {
//如果列表为null则返回空字符串
if (uintList == null) {
return string.Empty;
}
//转换
var result = string.Join(",", from v in uintList select v.ToString());
return result;
}
#endregion 转换无符号数字列表到由逗号隔开的数字组字符串
#region 获取格式化过的小数字符串,retain代表保留的小数点位数
/// <summary>
/// 获取格式化过的小数字符串,retain代表保留的小数点位数
/// 这个函数使用的是四舍五入
/// </summary>
/// <param name="obj">字符串</param>
/// <param name="retain">要保留的小数点位数</param>
/// <returns>格式化过的小数字符串</returns>
public static string GetDecimalString(object obj, int retain) {
var dec = obj as decimal?;
if (dec == null) {
dec = StringToDecimal(obj.ToString());
}
dec = Math.Round(dec.Value, retain, MidpointRounding.AwayFromZero);
var str = string.Format("{0:0." + new string('0', retain) + "}", dec);
return str;
}
#endregion 获取格式化过的小数字符串,retain代表保留的小数点位数
#region 通配符转换到正则
/// <summary>
/// 通配符转换到正则
/// </summary>
public static Regex WillcardToRegex(string willcard) {
return new Regex(
"^" + Regex.Escape(willcard).Replace(@"\*", ".*").Replace(@"\?", ".") +
"$",
RegexOptions.IgnoreCase | RegexOptions.Singleline
);
}
#endregion 通配符转换到正则
#region 客户端用的函数
public static string Left(string str, int len) {
if (str.Length > len) {
return str.Substring(0, len);
}
return str + "...";
}
public static string[] SplitString(string source, string delimiter) {
int iPos, iLength;
bool bEnd;
string sTemp;
IList<string> list = new List<string>();
sTemp = source;
iLength = delimiter.Length;
bEnd = sTemp.EndsWith(delimiter);
for (; ; )
{
iPos = sTemp.IndexOf(delimiter);
if (iPos < 0) {
break;
}
list.Add(sTemp.Substring(0, iPos));
sTemp = sTemp.Substring(iPos + iLength);
}
if (sTemp.Length >= 0 || bEnd) {
list.Add(sTemp);
}
var array = new string[list.Count];
var k = 0;
foreach (var item in list) {
array[k] = item;
k++;
}
return array;
}
public static IList<string> SplitStringList(string source, string delimiter) {
IList<string> list = new List<string>();
var array = SplitString(source, delimiter);
foreach (var item in array) {
list.Add(item);
}
return list;
}
public static char[] NumberArray() {
var str = "0123456789abcdefghijklmnopqrstuvwxyz.";
return str.ToCharArray();
}
/// <summary>
/// 根据分隔符,将IList转换成String
/// </summary>
/// <param name="list"></param>
/// <param name="split"></param>
public static string ConvertIListToString(IList<string> list, string split) {
var str = string.Empty;
var k = 0;
foreach (var item in list) {
if (k < list.Count - 1) {
str += item + split;
} else {
str += item;
}
k++;
}
return str;
}
/// <summary>
/// 去掉连续重复三个的字符
/// </summary>
/// <param name="str"></param>
public static string ClearRepeatChar(string str) {
var temp = str;
for (var i = 0; i < str.Length; i++) {
try {
var item = str.Substring(i, 1);
if (item != ".") {
var partter = item + "{3,}";
str = Regex.Replace(str, partter, item);
}
} catch {
}
}
return str;
}
/// <summary>
/// 将Object转换成String
/// </summary>
/// <param name="str"></param>
public static string ObjectToString(object str) {
if (str == null) {
return string.Empty;
}
return str.ToString();
}
#endregion 客户端用的函数
}
} |
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;
namespace Lab3.Models.FlightsViewModels
{
public class FlightViewModel {
public int Id { get; set; }
[Display(Name = "Company")]
public int AviaCompanyId { get; set; }
[Display(Name="Airplane")]
public int AirplaneId { get; set; }
[Display(Name = "From")]
public int HomeAirportId { get; set; }
[Display(Name = "To")]
public int DestinationAirportId { get; set; }
public DateTime Departure { get; set; }
public DateTime Arrival { get; set; }
}
}
|
using MyMovies.Domain.Enums;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
namespace MyMovies.Domain.Entities
{
public class User : Entity
{
public string UserName { get; set; }
[Required]
public string Login { get; set; }
[Required]
public string Password { get; set; }
public string Email { get; set; }
[Required]
public Language Language { get; set; }
public virtual List<Role> Roles { get; set; }
// public virtual List<User> Friends { get; set; }
}
}
|
namespace RosPurcell.Web.Constants.Search
{
public static class TagGroups
{
public const string Courses = "Courses";
public const string Cuisines = "Cuisines";
public const string Ingredients = "Ingredients";
}
}
|
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System;
public class MainMenue : MonoBehaviour {
GuiHelper guiHelper;
private bool wasDownLastFrame = false;
public static string GAME_TITLE = "Dark Space Conquest";
/*~~ STATUS ~~*/
enum Menue{Main, Settings};
Menue menue = Menue.Main;
private string MainMenueMessage = null; //If set, this message is displayed and needs to be confirmed, before the main menue is shown
/*~~ ---- ~~*/
void Start () {
guiHelper = GameObject.Find ("Menue").GetComponent<GuiHelper>();
if (guiHelper == null) {
throw new MissingComponentException ("Unable to find GuiHelper.");
}
MainMenueMessage = ApplicationModel.MainMenueMessage;
}
void OnGUI () {
//if (Screen.fullScreen){ //THIS is a fix for a Unity bug, which happens to appear sometimes - the f***ing game simply always starts in fullscreen - Todo: remove this code
// Screen.fullScreen = false;
//}
guiHelper.Prepare();
if (MainMenueMessage == "") {
MainMenueMessage = null;
}
if(MainMenueMessage != null){
RenderMenueMessage();
}else{
switch (menue) {
case Menue.Main: RenderMainMenue(); break;
case Menue.Settings: RenderSettingsMenue(); break;
/*default: menue = Menue.Main;
Debug.LogError("Invalid menue-value -going back to main menue.");*/
}
}
}
//Can be an error message, why the lobby/game was closed/left
void RenderMenueMessage(){
guiHelper.TitleText (GAME_TITLE);
var centeredStyle = GUI.skin.GetStyle("Label");
centeredStyle.alignment = TextAnchor.MiddleCenter;
GUI.Label (new Rect (0, 0, Screen.width, Screen.height), ApplicationModel.MainMenueMessage, centeredStyle);
if (guiHelper.ExitButton("OK") || Input.GetKeyDown(KeyCode.Escape)) // for escape an android back button
{
wasDownLastFrame = true;
MainMenueMessage = null; //The MainMenueMessage has been confirmed -> don't show it anymore
}
}
void RenderMainMenue(){
guiHelper.TitleText (GAME_TITLE);
float YPos = guiHelper.GetTitleSpace() + 10.0f;
if (GUI.Button(guiHelper.BigCenterElemRect(YPos), "Create Lobby")) {
ApplicationModel.EnterLobbyAsServer();
}
if (GUI.Button(guiHelper.BigCenterElemRect(YPos += guiHelper.BigElemHeight + guiHelper.BigElemSpacing), "Create private Lobby")) {
ApplicationModel.EnterLobbyAsPrivateServer();
}
if (GUI.Button (guiHelper.BigCenterElemRect(YPos+=guiHelper.BigElemHeight+guiHelper.BigElemSpacing), "Join Game")) {
ApplicationModel.EnterLobbyJoiner();
}
if( GUI.Button(guiHelper.BigCenterElemRect(YPos+=guiHelper.BigElemHeight+guiHelper.BigElemSpacing), "Settings") ){
menue = Menue.Settings;
}
if (GUI.Button(guiHelper.BigCenterElemRect(YPos += guiHelper.BigElemHeight + guiHelper.BigElemSpacing), "Quit") || (Input.GetKeyDown(KeyCode.Escape) && !wasDownLastFrame)) {
Application.Quit();
}
if (!Input.GetKeyDown(KeyCode.Escape)){
wasDownLastFrame = false;
}
}
void RenderSettingsMenue(){
guiHelper.TitleText ("Settings");
if (guiHelper.ExitButton("Back") || Input.GetKeyDown(KeyCode.Escape)){
Settings.SetMasterServer( Settings.GetMasterServerStringNorm() ); //Normalise the masterServerString (for better UX)
menue = Menue.Main;
wasDownLastFrame = true;
}
float LeftX = Screen.width / 2 - guiHelper.ElemWidth;
float RightX = Screen.width / 2;
float YPos = guiHelper.GetTitleSpace();
float RndBtnWidth = guiHelper.ElemWidth * 0.15f;//GuiHelper.X (60, 5, 20);
GUI.Label(guiHelper.ElemRect(LeftX, YPos), "Player Name");
Settings.SetPlayerName( GUI.TextField(new Rect(RightX, YPos, guiHelper.ElemWidth - RndBtnWidth, guiHelper.ElemHeight), Settings.PlayerName, Player.MAX_PLAYER_NAME_LENGTH) );
if(GUI.Button(new Rect(RightX + guiHelper.ElemWidth - RndBtnWidth, YPos+guiHelper.ElemHeight*0.2f, RndBtnWidth, guiHelper.ElemHeight * 0.63f), "")){
string newName;
do{
newName = Settings.GetRandomPlayerName();
}while(newName == Settings.PlayerName);
Settings.SetPlayerName( newName );
}
GUI.Label(guiHelper.ElemRect(LeftX, YPos+=guiHelper.ElemHeight+guiHelper.ElemSpacing), "Master Server");
Settings.SetMasterServer( GUI.TextField(guiHelper.ElemRect(RightX, YPos), Settings.GetMasterServerString(), 64) );
if( GUI.Button(guiHelper.SmallElemRect(RightX, YPos+=guiHelper.ElemHeight+guiHelper.ElemSpacing/2), "Local", guiHelper.SmallButtonStyle ) ){
Settings.SetLocalMasterServer();
}
if( GUI.Button(guiHelper.SmallElemRect(RightX + guiHelper.ElemWidth/2, YPos), "Unity", guiHelper.SmallButtonStyle) ){
Settings.SetUnityMasterServer();
}
}
}
|
using Fbtc.Application.Helper;
using Fbtc.Application.Interfaces;
using Fbtc.Domain.Entities;
using Fbtc.Domain.Interfaces.Services;
using prmToolkit.Validation;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Fbtc.Application.Services
{
public class UserProfileApplication : IUserProfileApplication
{
private readonly IUserProfileService _userProfileService;
public UserProfileApplication(IUserProfileService userProfileService)
{
_userProfileService = userProfileService;
}
public UserProfile GetByEmailPassword(string email, string password)
{
ArgumentsValidator.RaiseExceptionOfInvalidArguments(
RaiseException.IfNotEmail(email, "Atenção: E-Mail inválido"),
RaiseException.IfNullOrEmpty(password, "Atenção: Senha inválida")
);
return _userProfileService.GetByEmailPassword(email, password);
}
public UserProfile GetByPessoaId(int id)
{
return _userProfileService.GetByPessoaId(id);
}
public string GetNomeFotoByPessoaId(int id)
{
return _userProfileService.GetNomeFotoByPessoaId(id);
}
public UserProfile Login(string email, string password)
{
ArgumentsValidator.RaiseExceptionOfInvalidArguments(
RaiseException.IfNotEmail(email, "Atenção: E-Mail inválido"),
RaiseException.IfNullOrEmpty(password, "Atenção: Senha inválida")
);
return _userProfileService.Login(email, password);
}
public UserProfile LoginUser(UserProfileLogin userProfileLogin)
{
ArgumentsValidator.RaiseExceptionOfInvalidArguments(
RaiseException.IfNotEmail(userProfileLogin.EMail, "Atenção: E-Mail inválido"),
RaiseException.IfNullOrEmpty(userProfileLogin.PasswordHash, "Atenção: Senha inválida")
);
return _userProfileService.LoginUser(userProfileLogin);
}
public string RessetPasswordByEMail(string email)
{
ArgumentsValidator.RaiseExceptionOfInvalidArguments(
RaiseException.IfNotEmail(email, "Atenção: E-Mail inválido")
);
return _userProfileService.RessetPasswordByEMail(email);
}
public string RessetPasswordByPessoaId(int id)
{
return _userProfileService.RessetPasswordByPessoaId(id);
}
public string Save(UserProfile p)
{
ArgumentsValidator.RaiseExceptionOfInvalidArguments(
RaiseException.IfNullOrEmpty(p.Nome, "Nome não informado"),
RaiseException.IfNotEmail(p.EMail, "E-Mail inválido"),
RaiseException.IfNullOrEmpty(p.NrCelular, "NrCelular não informado")
);
UserProfile _p = new UserProfile() {
PessoaId = p.PessoaId,
Nome = Functions.AjustaTamanhoString(p.Nome, 100),
EMail = Functions.AjustaTamanhoString(p.EMail, 100),
NomeFoto = Functions.AjustaTamanhoString(p.NomeFoto, 100),
Sexo = p.Sexo,
NrCelular = Functions.AjustaTamanhoString(p.NrCelular, 15),
PasswordHash = Functions.AjustaTamanhoString(p.PasswordHash, 100),
PasswordHashReturned = Functions.AjustaTamanhoString(p.PasswordHashReturned, 100)
};
return _userProfileService.Save(p);
}
public string ValidaEMail(int pessoaId, string eMail)
{
return _userProfileService.ValidaEMail(pessoaId, eMail);
}
}
}
|
/**
* 自然框架之信息管理类项目的页面基类
* http://www.natureFW.com/
*
* @author
* 金洋(金色海洋jyk)
*
* @copyright
* Copyright (C) 2005-2013 金洋.
*
* Licensed under a GNU Lesser General Public License.
* http://creativecommons.org/licenses/LGPL/2.1/
*
* 自然框架之信息管理类项目的页面基类 is free software. You are allowed to download, modify and distribute
* the source code in accordance with LGPL 2.1 license, however if you want to use
* 自然框架之信息管理类项目的页面基类 on your site or include it in your commercial software, you must be registered.
* http://www.natureFW.com/registered
*/
/* ***********************************************
* author : 金洋(金色海洋jyk)
* email : jyk0011@live.cn
* function: 上传文件的共用页面
* history: created by 金洋
* **********************************************
*/
using System;
namespace Nature.Upload
{
/// <summary>
/// 上传文件的共用页面
/// </summary>
public partial class UploadFile : System.Web.UI.Page
{
/// <summary>
/// 控件ID
/// </summary>
protected string ControlID = "";
/// <summary>
/// 字段ID
/// </summary>
protected string ColID = "";
/// <summary>
/// 文件扩展名
/// </summary>
protected string FileExt = "";
/// <summary>
///
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void Page_Load(object sender, EventArgs e)
{
ControlID = Request.QueryString["cid"];
if (string.IsNullOrEmpty(ControlID))
{
Response.Write("cid参数不正确!");
Response.End();
}
int index = ControlID.LastIndexOf('_');
ColID = ControlID.Substring(index + 1);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ComputerScienceFinal
{
public static class HashTableFinal
{
class HashNode
{
public object key;
public object value;
HashNode next;
HashNode[] T;
// khoi tao do dai cua bang Hash
public void Init(int Size)
{
T = new HashNode[Size];
for (int i = 0; i < Size; i++)
{
T[i] = null;
}
}
// ham hash theo microsoft
public int Hashing(object key)
{
return Math.Abs(key.GetHashCode()) % T.Length;
}
// nhap tu khoa va tu can tim thay
public void Insert(object key, object value)
{
HashNode h = new HashNode();
h.key = key;
h.value = value;
int num = Hashing(key);
if (T[num] == null)
{
T[num] = h;
}
else
{
h.next = T[num];
T[num] = h;
}
}
// ham cho phep nhap tu khoa de hien tu can tim thay
public object LookUp(object key)
{
int num = Hashing(key);
HashNode current = T[num];
while (current != null)
{
if (current.key == key)
{
return current.value;
}
else
{
current = current.next;
}
}
return "Khong tim thay tu khoa tuong ung";
}
}
// ham chay HashTable
public static void RunHastable()
{
HashNode h = new HashNode();
h.Init(5);
h.Insert("Gold","Vang");
h.Insert("Silver","Bac");
h.Insert("Bronze", "Dong");
h.Insert("Diamond","Kim Cuong");
Console.WriteLine("Ket Qua Tu Khoa Can Tim: ");
Console.WriteLine(h.LookUp("Diamond"));
Console.WriteLine(h.LookUp("Gold"));
Console.WriteLine(h.LookUp("Silver"));
Console.WriteLine(h.LookUp("Blue"));
}
}
}
|
using System;
using System.Configuration;
namespace hello.world
{
public static class Program
{
public static void Main(string[] arguments)
{
Console.WriteLine(ConfigurationManager.AppSettings["hello-world"]);
int[] numbers = {4, 7, 11, 19, 23, 28, 31};
foreach (int number in numbers)
{
Console.WriteLine(number.ToString());
}
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class PlayerInput : MonoBehaviour
{
[SerializeField]
private Player _Player;
[SerializeField] private InputButton _LeftMoveButton, _RightMoveButton;
public void ToPlayMode()
{
gameObject.SetActive(true);
}
public void ToEditMode()
{
gameObject.SetActive(false);
}
private void Update()
{
if (_Player == null)
_Player = Player._Instance; //GameObject.FindGameObjectWithTag("Player").GetComponent<Player>();
if (_LeftMoveButton.buttonPressed)
{
_Player._Velocity.x = -1;
}
else if (_RightMoveButton.buttonPressed)
{
_Player._Velocity.x = 1;
}
else
_Player._Velocity.x = 0;
}
public void JumpNow()
{
_Player.Jump();
}
public void ShootNow()
{
_Player.Shoot(AttackTypes.Projectile);
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerControlCube : MonoBehaviour
{
// Start is called before the first frame update
private Rigidbody player;
void Start()
{
player = GetComponent<Rigidbody>();
}
public float rotation_speed = 10;
void FixedUpdate()
{
float xforce = Input.GetAxis("Horizontal");
Vector3 rotate = new Vector3(0f, rotation_speed * xforce, 0f);
player.AddTorque(rotate);
}
}
|
using EddiDataDefinitions;
using System;
using Utilities;
namespace EddiEvents
{
[PublicAPI]
public class DockingRequestedEvent : Event
{
public const string NAME = "Docking requested";
public const string DESCRIPTION = "Triggered when your ship requests docking at a station or outpost";
public const string SAMPLE = "{\"timestamp\":\"2016-06-10T14:32:03Z\",\"event\":\"DockingRequested\",\"StationName\":\"Jameson Memorial\", \"StationType\":\"Orbis\", \"MarketID\": 128666762}";
[PublicAPI("The station at which the commander has requested docking")]
public string station { get; private set; }
[PublicAPI("The localized model / type of the station at which the commander has requested docking")]
public string stationtype => stationDefinition?.localizedName;
// Not intended to be user facing
public long marketId { get; private set; }
public StationModel stationDefinition { get; private set; }
public DockingRequestedEvent(DateTime timestamp, string station, string stationType, long marketId) : base(timestamp, NAME)
{
this.station = station;
this.stationDefinition = StationModel.FromEDName(stationType);
this.marketId = marketId;
}
}
}
|
using System.Data.SqlTypes;
using System.IO;
namespace gView.Framework.Geometry
{
internal class GeometrySerialization
{
internal delegate void serializeDelegate(BinaryWriter bw, IGeometryDef gd);
static public SqlBytes GeometryToSqlBytes(IGeometry geometry)
{
GeometryDef geomDef = new GeometryDef();
geomDef.HasZ = geomDef.HasM = false;
serializeDelegate serialize = null;
if (geometry != null && geometry.GeometryType != GeometryType.Unknown)
{
geomDef.GeometryType = geometry.GeometryType;
serialize = geometry.Serialize;
}
if (serialize != null)
{
using (BinaryWriter writer = new BinaryWriter(new MemoryStream()))
{
writer.Write((int)geomDef.GeometryType);
serialize(writer, geomDef);
byte[] bytes = new byte[writer.BaseStream.Length];
writer.BaseStream.Position = 0;
writer.BaseStream.Read(bytes, (int)0, (int)writer.BaseStream.Length);
writer.Close();
return new SqlBytes(bytes);
}
}
return null;
}
static public IGeometry SqlBytesToGeometry(SqlBytes sqlbytes)
{
try
{
GeometryDef geomDef = new GeometryDef();
geomDef.HasZ = geomDef.HasM = false;
using (BinaryReader r = new BinaryReader(new MemoryStream()))
{
r.BaseStream.Write(sqlbytes.Buffer, 0, sqlbytes.Buffer.Length);
r.BaseStream.Position = 0;
switch ((GeometryType)r.ReadInt32())
{
case GeometryType.Aggregate:
AggregateGeometry ageom = new AggregateGeometry();
ageom.Deserialize(r, geomDef);
return ageom;
case GeometryType.Envelope:
Envelope env = new Envelope();
env.Deserialize(r, geomDef);
return env;
case GeometryType.Multipoint:
MultiPoint mp = new MultiPoint();
mp.Deserialize(r, geomDef);
return mp;
case GeometryType.Point:
Point p = new Point();
p.Deserialize(r, geomDef);
return p;
case GeometryType.Polygon:
Polygon polygon = new Polygon();
polygon.Deserialize(r, geomDef);
return polygon;
case GeometryType.Polyline:
Polyline line = new Polyline();
line.Deserialize(r, geomDef);
return line;
default:
return null;
}
}
}
catch
{
return null;
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using Kadastr.View.Forms;
namespace Kadastr.View.UserControls
{
public partial class MeansSurvey : DevExpress.XtraEditors.XtraUserControl
{
public MeansSurvey()
{
InitializeComponent();
}
private void simpleButton1_Click(object sender, EventArgs e)
{
Forms.MeansSurveyCatalog meansSurvey = new Forms.MeansSurveyCatalog();
meansSurvey.ShowDialog();
}
}
}
|
using System;
using Microsoft.AspNetCore.SignalR.Client;
using System.Threading.Tasks;
using MediatR;
using System.Threading;
using Microsoft.Extensions.Logging;
namespace AgentR.Client.SignalR
{
public static class HubConnectionExtensions
{
public static void HandleRequest<TRequest, TResponse>(this HubConnection connection, IMediator mediator) where TRequest : IRequest<TResponse>
{
connection = connection ?? throw new ArgumentNullException(nameof(HubConnection));
mediator = mediator ?? throw new ArgumentNullException(nameof(IMediator));
// Await the server to request registering any handlers
connection.OnRegisterHandlers(async () =>
{
await connection.RegisterHandler<TRequest, TResponse>(async (callbackId, request) =>
{
// Accept the request, blocking any other agents
var accepted = false;
try {
accepted = await connection.AcceptRequest(callbackId);
} catch (System.Net.WebSockets.WebSocketException) {
// TODO: Adding escape hatch from integration tests. Server is disconnecting during the AcceptRequest call.
return;
}
if (!accepted)
{
// Another agent must have handled the request or at was canceled
Logging.Logger.LogInformation($"Hub Canceled Request<{typeof(TRequest)}, {typeof(TResponse)}> - Id: {callbackId}");
return;
}
bool success = await connection.SendResponse(callbackId, () => mediator.Send<TResponse>(request));
Logging.Logger.LogInformation($"Sent Response<{typeof(TRequest)}, {typeof(TResponse)}> - Id: {callbackId} - Success: {success}");
});
});
}
public static Task<TResponse> SendRequest<TResponse>(this HubConnection connection, IRequest<TResponse> request, CancellationToken cancellationToken = default(CancellationToken))
{
connection = connection ?? throw new ArgumentNullException(nameof(HubConnection));
request = request ?? throw new ArgumentNullException(nameof(IRequest<TResponse>));
return connection.InvokeAsync<TResponse>(Constants.HubAgentRequestMethod, request.GetType(), typeof(TResponse), request, cancellationToken);
}
public static Task SendNotification<TNotification>(this HubConnection connection, TNotification notification, CancellationToken cancellationToken = default(CancellationToken)) where TNotification : INotification
{
connection = connection ?? throw new ArgumentNullException(nameof(HubConnection));
if (null == notification) throw new ArgumentNullException(nameof(TNotification));
return connection.InvokeAsync(Constants.HubAgentNotificationMethod, typeof(TNotification), notification, cancellationToken);
}
internal static async Task<bool> AcceptRequest(this HubConnection connection, int callbackId)
{
connection = connection ?? throw new ArgumentNullException(nameof(HubConnection));
var result = await connection.InvokeAsync<bool>(Constants.HubAcceptRequestMethod, callbackId);
return result;
}
internal static async Task<bool> ReturnResponse(this HubConnection connection, int callbackId, object response)
{
connection = connection ?? throw new ArgumentNullException(nameof(HubConnection));
var result = await connection.InvokeAsync<bool>(Constants.HubReturnResponseMethod, callbackId, response);
return result;
}
internal static async Task<bool> ReturnError(this HubConnection connection, int callbackId, Exception ex)
{
connection = connection ?? throw new ArgumentNullException(nameof(HubConnection));
ex = ex ?? throw new ArgumentNullException(nameof(Exception));
var result = await connection.InvokeAsync<bool>(Constants.HubReturnErrorMethod, callbackId, ex);
return result;
}
internal static async Task<IDisposable> RegisterHandler<TRequest, TResponse>(this HubConnection connection, Action<int, TRequest> callback) where TRequest : IRequest<TResponse>
{
connection = connection ?? throw new ArgumentNullException(nameof(HubConnection));
callback = callback ?? throw new ArgumentNullException(nameof(Action<int, TRequest>));
// register the request and response type with the server
var registration = await connection.InvokeAsync<AgentMethodRegistration>(Constants.HubRegisterHandlerMethod, new AgentHandlerRegistration
{
RequestType = typeof(TRequest),
ResponseType = typeof(TResponse),
});
// Remove any previous handlers for.
connection.Remove(registration.RequestMethod);
// Await any request from the server on the method it specified for the request and response type
var result = connection.On<int, TRequest>(registration.RequestMethod, (callbackId, request) =>
{
Logging.Logger.LogInformation($"Received Request<{typeof(TRequest)}, {typeof(TResponse)}> - Id: {callbackId}");
callback(callbackId, request);
});
Logging.Logger.LogInformation($"Handeling <{typeof(TRequest)}, {typeof(TResponse)}> on {registration.RequestMethod}");
return result;
}
internal static IDisposable OnRegisterHandlers(this HubConnection connection, Action callback)
{
connection = connection ?? throw new ArgumentNullException(nameof(HubConnection));
callback = callback ?? throw new ArgumentNullException(nameof(Action));
return connection.On(Constants.ClientRegisterHandlersMethod, callback);
}
internal static async Task<bool> SendResponse<TResponse>(this HubConnection connection, int callbackId, Func<Task<TResponse>> callback)
{
connection = connection ?? throw new ArgumentNullException(nameof(HubConnection));
callback = callback ?? throw new ArgumentNullException(nameof(Func<Task<TResponse>>));
try
{
var response = await callback();
// Send the result to the server
return await connection.ReturnResponse(callbackId, response);
}
catch (Exception ex)
{
return await connection.ReturnError(callbackId, ex);
}
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class ScreenMovement : MonoBehaviour
{
public Camera camara;
private GameObject reference;
private void Start()
{
reference = GameObject.Find("Personaje");
}
void Update()
{
camara.transform.position = new Vector3(camara.transform.position.x, reference.transform.position.y, camara.transform.position.z);
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
namespace PatronBuilder
{
interface IMotor
{
string especificacionesMotor();
}
class MotorBasico : IMotor
{
public string especificacionesMotor()
{
return "motor de 4 cilindros";
}
}
class MotorDeportivo:IMotor
{
public string especificacionesMotor()
{
return "motor de 8 cilidros";
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using WindowsFormsApplication2;
public partial class zjkxinzeng : System.Web.UI.Page
{
public static object SqlNull(TextBox obj)
{
if (obj.Text == null || obj.Text == "")
{
return DBNull.Value;
}
else
{
return obj.Text;
}
}
protected void txtread()
{
bzjxm.ReadOnly = false;//1
bgzdw.ReadOnly = false;//2
//bxb.ReadOnly = false;//3
//bzjlx.ReadOnly = false;//4
bzjcsny.ReadOnly = false;//5
// bxcsly.ReadOnly = false;//6
bxlxw.ReadOnly = false;//7
bbyxx.ReadOnly = false;//8
bbghm.ReadOnly = false;//9
bsjh.ReadOnly = false;//10
bemail.ReadOnly = false;//11
bxkzy.ReadOnly = false;//12
bxkly.ReadOnly = false;//13
bxmmc.ReadOnly = false;//14
bxmly.ReadOnly = false;//15
bjf.ReadOnly = false;//16
bxmwtdw.ReadOnly = false;//17
byjzq.ReadOnly = false;//18
bsfjt.ReadOnly = false;//19
bgrjj.ReadOnly = false;//19
}
protected void Page_Load(object sender, EventArgs e)
{
txtread();
if (!IsPostBack)
{
//初始化整型、时间类型的字段
bzjcsny.Text = null;
bjf.Text = null;
byjzq.Text = null;
xueke1Ddl.DataSource = xueke1();
xueke1Ddl.DataTextField = "value";
xueke1Ddl.DataValueField = "key";
xueke1Ddl.DataBind();
xueke2Ddl.DataSource = xueke2();
xueke2Ddl.DataTextField = "value";
xueke2Ddl.DataValueField = "key";
xueke2Ddl.DataBind();
bxb1();
bzjcs1();
if (Session["managertype"] == "董事长")
{
btnOk.Visible = false;
}
}
}
protected void qrxiugai(object sender, EventArgs e)
{
string mycns = ConfigurationSettings.AppSettings["connString"];
SqlConnection mycn = new SqlConnection(mycns);
mycn.Open();
try
{
string bbzjlx = "";
if (bzjlx.Items[0].Selected == true) { bbzjlx = "a"; }
if (bzjlx.Items[1].Selected == true) { bbzjlx = bbzjlx + "b"; }
if (bzjlx.Items[2].Selected == true) { bbzjlx = bbzjlx + "c"; }
if (bzjlx.Items[3].Selected == true) { bbzjlx = bbzjlx + "d"; }
string max, max1, max2, lx = "zj", lx1 = "专家";
string mymax1 = "select max(userID) from User_Reg where usertype = '" + lx1 + "'";
SqlCommand mycmd1 = new SqlCommand(mymax1, mycn);
SqlDataReader myrd1;
myrd1 = mycmd1.ExecuteReader();
myrd1.Read();
if (myrd1[0].ToString() != "")
{
max1 = myrd1[0].ToString();
max1 = max1.Replace(lx, "");
myrd1.Close();
}
else { max1 = "000001"; myrd1.Close(); }
string mymax2 = "select max(zjID) from zjk";
SqlCommand mycmd2 = new SqlCommand(mymax2, mycn);
SqlDataReader myrd2;
myrd2 = mycmd2.ExecuteReader();
myrd2.Read();
if (myrd2[0].ToString() != "")
{
max2 = myrd2[0].ToString();
max2 = max2.Replace(lx, "");
myrd2.Close();
}
else { max2 = "000001"; myrd2.Close(); }
int v = int.Parse(max1);
v++;
int w = int.Parse(max2);
w++;
if (v >= w)
{
max = v.ToString().PadLeft(6, '0');
max = lx + max;
}
else
{
max = w.ToString().PadLeft(6, '0');
max = lx + max;
}
string bxcsly1 = xueke2Ddl.SelectedValue.ToString();
Validator phone = new Validator("phone"); // 检查手机格式(中国)
Validator email = new Validator("email"); // 检查邮箱格式
if (bzjxm.Text == "")
{
Response.Write("<script>alert('“专家姓名” 未为填写正确!')</script>");
}
else if (bsjh.Text == "" || !phone.checkType(bsjh.Text.Trim()))
{
Response.Write("<script>alert('“手机号” 未为填写正确!')</script>");
}
else if (bemail.Text == "" || !email.checkType(bemail.Text.Trim()))
{
Response.Write("<script>alert('“邮箱” 未为填写正确!')</script>");
}
else
{
//string mycms = "insert into zjk(zjID,zjxm,gzdw,xb,zjlx,csny,xcsly1,xlxw,byxx,bghm,sjh,email,xkzy,zjcs) values('" + max + "','" + bzjxm.Text.Trim() + "','" + bgzdw.Text.Trim() + "','" + bxb.Text.Trim() + "','" + bbzjlx + "','" + bzjcsny.Text.Trim() + "','" + bxcsly1 + "','" + bxlxw.Text.Trim() + "','" + bbyxx.Text.Trim() + "','" + bbghm.Text.Trim() + "','" + bsjh.Text.Trim() + "','" + bemail.Text.Trim() + "','" + bxkzy.Text.Trim() + "', '" + bzjcs.Text.Trim() + "')";
//SqlCommand mycmds = new SqlCommand(mycms, mycn);
//mycmds.ExecuteNonQuery();
//string mycms1 = "insert into zjdbxkycg(zjID,xkly,xmmc,xmly,jf,xmwtdw,yjzq,sfjt) values('" + max + "' ,'" + bxkly.Text.Trim() + "','" + bxmmc.Text.Trim() + "','" + bxmly.Text.Trim() + "','" + bjf.Text.Trim() + "','" + bxmwtdw.Text.Trim() + "','" + byjzq.Text.Trim() + "','" + bsfjt.Text.Trim() + "')";
//SqlCommand mycmds1 = new SqlCommand(mycms1, mycn);
//mycmds1.ExecuteNonQuery();
string mycms = "insert into zjk(zjID,zjxm,gzdw,xb,zjlx,csny,xcsly1,xlxw,byxx,bghm,sjh,email,xkzy,zjcs,grjj) values('" + max + "','" + bzjxm.Text.Trim() + "','" + bgzdw.Text.Trim() + "','" + bxb.Text.Trim() + "','" + bbzjlx + "','" + bzjcsny.Text.Trim() + "','" + bxcsly1 + "','" + bxlxw.Text.Trim() + "','" + bbyxx.Text.Trim() + "','" + bbghm.Text.Trim() + "','" + bsjh.Text.Trim() + "','" + bemail.Text.Trim() + "','" + bxkzy.Text.Trim() + "', '" + bzjcs.Text.Trim() + "', '" + bgrjj.Text.Trim() + "')";
SqlCommand mycmds = new SqlCommand(mycms, mycn);
mycmds.ExecuteNonQuery();
if (bxkly.Text.Trim() != "" && bxmmc.Text.Trim() != "" && bxmly.Text.Trim() != "" && bjf.Text.Trim() != "" && bxmwtdw.Text.Trim() != "" && byjzq.Text.Trim() != "" && bsfjt.Text.Trim() != "")
{
string mycms1 = "insert into zjdbxkycg(zjID,xkly,xmmc,xmly,jf,xmwtdw,yjzq,sfjt) values('" + max + "' ,'" + bxkly.Text.Trim() + "','" + bxmmc.Text.Trim() + "','" + bxmly.Text.Trim() + "',@bjf,'" + bxmwtdw.Text.Trim() + "','" + byjzq.Text.Trim() + "','" + bsfjt.Text.Trim() + "')";
SqlCommand mycmds1 = new SqlCommand(mycms1, mycn);
mycmds1.Parameters.Add("@bjf", SqlNull(bjf));
mycmds1.ExecuteNonQuery();
}
else
{
}
Response.Write("<script>opener.location.href='right4.aspx';</script>");
Response.Write("<script>alert('新增数据成功!');</script>");
//Response.Write("<script>newwin=window.open('zjkxiugai.aspx?ID=" + max + "','newwin')</script>");
Response.Write("<script>window.opener = null;window.close();</script>");
}
}
catch (System.Exception ex)
{
Response.Write("<script>alert('" + ex.Message.Replace("'", "*") + "')</script>");
}
finally
{
mycn.Close();
}
}
public Dictionary<string, string> xueke1()
{
Dictionary<string, string> d = new Dictionary<string, string>();
string mycns = ConfigurationSettings.AppSettings["connString"];
SqlConnection sql = new SqlConnection(mycns);
sql.Open();
SqlCommand command = new SqlCommand("select * from xueke1", sql);
SqlDataReader reader = command.ExecuteReader();
while (reader.Read())//循环读每行
{
string id = reader["id"].ToString();
string value = reader["value"].ToString().Trim();
d.Add(id, value);
}
sql.Close();
return d;
}
public Dictionary<string, string> xueke2()
{
Dictionary<string, string> d = new Dictionary<string, string>();
string mycns = ConfigurationSettings.AppSettings["connString"];
SqlConnection sql = new SqlConnection(mycns);
string xueke1Id = xueke1Ddl.SelectedValue;
sql.Open();
SqlCommand command = new SqlCommand("select * from xueke2 where id like '" + xueke1Id + "%'", sql);
SqlDataReader reader = command.ExecuteReader();
while (reader.Read())//循环读每行
{
string id = reader["id"].ToString();
string value = reader["value"].ToString().Trim();
d.Add(id, value);
}
sql.Close();
return d;
}
protected void xueke1Ddl_SelectedIndexChanged(object sender, EventArgs e)
{
xueke2Ddl.DataSource = xueke2();
xueke2Ddl.DataTextField = "value";
xueke2Ddl.DataValueField = "key";
xueke2Ddl.DataBind();
}
protected void bxb1()
{
bxb.Items.Add(new ListItem("男")); //110
bxb.Items.Add(new ListItem("女")); //120
}
protected void bzjcs1()
{
bzjcs.Items.Add(new ListItem("校内")); //110
bzjcs.Items.Add(new ListItem("校外")); //120
}
} |
using System;
namespace FeriaVirtual.App.Desktop.Services.SignIn
{
public class InvalidAccessException
: Exception
{
public InvalidAccessException(string message)
: base(message) { }
}
}
|
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Xml;
namespace gView.Framework.UI.Dialogs
{
public partial class FormCommandParameters : Form
{
private XmlNode _commandDef;
private List<Control> _controls;
private string _command = "";
private IExplorerObject _exObject;
public FormCommandParameters(IExplorerObject exObject, XmlNode commandDef)
{
InitializeComponent();
_exObject = exObject;
if (_exObject == null)
{
return;
}
_commandDef = commandDef;
if (_commandDef == null)
{
return;
}
MakeGUI();
}
private void MakeGUI()
{
if (_commandDef == null)
{
return;
}
try
{
this.Text = _commandDef.Attributes["name"].Value;
XmlNodeList parameters = _commandDef.SelectNodes("parameters/parameter");
tablePanel.RowCount = parameters.Count;
tablePanel.ColumnCount = 3;
_controls = new List<Control>();
int row = 0;
foreach (XmlNode parameter in parameters)
{
Label label = new Label();
label.Text = parameter.Attributes["name"].Value;
label.Size = new Size(100, 20);
label.Dock = DockStyle.Top;
label.TextAlign = ContentAlignment.MiddleRight;
if (label.Text.IndexOf(":") == -1)
{
label.Text += " :";
}
tablePanel.Controls.Add(label, 0, row);
TextBox tb;
Button btn;
int val;
string defParameter = "";
if (_exObject is IExplorerObjectCommandParameters)
{
Dictionary<string, string> p = ((IExplorerObjectCommandParameters)_exObject).Parameters;
p.TryGetValue(parameter.Attributes["name"].Value, out defParameter);
}
switch (parameter.Attributes["type"].Value.ToLower())
{
case "file":
tb = new TextBox();
tb.Dock = DockStyle.Top;
if (defParameter != "")
{
tb.Text = defParameter;
}
tablePanel.Controls.Add(tb, 1, row);
btn = new Button();
btn.Text = "...";
btn.Name = row.ToString();
btn.Click += new EventHandler(Button_Click);
btn.Size = new Size(btn.Width, 20);
btn.Dock = DockStyle.Top;
tablePanel.Controls.Add(btn, 2, row);
_controls.Add(tb);
break;
case "string":
tb = new TextBox();
tb.Dock = DockStyle.Top;
if (defParameter != "")
{
tb.Text = defParameter;
}
tablePanel.Controls.Add(tb, 1, row);
_controls.Add(tb);
break;
case "number":
NumericUpDown updown = new NumericUpDown();
updown.Dock = DockStyle.Top;
if (parameter.Attributes["value"] != null && int.TryParse(parameter.Attributes["value"].Value, out val))
{
updown.Value = val;
}
tablePanel.Controls.Add(updown, 1, row);
_controls.Add(updown);
break;
case "option":
ComboBox cmb = new ComboBox();
cmb.DropDownStyle = ComboBoxStyle.DropDownList;
cmb.Dock = DockStyle.Top;
foreach (string v in parameter.Attributes["values"].Value.Split('|'))
{
cmb.Items.Add(v);
}
if (cmb.Items.Count > 0)
{
cmb.SelectedIndex = 0;
}
tablePanel.Controls.Add(cmb, 1, row);
_controls.Add(cmb);
break;
}
row++;
}
this.Height = panel1.Height + panel2.Height + 35 + row * 28;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
void Button_Click(object sender, EventArgs e)
{
if (_commandDef == null)
{
return;
}
try
{
int row = 0;
if (!int.TryParse(((Button)sender).Name, out row))
{
return;
}
XmlNode parameter = _commandDef.SelectNodes("parameters/parameter")[row];
switch (parameter.Attributes["dialog"].Value.ToLower())
{
case "open":
OpenFileDialog open = new OpenFileDialog();
open.Title = parameter.Attributes["name"].Value;
if (parameter.Attributes["filter"] != null)
{
open.Filter = parameter.Attributes["filter"].Value;
}
if (_controls[row].Text.Trim() != "")
{
open.FileName = ((_controls[row].Text.Trim().Replace("/", @"\").LastIndexOf(@"\") == _controls[row].Text.Trim().Length - 1) ? _controls[row].Text + "Filename" : _controls[row].Text);
}
if (open.ShowDialog() == DialogResult.OK)
{
_controls[row].Text = open.FileName;
}
break;
case "save":
SaveFileDialog save = new SaveFileDialog();
save.Title = parameter.Attributes["name"].Value;
if (parameter.Attributes["filter"] != null)
{
save.Filter = parameter.Attributes["filter"].Value;
}
if (_controls[row].Text.Trim() != "")
{
save.FileName = ((_controls[row].Text.Trim().Replace("/", @"\").LastIndexOf(@"\") == _controls[row].Text.Trim().Length - 1) ? _controls[row].Text + "Filename" : _controls[row].Text);
}
if (save.ShowDialog() == DialogResult.OK)
{
_controls[row].Text = save.FileName;
}
break;
}
}
catch { }
}
private void btnOK_Click(object sender, EventArgs e)
{
if (_commandDef == null)
{
return;
}
StringBuilder sb = new StringBuilder();
XmlNodeList exes = _commandDef.SelectNodes("exe[@call]");
foreach (XmlNode exe in exes)
{
string call = exe.Attributes["call"].Value;
for (int i = 0; i < _controls.Count; i++)
{
Control ctrl = _controls[i];
string txt = ctrl.Text;
if (ctrl is NumericUpDown)
{
txt = txt.Replace(",", ".");
}
call = call.Replace("{" + i + "}", ((txt.IndexOf(" ") == -1) ? txt : "\"" + txt + "\""));
}
if (sb.Length > 0)
{
sb.Append("\r\n");
}
sb.Append(call);
}
_command = sb.ToString();
}
public string Command
{
get { return _command; }
}
}
} |
using Google.Protobuf;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using System;
namespace ModelLibrary.Data
{
public class ProtobufJsonConvertor : JsonConverter
{
public override bool CanConvert(Type objectType)
{
return typeof(IMessage).IsAssignableFrom(objectType);
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
var converter = new ExpandoObjectConverter();
var o = converter.ReadJson(reader, objectType, existingValue, serializer);
var text = JsonConvert.SerializeObject(o);
var message = (IMessage) Activator.CreateInstance(objectType);
var parser = new JsonParser(JsonParser.Settings.Default.WithIgnoreUnknownFields(true));
return parser.Parse(text, message.Descriptor);
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
writer.WriteRawValue(JsonFormatter.Default.Format((IMessage)value));
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class RestQ : System.Web.UI.Page
{
TaskManager ts = new TaskManager();
TaskManager.QC qu;
protected void Page_Load(object sender, EventArgs e)
{
int pid = Int32.Parse(Session["PID"].ToString());
int paid = Int32.Parse(Session["PAID"].ToString());
string yn = Session["ANS"].ToString().TrimEnd();
qu = ts.getQus(pid, paid, yn);
Label1.Text = qu.qu;
}
protected void Button1_Click(object sender, EventArgs e)
{
Session["PAID"] = qu.id;
if (RadioButton1.Checked)
{
Session["ANS"] = "Y";
if (qu.isy == 0)
{
Response.Redirect("RestQ.aspx");
}
else
{
Response.Redirect("ShowSol.aspx");
}
}
else
{
Session["ANS"] = "N";
if (qu.isn == 0)
{
Response.Redirect("RestQ.aspx");
}
else
{
Response.Redirect("ShowSol.aspx");
}
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace StockTracking.DAL.DTO
{
public class PermissionsStates
{
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.Entity;
namespace JoshMangoff_COMP2007_Assignment2.Models
{
public class SampleData : DropCreateDatabaseAlways<FoodStoreContext>
{
/// <summary>
/// This method creates the data in the database
/// </summary>
/// <param name="context"></param>
protected override void Seed(FoodStoreContext context)
{
var foodtypes = new List<FoodType>
{
new FoodType { Name = "Appetizers" },
new FoodType { Name = "Main Courses" },
new FoodType { Name = "Desserts" },
new FoodType { Name = "Beverages" },
};
new List<Food>
{
//all images are from google images
new Food { Title = "Onion Rings", Description = "These crispy onion rings make for a great appetizer or side to your meal!", Type = foodtypes.Single(t => t.Name == "Appetizers"), Price = 4.99M, ImgUrl = "/Assets/images/items/onionrings.jpg" },
new Food { Title = "Garlic Bread with Cheese, 3 pieces", Description = "Three pieces of garlic bread with cheddar cheese!", Type = foodtypes.Single(t => t.Name == "Appetizers"), Price = 5.99M, ImgUrl = "/Assets/images/items/garlicbread.jpg" },
new Food { Title = "Large Pizza, 3 toppings", Description = "Large pizza with 3 toppings of your choice! Coose from over 20 different toppings!", Type = foodtypes.Single(t => t.Name == "Main Courses"), Price = 21.99M, ImgUrl = "/Assets/images/items/lpizza.jpg" },
new Food { Title = "Medium Pepperoni Pizza", Description = "Our oven-baked pepperoni pizza is always made with the freshest ingredients!", Type = foodtypes.Single(t => t.Name == "Main Courses"), Price = 15.99M, ImgUrl = "/Assets/images/items/ppizza.png" },
new Food { Title = "Vanilla Ice Cream Cone", Description = "Vanilla ice cream is always a great way to cool off after a summer day - or as dessert after a pizza!", Type = foodtypes.Single(t => t.Name == "Desserts"), Price = 6.99M, ImgUrl = "/Assets/images/items/vicecream.jpg" },
new Food { Title = "Chocolate Sundae", Description = "A decadent chocolate sundae, rich in flavour!", Type = foodtypes.Single(t => t.Name == "Desserts"), Price = 8.99M, ImgUrl = "/Assets/images/items/csundae.png" },
new Food { Title = "Water, 500mL", Description = "Natural spring water!", Type = foodtypes.Single(t => t.Name == "Beverages"), Price = 1.99M, ImgUrl = "/Assets/images/items/water.png" },
new Food { Title = "Pop, 350mL", Description = "A can of pop/soda, over 8 choices!", Type = foodtypes.Single(t => t.Name == "Beverages"), Price = 2.99M, ImgUrl = "/Assets/images/items/pop.png" },
}.ForEach(a => context.Foods.Add(a));
}
}
}
|
namespace P08AllSubtreesWithGivenSum
{
using System;
using System.Collections.Generic;
using BasicTree.Trees.Tree;
using CommonOperations;
public class EntryPoint
{
private static readonly Dictionary<int, Tree<int>> nodeByValue =
new Dictionary<int, Tree<int>>();
private static readonly TreeOperations Operations = new TreeOperations();
public static void Main()
{
Operations.ReadTreeValues(int.Parse(Console.ReadLine()), nodeByValue);
int searchedValue = int.Parse(Console.ReadLine());
var root = Operations.GetRootNode(nodeByValue);
foreach (var tree in GetPathsWithSum(root, searchedValue))
{
PrintInPreOrder(tree);
Console.WriteLine();
}
}
private static void PrintInPreOrder(Tree<int> tree)
{
Console.Write($"{tree.TreeValue} ");
foreach (var child in tree.TreeChildren)
{
PrintInPreOrder(child);
}
}
private static List<Tree<int>> GetPathsWithSum(Tree<int> root, int searchedValue)
{
Console.WriteLine($"Subtrees of sum {searchedValue}: ");
var roots = new List<Tree<int>>();
GetSubtreePathsWithSum(root, searchedValue, 0, roots);
return roots;
}
private static int GetSubtreePathsWithSum(
Tree<int> node,
int searchedValue,
int current,
List<Tree<int>> roots)
{
if (node == null)
{
return 0;
}
current = node.TreeValue;
foreach (var treeChild in node.TreeChildren)
{
current += GetSubtreePathsWithSum(treeChild, searchedValue, current, roots);
}
if (current == searchedValue)
{
roots.Add(node);
}
return current;
}
}
} |
using Library.API.Entities;
using Microsoft.EntityFrameworkCore;
using System;
namespace Library.API.Extensions
{
public static class ModelBuilderExtension
{
public static void SendData(this ModelBuilder modelBuilder)
{
modelBuilder.Entity<Author>().HasData(
new Author
{
Id = new Guid("48556951-e6b7-44fa-a24b-448cfc4c8c4c"),
Name = "Author 1",
BirthDate = new DateTimeOffset(new DateTime(1960, 11, 16)),
Email = "author1@xxx.com"
},
new Author
{
Id = new Guid("597e9f16-a810-4c34-98ff-92a53bbebcb9"),
Name = "Author 2",
BirthDate = new DateTimeOffset(new DateTime(1973, 6, 21)),
Email = "author2@xxx.com"
}
);
modelBuilder.Entity<Book>().HasData(
new Book
{
Id = new Guid("a87f37d4-70c1-4d8a-bd34-76ca4194982f"),
Title = "Book 1",
Description = "Description of Book 1",
Pages = 281,
AuthorId = new Guid("48556951-e6b7-44fa-a24b-448cfc4c8c4c")
},
new Book
{
Id = new Guid("c3357824-6d12-4a41-a544-76659e848263"),
Title = "Book 2",
Description = "Description of Book 2",
Pages = 370,
AuthorId = new Guid("48556951-e6b7-44fa-a24b-448cfc4c8c4c")
},
new Book
{
Id = new Guid("e1108d59-2bc3-4f2f-b643-f3d0cb3b7e0b"),
Title = "Book 3",
Description = "Description of Book 3",
Pages = 229,
AuthorId = new Guid("597e9f16-a810-4c34-98ff-92a53bbebcb9")
},
new Book
{
Id = new Guid("f1ea8f47-aed7-4c33-a1c7-8a96abfc89aa"),
Title = "Book 4",
Description = "Description of Book 4",
Pages = 440,
AuthorId = new Guid("597e9f16-a810-4c34-98ff-92a53bbebcb9")
}
);
}
}
}
|
using BencodeNET.Objects;
using BencodeNET.Parsing;
using BencodeNET.Torrents;
using System;
using System.IO;
using System.Windows.Forms;
using TorrentDotNet.HTTP;
using TorrentDotNet.Util;
// This is the code for your desktop app.
// Press Ctrl+F5 (or go to Debug > Start Without Debugging) to run your app.
namespace TorrentDotNet
{
public partial class MainWindowViewer : Form
{
public MainWindowViewer()
{
InitializeComponent();
treeView1.ExpandAll();
}
private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
// Click on the link below to continue learning how to build a desktop app using WinForms!
System.Diagnostics.Process.Start("http://aka.ms/dotnet-get-started-desktop");
}
private void button1_Click(object sender, EventArgs e)
{
MessageBox.Show("Thanks!");
}
/*
private void toolStripTextBox1_Click(object sender, EventArgs e)
{
MessageBox.Show("Test");
}
*/
private void toolStripLabel1_Click(object sender, EventArgs e)
{
}
// Menu Toolbar on Click Method
private void toolStrip1_ItemClicked(object sender, ToolStripItemClickedEventArgs e)
{
//MessageBox.Show("Test2");
}
private void AddTorrentFileButton_Click(object sender, EventArgs e)
{
var openfile = new OpenFileDialog
{
Filter = "Torrent Files|*.torrent",
Title = "Select Torrent File"
};
openfile.ShowDialog();
var parser = new BencodeParser();
var torrent = parser.Parse<Torrent>(openfile.FileName);
var addTorrent = new AddTorrentDialog();
var drive = new DriveInfo("C");
// Formatting Labels
((Label)addTorrent.Controls["TorrentSizeLabel"]).Text = Formatter.BytesToEnglish(torrent.TotalSize) + " (Space Left on drive: " + Formatter.BytesToEnglish(drive.AvailableFreeSpace) + ")";
((Label)addTorrent.Controls["TorrentDateLabel"]).Text = torrent.CreationDate.ToString();
((Label)addTorrent.Controls["TorrentHashLabel"]).Text = Formatter.HashFormatter(torrent.GetInfoHash());
((Label)addTorrent.Controls["TorrentCommentLabel"]).Text = torrent.Comment;
// Display Torrent Files in the AddTorrentMenu Window
var listview = ((ListView)addTorrent.Controls["FilesList"]);
var T = torrent.File;
// Only One File Exists
if (torrent.Files == null)
{
var item = new ListViewItem(new string[] { T.FileName, Formatter.BytesToEnglish(T.FileSize), "Normal" });
//var test = item.SubItems;
listview.Items.Add(item);
item.Checked = true;
}
// Multiple Files in the torrent
else
{
MultiFileInfoList files = torrent.Files;
foreach (MultiFileInfo f in files)
{
listview.Items.Add(new ListViewItem(new string[] { f.FileName, Formatter.BytesToEnglish(f.FileSize), "Normal" }));
}
}
((ComboBox)addTorrent.Controls["TorrentDirectory"]).Text = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory);
DialogResult result = addTorrent.ShowDialog();
if (result == DialogResult.OK)
{
var row = new ListViewItem(new string[] { (MainWindowListView.Items.Count + 1).ToString(), T.FileName, Formatter.BytesToEnglish(T.FileSize) });
MainWindowListView.Items.Add(row);
row.Selected = true;
var test2 = new Connection(torrent);
}
}
private void ExitButton_Click(object sender, EventArgs e)
{
Application.Exit();
}
private void helloWorldLabel_Click(object sender, EventArgs e)
{
}
private void splitContainer1_Panel1_Paint(object sender, PaintEventArgs e)
{
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
}
private void menuStrip1_ItemClicked(object sender, ToolStripItemClickedEventArgs e)
{
}
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
}
private void menuStrip1_ItemClicked_1(object sender, ToolStripItemClickedEventArgs e)
{
}
private void treeView1_AfterSelect(object sender, TreeViewEventArgs e)
{
}
private void groupBox1_Enter(object sender, EventArgs e)
{
}
private void listView1_SelectedIndexChanged(object sender, EventArgs e)
{
}
private void checkedListBox1_SelectedIndexChanged(object sender, EventArgs e)
{
}
private void toolStripContainer1_TopToolStripPanel_Click(object sender, EventArgs e)
{
}
private void tableLayoutPanel1_Paint(object sender, PaintEventArgs e)
{
}
private void label1_Click(object sender, EventArgs e)
{
}
private void label1_Click_1(object sender, EventArgs e)
{
}
private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
}
private void label1_Click_2(object sender, EventArgs e)
{
}
private void toolStripDropDownButton1_Click(object sender, EventArgs e)
{
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
namespace LivePerformance2016.CSharp
{
[DataContract]
public class Project
{
[DataMember]
public int ID { get; private set; }
[DataMember]
public int GebiedID { get; private set; }
[DataMember]
public DateTime DatumStart { get; private set; }
[DataMember]
public DateTime DatumEind { get; set; }
[DataMember]
public string Beschrijving { get; private set; }
public List<Bezoek> Bezoeken { get; private set; }
public Project(int id, DateTime datumstart, string beschrijving)
{
ID = id;
DatumStart = datumstart;
Beschrijving = beschrijving;
Bezoeken = new List<Bezoek>();
}
public Project(int id, int gebiedid, DateTime datumstart, DateTime datumeind, string beschrijving)
{
ID = id;
GebiedID = gebiedid;
DatumStart = datumstart;
DatumEind = datumeind;
Beschrijving = beschrijving;
Bezoeken = new List<Bezoek>();
}
public void AddBezoek(Bezoek bezoek)
{
if (Bezoeken == null)
{
Bezoeken = new List<Bezoek>();
}
Bezoeken.Add(bezoek);
}
public override string ToString()
{
string ret = Beschrijving;
return ret;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace DemoApp.Persistence.Common
{
public abstract class DesignerItemBase : PersistableItemBase
{
public DesignerItemBase(int id, double left, double top, double itemWidth, double itemHeight) : base(id)
{
this.Left = left;
this.Top = top;
this.ItemWidth = itemWidth;
this.ItemHeight = itemHeight;
}
public double ItemHeight { get; private set; }
public double ItemWidth { get; private set; }
public double Left { get; private set; }
public double Top { get; private set; }
}
}
|
#region MIT License
/*
* Copyright (c) 2009 University of Jyväskylä, Department of Mathematical
* Information Technology.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#endregion
using System;
using System.Collections.Generic;
using System.Numerics;
using Jypeli.Rendering;
namespace Jypeli.Effects
{
/// <summary>
/// Pistemäinen valonlähde.
/// </summary>
public class Light
{
/// <summary>
/// Paikka.
/// </summary>
public Vector Position { get; set; }
/// <summary>
/// Valaistun alueen säde
/// </summary>
public double Radius { get; set; } // TODO: Tämä säde on nyt hieman hämäävä.
/// <summary>
/// Voimakkuus väliltä [0.0, 1.0].
/// </summary>
public double Intensity { get; set; }
/// <summary>
/// Väri
/// </summary>
public Color Color { get; set; }
/// <summary>
/// Paikan X-koordinaatti.
/// </summary>
public double X
{
get
{
return Position.X;
}
set
{
Position = new Vector(value, Position.Y);
}
}
/// <summary>
/// Paikan Y-koordinaatti.
/// </summary>
public double Y
{
get
{
return Position.Y;
}
set
{
Position = new Vector(Position.X, value);
}
}
/// <summary>
/// Valo.
/// </summary>
public Light() : this(10, 1, Color.White)
{
}
/// <summary>
/// Valo
/// </summary>
/// <param name="radius">Valon säde</param>
/// <param name="intensity">Voimakkuus välillä 0 - 1</param>
public Light(double radius, double intensity) : this(radius, intensity, Color.White)
{
}
/// <summary>
/// Valo
/// </summary>
/// <param name="radius">Valon säde</param>
/// <param name="intensity">Voimakkuus välillä 0 - 1</param>
/// <param name="color">Väri</param>
public Light(double radius, double intensity, Color color)
{
Radius = radius;
Intensity = intensity;
Color = color;
}
}
}
|
// Copyright 2013 Ralf Abramowitsch
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using System;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Xml.Serialization;
namespace NotePadDnc13
{
public class SettingsHandler
{
private readonly string _settingsPath;
public SettingsHandler()
{
string appDataPath = Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData);
_settingsPath = Path.Combine(appDataPath, "DNC13", "NotePadDnc13", "settings.xml");
}
public Settings LoadSettings()
{
if (!File.Exists(_settingsPath)) return new Settings();
try
{
using (FileStream fs = File.OpenRead(_settingsPath))
{
XmlSerializer xmlSerializer = new XmlSerializer(typeof(SerializableSettings));
SerializableSettings serializableSettings = (SerializableSettings)xmlSerializer.Deserialize(fs);
return ConvertSettingsToSerializableSettings(serializableSettings);
}
}
catch (Exception ex)
{
Trace.TraceError("Error reading settings from '{0}'. Details: {1}", _settingsPath, ex);
return new Settings();
}
}
public void SaveSettings(Settings settings)
{
SerializableSettings serializableSettings = ConvertSettingsToSerializableSettings(settings);
string settingsDirectory = Path.GetDirectoryName(_settingsPath);
if (!Directory.Exists(settingsDirectory))
{
Directory.CreateDirectory(settingsDirectory);
}
try
{
using (FileStream fs = File.Create(_settingsPath))
{
XmlSerializer xmlSerializer = new XmlSerializer(typeof(SerializableSettings));
xmlSerializer.Serialize(fs, serializableSettings);
}
}
catch (Exception ex)
{
Trace.TraceError("Error writing settings. Details: " + ex);
}
}
private SerializableSettings ConvertSettingsToSerializableSettings(Settings settings)
{
SerializableSettings serializableSettings = new SerializableSettings();
serializableSettings.Font = settings.Font.Name;
serializableSettings.FontSize = settings.Font.Size;
serializableSettings.IsBold = settings.Font.Bold;
return serializableSettings;
}
private Settings ConvertSettingsToSerializableSettings(SerializableSettings serializableSettings)
{
Settings settings = new Settings();
string fontFamily = serializableSettings.Font;
float fontSize = serializableSettings.FontSize;
FontStyle style = serializableSettings.IsBold ? FontStyle.Bold : FontStyle.Regular;
settings.Font = new Font(fontFamily, fontSize, style);
return settings;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Globalization;
namespace Joqds.Tools.KpiExtractor.Contract
{
public class TimeBucket<TCalendar>:IComparable<TimeBucket<TCalendar>> where TCalendar:Calendar, new()
{
public static IEnumerable<TimeBucket<TCalendar>> GetBuckets(DateTime start, DateTime end, DatePart datePart,
bool startingPartial = false, bool endingPartial = false)
{
var timeBuckets = new List<TimeBucket<TCalendar>>();
var firstBucket = new TimeBucket<TCalendar>(start,datePart,partialStart: startingPartial);
var lastBucket = new TimeBucket<TCalendar>(end,datePart,partialEnd: endingPartial);
TimeBucket<TCalendar> current;
if(firstBucket.Given==firstBucket.StartPoint || startingPartial)
{
timeBuckets.Add(firstBucket);
current = firstBucket.Clone();
}
else
{
current = firstBucket.AddDatePart(1).Clone();
}
if (lastBucket.Given != lastBucket.EndPoint && !endingPartial)
{
lastBucket.AddDatePart(-1);
}
while (current.EndPoint<lastBucket.StartPoint)
{
timeBuckets.Add(current.AddDatePart(1).Clone());
}
timeBuckets.Add(lastBucket);
return timeBuckets;
}
static TimeBucket()
{
_calendar = new TCalendar();
}
private static readonly Calendar _calendar;
public TimeBucket(DateTime given,DatePart datePart, bool partialStart=false, bool partialEnd=false)
{
//todo: exact 0 must not increment or decrement start, end
Given = given;
DatePart = datePart;
PartialStart = partialStart;
PartialEnd = partialEnd;
EndPoint = datePart switch
{
DatePart.Minute => new DateTime(Given.Year, Given.Month, Given.Day, Given.Hour,
Given.Minute, 0).AddMinutes(1),
DatePart.Hour => new DateTime(Given.Year, Given.Month, Given.Day, Given.Hour, 0, 0)
.AddHours(1),
DatePart.Day => new DateTime(Given.Year, Given.Month, Given.Day).AddDays(1),
DatePart.Week => new DateTime(Given.Year, Given.Month, Given.Day)
.AddDays((int)DayOfWeek.Saturday - (int)Given.DayOfWeek)
.AddDays(7),
DatePart.Month => _calendar.AddMonths(
new DateTime(Given.Year, Given.Month, Given.Day).AddDays(
(_calendar.GetDayOfMonth(Given) - 1) * -1), 1),
DatePart.Year => _calendar.AddYears(
new DateTime(Given.Year, Given.Month, Given.Day).AddDays(
(_calendar.GetDayOfYear(Given) - 1) * -1), 1),
_ => throw new ArgumentOutOfRangeException(nameof(datePart), datePart, null)
};
StartPoint = datePart switch
{
DatePart.Minute => new DateTime(Given.Year, Given.Month, Given.Day, Given.Hour,
Given.Minute, 0),
DatePart.Hour => new DateTime(Given.Year, Given.Month, Given.Day, Given.Hour, 0, 0),
DatePart.Day => new DateTime(Given.Year, Given.Month, Given.Day),
DatePart.Week => new DateTime(Given.Year, Given.Month, Given.Day).AddDays(
(int)DayOfWeek.Saturday - (int)Given.DayOfWeek),
DatePart.Month => new DateTime(Given.Year, Given.Month, Given.Day).AddDays(
(_calendar.GetDayOfMonth(Given) - 1) * -1),
DatePart.Year => new DateTime(Given.Year, Given.Month, Given.Day).AddDays(
(_calendar.GetDayOfYear(Given) - 1) * -1),
_ => throw new ArgumentOutOfRangeException(nameof(datePart), datePart, null)
};
}
public DateTime StartPoint { get; set; }
public DateTime EndPoint { get; set; }
private bool PartialStart { get; set; }
private bool PartialEnd { get; set; }
public DateTime Start => PartialStart ? Given : StartPoint;
public DateTime End => PartialEnd ? Given : EndPoint;
public DateTime Given { get; set; }
public DatePart DatePart { get; set; }
public bool IsPartial => PartialStart || PartialEnd;
public TimeBucket<TCalendar> AddDatePart(int value)
{
Given = StartPoint = DatePart switch
{
DatePart.Minute => StartPoint.AddMinutes(value),
DatePart.Hour => StartPoint.AddHours(value),
DatePart.Day => StartPoint.AddDays(value),
DatePart.Week => StartPoint.AddDays(7 * value),
DatePart.Month => _calendar.AddMonths(StartPoint, value),
DatePart.Year => _calendar.AddYears(StartPoint, 1),
_ => throw new ArgumentOutOfRangeException(nameof(Contract.DatePart), DatePart, null)
};
EndPoint = DatePart switch
{
DatePart.Minute => EndPoint.AddMinutes(value),
DatePart.Hour => EndPoint.AddHours(value),
DatePart.Day => EndPoint.AddDays(value),
DatePart.Week => EndPoint.AddDays(7 * value),
DatePart.Month => _calendar.AddMonths(EndPoint, value),
DatePart.Year => _calendar.AddYears(EndPoint, 1),
_ => throw new ArgumentOutOfRangeException(nameof(Contract.DatePart), DatePart, null)
};
PartialStart = PartialEnd = false;
return this;
}
public TimeBucket<TCalendar> Clone()
{
return new TimeBucket<TCalendar>(Given,DatePart,PartialStart,PartialEnd);
}
public int CompareTo(TimeBucket<TCalendar> other)
{
return StartPoint.CompareTo(other.StartPoint);
}
}
} |
using System.Collections.Generic;
using System.Linq;
using OnlineClinic.Data.Entities;
namespace OnlineClinic.Data.Repositories
{
public class SpecializationRepository : Repository<Specialization>, ISpecializationRepository
{
public SpecializationRepository(OnlineClinicDbContext context): base(context) { }
public Dictionary<int, string> GetSpecializationIdAndNames() => GetAll().ToDictionary(s => s.Id, s => s.Name);
}
}
|
using System;
using System.Collections.Generic;
namespace CourseHunter_98_ModifyCollectionInForeach
{
class Program
{
static void Main(string[] args)
{
//RemoveInForeach();
//RemoveInFor();
//RemoveInForWromEnd();
RemoveAllDemo();
Console.ReadLine();
}
public static void RemoveInForeach()
{
List<int> list = new List<int> { 1, 2, 3, 43, 4, 5 };
foreach (var item in list)
{
if (item % 2 == 0)
{
list.Remove(item); // Выскочит ошибка нельзя модифицировать лист внутри foreach.
}
}
Console.WriteLine(list.Count);
// По сути он роскладывается в следующий код.
List<int>.Enumerator enumerator = list.GetEnumerator();
try
{
while (enumerator.MoveNext())
{
int item = enumerator.Current;
}
}
catch (Exception)
{
throw;
}
finally
{
enumerator.Dispose();
}
}
// Ок если foreach так защищен надо попробовать for.
public static void RemoveInFor()
{
List<int> list = new List<int> { 1, 2, 3, 4, 5, 56 };
for (int i = 0; i < list.Count; i++)
{
var item = list[i];
//if (item % 2 == 0)
//{
// list.Remove(item);
//}
// Это вроде работает.
if (item <= 3)
{
list.Remove(item);
--i; // Это можно назвать грязный хак.
}
// Но получается и так нельзя удалять элементы из листа.
// Это происходит из-за смещения индексов.
// В принципе мы это можем делать но отлько дикреминировав итератор
}
Console.WriteLine(list.Count);
}
// В принципе еще один вариант грязного удаления при помощи for может выглядеть следуще
public static void RemoveInForWromEnd()
{
List<int> list = new List<int> { 1, 2, 3, 4, 45, 6 };
for (int i = list.Count-1; i >= 0; i--)
{
var item = list[i];
if (item <= 3)
{
list.Remove(item);
}
}
Console.WriteLine(list.Count);
// Это более предпочтительный метод удаления из листа.
}
// Но есть еще способ
public static void RemoveAllDemo()
{
List<int> list = new List<int> { 1, 2, 3, 4, 5, 56 };
list.RemoveAll(x => x <= 3); // это GREEDY оператор он выполняется сразу.
Console.WriteLine(list.Count);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace GangOfFourDesignPatterns.Behavioral.Observer
{
class _TestObserver
{
public void Run(int i)
{
Console.WriteLine($"\n{i}) Observer\nObserver pattern allows a single object, known as the subject, to publish changes to its state and other observer objects that depend upon the subject are automatically notified of any changes to the subject's state.\n");
//concrete subject
var googleStock = new Stock();
//add concrete observers
googleStock.Add(new GoogleInvestorObserver(googleStock, "Julia"));
googleStock.Add(new GoogleInvestorObserver(googleStock, "Johanna"));
googleStock.Add(new GoogleInvestorObserver(googleStock, "Junior"));
//change price
googleStock.ChangePrice(918);
//notify changes to all investors who are monitoring
//googleStock.Notifiy();
Debug.Assert(googleStock.GetStockPrice() == 918, "Stock price is wrong");
//change price
googleStock.ChangePrice(919);
//notify changes to all investors who are monitoring
//googleStock.Notifiy();
Debug.Assert(googleStock.GetStockPrice() == 919, "Stock price is wrong");
}
}
}
|
using System;
using AGCompressedAir.Windows.Enums;
namespace AGCompressedAir.Windows.Common
{
public sealed class SearchEventArgs : EventArgs
{
public string SearchTerm { get; set; }
public SearchMode SearchMode { get; set; }
}
} |
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class GameDataService : IGameDataService {
private Dictionary<string, float> commonData = new Dictionary<string, float>() {
{"CellCountWidth",10},
{"CellCountHeight",10},
{"CellSize",1}
};
public float GetCommonData(string key) {
return commonData[key];
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace CommandPreprocessor
{
class CommandPreprocessorTest
{
static void Main(string[] args)
{
Console.WriteLine("***** BIENVENIDO AL TEST DEL PREPROCESADOR DE COMANDOS DE CNCmatic ® *****");
Console.WriteLine("***** Escriba un comando de codigo G, y el preprocesador le devolverá los comandos procesados que serán enviados a la maquina (Para salir inserte 'exit') *****");
Console.WriteLine();
string input = Console.ReadLine();
//Configuracion del preprocesador
CommandPreprocessor.GetInstance().ReferencePosition = new UnitsPosition();
Configuration.absoluteProgamming = true;
Configuration.defaultFeedrate = 60;
Configuration.millimetersCurveSection = 0.5;
Configuration.millimetersProgramming = true;
Configuration.configValueX = 200;
Configuration.configValueY = 200;
Configuration.configValueZ = 200;
while (input != "exit")
{
try
{
Console.WriteLine("Comandos a enviar a la maquina:");
List<string> result = CommandPreprocessor.GetInstance().ProcessProgram(new List<string> { input });
for (int i = 0; i < result.Count; i++)
{
Console.WriteLine("Comando " + i.ToString("00") + ": " + result[i]);
}
}
catch (Exception ex)
{
Console.WriteLine("ERROR AL PROCESAR COMANDO: " + ex);
}
finally
{
Console.WriteLine();
Console.WriteLine("Escriba nuevo comando o 'exit' para salir");
input = Console.ReadLine();
}
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using ApartmentApps.Api.ViewModels;
using ApartmentApps.Data;
using ApartmentApps.Data.Repository;
using ApartmentApps.Forms;
using ApartmentApps.Portal.Controllers;
using Ninject;
namespace ApartmentApps.Api.Modules
{
public class MaintenanceModule : Module<MaintenanceConfig>, IMenuItemProvider, IAdminConfigurable, IFillActions, IDashboardComponentProvider
{
public string SettingsController => "MaintenanceConfig";
public MaintenanceModule(IRepository<MaintenanceConfig> configRepo, IUserContext userContext, IKernel kernel) : base(kernel, configRepo, userContext)
{
}
public void PopulateMenuItems(List<MenuItemViewModel> menuItems)
{
var menuItem = new MenuItemViewModel("Maintenance", "fa-briefcase");
menuItem.Children.Add(new MenuItemViewModel("New Request", "fa-plus-square", "NewRequest", "MaitenanceRequests"));
if (UserContext.IsInRole("Maintenance") || UserContext.IsInRole("PropertyAdmin"))
{
menuItem.Children.Add(new MenuItemViewModel("Requests", "fa-folder", "Index", "MaitenanceRequests"));
}
if (UserContext.IsInRole("Maintenance") || UserContext.IsInRole("PropertyAdmin"))
{
menuItem.Children.Add(new MenuItemViewModel("Schedule", "fa-calendar-o", "MySchedule", "MaitenanceRequests"));
}
if (UserContext.IsInRole("Maintenance") || UserContext.IsInRole("PropertyAdmin"))
{
menuItem.Children.Add(new MenuItemViewModel("Monthly Report", "fa-area-chart", "MonthlyReport", "MaitenanceRequests"));
}
menuItems.Add(menuItem);
}
public void FillActions(List<ActionLinkModel> actions, object viewModel)
{
var mr = viewModel as MaintenanceRequestViewModel;
if (mr != null)
{
actions.Add(new ActionLinkModel("Details", "Details", "MaitenanceRequests", new { id = mr.Id }));
if (UserContext.IsInRole("MaintenanceSupervisor") || UserContext.IsInRole("PropertyAdmin"))
{
actions.Add(new ActionLinkModel("Edit", "Entry", "MaitenanceRequests", new { id = mr.Id })
{
IsDialog = true
});
actions.Add(new ActionLinkModel("Delete", "Delete", "MaitenanceRequests", new { key = mr.Id })
{
});
}
}
// If its actions for a maintenance request
if (mr != null && Config.SupervisorMode) // Only allow maintenance assigning when in supervisor mode
{
actions.Add(new ActionLinkModel("Assign To", "AssignRequest", "MaitenanceRequests", new { id = mr.Id }) { IsDialog = true });
}
}
public void PopulateComponents(DashboardArea area, List<ComponentViewModel> dashboardComponents)
{
/*
if (!UserContext.IsInRole("Admin") && !UserContext.IsInRole("PropertyAdmin"))
return;
var startDate = UserContext.CurrentUser.TimeZone.Now().Subtract(new TimeSpan(30, 0, 0, 0));
var endDate = UserContext.CurrentUser.TimeZone.Now().AddDays(1);
var mr = Kernel.Get<IRepository<MaitenanceRequest>>();
if (area == DashboardArea.LeftTop)
{
dashboardComponents.Add(new DashboardTitleViewModel($"Maintenance - {UserContext.CurrentUser.Property.Name}", null, 1));
dashboardComponents.Add(new DashboardStatViewModel()
{
Row = 1,
Stretch = "col-md-4",
Title = "New",
Value = WorkOrdersByRange(mr, startDate, endDate).Count(p => p.StatusId == "Submitted").ToString(),
Subtitle = "Last 30 Days"
});
dashboardComponents.Add(new DashboardStatViewModel()
{
Row = 1,
Stretch = "col-md-4",
Title = "Open",
Value = WorkOrdersByRange(mr, startDate, endDate).Count(p => p.StatusId != "Complete").ToString(),
Subtitle = "Last 30 Days"
});
dashboardComponents.Add(new DashboardStatViewModel()
{
Row = 1,
Stretch = "col-md-4",
Title = "Complete",
Value = WorkOrdersByRange(mr, startDate, endDate).Count(p => p.StatusId != "Complete").ToString(),
Subtitle = "Last 30 Days"
});
dashboardComponents.Add(new DashboardPieViewModel("Maintenance By User", "This Month", 3, CheckinsByRange(startDate, endDate).Where(p => p.StatusId == "Complete")
.GroupBy(p => p.Worker)
.Select(p => new DashboardPieViewModel.ChartData() { label = p.Key.FirstName + " " + p.Key.LastName, data = p.Count() })
.ToArray())
{
Row = 1,
Stretch = "col-md-12",
Title = "Complete",
Subtitle = "Last 30 Days"
});
}
*/
}
private IQueryable<MaintenanceRequestCheckin> CheckinsByRange(DateTime? startDate, DateTime? endDate)
{
var mrc = Kernel.Get<IRepository<MaintenanceRequestCheckin>>();
return mrc.Where(p => p.Date > startDate && p.Date < endDate);
}
private IQueryable<MaitenanceRequest> WorkOrdersByRange(IRepository<MaitenanceRequest> mr, DateTime? startDate, DateTime? endDate)
{
return mr.Where(p => p.SubmissionDate > startDate && p.SubmissionDate < endDate);
}
}
} |
using UnityEngine;
public class PrefabManager : MonoBehaviour
{
//Houses prefabs that need to be instantiated in UI
// Assign the prefab in the inspector
public GameObject itemPrefab; //for the items in item list in battle, menu, and shop
public GameObject magicPrefab; //for magic listed in menu
public GameObject equipPrefab;
public GameObject damagePrefab;
public GameObject itemVictoryPrefab;
public GameObject shopBuyItemPrefab;
public GameObject shopSellItemPrefab;
public GameObject shopBuyEquipPrefab;
public GameObject shopSellEquipPrefab;
public GameObject inactiveHeroButton;
public GameObject activeQuestListButton;
public GameObject bestiaryEntryButton;
public GameObject battleActionButton;
public GameObject battleMagicButton;
public GameObject battleItemButton;
//Singleton
private static PrefabManager m_Instance = null;
public static PrefabManager Instance
{
get
{
if (m_Instance == null)
{
m_Instance = (PrefabManager)FindObjectOfType(typeof(PrefabManager));
}
return m_Instance;
}
}
} |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.Design;
using System.Drawing;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using Phenix.Core;
namespace Phenix.Windows
{
/// <summary>
/// TextEdit管理组件
/// </summary>
[Description("TextEdit管理组件")]
[ProvideProperty("SelectAllOnEnter", typeof(TextEdit))] //切入焦点时可将文本设置为全选状态
[ToolboxItem(true), ToolboxBitmap(typeof(TextEditManager), "Phenix.Windows.TextEditManager")]
public sealed class TextEditManager : Component, IExtenderProvider, ISupportInitialize
{
/// <summary>
/// 初始化
/// </summary>
public TextEditManager()
: base() { }
/// <summary>
/// 初始化
/// </summary>
/// <param name="container">组件容器</param>
public TextEditManager(IContainer container)
: base()
{
if (container == null)
throw new ArgumentNullException("container");
container.Add(this);
}
#region 属性
private new bool DesignMode
{
get { return base.DesignMode || AppConfig.DesignMode; }
}
private Control _host;
/// <summary>
/// 所属容器
/// </summary>
[DefaultValue(null), Browsable(false)]
public Control Host
{
get
{
if (_host == null)
{
if (DesignMode)
{
IDesignerHost designer = this.GetService(typeof(IDesignerHost)) as IDesignerHost;
if (designer != null)
_host = designer.RootComponent as Control;
}
}
return _host;
}
set
{
if (!DesignMode && _host != null)
throw new InvalidOperationException("运行期不允许修改Host");
_host = value;
if (!DesignMode)
{
Form form = value as Form;
if (form != null)
form.Shown += new EventHandler(Host_Shown);
}
}
}
private readonly Dictionary<TextEdit, TextEditRuleStatus> _ruleStatuses = new Dictionary<TextEdit, TextEditRuleStatus>();
#endregion
#region 扩展程序属性
/// <summary>
/// 切入焦点时可将文本设置为全选状态
/// </summary>
[Description("切入焦点时可将文本设置为全选状态"), Category("Phenix")]
public bool GetSelectAllOnEnter(TextEdit source)
{
TextEditRuleStatus result;
if (_ruleStatuses.TryGetValue(source, out result))
return result.SelectAllOnEnter;
return true;
}
/// <summary>
/// 切入焦点时可将文本设置为全选状态
/// </summary>
public void SetSelectAllOnEnter(TextEdit source, bool value)
{
TextEditRuleStatus status;
if (_ruleStatuses.TryGetValue(source, out status))
status.SelectAllOnEnter = value;
else
_ruleStatuses.Add(source, new TextEditRuleStatus { SelectAllOnEnter = value });
}
#endregion
#region 事件
private void Host_Shown(object sender, EventArgs e)
{
InitializeRule();
}
#region TextEdit 事件
private void TextEdit_Enter(object sender, EventArgs e)
{
TextEdit textEdit = (TextEdit)sender;
textEdit.SelectAll();
}
#endregion
#endregion
#region 方法
#region IExtenderProvider 成员
/// <summary>
/// 是否可以将扩展程序属性提供给指定的对象
/// </summary>
/// <param name="extendee">要接收扩展程序属性的对象</param>
public bool CanExtend(object extendee)
{
return extendee is TextEdit;
}
#endregion
#region ISupportInitialize 成员
///<summary>
/// 开始初始化
///</summary>
public void BeginInit()
{
}
///<summary>
/// 结束初始化
///</summary>
public void EndInit()
{
if (!DesignMode && !(Host is Form))
Host_Shown(null, null);
}
#endregion
private void InitializeRule()
{
foreach (KeyValuePair<TextEdit, TextEditRuleStatus> kvp in _ruleStatuses)
if (kvp.Value.SelectAllOnEnter)
{
kvp.Key.Enter += new EventHandler(TextEdit_Enter);
}
}
#endregion
#region 内嵌类
[Serializable]
private class TextEditRuleStatus
{
private bool _selectAllOnEnter = true;
public bool SelectAllOnEnter
{
get { return _selectAllOnEnter; }
set { _selectAllOnEnter = value; }
}
}
#endregion
}
} |
using System.Collections.Generic;
namespace ACO
{
public class Vertex
{
public List<int> EdgesIndexes { get; } = new List<int>();
}
} |
using System;
using System.Collections.Generic;
using System.Net;
using System.Web.Mvc;
using Modelos;
using Servicos;
using WEBTeste.Util;
namespace WEBTeste.Controllers
{
[Authorize]
public class ClienteController : Controller
{
ClienteServico serv = new ClienteServico();
TratarString tratar = new TratarString();
IEnumerable<SelectListItem> tpCliente = new[]{
new SelectListItem() { Text = "Física", Value = "F" } ,
new SelectListItem() { Text = "Jurídica", Value = "J" }};
// GET: Cliente
public ActionResult Index(int? pagina)
{
int linhas = 5;
int qtCli = serv.ObterQuantidadeClientes();
if (qtCli <= linhas)
ViewBag.Pages = 1;
else
ViewBag.Pages = Convert.ToInt32(qtCli / linhas) + 1;
ViewBag.Page = pagina.GetValueOrDefault(1);
return View(serv.ObterClientes(pagina.GetValueOrDefault(1), linhas));
}
// GET: Cliente/Details/5
public ActionResult Detalhe(int? Pid)
{
if (Pid == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
var cliente = serv.InstanciarCliente();
cliente = serv.ObterCliente(Pid.Value);
if (cliente == null)
{
return HttpNotFound();
}
return View(cliente);
}
// GET: Cliente/Create
public ActionResult Incluir()
{
var cliente = serv.InstanciarCliente();
CriaList("F");
cliente.DtCriacao = DateTime.Now;
ViewData.Model = cliente;
return View();
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Incluir([Bind(Include = "NmCliente,DsEndereco,TpCliente,DtCriacao")] Cliente cliente,
FormCollection pForm)
{
if (ModelState.IsValid)
{
cliente.NuCep = Convert.ToInt32(tratar.RetirarEspLetra(pForm.GetValue("NuCep").AttemptedValue));
cliente.NuCnpjCpf = Convert.ToInt64(tratar.RetirarEspLetra(pForm.GetValue("NuCnpjCpf").AttemptedValue));
cliente.NuTelefone = Convert.ToInt64(tratar.RetirarEspLetra(pForm.GetValue("NuTelefone").AttemptedValue));
serv.IncluirCliente(cliente);
CriaList("F");
return RedirectToAction("Index");
}
CriaList(cliente.TpCliente);
ViewBag.Message = "Erro na inclusão.";
return View(cliente);
}
// GET: Cliente/Edit/5
public ActionResult Edit(int? Pid)
{
if (Pid == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
var cliente = serv.InstanciarCliente();
cliente = serv.ObterCliente(Pid.Value);
if (cliente == null)
{
return HttpNotFound();
}
CriaList(cliente.TpCliente);
return View(cliente);
}
// POST: Cliente/Edit/5
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit([Bind(Include = "Id,NmCliente,DsEndereco,TpCliente,DtCriacao")] Cliente cliente,
FormCollection pForm)
{
if (ModelState.IsValid)
{
cliente.NuCep = Convert.ToInt32(tratar.RetirarEspLetra(pForm.GetValue("NuCep").AttemptedValue));
cliente.NuCnpjCpf = Convert.ToInt64(tratar.RetirarEspLetra(pForm.GetValue("NuCnpjCpf").AttemptedValue));
cliente.NuTelefone = Convert.ToInt64(tratar.RetirarEspLetra(pForm.GetValue("NuTelefone").AttemptedValue));
serv.AtualizarCliente(cliente);
CriaList("F");
return RedirectToAction("Index");
}
CriaList(cliente.TpCliente);
return View(cliente);
}
// GET: Cliente/Delete/5
public ActionResult Excluir(int? Pid)
{
if (Pid == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
var cliente = serv.InstanciarCliente();
cliente = serv.ObterCliente(Pid.Value);
if (cliente == null)
{
return HttpNotFound();
}
return View(cliente);
}
// POST: Cliente/Delete/5
[HttpPost, ActionName("Excluir")]
[ValidateAntiForgeryToken]
public ActionResult ExcluirConfirmed(int Pid)
{
var cliente = serv.InstanciarCliente();
cliente = serv.ObterCliente(Pid);
serv.ExcluirCliente(cliente);
return RedirectToAction("Index");
}
private void CriaList(string pTpCliente)
{
ViewBag.TpCliente = new SelectList(tpCliente, "Value", "Text", pTpCliente);
}
public List<Cliente> ObterClientesNome(string pNmCliente, long pNuCnpjCpf)
{
if (pNuCnpjCpf != 0)
{
return serv.ObterPNome(pNmCliente, pNuCnpjCpf);
}
if (!string.IsNullOrEmpty(pNmCliente))
{
return serv.ObterPNome(pNmCliente, pNuCnpjCpf);
}
return null;
}
public string ObterNome (int? Pid)
{
if (Pid == null)
{
return "";
}
return serv.ObterNomeCliente(Pid.Value);
}
}
}
|
using Citycykler.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace CityCykler
{
public partial class produkt : System.Web.UI.Page
{
DataLinqDB db = new DataLinqDB();
protected void Page_Load(object sender, EventArgs e)
{
int idget = HelperClassAll.HelperClass.ReturnGetId();
var produkt = db.modelers.FirstOrDefault(i => i.id == idget);
if (produkt != null)
{
overskiftText.InnerText = produkt.Noticeable.text;
overskift.InnerText = produkt.overskift;
LiteralImg.Text = "<img src='img/Thumbs/" + produkt.img + "' />";
Literaltext.Text = produkt.text;
PrisText.InnerText = "Kr " + (produkt.pris).ToString("N2");
}
else
{
Response.Redirect("~/error.aspx?fejl404=true");
}
}
}
} |
using System.Collections;
using System.Linq;
using System;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
[Serializable]
public class SoundBG : MonoBehaviour {
//private AudioSource soundBG;
public BackgroundMusic[] BackgroundMusics;
private static BackgroundMusic[] _backgroundMusics;
private static AudioSource soundBG;
void Start () {
soundBG = GetComponent<AudioSource> ();
//soundBG.volume = PlayerPrefs.GetFloat ("Music");
_backgroundMusics = BackgroundMusics;
CheckBackgroundMusic(SceneManager.GetActiveScene().name);
}
public void Onchange(){
soundBG.volume = PlayerPrefs.GetFloat ("Music");
}
public static void myvolume(float changevalue)
{
soundBG.volume = changevalue;
}
public static void CheckBackgroundMusic(string sceneIndex)
{
foreach (var backgroundMusic in _backgroundMusics)
{
var isActive = backgroundMusic.CheckIfShouldBeActive(sceneIndex);
if (isActive)
{
if (soundBG.clip != backgroundMusic.AudioClip)
{
soundBG.clip = backgroundMusic.AudioClip;
soundBG.loop = true;
soundBG.Play();
}
}
}
}
public static void CheckBackgroundMusicPlayOnce(string sceneIndex)
{
foreach (var backgroundMusic in _backgroundMusics)
{
var isActive = backgroundMusic.CheckIfShouldBeActive(sceneIndex);
if (isActive)
{
if (soundBG.clip != backgroundMusic.AudioClip)
{
soundBG.clip = backgroundMusic.AudioClip;
soundBG.loop = false;
soundBG.Play();
}
}
}
}
public static void StopBackgroundMusic()
{
soundBG.enabled = false;
}
public static void StopBGMusic()
{
soundBG.Stop();
}
public static void PlayBackgroundMusic()
{
soundBG.enabled = true;
}
}
|
using System;
using System.Collections.Generic;
namespace IrsMonkeyApi.Models.DB
{
public partial class Irsoffice
{
public int IrsofficeId { get; set; }
public string IrsofficeName { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using Alabo.Industry.Shop.Orders.Domain.Enums;
namespace Alabo.Industry.Shop.Orders.ViewModels
{
public class ViewBuyProduct
{
public long ProductId { get; set; }
/// <summary>
/// 商品Guid
/// </summary>
public Guid ProductGuid { get; set; }
/// <summary>
/// 购买商品的SkuId
/// </summary>
public Guid SkuId { get; set; }
/// <summary>
/// 购买商品数量
/// </summary>
public int Count { get; set; }
/// <summary>
/// 行业Id
/// </summary>
public int IndustryId { get; set; }
/// <summary>
/// 商品行业实体 Id
/// </summary>
public long EntityId { get; set; }
/// <summary>
/// 获取或设置地址 Id
/// </summary>
public long AddressId { get; set; }
/// <summary>
/// 附加信息,用于前端显示
/// </summary>
public List<string> AttachInfo { get; set; } = new List<string>();
/// <summary>
/// 促销优惠活动ID
/// </summary>
public long PromotionalId { get; set; }
/// <summary>
/// 用户选择的出行时间(用来确定是否有活动)
/// </summary>
public string IndustryInfo { get; set; }
/// <summary>
/// 订单扩展信息,标识将产生的订单类型,直接购买的商品才能使用,购物车里只能是一般流程商品
/// </summary>
public OrderType Type { get; set; }
/// <summary>
/// 订单扩展信息,预约服务项
/// </summary>
public long SupplyId { get; set; }
/// <summary>
/// 预约项Id(“,”分隔)
/// </summary>
public string BookingRecordIds { get; set; }
/// <summary>
/// 服务是否预约
/// </summary>
public bool IsBooking { get; set; }
/// <summary>
/// 获取来源
/// </summary>
public string From { get; set; }
}
} |
using System.Drawing;
namespace KdTreeLib.UserControls
{
// Line structure to hold points, pen and additional IsVertical parameter for KdTreeBuilder
internal struct DrawingLine
{
public PointF Start { get; private set; }
public PointF End { get; private set; }
// TopLeft and BottomRight and used only by KdTreeNodesView
private PointF TopLeft { get; set; }
private PointF BottomRight { get; set; }
public RectangleF ContainingRectangle
{
get
{
return new RectangleF(TopLeft.X, TopLeft.Y, BottomRight.X - TopLeft.X, BottomRight.Y - TopLeft.Y);
}
}
public bool IsVertical { get; private set; }
public Pen Pen { get; private set; }
public DrawingLine(PointF Start, PointF End, Pen Pen, bool IsVertical = false)
: this()
{
this.Start = Start;
this.End = End;
this.Pen = Pen;
PointF _topLeft = new PointF();
PointF _bottomRight = new PointF();
// calculate TopLeft and BottomRight
if (Start.X > End.X)
{
_topLeft.X = End.X;
_bottomRight.X = Start.X;
}
else
{
_topLeft.X = Start.X;
_bottomRight.X = End.X;
}
if (Start.Y > End.Y)
{
_topLeft.Y = End.Y;
_bottomRight.Y = Start.Y;
}
else
{
_topLeft.Y = Start.Y;
_bottomRight.Y = End.Y;
}
TopLeft = _topLeft;
BottomRight = _bottomRight;
this.IsVertical = IsVertical;
}
// multiply the start and end position of the line by w (for width) and h (for height)
public DrawingLine Scale(float w, float h)
{
PointF _start = new PointF();
PointF _end = new PointF();
_start.X = Start.X * w;
_start.Y = Start.Y * h;
_end.X = End.X * w;
_end.Y = End.Y * h;
return new DrawingLine(_start, _end, Pen, IsVertical);
}
// adds x and/or y to start and end positions of the line
public DrawingLine AddXY(float? x, float? y)
{
PointF _start = new PointF();
PointF _end = new PointF();
if (x.HasValue)
{
_start.X = Start.X + x.Value;
_end.X = End.X + x.Value;
}
else
{
_start.X = Start.X;
_end.X = End.X;
}
if (y.HasValue)
{
_start.Y = Start.Y + y.Value;
_end.Y = End.Y + y.Value;
}
else
{
_start.Y = Start.Y;
_end.Y = End.Y;
}
return new DrawingLine(_start, _end, Pen, IsVertical);
}
}
}
|
using Domain.Models;
namespace Business.Interfaces
{
public interface IApplication : IGeneric<Client>
{
}
}
|
namespace csxsltproc
{
class XSLT
{
static void AbortIfFileNotExisting(string fileName)
{
if (!System.IO.File.Exists(fileName))
{
System.Console.Error.WriteLine(
"File \"{0}\" does not exist.");
System.Environment.Exit(1);
}
}
static void CreateParentDirectoriesOrAbort(string outFile)
{
try
{
System.IO.Directory.CreateDirectory(
System.IO.Path.GetDirectoryName(
System.IO.Path.GetFullPath(outFile)));
}
catch (System.Exception ex)
{
System.Console.Error.WriteLine(
"Failed to create output directories for \"{0}\":",
outFile);
System.Console.Error.WriteLine(ex);
System.Environment.Exit(2);
}
}
static int Main(string[] args)
{
try
{
if (args.Length != 3)
{
System.Console.WriteLine(
"Usage: xslt XMLFILE XSLFILE OUTFILE");
System.Console.WriteLine();
System.Console.WriteLine(
"Transforms XMLFILE into OUTFILE"
+ " using the XML Stylesheet Transform specified in XSLFILE.");
return 0;
}
string xmlFile = args[0];
string xslFile = args[1];
string outFile = args[2];
// Check the input files exist
AbortIfFileNotExisting(xmlFile);
AbortIfFileNotExisting(xslFile);
var transform = new System.Xml.Xsl.XslCompiledTransform();
var settings = new System.Xml.Xsl.XsltSettings
{
EnableDocumentFunction = true
};
// Load and compile the XSL file
try
{
transform.Load(xslFile, settings, new System.Xml.XmlUrlResolver());
}
catch (System.Exception ex)
{
System.Console.Error.WriteLine(
"Error loading XSL file: {0}",
ex);
return 2;
}
// Ensure any parent directories of the output file are created
CreateParentDirectoriesOrAbort(outFile);
// Transform the XML file into the output file
try
{
using (var xmlWriter = System.Xml.XmlWriter.Create(outFile, transform.OutputSettings))
{
transform.Transform(xmlFile, xmlWriter);
}
}
catch (System.Exception ex)
{
System.Console.Error.WriteLine(
"Error transforming XML file: {0}",
ex);
return 3;
}
// All done
System.Console.WriteLine(
"{0} => {1}",
System.IO.Path.GetFileName(xmlFile),
System.IO.Path.GetFileName(outFile));
return 0;
}
catch (System.Exception ex)
{
System.Console.WriteLine(
"Error: {0}", ex);
return 4;
}
}
}
} |
using System;
using Quark.Spell;
using Quark.Utilities;
using UnityEngine;
namespace Quark.Buff
{
public class Buff : ITaggable, Identifiable
{
public string Name { get; set; }
protected float Interval;
protected float Duration;
protected Character Possessor { get; private set; }
protected Cast _context { get; private set; }
public bool CleanedUp { get; protected set; }
public int MaxStacks = 1;
public int CurrentStacks = 1;
public StackBehavior Behaviour = StackBehavior.Nothing;
public Buff()
{
Logger.GC("Buff::ctor");
}
~Buff()
{
Logger.GC("Buff::dtor");
}
public string Identifier
{
get
{
return Name + "@" + _context.Spell.Identifier;
}
}
/// <summary>
/// Sets the Cast context where this Buff runs in
/// </summary>
/// <param name="context">The Cast context</param>
public void SetContext(Cast context)
{
_context = context;
}
/// <summary>
/// This ratio indicates the rate of its alive time to its total duration
/// </summary>
public virtual float LifeRatio
{
get
{
return this.Duration > 0 ? this.Alive / this.Duration : 0;
}
}
/// <summary>
/// The time span in seconds where this Buff was running
/// </summary>
protected float Alive
{
get
{
return Time.timeSinceLevelLoad - this._posessionTime;
}
}
/// <summary>
/// This variable is stored for calculating the alive time of the Buff instances
/// </summary>
private float _posessionTime = 0;
/// <summary>
/// This variable is stored for checking whether the Tick method should be called or not in a given frame
/// </summary>
private float _lastTick = 0;
bool _terminated = false;
/// <summary>
/// Immediately finalize this Buff
/// </summary>
protected void Terminate()
{
_terminated = true;
_lastTick = Mathf.Infinity;
}
public void ResetBeginning()
{
_posessionTime = Time.timeSinceLevelLoad;
}
/// <summary>
/// This function controls the state of the buff for whether it should call the OnTick function in this frame or not and also it checks if it has completed its lifespan or not
/// </summary>
private void Tick()
{
if (Time.timeSinceLevelLoad - _lastTick >= Interval)
{
_lastTick = Time.timeSinceLevelLoad;
this.OnTick();
}
if (LifeRatio >= 1 || _terminated)
{
this.Deregister();
this.OnDone();
}
}
public virtual string[] Tags
{
get
{
return new string[] { "buff" };
}
set
{
}
}
/// <summary>
/// Register proper events to the Messenger.
/// This method should <b>not</b> contain any gameplay related logic
/// Refer to the <c>OnPossess()</c> for gameplay logic on possession
/// </summary>
protected virtual void Register()
{
Messenger.AddListener("Update", this.Tick);
}
/// <summary>
/// Deregister pre registered events from the messenger.
/// </summary>
protected virtual void Deregister()
{
Messenger.RemoveListener("Update", this.Tick);
}
/// <summary>
/// This event handler is called right after the owning <c>BuffContainer</c> possesses this buff
/// </summary>
public virtual void OnPossess(Character possessor)
{
Possessor = possessor;
_posessionTime = Time.timeSinceLevelLoad;
_lastTick = Time.timeSinceLevelLoad;
Register();
PossessEffects.Run(Possessor, _context);
}
/// <summary>
/// This event handler is called when the same Buff is attached again
/// </summary>
protected virtual void OnStack()
{
StackEffects.Run(Possessor, _context);
}
/// <summary>
/// Handles the tick event
/// </summary>
protected virtual void OnTick()
{
TickEffects.Run(Possessor, _context);
}
/// <summary>
/// Executes the finalization logic of this buff
/// </summary>
protected virtual void OnDone()
{
DoneEffects.Run(Possessor, _context);
this.CleanedUp = true;
}
protected virtual EffectCollection PossessEffects { get { return new EffectCollection { }; } }
protected virtual EffectCollection StackEffects { get { return new EffectCollection { }; } }
protected virtual EffectCollection TickEffects { get { return new EffectCollection { }; } }
protected virtual EffectCollection DoneEffects { get { return new EffectCollection { }; } }
}
public enum StackBehavior
{
ResetBeginning = 1,
IncreaseStacks = 2,
Nothing = 4
}
} |
using Microsoft.AspNetCore.Mvc.ModelBinding;
using System;
namespace EasyWebApp.Data.Exception
{
public class ModelStateException : RankException
{
public ModelStateDictionary ModelState { get; }
public ModelStateException(string key, string errorMessage)
{
ModelState = new ModelStateDictionary();
ModelState.AddModelError(key, errorMessage);
}
public ModelStateException(ModelStateDictionary modelState)
{
ModelState = modelState;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Text;
using System.Threading.Tasks;
using System.Transactions;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using NinjaStore.Common.Models;
using NinjaStore.Common.Repositories;
namespace NinjaStore.Common.UnitTest
{
[TestClass]
public class ProductTest
{
#region Data Members
private ProductRepository _productRepository;
private readonly List<string> _cleanupIds = new List<string>();
#endregion
#region Initialize and Cleanup Methods
[TestInitialize]
public void Initialize()
{
InitializeProductRepository().GetAwaiter().GetResult();
}
[TestCleanup]
public void Cleanup()
{
foreach (var id in _cleanupIds)
{
_productRepository.DeleteProduct(id).GetAwaiter().GetResult();
}
}
#endregion
#region Tests
[TestMethod]
public void GetAllProductsTest()
{
var result = _productRepository.GetAllProducts();
Assert.IsTrue(result.Count > 0);
}
[TestMethod]
public void GetProductByIdTest()
{
var result = _productRepository.GetProductById("2");
Assert.IsTrue(result.Count > 0);
Assert.IsTrue(result.Id == "2");
}
[TestMethod]
public async Task CreateProductTest()
{
var expected = new Product
{
Price = 1000.00,
Count = 5,
Name = "Create Product Name",
Id = Guid.NewGuid().ToString()
};
await _productRepository.CreateProduct(expected);
var actual = _productRepository.GetProductById(expected.Id);
Assert.AreEqual(actual.Id, expected.Id, true, CultureInfo.CurrentCulture);
_cleanupIds.Add(expected.Id);
}
[TestMethod]
public async Task DeleteProductTest()
{
var newProduct = new Product
{
Price = 1000.00,
Count = 5,
Name = "Product to delete",
Id = Guid.NewGuid().ToString()
};
// Create the product and make sure it's there
await _productRepository.CreateProduct(newProduct);
var actual = _productRepository.GetProductById(newProduct.Id);
Assert.AreEqual(actual.Id, newProduct.Id, true, CultureInfo.CurrentCulture);
// Delete the product and check to see if it's gone
await _productRepository.DeleteProduct(newProduct.Id);
var result = _productRepository.GetProductById(newProduct.Id);
Assert.IsNull(result);
}
[TestMethod]
public async Task UpdateProductTest()
{
const string productId = "1";
var product = _productRepository.GetProductById(productId);
// Assign a random value to the price
// update the product.
var random = new Random();
product.Price = random.NextDouble() * (500.0 - 1.0) + 1.0;
await _productRepository.UpdateProduct(product);
var result = _productRepository.GetProductById(product.Id);
Assert.AreEqual(result.Price, product.Price);
}
#endregion
#region Private Methods
private async Task InitializeProductRepository()
{
var docDbSettings = new DocumentDbSettings
{
AuthKey = "",
CollectionId = "",
DatabaseId = "",
Endpoint = ""
};
_productRepository = new ProductRepository(docDbSettings);
await _productRepository.Initialize();
}
#endregion
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace LimenawebApp.Models.Payments
{
public class Mdl_Banks
{
}
public class GetBanks_api
{
public int code { get; set; }
public string message { get; set; }
public List<Banks_api> data { get; set; }
}
public class Banks_api
{
public string bankCode { get; set; }
public string bankName { get; set; }
public string dfltAcct { get; set; }
public string dfltBranch { get; set; }
public int? nextChckNo { get; set; }
public string locked { get; set; }
public string dataSource { get; set; }
public int userSign { get; set; }
public string swiftNum { get; set; }
public string iban { get; set; }
public string countryCod { get; set; }
public string postOffice { get; set; }
public string aliasName { get; set; }
public int absEntry { get; set; }
public int? dfltActKey { get; set; }
public int? nextNum { get; set; }
public string bsPstDate { get; set; }
public string bsValDate { get; set; }
public int? bnkOpCode { get; set; }
public string bsDocDate { get; set; }
}
} |
using System.Collections.Generic;
using buildingEnergyLoss.Model;
namespace buildingEnergyLoss.Repository
{
public interface ITypeOfCountryRepository
{
List<TypeOfCountry> GetTypeOfCountries();
}
}
|
using System;
using System.Data.SqlClient;
using System.Linq;
using System.Threading;
using System.Web.Mvc;
using WebApi;
using Welic.Dominio.Models.Menu.Servicos;
using Welic.Dominio.Models.Users.Servicos;
using WebApi.Helpers;
namespace WebApi.Controllers
{
public class BaseController : Controller
{
private readonly IServicoMenu _servicoMenu;
private readonly IServiceUser _serviceUser;
public BaseController(IServicoMenu servicoMenu, IServiceUser serviceUser)
{
_servicoMenu = servicoMenu;
_serviceUser = serviceUser;
}
public BaseController()
{
}
public ActionResult Menu(string email)
{
string query = Query.Q001;
var usuario = _serviceUser.Query().Select(x => x).FirstOrDefault(x => x.Email == email);
var list = _servicoMenu.SelectQuery(query, new SqlParameter("UserId", usuario.Id)).ToList();
return PartialView(list);
}
public PartialViewResult NavBar()
{
return PartialView();
}
protected override IAsyncResult BeginExecuteCore(AsyncCallback callback, object state)
{
// Attempt to read the culture cookie from Request
if (!(RouteData.Values["culture"] is string cultureName))
cultureName = Request.UserLanguages != null && Request.UserLanguages.Length > 0 ? Request.UserLanguages[0] : null; // obtain it from HTTP header AcceptLanguages
// Validate culture name
cultureName = CultureHelper.GetImplementedCulture(cultureName); // This is safe
if (RouteData.Values["culture"] as string != cultureName)
{
// Force a valid culture in the URL
RouteData.Values["culture"] = cultureName.ToLowerInvariant(); // lower case too
// Redirect user
Response.RedirectToRoute(RouteData.Values);
}
// Modify current thread's cultures
Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo(cultureName);
Thread.CurrentThread.CurrentUICulture = Thread.CurrentThread.CurrentCulture;
return base.BeginExecuteCore(callback, state);
}
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class hingeJointTestScript : MonoBehaviour {
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
//float angle;
//Vector3 vecAxis;
//transform.localRotation.ToAngleAxis(out angle, out vecAxis);
//Debug.Log(angle + " " + vecAxis );
//Debug.Log(transform.localEulerAngles);
//transform.rotation = Quaternion.Euler(0, 20 ,0);
//transform.rotation = Quaternion.AngleAxis(1, transform.up) * transform.rotation; // angleaxis create a relative rotation so we have to multiply that by the previous one
//transform.Rotate(transform.up, 0.1f, Space.World); // transform.up meams local y-axis expressed in world coordinate, that is why we have to use space.world for the last argument
//float angle = 10f;
//JointLimits jl = new JointLimits();
//jl.min = angle;
//jl.max = angle;
//transform.GetComponent<HingeJoint>().limits = jl;
JointSpring spr = transform.GetComponent<HingeJoint>().spring;
spr.targetPosition = -45; // myInputData is the input from my sensor
spr.spring = 100;
transform.GetComponent<HingeJoint>().spring = spr;
Debug.Log(transform.GetComponent<HingeJoint>().angle);
}
}
|
public enum ProductType
{
Gold,
Silver,
Diamond,
}
|
using Alabo.App.Share.RewardRuless.Domain.Entities;
using Alabo.Datas.UnitOfWorks;
using Alabo.Domains.Repositories;
using MongoDB.Bson;
namespace Alabo.App.Share.RewardRuless.Domain.Repositories
{
public class RewardRuleRepository : RepositoryMongo<RewardRule, ObjectId>, IRewardRuleRepository
{
public RewardRuleRepository(IUnitOfWork unitOfWork) : base(unitOfWork)
{
}
}
} |
namespace MySurveys.Services.Contracts
{
using System.Linq;
using Models;
public interface ISurveyService : IService
{
IQueryable<Survey> GetAll();
IQueryable<Survey> GetAllPublic();
Survey GetById(int id);
Survey GetById(string id);
Survey Add(Survey survey);
Survey Update(Survey survey);
void Delete(object id);
IQueryable<Survey> GetMostPopular(int numberOfSurveys);
}
}
|
using UnityEngine;
using System.Collections;
namespace EventSystem {
public class NewMonthEvent : GameEvent {
public NewMonthEvent () {}
}
} |
using Barker.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;
namespace Barker.Data.UserService
{
public class UserService : IUserService
{
HttpClient client;
string uri = "https://localhost:44374/Users";
public UserService()
{
client = new HttpClient();
}
public async Task<User> CreateUserAsync(User user)
{
string userAsJson = JsonSerializer.Serialize(user);
HttpContent content = new StringContent(userAsJson,
Encoding.UTF8,
"application/json");
var returnContent = await client.PostAsync(uri, content);
string returnJson = await returnContent.Content.ReadAsStringAsync();
return JsonSerializer.Deserialize<User>(returnJson);
}
public async Task DeleteUserAsync(int userID)
{
await client.DeleteAsync($"{uri}/{userID}");
}
public async Task<User> GetUserAsync(string email)
{
string message = await client.GetStringAsync($"{uri}/{email}");
return JsonSerializer.Deserialize<User>(message);
}
public async Task<User> GetUserAsync(int id)
{
string message = await client.GetStringAsync($"{uri}/{id}");
return JsonSerializer.Deserialize<User>(message);
}
public async Task<User> UpdateUserAsync(User user)
{
string userAsJson = JsonSerializer.Serialize(user);
HttpContent content = new StringContent(userAsJson,
Encoding.UTF8,
"application/json");
var returnContent = await client.PatchAsync(uri, content);
string returnJson = await returnContent.Content.ReadAsStringAsync();
return JsonSerializer.Deserialize<User>(returnJson);
}
}
}
|
using UnityEngine;
using System.Collections;
using GameVariables;
public class CombatMenuManager : MonoBehaviour {
// Use this for initialization
void Start () {
}
public void StartCombat()
{
}
public void EndCombat()
{
int randomTempExpObtained = Random.Range(100,1000);
GameEvent.EndCombat(randomTempExpObtained);
}
}
|
using System.ComponentModel;
using System.Runtime.CompilerServices;
namespace MainTool.WPF
{
public abstract class BindableBase : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
/// <summary>
/// This method is called by the Set accessor of each property.
/// The CallerMemberName attribute that is applied to the optional propertyName
/// parameter causes the property name of the caller to be substituted as an argument.
/// </summary>
/// <param name="propertyName">Name of changed property.</param>
protected void RaisePropertyChanged([CallerMemberName] string propertyName = "")
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
namespace TYNMU.manger.News
{
public partial class SetNews : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (Session.Count == 0 || Session["IsLogin"] == null)
{
Response.Write("<script language='JavaScript'>parent.window.location='../Login.aspx';</script>");
return;
}
}
protected void GVNews_RowEditing(object sender, GridViewEditEventArgs e)
{
string url = "AddNews.aspx?type=Edit&ID=" + this.GVNews.Rows[Convert.ToInt32(e.NewEditIndex)].Cells[0].Text;
Response.Redirect(url);
}
protected void GVNews_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
string sSql = "delete from T_News where ID ='" + GVNews.Rows[e.RowIndex].Cells[0].Text + "'";
//Response.Write(GVNews.Rows[e.RowIndex].Cells[0].Text);
Data.DAO.NonQuery(sSql);
GVNews.DataBind();
}
}
} |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using Microsoft.WindowsAPICodePack.Dialogs;
using Polaris.ViewModels;
namespace Polaris.Views {
/// <summary>
/// MainWindow.xaml の相互作用ロジック
/// </summary>
public partial class MainWindow : Window {
/// <summary>
/// ctor
/// </summary>
public MainWindow()
#region
{
InitializeComponent();
TextCompositionManager.AddPreviewTextInputHandler( m_searchTermTextBox, OnPreviewTextInput );
TextCompositionManager.AddPreviewTextInputUpdateHandler( m_searchTermTextBox, OnPreviewTextInputUpdate );
}
#endregion
/// <summary>
/// ロード時
/// </summary>
private void OnLoaded( object sender, RoutedEventArgs e )
#region
{
ViewModel.OnLoaded();
}
#endregion
/// <summary>
/// ファイルオープンダイアログボタン押した
/// </summary>
private void OnDirOpenDlgClick( object sender, RoutedEventArgs e )
#region
{
var comnOpenFileDlg = new CommonOpenFileDialog();
comnOpenFileDlg.Title = "検索するフォルダを選択してください";
comnOpenFileDlg.InitialDirectory = ViewModel.SearchDirectory;
// フォルダ選択モードにする
comnOpenFileDlg.IsFolderPicker = true;
// フォルダが選択されたら変更をかける
if( CommonFileDialogResult.Ok == comnOpenFileDlg.ShowDialog() ) {
ViewModel.SearchDirectory = comnOpenFileDlg.FileName;
}
}
#endregion
/// <summary>
/// インデクスダイアログボタン押した
/// </summary>
private void OnIndexingDlgClick( object sender, RoutedEventArgs e )
#region
{
// ここで予測時間とか出しておきたい
var fileCountStr = ViewModel.CheckFiles();
if( MessageBoxResult.OK != MessageBox.Show( fileCountStr, "確認", MessageBoxButton.OKCancel ) ) {
return;
}
var idxDlg = new IndexingDialog();
// 検索ディレクトリを設定
idxDlg.SearchDirectory = ViewModel.SearchDirectory;
// 表示するとインデクス化を開始する。完了するまで待機
idxDlg.ShowDialog();
}
#endregion
private bool m_isImeOnConv = false;
private int m_enterKeyBuffer { get; set; }
/// <summary>
/// テキスト入力前
/// </summary>
private void OnPreviewTextInput( object sender, TextCompositionEventArgs e )
#region
{
m_enterKeyBuffer = m_isImeOnConv ? 1 : 0;
m_isImeOnConv = false;
}
#endregion
/// <summary>
/// テキスト入力更新
/// </summary>
private void OnPreviewTextInputUpdate( object sender, TextCompositionEventArgs e )
#region
{
m_isImeOnConv = (e.TextComposition.CompositionText.Length != 0);
}
#endregion
/// <summary>
/// 検索ディレクトリにフォーカスが入ったとき
/// </summary>
private void SearchDirectoryTextBox_GotFocus( object sender, RoutedEventArgs e )
#region
{
Dispatcher.InvokeAsync( () => {
Task.Delay( 0 );
var tb = sender as TextBox;
tb?.SelectAll();
} );
}
#endregion
/// <summary>
/// 検索ディレクトリ名変更時
/// </summary>
private void SearchedDirectoryTextChanged( object sender, TextChangedEventArgs e )
#region
{
ViewModel.SearchDirectory = m_searchDirectoryTextBox.Text;
}
#endregion
/// <summary>
/// 検索文言
/// </summary>
private void searchTermTextBox_KeyUp( object sender, KeyEventArgs e )
#region
{
if( m_isImeOnConv == false && e.Key == Key.Enter && m_enterKeyBuffer == 1 ) {
m_enterKeyBuffer = 0;
} else if( m_isImeOnConv == false && e.Key == Key.Enter && m_enterKeyBuffer == 0 ) {
ViewModel.SearchTerm = m_searchTermTextBox.Text;
}
}
#endregion
/// <summary>
/// リストビューのファイル開く
/// </summary>
private void ListViewItem_OpenFile( object sender, RoutedEventArgs e )
#region
{
if( sender is MenuItem menuItem ) {
ViewModel.OpenFile( menuItem.DataContext );
}
}
#endregion
/// <summary>
/// リストビューのファイル開く(ダブルクリックイベント)
/// </summary>
private void ListViewItem_MouseDoubleClick( object sender, MouseButtonEventArgs e )
#region
{
if( sender is ListViewItem item ) {
ViewModel.OpenFile( item.DataContext );
}
}
#endregion
/// <summary>
/// リストビューのフォルダ開く
/// </summary>
private void ListViewItem_OpenFolder( object sender, RoutedEventArgs e )
#region
{
if( sender is MenuItem menuItem ) {
ViewModel.OpenDirectory( menuItem.DataContext );
}
}
#endregion
/// <summary>
/// ビューモデル
/// </summary>
public MainWindowViewModel ViewModel
#region
{
get {
return DataContext as MainWindowViewModel;
}
}
#endregion
}
}
|
using System.IO;
using Microsoft.Win32;
namespace TRPO_labe_1.Model.FileHelpers
{
static class FileLoadHelper
{
public static string LoadInfoFromFile(string path)
{
string text = "";
OpenFileDialog dialog = new OpenFileDialog();
dialog.Filter = "txt|*.txt";
dialog.Multiselect = false;
dialog.InitialDirectory = $"{Directory.GetCurrentDirectory()}";
if (dialog.ShowDialog().Value)
{
FileSettings.FilePath = dialog.FileName;
using (var reader = new StreamReader(FileSettings.FilePath))
text = reader.ReadToEnd();
}
return text;
}
}
}
|
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class Fader : MonoBehaviour
{
public Image fadeImage;
private void Awake()
{
}
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
}
public void DoFade(float alpha, float duration, Action<bool> callback)
{
StartCoroutine(DoFadeCoroutine(alpha, duration, callback));
}
IEnumerator DoFadeCoroutine(float alpha, float duration, Action<bool> callback) {
float startAlpha = fadeImage.color.a;
float endAlpha = alpha;
for (float f = 0.0f; f <= duration; f += Time.deltaTime)
{
Color c = fadeImage.color;
c.a = Mathf.Lerp(startAlpha, endAlpha, f/duration);
fadeImage.color = c;
yield return null;
}
Color final = fadeImage.color;
final.a = endAlpha;
fadeImage.color = final;
callback.Invoke(true);
}
}
|
namespace Business.Constants
{
public static class Messages
{
public static string CarIsNotAppropriate = "Araba kiranlanmış durumdadır.";
public static string CarImageLimitExceeded="Bir arabanın en fazla 5 adet resmi olabilir.";
public static string UserNotFound="Kullanıcı Bulunamadı";
public static string PasswordError="Kullanıcı Parola Hatalı";
public static string SuccessfulLogin="Giriş Başarılı";
public static string UserRegistered="Kullanıcı kaydedildi.";
public static string EmailIsUsed="Email sistemde kayıtlıdır.";
public static string EmailIsNotUsed="Email kullanılabilir";
public static string AccessTokenCreated="Token Oluşturuldu";
public static string WeakPassword="Şifreniz uygun değil.";
public static string PasswordRequirement="Parola Min 5 karakter maksimum 8 karakterden oluşmalı.En az bir büyük harf,bir küçük harf ve bir rakam içermelidir.";
public static string AuthorizationDenied="Yetkiniz Yok";
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.