text stringlengths 13 6.01M |
|---|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;
namespace Moonmile.XmlDom
{
/// <summary>
/// XNode をツリー構造でサーチするクラス
/// </summary>
public class XNavigator : IEnumerable<XNode>
{
XNode _root;
public XNavigator(XNode root)
{
_root = root;
}
public IEnumerator<XNode> GetEnumerator()
{
return new Enumerator(_root);
}
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return new Enumerator(_root);
}
protected class Enumerator : IEnumerator<XNode>
{
XNode _root;
XNode _cur;
public Enumerator(XNode root)
{
_root = root;
}
public XNode Current
{
get { return _cur; }
}
public void Dispose()
{
}
object System.Collections.IEnumerator.Current
{
get { return _cur; }
}
public bool MoveNext()
{
if (_cur == null)
{
_cur = _root;
return true;
}
if (_cur.NodeType == System.Xml.XmlNodeType.Element &&
((XElement)_cur).Nodes().Count() > 0)
{
_cur = ((XElement)_cur).FirstNode;
return true;
}
if (_cur.NextNode != null)
{
_cur = _cur.NextNode;
return true;
}
XNode cur = _cur;
while (true)
{
XElement pa1 = cur.Parent;
if (pa1 == null)
{
_cur = null;
return false;
}
if (pa1.NextNode != null)
{
_cur = pa1.NextNode;
return true;
}
cur = pa1;
}
}
public void Reset()
{
_cur = null;
}
}
}
/// <summary>
/// XNodeをXElement風に使う拡張クラス
/// </summary>
public static class XNodeExtentions
{
public static string TagName(this XNode n)
{
if (n.NodeType == System.Xml.XmlNodeType.Element)
{
return ((XElement)n).Name.ToString();
}
else
{
return "";
}
}
public static string Value(this XNode n)
{
if (n.NodeType == System.Xml.XmlNodeType.Element)
{
return ((XElement)n).Value;
}
else
{
return "";
}
}
public static string Attrs(this XNode n, string key)
{
if (n.NodeType == System.Xml.XmlNodeType.Element)
{
var attr = ((XElement)n).Attribute(key);
if (attr != null)
{
return attr.Value;
}
}
return "";
}
public static XNode Child(this XNode nd, string tag)
{
if (nd.NodeType == System.Xml.XmlNodeType.Element)
{
return ((XElement)nd).Nodes().Where(n => n.TagName() == tag).FirstOrDefault();
}
else
{
return null;
}
}
}
}
|
using Nancy;
using Nancy.ModelBinding;
using Newtonsoft.Json;
using Twitalysis;
using Twitalysis.DataAccess;
using System.IO;
using Twitalysis.Instrumentation;
using System;
using System.Collections.Generic;
namespace Twitalysis.Nancy
{
public class TwitModule : NancyModule
{
private static FriendProcessor processor = null;
private static DependencyInjection dependencyInjection = null;
private static bool initialized = false;
public TwitModule()
{
// initial setup.
// TODO: there is probably a better way to initialize once in Nancy...read some docs :)
if (!initialized)
{
dependencyInjection = new DependencyInjection();
processor = new FriendProcessor(dependencyInjection);
initialized = true;
}
// routing
Get["/twit/atreplies"] = parameters =>
{
InMemoryPerformanceCounters counter = new InMemoryPerformanceCounters("GetAtReplies");
counter.BeginRequest();
bool success = true;
// TODO: proper error handling, with some error codes, etc
if (processor == null)
{
success = false;
counter.EndRequest(success);
return "Error! No friend processor.";
}
string atReplies = string.Empty;
try
{
atReplies = processor.GetRecentAtReplies();
}
catch (Exception e)
{
dependencyInjection.Logger.Log(String.Format("Failed to retrieve @reply data! Exception: {0}", e.ToString()));
success = false;
}
// TODO: include more metadata -- success, latency, etc
dependencyInjection.Logger.Log("GetAtReplies API called.");
counter.EndRequest(success);
return atReplies;
};
Get["/twit/followerratings"] = parameters =>
{
InMemoryPerformanceCounters counter = new InMemoryPerformanceCounters("GetFollowerRatings");
counter.BeginRequest();
bool success = true;
// TODO: proper error handling, with some error codes, etc
if (processor == null)
{
success = false;
counter.EndRequest(success);
return "Error! No friend processor.";
}
IEnumerable<FollowerWithRating> followers = null;
try
{
followers = processor.GetFollowerRatings();
}
catch (Exception e)
{
dependencyInjection.Logger.Log(String.Format("Failed to retrieve follower data! Exception: {0}", e.ToString()));
success = false;
}
// TODO: include more metadata -- success, latency, etc
dependencyInjection.Logger.Log("GetFollowerRatings API called.");
counter.EndRequest(success);
return JsonConvert.SerializeObject(followers);
};
// debug data
Post["/auth"] = parameters =>
{
// deserialize the post body -- consumer key and secret.
// this is for debug reasons right now. in "production" this must be disabled.
InMemoryPerformanceCounters counter = new InMemoryPerformanceCounters("Auth");
counter.BeginRequest();
bool success = true;
try
{
StreamReader reader = new StreamReader(Request.Body);
TwitterAuthData authData = JsonConvert.DeserializeObject<TwitterAuthData>(reader.ReadToEnd());
processor.UpdateAuthData(authData);
}
catch (Exception e)
{
dependencyInjection.Logger.Log(String.Format("Failed to update auth data! Exception: {0}", e.ToString()));
success = false;
}
// TODO: include more metadata
dependencyInjection.Logger.Log("Auth API called.");
counter.EndRequest(success);
return "Updated.";
};
}
}
} |
using System;
using System.Timers;
namespace DiscordBotTest.Models
{
public class UserReminder
{
public ulong UserId { get; set; }
public string Message { get; set; }
public TimeSpan TimeSpan { get; set; }
public Timer Timer { get; set; }
public bool HasReminded { get; set; }
}
}
|
using CP.i8n;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CriticalPath.Data
{
partial class ProductCategoryDTO
{
partial void Initiliazing(ProductCategory entity)
{
ParentCategory = entity.ParentCategory == null ? null : new ProductCategoryDTO(entity.ParentCategory);
}
[Display(ResourceType = typeof(EntityStrings), Name = "ParentCategory")]
public ProductCategoryDTO ParentCategory { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace KKCSInvoiceProject
{
public partial class Administrator : Form
{
public Administrator()
{
InitializeComponent();
}
private void btn_alerts_Click(object sender, EventArgs e)
{
AdminAlerts aa = new AdminAlerts();
aa.Show();
}
private void btn_flighttimes_Click(object sender, EventArgs e)
{
AdminFlightTimes aft = new AdminFlightTimes();
aft.Show();
}
}
}
|
using System.Reactive;
using System.Reactive.Linq;
using MVVMSidekick.ViewModels;
using MVVMSidekick.Views;
using MVVMSidekick.Reactive;
using MVVMSidekick.Services;
using MVVMSidekick.Commands;
using IndoorMap;
using IndoorMap.ViewModels;
using System;
using System.Net;
using System.Windows;
namespace MVVMSidekick.Startups
{
internal static partial class StartupFunctions
{
static Action ShopDetailsPageConfig =
CreateAndAddToAllConfig(ConfigShopDetailsPage);
public static void ConfigShopDetailsPage()
{
ViewModelLocator<ShopDetailsPage_Model>
.Instance
.Register(context =>
new ShopDetailsPage_Model())
.GetViewMapper()
.MapToDefault<ShopDetailsPage>();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace PromotionEngineApp
{
public class ProductModel
{
public int ProductID { get; set; }
public int ProductBasePrice { get; set; }
public string ProductSKUId { get; set; }
public int ProductCount { get; set; }
public bool PromotionCodeApplied { get; set; }
}
}
|
using Nest;
using System;
using System.Collections.Generic;
using System.Text;
namespace CoreFrameWork.ElasticSearch
{
/// <summary>
/// Elastic客户端工厂扩展
/// </summary>
public static class ElasticClientFactoryExtensions
{
public static ElasticClient CreateClient(this IElasticClientFactory elasticClientFactory)
{
return elasticClientFactory.CreateClient(Microsoft.Extensions.Options.Options.DefaultName);
}
}
}
|
//
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the MIT License. See LICENSE file in the project root for full license information.
//
#region Usings
using System;
using DotNetNuke.Services.Search;
#endregion
namespace DotNetNuke.Services.Exceptions
{
#pragma warning disable 0618
public class SearchException : BasePortalException
{
private readonly SearchItemInfo m_SearchItem;
//default constructor
public SearchException()
{
}
public SearchException(string message, Exception inner, SearchItemInfo searchItem) : base(message, inner)
{
m_SearchItem = searchItem;
}
public SearchItemInfo SearchItem
{
get
{
return m_SearchItem;
}
}
}
#pragma warning restore 0618
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using BusinessOwnerDetails;
using Microsoft.Extensions.Logging;
/*Grocery Stores Project Combines two JSON files.
* One file named BusinessOwner has the information about business owners and their titles
* Another file named GroceryStore has information like address, location, zip etc
* The field common to both of these JSON is Account Number
* By matching the Account Number we can determine the owner name and nearby grocery stores and display the information in a table
*/
namespace GroceryStores.Pages
{
public class GroceryBusinessOwnersModel : PageModel
{
private readonly ILogger<GroceryBusinessOwnersModel> _logger;
public GroceryBusinessOwnersModel(ILogger<GroceryBusinessOwnersModel> logger)
{
_logger = logger;
}
public void OnGet()
{
using (WebClient webClient = new WebClient())
{
string businessOwnerEndPoint = "https://data.cityofchicago.org/resource/r5kz-chrr.json";
string BusinessOwnerJsonString = webClient.DownloadString(businessOwnerEndPoint);
BusinessOwner[] allBusinessOwners = BusinessOwner.FromJson(BusinessOwnerJsonString);
ViewData["allBusinessOwners"] = allBusinessOwners;
string groceryStoreEndPoint = "https://data.cityofchicago.org/resource/53t8-wyrc.json";
string GroceryStoreJsonString = webClient.DownloadString(groceryStoreEndPoint);
GroceryStore[] allGroceryStores = GroceryStore.FromJson(GroceryStoreJsonString);
ViewData["allGroceryStores"] = allGroceryStores;
IDictionary<long, GroceryStore> groceryStoresMap = new Dictionary<long, GroceryStore>();
List<BusinessOwner> businessOwnerList = new List<BusinessOwner>();
foreach (GroceryStore grocery in allGroceryStores)
{
if (!groceryStoresMap.ContainsKey(grocery.ZipCode))
{
groceryStoresMap.Add(grocery.ZipCode, grocery);
}
}
foreach (BusinessOwner businessRec in allBusinessOwners)
{
if (groceryStoresMap.ContainsKey(businessRec.ZipCode))
{
businessOwnerList.Add(businessRec);
}
}
ViewData["businessOwners"] = businessOwnerList;
}
}
}
}
|
using System;
namespace SlurryReactor.Entity
{
public class ConstantInputModel
{
/// <summary>
/// Gas constant
/// </summary>
public double R { get; } = 8.314;
/// <summary>
/// Hydrogen molar mass
/// </summary>
public double HydrogenMass { get; } = 2;
/// <summary>
/// Synthesis gas molar mass
/// </summary>
public double SynthesisGasMass { get; } = 28;
/// <summary>
/// Carbon dioxide molar mass
/// </summary>
public double CarbonDioxideMass { get; } = 44;
/// <summary>
/// Water molar mass
/// </summary>
public double WaterMass { get; } = 18;
/// <summary>
/// Methan molar mass
/// </summary>
public double MethanMass { get; } = 16;
/// <summary>
/// CH2 molar mass
/// </summary>
public double MethyleneGroupMass { get; } = 14;
public double GetMolarMass(int index)
{
switch (index)
{
case 1:
return HydrogenMass;
case 2:
return SynthesisGasMass;
case 3:
return CarbonDioxideMass;
case 4:
return WaterMass;
case 5:
return MethanMass;
default:
throw new NotSupportedException("Molar mass for component > 5 should calculated");
}
}
/// <summary>
/// Activation energy for shift reaction
/// </summary>
public double Esh { get; set; }
/// <summary>
/// Reaction rate constant for shift reaction
/// </summary>
public double Ksh { get; set; }
/// <summary>
/// Activation energy for Fisher-Tropch reaction
/// </summary>
public double Eft { get; set; }
/// <summary>
/// Reaction rate constant for Fisher-Tropch reaction
/// </summary>
public double Kft { get; set; }
/// <summary>
/// Hydrogen rate constant
/// </summary>
public double K1 { get; set; }
/// <summary>
/// Synthesis gas rate constant
/// </summary>
public double K2 { get; set; }
/// <summary>
/// Carbon dioxide rate constant
/// </summary>
public double K3 { get; set; }
/// <summary>
/// Water rate constant
/// </summary>
public double K4 { get; set; }
/// <summary>
/// Methan rate constant
/// </summary>
public double K5 { get; set; }
/// <summary>
/// Specific rate constant
/// </summary>
public double K { get; set; }
public double GetK(int index)
{
switch (index)
{
case 1:
return K1;
case 2:
return K2;
case 3:
return K3;
case 4:
return K4;
case 5:
return K5;
default:
return K;
}
}
/// <summary>
/// Hydrogen parameter
/// </summary>
public double B1 { get; set; }
/// <summary>
/// Synthesis gas parameter
/// </summary>
public double B2 { get; set; }
/// <summary>
/// Carbon dioxide parameter
/// </summary>
public double B3 { get; set; }
/// <summary>
/// Water parameter
/// </summary>
public double B4 { get; set; }
/// <summary>
/// Methan parameter
/// </summary>
public double B5 { get; set; }
/// <summary>
/// Specific parameter
/// </summary>
public double B { get; set; }
/// <summary>
/// Zero specific parameter
/// </summary>
public double B0 { get; set; }
public double GetB(int index)
{
switch (index)
{
case 0:
return B0;
case 1:
return B1;
case 2:
return B2;
case 3:
return B3;
case 4:
return B4;
case 5:
return B5;
default:
return B;
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
using FastSQL.Sync.Core.Enums;
namespace FastSQL.Sync.Core.Processors
{
public class CustomerProcessor : IProcessor
{
public string Id => "customer_processor_PmuKvXrqRkiYYfpyw2355eKQ==";
public string Name => "Customer Processor";
public string Description => "Customer Processor";
public ProcessorType Type => ProcessorType.Entity;
}
}
|
using syscrawl.Game.Models.Levels;
namespace syscrawl.Game.Services.Levels
{
public class SpecificLevelGenerator : ILevelGenerator
{
public LevelGraph Generate()
{
var graph = new LevelGraph();
var entranceNode =
graph.CreateNode<EntranceNode>(
"Entrance 0", null);
var fw1 =
graph.CreateNode<FirewallNode>(
"fw1", entranceNode);
var c1 =
graph.CreateNode<ConnectorNode>(
"c1", fw1);
var c11 =
graph.CreateNode<ConnectorNode>(
"c11", fw1);
graph.CreateNode<FilesystemNode>(
"system1", c11);
graph.CreateNode<FilesystemNode>(
"system2", c11);
var c12 =
graph.CreateNode<ConnectorNode>(
"c12", fw1);
var fw2c1 =
graph.CreateNode<FirewallNode>(
"fw2c1", c1);
var fw2c =
graph.CreateNode<ConnectorNode>(
"fwc1", fw2c1);
graph.CreateNode<FilesystemNode>(
"fs4", fw2c);
var fwc1 =
graph.CreateNode<FirewallNode>(
"fwc1", c1);
graph.CreateNode<FilesystemNode>(
"fs1", fwc1);
graph.CreateNode<FilesystemNode>(
"fs2", fwc1);
graph.CreateNode<FilesystemNode>(
"fs3", fwc1);
graph.CreateNode<ConnectorNode>(
"c2", fw1);
graph.CreateNode<ConnectorNode>(
"c3", fw1);
return graph;
}
}
} |
using System;
/*Write a program that allocates array of 20 integers and initializes each element by its index multiplied by 5.
Print the obtained array on the console.
*/
class Program
{
static void Main()
{
int[] numbers = new int[20];
for(int i = 0; i < numbers.Length; i++)
{
numbers[i] = i * 5;
}
string allNumbers = string.Join(", ",numbers);
Console.WriteLine(allNumbers);
}
}
|
using Grifling.Blog.DomainModels;
using NHibernate;
using NHibernate.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace Grifling.Service.Services
{
public interface IAccountUserService
{
AccountUser User(string email);
AccountUser User(Guid id);
IList<AccountUser> Users();
bool EmailExist(string Email);
}
public class AccountUserService : IAccountUserService
{
private ISession _session;
public AccountUserService(ISession session)
{
_session = session;
}
public AccountUser User(string email)
{
return _session.Query<AccountUser>().Where(x => x.Email == email).Fetch(s => s.Password).FirstOrDefault();
}
public AccountUser User(Guid id)
{
return _session.Get<AccountUser>(id);
}
public IList<AccountUser> Users()
{
return _session.Query<AccountUser>().ToList();
}
public bool EmailExist(string Email)
{
int nr = _session.Query<AccountUser>().Where(x => x.Email == Email).ToList().Count;
if(nr > 0)
{
return true;
}
return false;
}
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerMovement : MonoBehaviour {
public Rigidbody rigidBody;
private Vector3 position;
private float width;
private float height;
public float forwardForce = 2000f;
public float sidewaysForce = 100f;
float scoreMultiplier = 1;
int maxScoreMultiplier = 5;
void Awake() {
width = (float)Screen.width / 2.0f;
height = (float)Screen.height / 2.0f;
// Position used for the cube.
position = new Vector3(0.0f, 1.0f, 0.0f);
}
// Start is called before the first frame update
void Start() {
}
// Update is called once per frame
void Update() {
if (scoreMultiplier <= maxScoreMultiplier) {
scoreMultiplier += Time.deltaTime / 10;
}
//if (Input.touchCount > 0) {
// Touch touch = Input.GetTouch(0);
// if (touch.phase == TouchPhase.Moved) {
// Vector2 touchPosition = touch.position;
// touchPosition.x = (touchPosition.x - width) / width;
// position = new Vector3(-touchPosition.x, 1.0f, 0.0f);
// transform.position = position;
// }
//}
//add a forward force
rigidBody.AddForce(0, 0, forwardForce * Time.deltaTime);
if (Input.GetKey("d")) {
rigidBody.AddForce(sidewaysForce * Time.deltaTime, 0, 0, ForceMode.VelocityChange);
}
if (Input.GetKey("a")) {
rigidBody.AddForce(-sidewaysForce * Time.deltaTime, 0, 0, ForceMode.VelocityChange);
}
//check if player fell off the ground
if (rigidBody.position.y < -1f) {
FindObjectOfType<GameManager>().EndGame();
}
}
}
|
using Dapper;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleAppGeneratePDFFile
{
public class Helper
{
//ConnectionStringSettings mySQLConSettings = ConfigurationManager.ConnectionStrings["MyDBConnection"];
public static string GetConnectionString()
{
string con = ConfigurationManager.ConnectionStrings["MyDbConnectionString"].ConnectionString;
return ConfigurationManager.ConnectionStrings["MyDbConnectionString"].ConnectionString;
}
}
#region MyRegion
#endregion
}
|
using System;
using System.Collections;
using System.IO;
namespace ReadyGamerOne.Utility
{
public static class FileUtil
{
/// <summary>
/// 当前可执行文件路径
/// </summary>
public static string CurrentRunDirectory => Environment.CurrentDirectory;
/// <summary>
/// 获取父级目录
/// </summary>
/// <param name="pathNum"></param>
/// <returns></returns>
public static string GetRunDirectoryInParentPath(int pathNum=3)
{
// /Server/Server/bin/Debug/server.exe
DirectoryInfo pathInfo = Directory.GetParent(CurrentRunDirectory);
while (pathNum > 0 && pathInfo.Parent != null)
{
var info = pathInfo.Parent;
pathNum--;
}
//返回一个完整的文件夹路径
return pathInfo.FullName;
}
/// <summary>
/// 创建文件夹
/// </summary>
/// <param name="path"></param>
/// <returns></returns>
public static string CreateFolder(string path)
{
//如果目录存在则创建
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
return path;
}
/// <summary>
/// 创建目录
/// </summary>
/// <param name="path"></param>
/// <param name="foldName"></param>
/// <returns></returns>
public static string CreateFolder(string path,string foldName)
{
var fullPath = path + "//" + foldName;
if (!Directory.Exists(fullPath))
Directory.CreateDirectory(fullPath);
return fullPath;
}
/// <summary>
/// 创建文件(初始化文本)
/// </summary>
/// <param name="path"></param>
/// <param name="fileName"></param>
/// <param name="info"></param>
public static void CreateFile(string path,string fileName,string info=null)
{
CreateFolder(path);
var fileInfo = new FileInfo(path + "//" + fileName);
if (fileInfo.Exists)
fileInfo.Delete();
var streamWriter = fileInfo.CreateText();
if(!string.IsNullOrEmpty(info))
streamWriter.WriteLine(info);
streamWriter.Close();
streamWriter.Dispose();
}
/// <summary>
/// 向文件中添加信息
/// </summary>
/// <param name="path"></param>
/// <param name="fileName"></param>
/// <param name="info"></param>
public static void AddInfoToFile(string path,string fileName,string info)
{
CreateFolder(path);
var fileInfo = new FileInfo(path + "//" + fileName);
var streamWriter = !fileInfo.Exists ? fileInfo.CreateText() : fileInfo.AppendText();
streamWriter.WriteLine(info);
streamWriter.Close();
streamWriter.Dispose();
}
/// <summary>
/// 读取文件
/// </summary>
/// <param name="path"></param>
/// <param name="fileName"></param>
/// <returns></returns>
public static string LoadFile(string path,string fileName)
{
if (!FileExist(path, fileName))
return null;
var streamReader = new StreamReader(path + "//" + fileName);
var arr = new ArrayList();
while (true)
{
var line = streamReader.ReadLine();
if (line == null)
break;
arr.Add(line);
}
streamReader.Close();
streamReader.Dispose();
string ans = "";
foreach (var str in arr)
ans += str;
return ans;
}
/// <summary>
/// 判断文件是否存在
/// </summary>
/// <param name="path"></param>
/// <param name="fileName"></param>
/// <returns></returns>
public static bool FileExist(string path,string fileName)
{
if (!Directory.Exists(path))
return false;
if (!File.Exists(path + "//" + fileName))
return false;
return true;
}
}
} |
using ETLBox.Exceptions;
using System;
using System.Reflection;
namespace ETLBox.Helper
{
/// <summary>
/// Reflection helper class that allows to directly set values in properties.
/// </summary>
public static class PropertyInfoExtension
{
/// <summary>
/// Sets a value in a property. If this is not possible, this method throws an exception.
/// </summary>
/// <param name="pi">The property info for the property</param>
/// <param name="obj">The object that contains the property</param>
/// <param name="value">The new value for the property</param>
public static void SetValueOrThrow(this PropertyInfo pi, object obj, object value)
{
if (pi.CanWrite)
pi.SetValue(obj, value);
else
throw new ETLBoxException($"Can't write into property {pi?.Name} - property has no setter definition.");
}
/// <summary>
/// Tries to set a value in a property. If not possible, it will do nothing.
/// </summary>
/// <param name="pi">The property info for the property</param>
/// <param name="obj">The object that contains the property</param>
/// <param name="value">The new value for the property</param>
/// <param name="enumType">If the property is an enum type, this will need special handling - pass the enum type here. Default value is null.</param>
public static void TrySetValue(this PropertyInfo pi, object obj, object value, Type enumType = null)
{
if (pi.CanWrite)
{
if (enumType != null && value != null && enumType.IsEnum)
{
pi.SetValue(obj, Enum.Parse(enumType, value?.ToString()));
}
else
{
pi.SetValue(obj, value);
}
}
}
}
}
|
using AuthService.Models;
namespace AuthService.Services
{
public interface IUserService {
void Create(User user);
void Delete(User user);
// require to pass the Bson object id
void Get(string id);
}
} |
using UnityEngine;
using System.Collections;
public class Passos : MonoBehaviour {
private string[] passosTrilha = new string[12];
private string[] passosFunc = new string[4];
private int elementoInt;
public void passos(string elemento, string comando, string local){
Debug.Log(elemento+" "+comando+" "+local);
int.TryParse(elemento , out elementoInt);
if(local=="trilha"){
passosTrilha[elementoInt-1] = comando;
}else if(local=="funcao"){
passosFunc[elementoInt-1] = comando;
}
}
}
|
using LibraryManagement.Data.Interfaces;
using LibraryManagement.Data.Model;
using LibraryManagement.ViewModel;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Linq;
namespace LibraryManagement.Controllers
{
public class AuthorController : Controller
{
private readonly IAuthorRepository _authorRepository;
public AuthorController(IAuthorRepository authorRepository)
{
_authorRepository = authorRepository;
}
[Route("Author")]
public IActionResult List()
{
var authors = _authorRepository.GetAllWithBooks();
if (authors.Count() == 0) return View("Empty");
return View(authors);
}
public IActionResult Update(int id)
{
var author = _authorRepository.GetById(id);
if (author == null) return NotFound();
return View(author);
}
[HttpPost]
public IActionResult Update(Author author)
{
if (!ModelState.IsValid)
{
return View(author);
}
_authorRepository.Update(author);
return RedirectToAction("List");
}
public IActionResult Create()
{
var viewModel = new CreateAuthorViewModel
{ Referer = Request.Headers["Referer"].ToString() };
return View(viewModel);
}
[HttpPost]
public IActionResult Create(CreateAuthorViewModel authorVM)
{
if (!ModelState.IsValid)
{
return View(authorVM);
}
_authorRepository.Create(authorVM.Author);
if (!String.IsNullOrEmpty(authorVM.Referer))
{
return Redirect(authorVM.Referer);
}
return RedirectToAction("List");
}
public IActionResult Delete(int id)
{
var author = _authorRepository.GetById(id);
_authorRepository.Delete(author);
return RedirectToAction("List");
}
}
}
|
using System;
using System.Linq;
using BusinessLayer.SortingAlgorithms;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace SortingApp.UnitTests.SortingAlgorithms
{
/// <summary>
/// Tests for InsertionSorter class.
/// </summary>
/// <owner>Anton Petrenko</owner>
[TestClass]
public class InsertionSorterTest
{
/// <summary>
/// Tests Sort method if pass null collection it will throw ArgumentNullException.
/// </summary>
/// <owner>Anton Petrenko</owner>
[TestMethod]
public void InsertionSorter_Sort_PassNullCollection_ThrowArgumentNullException()
{
//
// Arrange.
//
double[] array = null;
var insertionSorter = new InsertionSorter<double>();
//
// Assert.
//
Assert.ThrowsException<ArgumentNullException>(() => insertionSorter.Sort(array));
}
/// <summary>
/// Tests Sort method if pass sorted collection it will leave sorted collection.
/// </summary>
/// <owner>Anton Petrenko</owner>
[TestMethod]
public void InsertionSorter_Sort_PassSortedCollection_GetSortedCollection()
{
//
// Arrange.
//
var actualArray = new double[] { 0.15, 0.2, 1.56, 5.0, 9.99 };
var expectedArray = new double[] { 0.15, 0.2, 1.56, 5.0, 9.99 };
var insertionSorter = new InsertionSorter<double>();
bool isCollectionSorted;
//
// Act.
//
insertionSorter.Sort(actualArray);
isCollectionSorted = actualArray.SequenceEqual(expectedArray);
//
// Assert.
//
Assert.IsTrue(isCollectionSorted);
}
/// <summary>
/// Tests Sort method if pass unsorted collection it will make sorted collection.
/// </summary>
/// <owner>Anton Petrenko</owner>
[TestMethod]
public void InsertionSorter_Sort_PassUnsortedCollection_GetSortedCollection()
{
//
// Arrange.
//
var actualArray = new double[] { 1.56, 0.2, 376.0, 0.15};
var expectedArray = new double[] { 0.15, 0.2, 1.56, 376.0 };
var insertionSorter = new InsertionSorter<double>();
bool isCollectionSorted;
//
// Act.
//
insertionSorter.Sort(actualArray);
isCollectionSorted = actualArray.SequenceEqual(expectedArray);
//
// Assert.
//
Assert.IsTrue(isCollectionSorted);
}
}
}
|
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ChatWith : MonoBehaviour {
public GameObject target =null;
private float dis = 0;
private float chatRange = 1.2f;
private Animator animator;
private Player player;
public GameObject chatting;
public bool isChat =false;
private GameObject chatCanvas;
private void Start()
{
chatCanvas = GameObject.Find("Main_Canvas/Chat");
chatCanvas.SetActive(false);
animator = transform.GetComponent<Animator>();
player = gameObject.GetComponent<Player>();
}
private void Update()
{
WalkTo();
}
private void WalkTo()
{
if (target)
{
dis = (gameObject.transform.position - target.transform.position).magnitude;
if (dis <= chatRange && isChat)
{
player.target = this.transform.position;
animator.SetFloat("Speed", 0);
player.isChat = true;
chatCanvas.SetActive(true);
chatCanvas.GetComponent<ShowWords>().xmlName = target.name;
}
}
}
}
|
using System;
namespace InterviewCake
{
public class FindRotationPoint
{
string[] words = new string[]{
"ptolemaic",
"retrograde",
"supplant",
"undulate",
"xenoepist",
"asymptote", // <-- rotates here return 5
"babka",
"banoffee",
"engender",
"karpatka",
"othellolagkage",
"x",
"y",
"z",
};
private int BSRotPoint(string[] words, int min, int max)
{
int midPoint=(min+max)/2;
int compare=string.Compare(words[min],words[midPoint]);
if (compare==1) //B>A
return BSRotPoint(words,min,midPoint);
else if (compare==0)
return max;
else // -1 A<B
return BSRotPoint(words,midPoint,max);
}
public int FindRotPoint(string[] words)
{
if (words.Length==0)
return -1;
int rotPoint=0;
for (int i=1;i<words.Length;i++)
{
Console.WriteLine(words[i]);
int compare=string.Compare(words[i],words[i+1]);
// Console.Write(compare);
if (compare==1)
{
rotPoint=i+1;
break;
}
}
return rotPoint;;
}
public void TestRotPoint()
{
Console.WriteLine(BSRotPoint(words,0,words.Length));
}
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
/*
* This class refers to the hand slots of the player.
*/
public class SC_Tile : MonoBehaviour
{
public delegate void SlotClickedHandler(string _index, int handIndex);
public static event SlotClickedHandler OnSlotClicked;
public int index;
public Image slotImage;
public SC_GlobalEnums.SlotState state;
#region MonoBehaviour
private void Awake()
{
index = int.Parse(name.Substring(name.Length - 2));
}
#endregion
#region Logic
public void Click()
{
if (OnSlotClicked != null)
OnSlotClicked(slotImage.sprite.name, index);
}
// Changes the slot state to 'Empty' or 'Occupied', if the new state is not Empty, then set a sprite as well.
public void ChangeSlotState(SC_GlobalEnums.SlotState _newState, Sprite _newSprite)
{
if(slotImage != null)
{
if (_newState == SC_GlobalEnums.SlotState.Empty)
{
slotImage.enabled = false;
}
else
{
slotImage.sprite = _newSprite;
slotImage.enabled = true;
}
state = _newState;
}
}
public bool isEmpty()
{
if (state == SC_GlobalEnums.SlotState.Empty)
return true;
else
return false;
}
#endregion
}
|
using System.Collections.Generic;
using System.Threading.Tasks;
namespace UWCDemo
{
public interface IHttpJokes
{
Task<IEnumerable<Joke>> GetJokesAsync(int page, int limit);
}
}
|
using GameLib;
using JumpAndRun.API;
using JumpAndRun.TerrainGeneration;
using System;
namespace JumpAndRun.Content.TerrainGeneration.Generators
{
public class StandartGenerator : IWorldGenerator
{
private IBiom _biom;
public int Seed { get; }
public StandartGenerator(int seed)
{
var rnd = new Random(Seed);
_biom = ContentManager.Instance.Biomes[rnd.Next(ContentManager.Instance.Biomes.Count)];
Seed = seed;
}
public Chunk GenerateChunk(Index2 position)
{
var chunk = new Chunk(position, 1);
var rnd = new Random((Seed + position.X) * position.Y);
if ((float)rnd.NextDouble() < _biom.Size)
{
_biom = ContentManager.Instance.Biomes[rnd.Next(ContentManager.Instance.Biomes.Count)];
}
if(_biom.BaseHeight > position.Y * Chunk.Sizey && _biom.BaseHeight < (position.Y + 1) * Chunk.Sizey)
{
for (var x = 0; x < Chunk.Sizex; x++)
{
var height = rnd.Next(-1, 2) + _biom.BaseHeight - (Chunk.Sizey * position.Y);
SetBlock(chunk, _biom.Surface, x, height);
for (var y = 0; y < height; y++)
{
SetBlock(chunk, _biom.Filler, x, y);
}
for (var y = height+1; y < Chunk.Sizey; y++)
{
SetBlock(chunk, null, x, y);
}
}
}
else if(_biom.BaseHeight > position.Y * Chunk.Sizey)
{
for (var x = 0; x < Chunk.Sizex; x++)
{
for (var y = 0; y < Chunk.Sizey; y++)
{
SetBlock(chunk, _biom.Filler, x, y);
}
}
}
else
{
for (var x = 0; x < Chunk.Sizex; x++)
{
for (var y = 0; y < Chunk.Sizey; y++)
{
SetBlock(chunk, null, x, y);
}
}
}
return chunk;
}
private static void SetBlock(Chunk chunk, IBlock block, int x, int y)
{
chunk.SetBlock(block, x, y, 0);
chunk.SetBlock(block, x, y, 1);
chunk.SetBlock(block, x, y, 2);
if(y != 47)
chunk.SetBlock(block, x, y + 1, 2);
}
}
}
|
using ShopApp.Entities;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
namespace ShopApp.WebUI.Models
{
public class BrandModel
{
public int Id { get; set; }
[Display(Name = "Marka Adı")]
public string Name { get; set; }
public List<Product> Products { get; set; }
}
}
|
namespace Bindable.Linq.Interfaces
{
/// <summary>
/// Implemented by objects that provide a Refresh method.
/// </summary>
public interface IRefreshable
{
/// <summary>
/// Refreshes the object.
/// </summary>
void Refresh();
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
[RequireComponent(typeof(Image))]
public class UIBossHealthBar : MonoBehaviour {
[Tooltip("Boss Game Object")]
[SerializeField] private EnemyActor m_enemyActor;
[Tooltip("Rate at which fade in happens")]
[SerializeField] [Range(0.0001f, 1f)] private float m_fFadeIn = 0.01f;
[Tooltip("Rate at which fade out happens")]
[SerializeField] [Range(0.0001f, 1f)] private float m_fFadeOut = 0.01f;
private Image m_healthBar;
private Image m_healthBarFilled;
// Use this for initialization
void Start () {
m_healthBar = gameObject.GetComponent<Image>();
m_healthBarFilled = new List<Image>(GetComponentsInChildren<Image>()).Find(img => img != m_healthBar);
// set alpha
m_healthBar.canvasRenderer.SetAlpha(0f);
m_healthBarFilled.canvasRenderer.SetAlpha(0f);
// move to top of hierarchy
m_healthBar.transform.SetSiblingIndex(0);
}
// Update is called once per frame
void FixedUpdate () {
// fill bar according to boss' health
m_healthBarFilled.fillAmount = (float)m_enemyActor.m_nCurrentHealth / (float)m_enemyActor.m_nHealth;
if (m_enemyActor.m_bIsActive && m_healthBar.canvasRenderer.GetAlpha() < 1) {
// increase alpha
m_healthBar.canvasRenderer.SetAlpha(m_healthBar.canvasRenderer.GetAlpha() + m_fFadeIn);
m_healthBarFilled.canvasRenderer.SetAlpha(m_healthBarFilled.canvasRenderer.GetAlpha() + m_fFadeIn);
}
if (!m_enemyActor.m_bIsAlive) {
// decrease alpha
m_healthBar.canvasRenderer.SetAlpha(m_healthBar.canvasRenderer.GetAlpha() - m_fFadeOut);
m_healthBarFilled.canvasRenderer.SetAlpha(m_healthBarFilled.canvasRenderer.GetAlpha() - m_fFadeOut);
if (m_healthBar.canvasRenderer.GetAlpha() <= 0) {
Destroy(gameObject);
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Models;
using SubSonic;
using ZrSoft;
using Core;
using System.Data;
using System.IO;
using Microsoft.Reporting.WebForms;
using System.Text;
namespace mvcProject.Areas.Sys.Controllers
{
public class RatingController : Controller
{
public string msg = "";
public int status = 1;
string LogStr = "";
ControllerHelper c = new ControllerHelper();
QueryPaged query = new QueryPaged();
[PowerFilter]
public ActionResult Index()
{
return View();
}
[PowerFilter]
public ActionResult Info(string id)
{
Sys_Rating entity = new Sys_Rating(id);
return View(entity);
}
[HttpPost]
[LoginPower]
public JsonResult GetList(GridPager pager, string queryStr)
{
if (pager.rows == 0)
pager.rows = Core.Config.PageSize;
List<QueryModel> qList = c.getQList(queryStr);
query.pager = pager;
query.TableName = Sys_Rating.Schema;
query.init();
GetQuery(qList);
int total = 0;
List<Sys_Rating> list = query.Paged(ref total).ExecuteTypedList<Sys_Rating>();
var json = new
{
total = total,
pager = query.pager,
rows = list.Select((r, i) => new
{
RowNumber = (i++) + (pager.page - 1) * pager.rows + 1,
Id = r.Id,
Type = r.Type,
Name = r.Name,
Memo = r.Memo,
AdminId = r.AdminId,
PubDate = string.Format("{0:yyyy-MM-dd}", r.PubDate),
EditAdminId = r.EditAdminId,
EditPubDate = string.Format("{0:yyyy-MM-dd}", r.EditPubDate)
})
};
return Json(json);
}
[HttpPost]
public JsonResult GetAllList()
{
SqlQuery sq = new Select().From<Sys_Rating>();
List<Sys_Rating> list = sq.ExecuteTypedList<Sys_Rating>();
var json = new
{
total = list.Count,
rows = (from r in list
select new
{
Id = r.Id,
Type = r.Type,
Name = r.Name,
Memo = r.Memo,
AdminId = r.AdminId,
PubDate = string.Format("{0:yyyy-MM-dd}", r.PubDate),
EditAdminId = r.EditAdminId,
EditPubDate = string.Format("{0:yyyy-MM-dd}", r.EditPubDate)
}
).ToArray()
};
return Json(json);
}
#region 拼接查询条件
//拼接查询条件
public void GetQuery(List<QueryModel> qList)
{
GetQuery(qList, null);
}
public void GetQuery(List<QueryModel> qList, string[] coulums)
{
if (c.GetQueryStr(qList, "searchtype") == "0")
{
//精确查询
query.IsEqualTo(qList, Sys_Rating.Columns.Id);
query.IsEqualTo(qList, Sys_Rating.Columns.Name);
query.IsEqualTo(qList, Sys_Rating.Columns.Memo);
query.IsEqualTo(qList, Sys_Rating.Columns.AdminId);
query.IsEqualTo(qList, Sys_Rating.Columns.EditAdminId);
}
else
{
//模糊查询
query.Like(qList, Sys_Rating.Columns.Id);
query.Like(qList, Sys_Rating.Columns.Name);
query.Like(qList, Sys_Rating.Columns.Memo);
query.Like(qList, Sys_Rating.Columns.AdminId);
query.Like(qList, Sys_Rating.Columns.EditAdminId);
}
query.IsEqualTo(qList, Sys_Rating.Columns.Type);
//query.IsGreaterThanOrEqualTo(qList, Sys_Rating.Columns.PubDate);
//query.IsLessThanOrEqualTo(qList, Sys_Rating.Columns.PubDate);
//query.IsGreaterThanOrEqualTo(qList, Sys_Rating.Columns.EditPubDate);
//query.IsLessThanOrEqualTo(qList, Sys_Rating.Columns.EditPubDate);
}
#endregion
#region Create
[PowerFilter]
public ActionResult Create()
{
return View();
}
[HttpPost]
[PowerFilter]
public JsonResult Create(Sys_Rating model)
{
try
{
model.Id = Utils.GetNewDateID();
model.AdminId = LoginInfo.AdminID;
model.PubDate = DateTime.Now;
model.EditAdminId = LoginInfo.AdminID;
model.EditPubDate = DateTime.Now;
model.Save();
status = 1;
msg = Tip.InsertSucceed;
}
catch
{
status = 0;
msg = Tip.InsertFail;
}
GUI.InsertLog("等级说明", "新增", msg + ":" + model.Id + ",类别:" + model.Type + ",名称:" + model.Name + ",备注:" + model.Memo + ",:" + model.AdminId + ",:" + model.PubDate + ",:" + model.EditAdminId + ",:" + model.EditPubDate + "");
return ControllerHelper.jsonresult(status, msg);
}
#endregion
#region Edit
[PowerFilter]
public ActionResult Edit(string id)
{
Sys_Rating entity = new Sys_Rating(id);
return View(entity);
}
[HttpPost]
[PowerFilter]
public JsonResult Edit(Sys_Rating model)
{
try
{
Sys_Rating entity = new Sys_Rating(model.Id);
if (!string.IsNullOrEmpty(entity.Id))
{
LogStr = ""
+ "Id:" + model.Id
+ ",类别:" + model.Type
+ ",名称:" + model.Name
+ ",备注:" + model.Memo
+ ",:" + model.AdminId
+ ",:" + model.PubDate
+ ",:" + model.EditAdminId
+ ",:" + model.EditPubDate
+ "";
entity.Type = model.Type;
entity.Name = model.Name;
entity.Memo = model.Memo;
entity.AdminId = model.AdminId;
entity.PubDate = model.PubDate;
entity.EditAdminId = model.EditAdminId;
entity.EditPubDate = model.EditPubDate;
entity.Save();
status = 1;
msg = Tip.EditSucceed;
}
else
{
status = 0;
msg = Tip.EditFail;
}
}
catch (Exception e)
{
status = 0;
msg = Tip.EditFail + Utils.NoHTML(e.Message);
}
GUI.InsertLog("等级说明", "编辑", msg + LogStr);
return ControllerHelper.jsonresult(status, msg);
}
#endregion
#region Delete
[HttpPost]
public JsonResult Delete(string id)
{
if (!string.IsNullOrWhiteSpace(id))
{
try
{
//这里书写需要删除的逻辑代码
new Delete().From<Sys_Rating>().Where(Sys_Rating.Columns.Id).In(id.Split(','))
.Execute();
status = 1;
msg = Tip.DeleteSucceed;
}
catch (Exception e)
{
status = 0;
msg = Tip.DeleteFail + Utils.NoHTML(e.Message);
}
}
else
{
}
GUI.InsertLog("等级说明", "删除", msg + LogStr);
return ControllerHelper.jsonresult(status, msg);
}
#endregion
#region 导出到PDF EXCEL WORD
[PowerFilter]
public ActionResult Export(string type, string queryStr)
{
GridPager pager = new GridPager();
List<QueryModel> qList = c.getQList(queryStr);
query.pager = pager;
query.TableName = Sys_Rating.Schema;
query.init();
GetQuery(qList);
List<Sys_Rating> list = query.Paged().ExecuteTypedList<Sys_Rating>();
LocalReport localReport = new LocalReport();
try
{
localReport.ReportPath = Server.MapPath("~/Report/Sys_Rating.rdlc");
ReportDataSource reportDataSource = new ReportDataSource("DataSet", list);
localReport.DataSources.Add(reportDataSource);
if (type.ToLower() == "print")
{
//直接打印
ReportPrint.Run(localReport);
return View("/views/export/print.cshtml");
}
string reportType = type;
string mimeType;
string encoding;
string fileNameExtension;
string deviceInfo =
"<DeviceInfo>" +
"<OutPutFormat>" + type + "</OutPutFormat>" +
"<PageWidth>11in</PageWidth>" +
"<PageHeight>11in</PageHeight>" +
"<MarginTop>0.5in</MarginTop>" +
"<MarginLeft>1in</MarginLeft>" +
"<MarginRight>1in</MarginRight>" +
"<MarginBottom>0.5in</MarginBottom>" +
"</DeviceInfo>";
Warning[] warnings;
string[] streams;
byte[] renderedBytes;
renderedBytes = localReport.Render(
reportType,
deviceInfo,
out mimeType,
out encoding,
out fileNameExtension,
out streams,
out warnings
);
string ExportName = "等级说明";
GUI.InsertLog("等级说明", "导出", "导出[" + ExportName + "]成功![" + type.ToLower() + "]");
switch (type.ToLower())
{
case "pdf":
ExportName += ".pdf";
break;
case "image":
ExportName += ".png";
break;
case "excel":
ExportName += ".xls";
break;
case "word":
ExportName += ".doc";
break;
}
return File(renderedBytes, mimeType, ExportName);
}
catch (Exception ex)
{
Utils.WriteFile("D://", "222.txt", ex.Message);
return View("/views/export/error.cshtml");
}
}
#endregion
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class EnemyToBoxes : MonoBehaviour {
[SerializeField]
public GameObject cargo;
// Use this for initialization
void Start() {
cargo.SetActive(false);
}
// Update is called once per frame
void Update() {
}
private void OnTriggerEnter(Collider _col) {
if (_col.tag == "EnemyBody") {
Destroy(_col.transform.parent.gameObject);
cargo.SetActive(true);
AudioSource audio = GetComponent<AudioSource>();
audio.Play();
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class scrCompetenceMenu : MonoBehaviour {
public static scrCompetenceMenu CompetenceMenu;
[Header("Public Values")]
public bool inCompetenceMenu;
[Header("Stocked Values")]
Vector3 pausedPlayerRigidbody;
private void Start()
{
CompetenceMenu = this;
}
private void Update()
{
if (Input.GetKeyDown(KeyCode.Tab))
{
if (!inCompetenceMenu)
EnterCompetenceMenu();
else
ExitCompetenceMenu();
}
}
void EnterCompetenceMenu()
{
inCompetenceMenu = true;
}
void ExitCompetenceMenu()
{
inCompetenceMenu = false;
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Sunny.Lib;
using System.Security.Cryptography;
namespace Sunny.Tools
{
public class AlipayHelper
{
private static AlipayUnionPaySignConfiguration signConfig = null;
static AlipayHelper()
{
LoadSpecialConfigurationValue();
}
public static string ProcessParameters(Dictionary<string, string> paras)
{
string str = string.Empty;
paras = SortRequstParameters(paras);
string sign = GetSign(paras, paras[AlipayConst.Encoding], paras[AlipayConst.SignType], signConfig.PrivateKey);
if (paras.ContainsKey(AlipayConst.Sign))
{
paras[AlipayConst.Sign] = sign;
}
else
{
paras.Add(AlipayConst.Sign, sign);
}
str = HttpHelper.ConcatenatedParameters2RequestString(paras);
return str;
}
private static void LoadSpecialConfigurationValue()
{
signConfig = AlipayUnionPaySignConfigurationSectionHandler.GetConfigurationObject(AlipayUnionPaySignConfigurationSectionHandler.GroupName, AlipayConst.ConfigName);
}
private static string GetSign(Dictionary<string, string> inputPara, string providerCharset, string sign_type, string privateKey)
{
//Only support MD5, if not MD5, throw exception.
if (sign_type.ToUpper() != "MD5")
{
}
Dictionary<string, string> signParameters = new Dictionary<string, string>();
//Remove the empty and the unnecessary signature parameters
foreach (KeyValuePair<string, string> temp in inputPara)
{
if (temp.Key.ToUpper() != AlipayConst.Sign.ToUpper() && temp.Key.ToUpper() != AlipayConst.SignType.ToUpper() && temp.Value != "" && temp.Value != null)
{
signParameters.Add(temp.Key, temp.Value);
}
}
//Create the format type "key=value", use "&" connect all the item
StringBuilder builder = new StringBuilder();
foreach (KeyValuePair<string, string> temp in signParameters)
{
builder.AppendFormat("{0}={1}&", temp.Key, temp.Value);
}
//Remove the last "&"
int nLen = builder.Length;
builder.Remove(nLen - 1, 1);
return MD5Hash(builder.ToString() + privateKey, ConvertHelper.GetEncodingByName(providerCharset));
}
private static Dictionary<string, string> SortRequstParameters(Dictionary<string, string> dictionary)
{
//Create a array with all the Keys, and sort the array by A-Z;
string[] paramsArray = new string[dictionary.Keys.Count];
dictionary.Keys.CopyTo(paramsArray, 0);
//Sort all the parameters as A-Z
Array.Sort<string>(paramsArray, StringComparer.Ordinal);
//Create the format type "key=value", use "&" connect all the item
Dictionary<string, string> resultDic = new Dictionary<string, string>();
foreach (string oneKey in paramsArray)
{
if (!string.IsNullOrEmpty(dictionary[oneKey]))
{
resultDic.Add(oneKey, dictionary[oneKey]);
}
}
return resultDic;
}
private static string MD5Hash(string content, Encoding encodeType)
{
MD5 md = MD5.Create();
if (encodeType == null)
{
encodeType = Encoding.Default;
}
byte[] buffer = md.ComputeHash(encodeType.GetBytes(content));
StringBuilder builder = new StringBuilder();
for (int i = 0; i <= buffer.Length - 1; i++)
{
builder.Append(buffer[i].ToString("x2"));
}
return builder.ToString();
}
}
public class AlipayConst
{
public static string Sign = "sign";
public static string SignType = "sign_type";
public static string Encoding = "_input_charset";
public static string ConfigName = "alipay";
}
}
|
using PetSharing.Contracts.PetProfilesContract;
using PetSharing.Contracts.UserContracts;
using System;
using System.Collections.Generic;
using System.Text;
namespace PetSharing.Contracts
{
public class HomeContract
{
//public string Phone { get; set; }
//public string FullName { get; set; }
//public string Email { get; set; }
//public string PicUrl { get; set; }
//public string UserName { get; set; }
public UserFullInfoContract User { get; set; }
public List<PetProfileShortInfoContract> Pets { get; set; }
public List<PostContract> Posts { get; set; }
public HomeContract()
{
Pets = new List<PetProfileShortInfoContract>();
Posts = new List<PostContract>();
}
}
}
|
/*
* Copyright 2019 Samsung Electronics Co., Ltd. All rights reserved.
*
* Licensed under the Flora License, Version 1.1 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://floralicense.org/license
*
* 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.Windows.Input;
using Ultraviolet.Interfaces;
using Xamarin.Forms;
namespace Ultraviolet.ViewModels
{
/// <summary>
/// ViewModel class for InformationPage.
/// </summary>
public class InformationViewModel : BaseViewModel
{
/// <summary>
/// Navigation service obtained by dependency service.
/// </summary>
private readonly INavigationService _navigationService;
/// <summary>
/// Navigates to the next page.
/// </summary>
public ICommand ShowMainPageCommand { get; private set; }
/// <summary>
/// Initializes class.
/// </summary>
public InformationViewModel()
{
_navigationService = DependencyService.Get<INavigationService>();
ShowMainPageCommand = new Command(ExecuteShowMainPage);
}
/// <summary>
/// Executed by <see cref="ShowMainPageCommand"/>
/// </summary>
private void ExecuteShowMainPage()
{
_navigationService.NavigateTo<MainViewModel>();
}
}
}
|
using Microsoft.EntityFrameworkCore;
using Ramazan.UdemyBlogWebSite.DataAccess.Concreate.EntityFrameworkCore.Mapping;
using Ramazan.UdemyBlogWebSite.Entities.Concreate;
using System;
using System.Collections.Generic;
using System.Text;
namespace Ramazan.UdemyBlogWebSite.DataAccess.Concreate.EntityFrameworkCore.Context
{
public class UdemyBlogWebSiteContext:DbContext
{
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseSqlServer("server=DESKTOP-4DC573S\\SQLEXPRESS;Database=UdemyBlogWebSite;Integrated Security=true");
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.ApplyConfiguration(new AppUserMap());
modelBuilder.ApplyConfiguration(new BlogMap());
modelBuilder.ApplyConfiguration(new CommentMap());
modelBuilder.ApplyConfiguration(new CategoryMap());
modelBuilder.ApplyConfiguration(new CategoryBlogMap());
}
public DbSet<AppUser> AppUsers { get; set; }
public DbSet<Blog> Blogs { get; set; }
public DbSet<Category> Categories { get; set; }
public DbSet<CategoryBlog> CategoryBlogs { get; set; }
public DbSet<Comment> Comments { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NUnit.Framework;
using Infnet.Engesoft.SysBank.Model.Dominio;
namespace Infnet.Engesoft.SysBank.Model.Teste
{
[TestFixture]
public class ServicoDepositoTeste
{
[Test]
public void TesteDepositoContaNormal()
{
var ccN = new ContaCorrenteNormal();
ccN.Saldo = 850.00m;
var deposito = new DepositoService(ccN, 150);
deposito.Executar();
var expected = 1000.00m;
var actual = ccN.Saldo;
Assert.AreEqual(expected, actual);
}
[Test]
public void TesteDepositoContaExpecial()
{
var ccN = new ContaCorrenteEspecial();
ccN.Saldo = 750.00m;
var deposito = new DepositoService(ccN, 500);
deposito.Executar();
var expected = 1250.00m;
var actual = ccN.Saldo;
Assert.AreEqual(expected, actual);
}
}
}
|
using System.IO;
using Microsoft.Xna.Framework.Content.Pipeline;
using Newtonsoft.Json;
namespace MonoGame.Extended.Content.Pipeline.Animations
{
[ContentImporter(".aa", DefaultProcessor = "AstridAnimatorProcessor", DisplayName = "Astrid Animator Importer - MonoGame.Extended")]
public class AstridAnimatorImporter : ContentImporter<ContentImporterResult<AstridAnimatorFile>>
{
public override ContentImporterResult<AstridAnimatorFile> Import(string filename, ContentImporterContext context)
{
using (var streamReader = new StreamReader(filename))
using (var jsonReader = new JsonTextReader(streamReader))
{
var serializer = new JsonSerializer();
var data = serializer.Deserialize<AstridAnimatorFile>(jsonReader);
return new ContentImporterResult<AstridAnimatorFile>(filename, data);
}
}
}
} |
using UnityEngine;
public interface IDamagable {
void TakeDamage(int damage);
float GetHitPoints();
GameObject GetGameObject();
}
public interface ISellable {
int SellObject(int money);
int BuyObject(int money);
}
public interface IUpgradeable {
int UpgradeObject(int money);
int TimesUpgraded();
int UpgradeCost();
int UpgradeDamage();
}
public interface ISelectable {
bool IsSelected(bool choice);
} |
using System;
//For MethodImpl
using System.Runtime.CompilerServices;
namespace Unicorn
{
public class AudioData
{
public IntPtr native_handle = IntPtr.Zero;
public int index
{
get { return get_Index_Internal(native_handle); }
set { set_Index_Internal(native_handle, value); }
}
public bool isBGM
{
get { return get_IsBGM_Internal(native_handle); }
set { set_IsBGM_Internal(native_handle, value); }
}
public bool isLoop
{
get { return get_IsLoop_Internal(native_handle); }
set { set_IsLoop_Internal(native_handle, value); }
}
public bool playOnAwake
{
get { return get_PlayOnAwake_Internal(native_handle); }
set { set_PlayOnAwake_Internal(native_handle, value); }
}
public float volume
{
get { return get_Volume_Internal(native_handle); }
set { set_Volume_Internal(native_handle, value); }
}
public bool is3D
{
get { return get_Is3D_Internal(native_handle); }
set { set_Is3D_Internal(native_handle, value); }
}
public float minDist
{
get { return get_MinDist_Internal(native_handle); }
set { set_MinDist_Internal(native_handle, value); }
}
public float maxDist
{
get { return get_MaxDist_Internal(native_handle); }
set { set_MaxDist_Internal(native_handle, value); }
}
public bool mute
{
get { return get_IsMute_Internal(native_handle); }
set { set_IsMute_Internal(native_handle, value); }
}
public bool pause
{
get { return get_IsPause_Internal(native_handle); }
set { set_IsPause_Internal(native_handle, value); }
}
public void Play()
{
Play_Internal(native_handle);
}
public void Stop()
{
Stop_Internal(native_handle);
}
[MethodImpl(MethodImplOptions.InternalCall)]
public extern static int get_Index_Internal(IntPtr native_handle);
[MethodImpl(MethodImplOptions.InternalCall)]
public extern static void set_Index_Internal(IntPtr native_handle, int val);
[MethodImpl(MethodImplOptions.InternalCall)]
public extern static bool get_IsBGM_Internal(IntPtr native_handle);
[MethodImpl(MethodImplOptions.InternalCall)]
public extern static void set_IsBGM_Internal(IntPtr native_handle, bool val);
[MethodImpl(MethodImplOptions.InternalCall)]
public extern static bool get_IsLoop_Internal(IntPtr native_handle);
[MethodImpl(MethodImplOptions.InternalCall)]
public extern static void set_IsLoop_Internal(IntPtr native_handle, bool val);
[MethodImpl(MethodImplOptions.InternalCall)]
public extern static bool get_PlayOnAwake_Internal(IntPtr native_handle);
[MethodImpl(MethodImplOptions.InternalCall)]
public extern static void set_PlayOnAwake_Internal(IntPtr native_handle, bool val);
[MethodImpl(MethodImplOptions.InternalCall)]
public extern static float get_Volume_Internal(IntPtr native_handle);
[MethodImpl(MethodImplOptions.InternalCall)]
public extern static void set_Volume_Internal(IntPtr native_handle, float val);
[MethodImpl(MethodImplOptions.InternalCall)]
public extern static bool get_Is3D_Internal(IntPtr native_handle);
[MethodImpl(MethodImplOptions.InternalCall)]
public extern static void set_Is3D_Internal(IntPtr native_handle, bool val);
[MethodImpl(MethodImplOptions.InternalCall)]
public extern static float get_MinDist_Internal(IntPtr native_handle);
[MethodImpl(MethodImplOptions.InternalCall)]
public extern static void set_MinDist_Internal(IntPtr native_handle, float val);
[MethodImpl(MethodImplOptions.InternalCall)]
public extern static float get_MaxDist_Internal(IntPtr native_handle);
[MethodImpl(MethodImplOptions.InternalCall)]
public extern static void set_MaxDist_Internal(IntPtr native_handle, float val);
[MethodImpl(MethodImplOptions.InternalCall)]
public extern static bool get_IsMute_Internal(IntPtr native_handle);
[MethodImpl(MethodImplOptions.InternalCall)]
public extern static void set_IsMute_Internal(IntPtr native_handle, bool val);
[MethodImpl(MethodImplOptions.InternalCall)]
public extern static bool get_IsPause_Internal(IntPtr native_handle);
[MethodImpl(MethodImplOptions.InternalCall)]
public extern static void set_IsPause_Internal(IntPtr native_handle, bool val);
[MethodImpl(MethodImplOptions.InternalCall)]
public extern static void Play_Internal(IntPtr native_handle);
[MethodImpl(MethodImplOptions.InternalCall)]
public extern static void Stop_Internal(IntPtr native_handle);
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Savarankiskas2
{
class Program
{
static void Main(string[] args)
{
BibliotekosKnyga pasaka = new BibliotekosKnyga(1234, "Pasakecia", "Jonas", new DateTime(2019, 12, 4));
int rezult = pasaka.GrazintiKiekDienuPasSkaitytoja();
Console.WriteLine(pasaka.Pavadinimas);
Console.WriteLine(pasaka.SkaitytojoVardas);
Console.WriteLine(rezult);
Console.ReadLine();
}
}
}
|
namespace Record_Unique_Names
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
public class RecordUniqueNames
{
public static void Main(string[] args)
{
//var for number of student;
var numberStudent = int.Parse(Console.ReadLine());
//hash set for result;
var result = new HashSet<string>();
//add item to result;
for (int i = 1; i <= numberStudent; i++)
{
//var for input;
var input = Console.ReadLine();
result.Add(input);
}
//print the result;
foreach (var name in result)
{
Console.WriteLine(name);
}
}
}
}
|
//
// HttpListenerPrefixCollection.cs
// Copied from System.Net.HttpListenerPrefixCollection.cs
//
// Author:
// Gonzalo Paniagua Javier (gonzalo@novell.com)
//
// Copyright (c) 2005 Novell, Inc. (http://www.novell.com)
// Copyright (c) 2012-2013 sta.blockhead
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.Collections;
using System.Collections.Generic;
namespace Reactor.Net
{
public class HttpListenerPrefixCollection : ICollection<string>, IEnumerable<string>, IEnumerable
{
List<string> prefixes = new List<string>();
HttpListener listener;
internal HttpListenerPrefixCollection(HttpListener listener)
{
this.listener = listener;
}
public int Count
{
get
{
return prefixes.Count;
}
}
public bool IsReadOnly
{
get
{
return false;
}
}
public bool IsSynchronized
{
get
{
return false;
}
}
public void Add(string uriPrefix)
{
listener.CheckDisposed();
ListenerPrefix.CheckUri(uriPrefix);
if (prefixes.Contains(uriPrefix))
{
return;
}
prefixes.Add(uriPrefix);
if (listener.IsListening)
{
EndPointManager.AddPrefix(uriPrefix, listener);
}
}
public void Clear()
{
listener.CheckDisposed();
prefixes.Clear();
if (listener.IsListening)
{
EndPointManager.RemoveListener(listener);
}
}
public bool Contains(string uriPrefix)
{
listener.CheckDisposed();
return prefixes.Contains(uriPrefix);
}
public void CopyTo(string[] array, int offset)
{
listener.CheckDisposed();
prefixes.CopyTo(array, offset);
}
public void CopyTo(Array array, int offset)
{
listener.CheckDisposed();
((ICollection)prefixes).CopyTo(array, offset);
}
public IEnumerator<string> GetEnumerator()
{
return prefixes.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return prefixes.GetEnumerator();
}
public bool Remove(string uriPrefix)
{
listener.CheckDisposed();
if (uriPrefix == null)
{
throw new ArgumentNullException("uriPrefix");
}
bool result = prefixes.Remove(uriPrefix);
if (result && listener.IsListening)
{
EndPointManager.RemovePrefix(uriPrefix, listener);
}
return result;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using PowerShapeDotNet.Enums;
using PowerShapeDotNet.Macros;
namespace PowerShapeDotNet.Objects
{
/// <summary>
/// class for Arc Type Objects
/// </summary>
public class PSDNObjectArc : PSDNObjectBase
{
#region PROPIERTIES
/// <summary>
/// Gets or sets the start position of the arc
/// </summary>
/// <value>
/// The start position of the arc
/// </value>
public PSDNPoint3D Start
{
get
{
return psMacros.Arc_Start(ObjectName);
}
}
/// <summary>
/// Gets or sets the end position of the arc
/// </summary>
/// <value>
/// The end position of the arc
/// </value>
public PSDNPoint3D End
{
get
{
return psMacros.Arc_End(ObjectName);
}
}
/// <summary>
/// Gets or sets the mid position of the arc
/// </summary>
/// <value>
/// The mid position of the arc
/// </value>
public PSDNPoint3D Mid
{
get
{
return psMacros.Arc_Mid(ObjectName);
}
set
{
this.Select(true);
psMacros.SendMacro("MODIFY", "THROUGH X " + value.X, "THROUGH Y " + value.Y, "THROUGH Z " + value.Z, "ACCEPT");
}
}
/// <summary>
/// Gets or sets the diameter.
/// </summary>
/// <value>
/// The diameter.
/// </value>
public float Diameter
{
get
{
return Radius*2;
}
set
{
this.Select(true);
psMacros.SendMacro("MODIFY", "DIAMETER CHANGE_DIMENSION", "DIMENSION " + value.ToString(), "ACCEPT");
}
}
/// <summary>
/// Gets or sets the radius value of the arc
/// </summary>
/// <value>
/// radius of the arc
/// </value>
public int Radius
{
get
{
return psMacros.Arc_Radius(ObjectName);
}
set
{
this.Select(true);
psMacros.SendMacro("MODIFY", "RADIUS CHANGE_DIMENSION", "DIMENSION " + value.ToString(), "ACCEPT");
}
}
/// <summary>
/// Gets or sets the centre position of the arc
/// </summary>
/// <value>
/// The centre position of the arc
/// </value>
public PSDNPoint3D Centre
{
get
{
return psMacros.Arc_Centre(ObjectName);
}
set
{
this.Select(true);
psMacros.SendMacro("MODIFY", "CENTRE X " + value.X, "CENTRE Y " + value.Y, "CENTRE Z " + value.Z, "ACCEPT");
}
}
/// <summary>
/// Gets or sets the length of the circumference of the arc
/// </summary>
/// <value>
/// length of the circumference of the arc
/// </value>
public float Length
{
get
{
return psMacros.Arc_Length(ObjectName);
}
}
/// <summary>
/// Gets or sets the the centre mark type
/// </summary>
/// <value>
/// the centre mark type
/// </value>
public TypeCentreMark CentreMark
{
get
{
return psMacros.Arc_CentreMark(ObjectName);
}
set
{
this.Select(true);
psMacros.SendMacro("MODIFY", "CENTREMARK " + value.ToString().ToUpper(), "ACCEPT");
}
}
/// <summary>
/// Gets or sets the start angle of the arc
/// </summary>
/// <value>
/// The start angle of the arc
/// </value>
public float StartAngle
{
get
{
return psMacros.Arc_StartAngle(ObjectName);
}
}
/// <summary>
/// Gets or sets the end angle of the arc
/// </summary>
/// <value>
/// The end angle of the arc
/// </value>
public float EndAngle
{
get
{
return psMacros.Arc_EndAngle(ObjectName);
}
}
/// <summary>
/// Gets or sets the span angle of the arc
/// </summary>
/// <value>
/// The span angle of the arc
/// </value>
public float SpanAngle
{
get
{
return psMacros.Arc_SpanAngle(ObjectName);
}
set
{
this.Select(true);
psMacros.SendMacro("MODIFY", "SPAN " + value.ToString(), "ACCEPT");
}
}
#endregion
#region CONSTRUCTORS
/// <summary>
/// Initializes a new instance of the <see cref="PSDNObjectArc"/> class.
/// </summary>
/// <param name="state">The state.</param>
/// <param name="index">The index.</param>
public PSDNObjectArc(ObjectState state, int index) : base(state, index) { }
/// <summary>
/// Initializes a new instance of the <see cref="PSDNObjectArc"/> class.
/// </summary>
/// <param name="typeObject">The type object.</param>
/// <param name="nameObject">The name object.</param>
public PSDNObjectArc(TypeObject typeObject, string nameObject) : base (typeObject, nameObject) { }
/// <summary>
/// Initializes a new instance of the <see cref="PSDNObjectArc"/> class.
/// </summary>
/// <param name="typeObject">The type object.</param>
/// <param name="idObject">The identifier object.</param>
public PSDNObjectArc(TypeObject typeObject, int idObject) : base (typeObject, idObject) { }
#endregion
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.EntityFrameworkCore;
using WebApp.EFGetStarted.AspNetCore.NewDb.Models;
namespace WebApp.EFGetStarted.AspNetCore.NewDb.Controllers
{
public class tbBlogsController : Controller
{
private readonly dbBloggingKP2Context _context;
public tbBlogsController(dbBloggingKP2Context context)
{
_context = context;
}
// GET: tbBlogs
public async Task<IActionResult> Index()
{
return View(await _context.Blogs.ToListAsync());
}
// GET: tbBlogs/Details/5
public async Task<IActionResult> Details(int? id)
{
if (id == null)
{
return NotFound();
}
var tbBlog = await _context.Blogs
.FirstOrDefaultAsync(m => m.Id == id);
if (tbBlog == null)
{
return NotFound();
}
return View(tbBlog);
}
// GET: tbBlogs/Create
public IActionResult Create()
{
return View();
}
// POST: tbBlogs/Create
// 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 async Task<IActionResult> Create([Bind("Id,Url")] tbBlog tbBlog)
{
if (ModelState.IsValid)
{
_context.Add(tbBlog);
await _context.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
return View(tbBlog);
}
// GET: tbBlogs/Edit/5
public async Task<IActionResult> Edit(int? id)
{
if (id == null)
{
return NotFound();
}
var tbBlog = await _context.Blogs.FindAsync(id);
if (tbBlog == null)
{
return NotFound();
}
return View(tbBlog);
}
// POST: tbBlogs/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 async Task<IActionResult> Edit(int id, [Bind("Id,Url")] tbBlog tbBlog)
{
if (id != tbBlog.Id)
{
return NotFound();
}
if (ModelState.IsValid)
{
try
{
_context.Update(tbBlog);
await _context.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException)
{
if (!tbBlogExists(tbBlog.Id))
{
return NotFound();
}
else
{
throw;
}
}
return RedirectToAction(nameof(Index));
}
return View(tbBlog);
}
// GET: tbBlogs/Delete/5
public async Task<IActionResult> Delete(int? id)
{
if (id == null)
{
return NotFound();
}
var tbBlog = await _context.Blogs
.FirstOrDefaultAsync(m => m.Id == id);
if (tbBlog == null)
{
return NotFound();
}
return View(tbBlog);
}
// POST: tbBlogs/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public async Task<IActionResult> DeleteConfirmed(int id)
{
var tbBlog = await _context.Blogs.FindAsync(id);
_context.Blogs.Remove(tbBlog);
await _context.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
private bool tbBlogExists(int id)
{
return _context.Blogs.Any(e => e.Id == id);
}
}
}
|
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using Worldbuilder;
public class Init : MonoBehaviour
{
public int nombreTuile = 0;
// Use this for initialization
void Start()
{
//instatiating mainmenu.
//GameObject startmenu = Instantiate(Resources.Load("ui/menuGO")) as GameObject;
GameObject cam = new GameObject();
cam.AddComponent<Camera>();
cam.gameObject.AddComponent<camera>();
//instantiating environement
Environnement environnement = new Environnement();
//instanciating map with it's parameters
Map map = new Map("1v1", environnement);
//Debug.Log(map.mapname);
//getting global map path
string mapfilepath = map.getCheminMap(map.MapName);
//Debug.Log(mapfilepath);
//getting map full path
map.MapFilePath = mapfilepath;
//Debug.Log(map.mapfilepath);
// checking if file exist
if (map.MapFilePath == "error")
{
Debug.LogError("error occured opening map file");
}
else
{
//Debug.Log("path ok");
string zoneNom;
string[] mapParts = new string[100];
//populating map.ZoneColorMap acording to image
map.ZoneColorMap = Tools.getColor(map.MapFilePath);
string textfile = map.getZoneDefTXT(map.MapName);
//grabing zone references
mapParts = Tools.getMapZones(textfile);
map.ZoneMap = new List<List<Zone>>();
List<Zone> row = new List<Zone>();
//instanciating every zone + adding "border" zones (not interactive)
for (int i = 0; i < (map.ZoneColorMap.Count) + 2; i++)
{
GameObject zonepos = Instantiate(Resources.Load("map/zonepointer")) as GameObject;
zonepos.transform.position = new Vector3((i * 16) - 16, 0, - 16);
Zone zone = new Zone("border", zonepos);
row.Add(zone);
}
map.ZoneMap.Add(row);
for (int i = 0; i < map.ZoneColorMap.Count; i++)
{
if (map.ZoneColorMap.Count > 1)
{
row = new List<Zone>();
{
GameObject zonePos = Instantiate(Resources.Load("map/zonepointer")) as GameObject;
zonePos.transform.position = new Vector3(-16, 0, i * 16);
Zone zone = new Zone("border", zonePos);
row.Add(zone);
}
for (int j = 0; j < map.ZoneColorMap[i].Count; j++)
{
//Debug.Log("instanciating zones");
{
GameObject zonepos = Instantiate(Resources.Load("map/zonepointer")) as GameObject;
zonepos.transform.position = new Vector3(i * 16, 0, j * 16);
if (map.ZoneColorMap[i][j].A == 255)
{
string tempcolor = Tools.colorToString(map.ZoneColorMap[i][j]);
zoneNom = Tools.getNomZone(mapParts, tempcolor);
Zone zone = new Zone(zoneNom, zonepos);
row.Add(zone);
}
else
{
Zone zone = new Zone("empty", zonepos);
row.Add(zone);
}
}
}
{
GameObject zonepos = Instantiate(Resources.Load("map/zonepointer")) as GameObject;
zonepos.transform.position = new Vector3(map.ZoneColorMap.Count * 16, 0, i * 16);
Zone zone = new Zone("border", zonepos);
row.Add(zone);
}
map.ZoneMap.Add(row);
}
else
{
row = new List<Zone>();
for (int j = 0; j < map.ZoneColorMap[i].Count; j++)
{
{
GameObject zonePos = Instantiate(Resources.Load("map/zonepointer")) as GameObject;
zonePos.transform.position = new Vector3((i*16)-16, 0, j * 16);
Zone zone = new Zone("border", zonePos);
row.Add(zone);
}
//Debug.Log("instanciating zones");
{
GameObject zonepos = Instantiate(Resources.Load("map/zonepointer")) as GameObject;
zonepos.transform.position = new Vector3(i * 16, 0, j * 16);
if (map.ZoneColorMap[i][j].A == 255)
{
string tempcolor = Tools.colorToString(map.ZoneColorMap[i][j]);
zoneNom = Tools.getNomZone(mapParts, tempcolor);
Zone zone = new Zone(zoneNom, zonepos);
row.Add(zone);
}
else
{
Zone zone = new Zone("empty", zonepos);
row.Add(zone);
}
}
{
GameObject zonepos = Instantiate(Resources.Load("map/zonepointer")) as GameObject;
zonepos.transform.position = new Vector3(map.ZoneColorMap.Count * 16, 0, j * 16);
Zone zone = new Zone("border", zonepos);
row.Add(zone);
}
}
map.ZoneMap.Add(row);
}
}
row = new List<Zone>();
for (int o = 0; o < (map.ZoneColorMap.Count) + 2; o++)
{
GameObject zonepos = Instantiate(Resources.Load("map/zonepointer")) as GameObject;
zonepos.transform.position = new Vector3(((o * 16) - 16), 0, (map.ZoneColorMap[0].Count * 16));
Zone zone = new Zone("border", zonepos);
row.Add(zone);
}
map.ZoneMap.Add(row);
}
cam.transform.position = new Vector3(((map.ZoneMap.Count / 2) * 16) - 8, 15, ((map.ZoneMap[1].Count / 2) * 16) - 8);
//populating every zone Tiles
//Debug.Log("populating empty tile");
for (int i = 0; i < map.ZoneMap.Count; i++)
{
for (int j = 0; j < map.ZoneMap[i].Count; j++)
{
if (map.ZoneMap[i][j].Type == "empty")
{
for (int k = 0; k < 16; k++)
{
List<Tuile> tilerow = new List<Tuile>();
for (int l = 0; l < 16; l++)
{
GameObject tileHolder = Instantiate(Resources.Load("tile/TileHolder")) as GameObject;
Renderer rnd = tileHolder.GetComponent<Renderer>();
Tuile tile = new Tuile("empty", map.ZoneMap[i][j], tileHolder, l, 0, k);
rnd.material = tileHolder.GetComponent<TileHolder>().mats[0];
tileHolder.GetComponent<TileHolder>().tile = tile;
tileHolder.tag = "empty";
tile.WorldPosition = new Vector3((k + (16 * j)), 0, l + (16 * i));
tilerow.Add(tile);
}
Map.tuileMap.Add(tilerow);
}
}
else if (map.ZoneMap[i][j].Type == "border")
{
for (int k = 0; k < 16; k++)
{
List<Tuile> tilerow = new List<Tuile>();
for (int l = 0; l < 16; l++)
{
GameObject tileHolder = Instantiate(Resources.Load("tile/TileHolder")) as GameObject;
Renderer rnd = tileHolder.GetComponent<Renderer>();
Tuile tile = new Tuile("border", map.ZoneMap[i][j], tileHolder, l, 0, k);
rnd.material = tileHolder.GetComponent<TileHolder>().mats[0];
tileHolder.GetComponent<TileHolder>().tile = tile;
tileHolder.tag = "border";
tile.WorldPosition = new Vector3((k + (16 * i)), 0, l + (16 * j));
tilerow.Add(tile);
}
Map.tuileMap.Add(tilerow);
}
}
else
{
//Debug.Log("grabbing file directory");
string imagepath = map.ZoneMap[i][j].getzoneimagepath(map.ZoneMap[i][j].Type, map.MapName);
//Debug.Log(imagepath);
//Debug.Log("grabbing tile color list");
Debug.Log("imagepath : " + imagepath);
Debug.Log("zonemap type : " + map.ZoneMap[i][j].Type);
List<List<System.Drawing.Color>> tilescolor = Tools.getColor(imagepath + map.ZoneMap[i][j].Type + ".png");
//Debug.Log("grabbing zone tile definitions");
string[] tilref = Tools.getMapZones(imagepath + "Tiles.txt");
for (int k = 0; k < 16; k++)
{
List<Tuile> tilerow = new List<Tuile>();
for (int l = 0; l < 16; l++)
{
GameObject tileHolder = Instantiate(Resources.Load("tile/TileHolder")) as GameObject;
Renderer rnd = tileHolder.GetComponent<Renderer>();
if (tilescolor[l][k].A == 255)
{
string tilemame = Tools.getNomZone(tilref, Tools.colorToString(tilescolor[l][k]));
if (tilemame == "openfloorTile")
{
Tuile tile = new Tuile("openfloorTile", map.ZoneMap[i][j], tileHolder, l, -1, k);
rnd.material = tileHolder.GetComponent<TileHolder>().mats[2];
tileHolder.GetComponent<TileHolder>().tile = tile;
tileHolder.tag = "floor";
tile.WorldPosition = new Vector3((k + (16 * i)), 0, l + (16 * j));
tilerow.Add(tile);
}
else if (tilemame == "wallTile")
{
Tuile tile = new Tuile("wallTile", map.ZoneMap[i][j], tileHolder, l, 0, k);
rnd.material = tileHolder.GetComponent<TileHolder>().mats[2];
tileHolder.GetComponent<TileHolder>().tile = tile;
tileHolder.tag = "wall";
tile.WorldPosition = new Vector3((k + (16 * i)), 0, l + (16 * j));
tilerow.Add(tile);
}
else if (tilemame == "collumn")
{
Tuile tile = new Tuile("collumn", map.ZoneMap[i][j], tileHolder, l, 0, k);
rnd.material = tileHolder.GetComponent<TileHolder>().mats[2];
tileHolder.GetComponent<TileHolder>().tile = tile;
tileHolder.tag = "wall";
tile.WorldPosition = new Vector3((k + (16 * i)), 0, l + (16 * j));
tilerow.Add(tile);
}
else if (tilemame == "tombeau")
{
Tuile tile = new Tuile("tombeau", map.ZoneMap[i][j], tileHolder, l, 0, k);
rnd.material = tileHolder.GetComponent<TileHolder>().mats[2];
tileHolder.GetComponent<TileHolder>().tile = tile;
tileHolder.tag = "wall";
tile.WorldPosition = new Vector3((k + (16 * i)), 0, l + (16 * j));
tilerow.Add(tile);
}
}
else
{
Tuile tile = new Tuile("empty", map.ZoneMap[i][j], tileHolder, l, 0, k);
rnd.material = tileHolder.GetComponent<TileHolder>().mats[0];
tileHolder.GetComponent<TileHolder>().tile = tile;
tileHolder.tag = "empty";
tile.WorldPosition = new Vector3((k + (16 * i)), 0, l + (16 * j));
tilerow.Add(tile);
}
}
Map.tuileMap.Add(tilerow);
}
}
}
}
//generating map global tilemap
map.GenererTuileMap();
//updating tiles according to surounding
// map.tileCheckForEmptyToWall();
}
// Update is called once per frame
void Update()
{
nombreTuile = Map.tuileMap.Count;
}
}
|
namespace DxMessaging.Unity.Networking
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using Core;
using Core.Extensions;
using Core.Messages;
using global::Core.Extension;
using global::Core.Helper;
using global::Core.Serialization;
using global::Networking.Utils;
using global::Unity.Collections;
using global::Unity.Netcode;
using UnityEngine;
using Object = UnityEngine.Object;
[RequireComponent(typeof(NetworkObject))]
public class NetworkMessagingManager : NetworkMessageAwareComponent
{
[Serializable]
private struct SerializedMessage
{
public IMessage Message;
public NetworkObjectReference? AssociatedObjectReference;
}
private const string NamedMessage = "NetworkMessage";
private HashSet<Type> _networkMessageTypes;
private readonly Lazy<CustomMessagingManager> _customMessagingManager = new(() => NetworkManager.Singleton.CustomMessagingManager);
protected override void Awake()
{
base.Awake();
DontDestroyOnLoad(transform.parent);
_networkMessageTypes = Assembly.GetAssembly(typeof(NetworkMessagingManager))
.GetTypes()
.Where(type => type.IsDefined(typeof(NetworkMessageAttribute), true))
.ToHashSet();
// Don't want to be enabled on clients. Wait until we've been Network Spawned
enabled = false;
}
public override void OnNetworkSpawn()
{
if (NetUtils.IsHost())
{
enabled = true;
}
_customMessagingManager.Value.RegisterNamedMessageHandler(NamedMessage, OnMessageReceivedOverNetwork);
}
protected override void RegisterMessageHandlers()
{
_messageRegistrationToken.RegisterGlobalAcceptAll(AcceptAllUntargeted, AcceptAllTargeted,
AcceptAllBroadcast);
}
private void AcceptAllBroadcast(InstanceId source, IBroadcastMessage message)
{
if (!IsNetworkedMessage(message.GetType()))
{
return;
}
NetworkObjectReference? sourceReference = TryGetNetworkObjectReferenceFromGameObject(source.Object);
if (!sourceReference.HasValue)
{
this.LogError("Trying to send networked broadcasted message on a non-networked object");
return;
}
SendSerializedMessage(message, sourceReference);
}
private void AcceptAllTargeted(InstanceId target, ITargetedMessage message)
{
if (!IsNetworkedMessage(message.GetType()))
{
return;
}
NetworkObjectReference? targetReference = TryGetNetworkObjectReferenceFromGameObject(target.Object);
if (!targetReference.HasValue)
{
this.LogError("Trying to send networked targeted message on a non-networked object");
return;
}
SendSerializedMessage(message, targetReference);
}
private void AcceptAllUntargeted(IUntargetedMessage message)
{
if (!IsNetworkedMessage(message.GetType()))
{
return;
}
SendSerializedMessage(message);
}
private void SendSerializedMessage(IMessage message, NetworkObjectReference? reference = null)
{
SerializedMessage serializedMessage = new() { Message = message, AssociatedObjectReference = reference};
byte[] bytes = Serializer.BinarySerialize(serializedMessage);
using var writer = new FastBufferWriter(1000, Allocator.Temp, 100000);
writer.WriteValueSafe(bytes);
foreach ((ulong clientId, NetworkClient _) in NetworkManager.ConnectedClients)
{
if (clientId != NetworkManager.Singleton.LocalClientId)
{
_customMessagingManager.Value.SendNamedMessage(NamedMessage, clientId, writer, NetworkDelivery.Reliable);
}
}
}
private void OnMessageReceivedOverNetwork(ulong _, FastBufferReader reader)
{
reader.ReadValueSafe(out byte[] data);
SerializedMessage serializedMessage = Serializer.BinaryDeserialize<SerializedMessage>(data);
IMessage message = serializedMessage.Message;
NetworkObject networkObject = null;
if (serializedMessage.AssociatedObjectReference != null)
{
if (!serializedMessage.AssociatedObjectReference.Value.TryGet(out networkObject))
{
this.LogWarn("Unable to find associated object reference for message");
return;
}
}
switch (message)
{
case ITargetedMessage targetedMessage:
targetedMessage.EmitGameObjectTargeted(networkObject!.gameObject);
break;
case IBroadcastMessage broadcastMessage:
broadcastMessage.EmitGameObjectBroadcast(networkObject!.gameObject);
break;
case IUntargetedMessage untargetedMessage:
untargetedMessage.EmitUntargeted();
break;
}
}
private static NetworkObjectReference? TryGetNetworkObjectReferenceFromGameObject(Object go)
{
if (go.TryGetComponent(out NetworkObject networkObject))
{
return new NetworkObjectReference(networkObject);
}
return null;
}
private bool IsNetworkedMessage(Type messageType) => _networkMessageTypes.Contains(messageType);
}
}
|
//------------------------------------------------------------------------------
// The contents of this file are subject to the nopCommerce Public License Version 1.0 ("License"); you may not use this file except in compliance with the License.
// You may obtain a copy of the License at http://www.nopCommerce.com/License.aspx.
//
// Software distributed under the License is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or implied.
// See the License for the specific language governing rights and limitations under the License.
//
// The Original Code is nopCommerce.
// The Initial Developer of the Original Code is NopSolutions.
// All Rights Reserved.
//
// Contributor(s): _______.
//------------------------------------------------------------------------------
using System;
using System.Collections.Specialized;
using System.Configuration.Provider;
using System.Data;
using System.Data.Common;
using Microsoft.Practices.EnterpriseLibrary.Data;
namespace NopSolutions.NopCommerce.DataAccess.Content.Polls
{
/// <summary>
/// Poll provider for SQL Server
/// </summary>
public partial class SQLPollProvider : DBPollProvider
{
#region Fields
private string _sqlConnectionString;
#endregion
#region Utilities
private DBPoll GetPollFromReader(IDataReader dataReader)
{
DBPoll poll = new DBPoll();
poll.PollID = NopSqlDataHelper.GetInt(dataReader, "PollID");
poll.LanguageID = NopSqlDataHelper.GetInt(dataReader, "LanguageID");
poll.Name = NopSqlDataHelper.GetString(dataReader, "Name");
poll.SystemKeyword = NopSqlDataHelper.GetString(dataReader, "SystemKeyword");
poll.Published = NopSqlDataHelper.GetBoolean(dataReader, "Published");
poll.DisplayOrder = NopSqlDataHelper.GetInt(dataReader, "DisplayOrder");
return poll;
}
private DBPollAnswer GetPollAnswerFromReader(IDataReader dataReader)
{
DBPollAnswer pollAnswer = new DBPollAnswer();
pollAnswer.PollAnswerID = NopSqlDataHelper.GetInt(dataReader, "PollAnswerID");
pollAnswer.PollID = NopSqlDataHelper.GetInt(dataReader, "PollID");
pollAnswer.Name = NopSqlDataHelper.GetString(dataReader, "Name");
pollAnswer.Count = NopSqlDataHelper.GetInt(dataReader, "Count");
pollAnswer.DisplayOrder = NopSqlDataHelper.GetInt(dataReader, "DisplayOrder");
return pollAnswer;
}
#endregion
#region Methods
/// <summary>
/// Initializes the provider with the property values specified in the application's configuration file. This method is not intended to be used directly from your code
/// </summary>
/// <param name="name">The name of the provider instance to initialize</param>
/// <param name="config">A NameValueCollection that contains the names and values of configuration options for the provider.</param>
public override void Initialize(string name, NameValueCollection config)
{
if (config == null)
{
throw new ArgumentNullException("config");
}
base.Initialize(name, config);
string connectionStringName = config["connectionStringName"];
if (String.IsNullOrEmpty(connectionStringName))
throw new ProviderException("Connection name not specified");
this._sqlConnectionString = NopSqlDataHelper.GetConnectionString(connectionStringName);
if ((this._sqlConnectionString == null) || (this._sqlConnectionString.Length < 1))
{
throw new ProviderException(string.Format("Connection string not found. {0}", connectionStringName));
}
config.Remove("connectionStringName");
if (config.Count > 0)
{
string key = config.GetKey(0);
if (!string.IsNullOrEmpty(key))
{
throw new ProviderException(string.Format("Provider unrecognized attribute. {0}", new object[] { key }));
}
}
}
/// <summary>
/// Gets a poll
/// </summary>
/// <param name="PollID">The poll identifier</param>
/// <returns>Poll</returns>
public override DBPoll GetPollByID(int PollID)
{
DBPoll poll = null;
if (PollID == 0)
return poll;
Database db = NopSqlDataHelper.CreateConnection(_sqlConnectionString);
DbCommand dbCommand = db.GetStoredProcCommand("Nop_PollLoadByPrimaryKey");
db.AddInParameter(dbCommand, "PollID", DbType.Int32, PollID);
using (IDataReader dataReader = db.ExecuteReader(dbCommand))
{
if (dataReader.Read())
{
poll = GetPollFromReader(dataReader);
}
}
return poll;
}
/// <summary>
/// Gets a poll
/// </summary>
/// <param name="SystemKeyword">Poll system keyword</param>
/// <returns>Poll</returns>
public override DBPoll GetPollBySystemKeyword(string SystemKeyword)
{
DBPoll poll = null;
Database db = NopSqlDataHelper.CreateConnection(_sqlConnectionString);
DbCommand dbCommand = db.GetStoredProcCommand("Nop_PollLoadBySystemKeyword");
db.AddInParameter(dbCommand, "SystemKeyword", DbType.String, SystemKeyword);
using (IDataReader dataReader = db.ExecuteReader(dbCommand))
{
if (dataReader.Read())
{
poll = GetPollFromReader(dataReader);
}
}
return poll;
}
/// <summary>
/// Gets poll collection
/// </summary>
/// <param name="LanguageID">Language identifier. 0 if you want to get all news</param>
/// <param name="PollCount">Poll count to load. 0 if you want to get all polls</param>
/// <param name="showHidden">A value indicating whether to show hidden records</param>
/// <returns>Poll collection</returns>
public override DBPollCollection GetPolls(int LanguageID, int PollCount, bool showHidden)
{
DBPollCollection pollCollection = new DBPollCollection();
Database db = NopSqlDataHelper.CreateConnection(_sqlConnectionString);
DbCommand dbCommand = db.GetStoredProcCommand("Nop_PollLoadAll");
db.AddInParameter(dbCommand, "LanguageID", DbType.Int32, LanguageID);
db.AddInParameter(dbCommand, "PollCount", DbType.Int32, PollCount);
db.AddInParameter(dbCommand, "ShowHidden", DbType.Boolean, showHidden);
using (IDataReader dataReader = db.ExecuteReader(dbCommand))
{
while (dataReader.Read())
{
DBPoll poll = GetPollFromReader(dataReader);
pollCollection.Add(poll);
}
}
return pollCollection;
}
/// <summary>
/// Deletes a poll
/// </summary>
/// <param name="PollID">The poll identifier</param>
public override void DeletePoll(int PollID)
{
Database db = NopSqlDataHelper.CreateConnection(_sqlConnectionString);
DbCommand dbCommand = db.GetStoredProcCommand("Nop_PollDelete");
db.AddInParameter(dbCommand, "PollID", DbType.Int32, PollID);
int retValue = db.ExecuteNonQuery(dbCommand);
}
/// <summary>
/// Inserts a poll
/// </summary>
/// <param name="LanguageID">The language identifier</param>
/// <param name="Name">The name</param>
/// <param name="SystemKeyword">The system keyword</param>
/// <param name="Published">A value indicating whether the entity is published</param>
/// <param name="DisplayOrder">The display order</param>
/// <returns>Poll</returns>
public override DBPoll InsertPoll(int LanguageID, string Name,
string SystemKeyword, bool Published, int DisplayOrder)
{
DBPoll poll = null;
Database db = NopSqlDataHelper.CreateConnection(_sqlConnectionString);
DbCommand dbCommand = db.GetStoredProcCommand("Nop_PollInsert");
db.AddOutParameter(dbCommand, "PollID", DbType.Int32, 0);
db.AddInParameter(dbCommand, "LanguageID", DbType.Int32, LanguageID);
db.AddInParameter(dbCommand, "Name", DbType.String, Name);
db.AddInParameter(dbCommand, "SystemKeyword", DbType.String, SystemKeyword);
db.AddInParameter(dbCommand, "Published", DbType.Boolean, Published);
db.AddInParameter(dbCommand, "DisplayOrder", DbType.Int32, DisplayOrder);
if (db.ExecuteNonQuery(dbCommand) > 0)
{
int PollID = Convert.ToInt32(db.GetParameterValue(dbCommand, "@PollID"));
poll = GetPollByID(PollID);
}
return poll;
}
/// <summary>
/// Updates the poll
/// </summary>
/// <param name="PollID">The poll identifier</param>
/// <param name="LanguageID">The language identifier</param>
/// <param name="Name">The name</param>
/// <param name="SystemKeyword">The system keyword</param>
/// <param name="Published">A value indicating whether the entity is published</param>
/// <param name="DisplayOrder">The display order</param>
/// <returns>Poll</returns>
public override DBPoll UpdatePoll(int PollID, int LanguageID, string Name,
string SystemKeyword, bool Published, int DisplayOrder)
{
DBPoll poll = null;
Database db = NopSqlDataHelper.CreateConnection(_sqlConnectionString);
DbCommand dbCommand = db.GetStoredProcCommand("Nop_PollUpdate");
db.AddInParameter(dbCommand, "PollID", DbType.Int32, PollID);
db.AddInParameter(dbCommand, "LanguageID", DbType.Int32, LanguageID);
db.AddInParameter(dbCommand, "Name", DbType.String, Name);
db.AddInParameter(dbCommand, "SystemKeyword", DbType.String, SystemKeyword);
db.AddInParameter(dbCommand, "Published", DbType.Boolean, Published);
db.AddInParameter(dbCommand, "DisplayOrder", DbType.Int32, DisplayOrder);
if (db.ExecuteNonQuery(dbCommand) > 0)
poll = GetPollByID(PollID);
return poll;
}
/// <summary>
/// Is voting record already exists
/// </summary>
/// <param name="PollID">Poll identifier</param>
/// <param name="CustomerID">Customer identifier</param>
/// <returns>Poll</returns>
public override bool PollVotingRecordExists(int PollID, int CustomerID)
{
bool result = false;
Database db = NopSqlDataHelper.CreateConnection(_sqlConnectionString);
DbCommand dbCommand = db.GetStoredProcCommand("Nop_PollVotingRecordExists");
db.AddInParameter(dbCommand, "PollID", DbType.Int32, PollID);
db.AddInParameter(dbCommand, "CustomerID", DbType.String, CustomerID);
if ((int)db.ExecuteScalar(dbCommand) > 0)
result = true;
return result;
}
/// <summary>
/// Gets a poll answer
/// </summary>
/// <param name="PollAnswerID">Poll answer identifier</param>
/// <returns>Poll answer</returns>
public override DBPollAnswer GetPollAnswerByID(int PollAnswerID)
{
DBPollAnswer pollAnswer = null;
if (PollAnswerID == 0)
return pollAnswer;
Database db = NopSqlDataHelper.CreateConnection(_sqlConnectionString);
DbCommand dbCommand = db.GetStoredProcCommand("Nop_PollAnswerLoadByPrimaryKey");
db.AddInParameter(dbCommand, "PollAnswerID", DbType.Int32, PollAnswerID);
using (IDataReader dataReader = db.ExecuteReader(dbCommand))
{
if (dataReader.Read())
{
pollAnswer = GetPollAnswerFromReader(dataReader);
}
}
return pollAnswer;
}
/// <summary>
/// Gets a poll answers by poll identifier
/// </summary>
/// <param name="PollID">Poll identifier</param>
/// <returns>Poll answer collection</returns>
public override DBPollAnswerCollection GetPollAnswersByPollID(int PollID)
{
DBPollAnswerCollection pollAnswerCollection = new DBPollAnswerCollection();
Database db = NopSqlDataHelper.CreateConnection(_sqlConnectionString);
DbCommand dbCommand = db.GetStoredProcCommand("Nop_PollAnswerLoadByPollID");
db.AddInParameter(dbCommand, "PollID", DbType.Int32, PollID);
using (IDataReader dataReader = db.ExecuteReader(dbCommand))
{
while (dataReader.Read())
{
DBPollAnswer pollAnswer = GetPollAnswerFromReader(dataReader);
pollAnswerCollection.Add(pollAnswer);
}
}
return pollAnswerCollection;
}
/// <summary>
/// Deletes a poll answer
/// </summary>
/// <param name="PollAnswerID">Poll answer identifier</param>
public override void DeletePollAnswer(int PollAnswerID)
{
Database db = NopSqlDataHelper.CreateConnection(_sqlConnectionString);
DbCommand dbCommand = db.GetStoredProcCommand("Nop_PollAnswerDelete");
db.AddInParameter(dbCommand, "PollAnswerID", DbType.Int32, PollAnswerID);
int retValue = db.ExecuteNonQuery(dbCommand);
}
/// <summary>
/// Inserts a poll answer
/// </summary>
/// <param name="PollID">The poll identifier</param>
/// <param name="Name">The poll answer name</param>
/// <param name="Count">The current count</param>
/// <param name="DisplayOrder">The display order</param>
/// <returns>Poll answer</returns>
public override DBPollAnswer InsertPollAnswer(int PollID, string Name, int Count, int DisplayOrder)
{
DBPollAnswer pollAnswer = null;
Database db = NopSqlDataHelper.CreateConnection(_sqlConnectionString);
DbCommand dbCommand = db.GetStoredProcCommand("Nop_PollAnswerInsert");
db.AddOutParameter(dbCommand, "PollAnswerID", DbType.Int32, 0);
db.AddInParameter(dbCommand, "PollID", DbType.Int32, PollID);
db.AddInParameter(dbCommand, "Name", DbType.String, Name);
db.AddInParameter(dbCommand, "Count", DbType.Int32, Count);
db.AddInParameter(dbCommand, "DisplayOrder", DbType.Int32, DisplayOrder);
if (db.ExecuteNonQuery(dbCommand) > 0)
{
int PollAnswerID = Convert.ToInt32(db.GetParameterValue(dbCommand, "@PollAnswerID"));
pollAnswer = GetPollAnswerByID(PollAnswerID);
}
return pollAnswer;
}
/// <summary>
/// Updates the poll answer
/// </summary>
/// <param name="PollAnswerID">The poll answer identifier</param>
/// <param name="PollID">The poll identifier</param>
/// <param name="Name">The poll answer name</param>
/// <param name="Count">The current count</param>
/// <param name="DisplayOrder">The display order</param>
/// <returns>Poll answer</returns>
public override DBPollAnswer UpdatePollAnswer(int PollAnswerID, int PollID, string Name, int Count, int DisplayOrder)
{
DBPollAnswer pollAnswer = null;
Database db = NopSqlDataHelper.CreateConnection(_sqlConnectionString);
DbCommand dbCommand = db.GetStoredProcCommand("Nop_PollAnswerUpdate");
db.AddInParameter(dbCommand, "PollAnswerID", DbType.Int32, PollAnswerID);
db.AddInParameter(dbCommand, "PollID", DbType.Int32, PollID);
db.AddInParameter(dbCommand, "Name", DbType.String, Name);
db.AddInParameter(dbCommand, "Count", DbType.Int32, Count);
db.AddInParameter(dbCommand, "DisplayOrder", DbType.Int32, DisplayOrder);
if (db.ExecuteNonQuery(dbCommand) > 0)
pollAnswer = GetPollAnswerByID(PollAnswerID);
return pollAnswer;
}
/// <summary>
/// Creates a poll voting record
/// </summary>
/// <param name="PollAnswerID">The poll answer identifier</param>
/// <param name="CustomerID">Customer identifer</param>
public override void CreatePollVotingRecord(int PollAnswerID, int CustomerID)
{
Database db = NopSqlDataHelper.CreateConnection(_sqlConnectionString);
DbCommand dbCommand = db.GetStoredProcCommand("Nop_PollVotingRecordCreate");
db.AddInParameter(dbCommand, "PollAnswerID", DbType.Int32, PollAnswerID);
db.AddInParameter(dbCommand, "CustomerID", DbType.Int32, CustomerID);
db.ExecuteNonQuery(dbCommand);
}
#endregion
}
}
|
using System;
using System.Text;
using System.Text.RegularExpressions;
using System.Collections;
namespace Pop3
{
public class Pop3MessageComponents
{
private ArrayList m_component = new ArrayList();
public IEnumerator ComponentEnumerator
{
get
{
return m_component.GetEnumerator();
}
}
public int NumberOfComponents
{
get
{
return m_component.Count;
}
}
public Pop3MessageComponents(string[] lines, long startofbody, string multipartboundary, string maincontenttype)
{
long stopOfBody = lines.Length;
if (multipartboundary == null)
{
StringBuilder sbText = new StringBuilder();
for (long i = startofbody; i < stopOfBody; i++)
{
sbText.Append(lines[i].Replace("\n", "").Replace("\r", ""));
}
//create a new component
m_component.Add(new Pop3Component(maincontenttype, sbText.ToString()));
}
else
{
string boundary = multipartboundary;
bool firstcomponent = true;
//loop through email
for (long i = startofbody; i < stopOfBody; )
{
bool boundaryfound = true;
string contentType = null;
string name = null;
string filename = null;
string contenttransfer = null;
string description = null;
string disposition = null;
string data = null;
//if first block
if (firstcomponent)
{
boundaryfound = false;
firstcomponent = false;
while (i < stopOfBody)
{
string line = lines[i].Replace("\n", "").Replace("\r", "");
//if multipart boundary found then exit loop
if (Pop3Parse.GetSubHeaderLineType(line, boundary) == Pop3Parse.MultipartBoundaryFound)
{
boundaryfound = true;
++i;
break;
}
else
{
++i;
}
}
}
//check to see whether multipart boundary was found
if (!boundaryfound)
{
throw new Pop3MissingBoundaryException("Missing multipart boundary: " + boundary);
}
bool endofheader = false;
//read header info
while ((i < stopOfBody))
{
string line = lines[i].Replace("\n", "").Replace("\r", "");
int linetype = Pop3Parse.GetSubHeaderLineType(line, boundary);
switch (linetype)
{
case Pop3Parse.ContentTypeType:
contentType = Pop3Parse.ContentType(line);
break;
case Pop3Parse.ContentTransferEncodingType:
contenttransfer = Pop3Parse.ContentTransferEncoding(line);
break;
case Pop3Parse.ContentDispositionType:
disposition = Pop3Parse.ContentDisposition(line);
break;
case Pop3Parse.ContentDescriptionType:
description = Pop3Parse.ContentDescription(line);
break;
case Pop3Parse.EndOfHeader:
endofheader = true;
break;
}
++i;
if (endofheader)
{
break;
}
else
{
while (i < stopOfBody)
{
//if more lines to read for this line
if (line.Substring(line.Length - 1, 1).Equals(";"))
{
string nextline = lines[i].Replace("\r", "").Replace("\n", "");
switch (Pop3Parse.GetSubHeaderNextLineType(nextline))
{
case Pop3Parse.NameType:
name = Pop3Parse.Name(nextline);
break;
case Pop3Parse.FilenameType:
filename = Pop3Parse.Filename(nextline);
break;
case Pop3Parse.EndOfHeader:
endofheader = true;
break;
}
if (!endofheader)
{
//point line to current line
line = nextline;
++i;
}
else
{
break;
}
}
else
{
break;
}
}
}
}
boundaryfound = false;
StringBuilder sbText = new StringBuilder();
bool emailComposed = false;
//store the actual data
while (i < stopOfBody)
{
//get the next line
string line = lines[i].Replace("\n", "");
//if we've found the boundary
if (Pop3Parse.GetSubHeaderLineType(line, boundary) == Pop3Parse.MultipartBoundaryFound)
{
boundaryfound = true;
++i;
break;
}
else if (Pop3Parse.GetSubHeaderLineType(line, boundary) == Pop3Parse.ComponentsDone)
{
emailComposed = true;
break;
}
//add this line to data
sbText.Append(lines[i]);
++i;
}
if (sbText.Length > 0)
{
data = sbText.ToString();
}
//create a new component
m_component.Add(new Pop3Component(contentType, name, filename, contenttransfer, description, disposition, data));
//if all multiparts have been composed then exit
if (emailComposed)
{
break;
}
}
}
}
}
}
|
using Microsoft.VisualBasic;
using System;
using System.Collections.Generic;
using System.Windows.Forms;
using System.Linq;
using TNBase.Objects;
using TNBase.DataStorage;
using Microsoft.Extensions.DependencyInjection;
namespace TNBase
{
public partial class FormBrowseCollectors
{
private readonly IServiceLayer serviceLayer = Program.ServiceProvider.GetRequiredService<IServiceLayer>();
int limit = 15;
int offset = 0;
public void ClearList()
{
lstBrowse.Items.Clear();
}
public void refreshList()
{
ClearList();
List<Collector> theCollectors = new List<Collector>();
theCollectors = serviceLayer.GetCollectors().Skip(offset).Take(limit).ToList();
foreach (Collector tCollector in theCollectors)
{
addToCollectors(tCollector);
}
}
// Add items to the list.
public void addToCollectors(Collector theCollector)
{
//Add items in the listview
string[] arr = new string[12];
ListViewItem itm = null;
//Add first item
arr[0] = theCollector.Id.ToString();
arr[1] = theCollector.Forename;
arr[2] = theCollector.Surname;
arr[3] = theCollector.Number;
arr[4] = theCollector.Postcodes;
itm = new ListViewItem(arr);
lstBrowse.Items.Add(itm);
}
private void btnRemove_Click(object sender, EventArgs e)
{
int theIndex = 0;
theIndex = lstBrowse.FocusedItem.Index;
// First sub item is wallet number.
int Id = 0;
Id = int.Parse(lstBrowse.Items[theIndex].SubItems[0].Text);
DialogResult result = MessageBox.Show("Are you sure you wish to delete the selected collector?", ModuleGeneric.getAppShortName(), MessageBoxButtons.YesNo);
if (result == DialogResult.No) {
return;
} else if (result == DialogResult.Yes) {
if (!serviceLayer.DeleteCollector(serviceLayer.GetCollector(Id))) {
Interaction.MsgBox("Error: Failed to delete collector!");
} else {
Interaction.MsgBox("Successfully deleted collector.");
}
}
refreshList();
}
private void btnEdit_Click(object sender, EventArgs e)
{
int theIndex = 0;
try {
theIndex = lstBrowse.FocusedItem.Index;
// First sub item is wallet number.
int id = 0;
id = int.Parse(lstBrowse.Items[theIndex].SubItems[0].Text);
Collector theCollector = serviceLayer.GetCollector(id);
My.MyProject.Forms.formAddCollectors.Show();
My.MyProject.Forms.formAddCollectors.SetupEditMode(theCollector);
refreshList();
} catch (Exception ex) {
// Probably nothing selected... ignore.
}
}
private void btnDone_Click(object sender, EventArgs e)
{
this.Close();
}
private void btnFirst_Click(object sender, EventArgs e)
{
offset = 0;
refreshList();
}
private void btnPrevious_Click(object sender, EventArgs e)
{
if ((offset - limit) >= 0)
{
offset -= limit;
}
else
{
offset = 0;
}
refreshList();
}
private void btnNext_Click(object sender, EventArgs e)
{
if ((offset + limit) < serviceLayer.GetCollectors().Count())
{
offset += limit;
}
refreshList();
}
private void btnLast_Click(object sender, EventArgs e)
{
offset = serviceLayer.GetCollectors().Count - limit;
refreshList();
}
private void formBrowseCollectors_Load(object sender, EventArgs e)
{
refreshList();
}
public FormBrowseCollectors()
{
Load += formBrowseCollectors_Load;
InitializeComponent();
}
}
}
|
namespace Api.Courses.Helpers
{
public class Response
{
public bool IsSuccess { get; set; }
public string ErrorMessage { get; set; }
public dynamic Data { get; set; }
public Response()
{
IsSuccess = false;
ErrorMessage = string.Empty;
Data = null;
}
}
}
|
using BlazoServerGridTestrApp9.Data;
using Microsoft.AspNetCore.Components;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace BlazoServerGridTestrApp9.Components
{
public partial class GridView
{
public Employee[] employees;
[Parameter] public Employee[] DataSource { get; set; }
[Parameter] public RenderFragment ChildContent { get; set; }
protected override void OnParametersSet()
{
employees = DataSource;
base.OnParametersSet();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using kemuyi.BLL;
namespace 网站
{
public partial class questions : System.Web.UI.Page
{
static Random ran = new Random();
static int QuesID = ran.Next(1, 10);
static int []aaa=new int [99] ;
protected void Page_Load(object sender, EventArgs e)
{
TextBox1.Text = QuestionManager.GetQues(QuesID).Content;
TextBox2.Text = QuestionManager.GetQues(QuesID + 1).Content;
TextBox3.Text = QuestionManager.GetQues(QuesID + 2).Content;
TextBox4.Text = QuestionManager.GetQues(QuesID + 3).Content;
TextBox5.Text = QuestionManager.GetQues(QuesID + 4).Content;
TextBox6.Text = QuestionManager.GetQues(QuesID + 5).Content;
TextBox7.Text = QuestionManager.GetQues(QuesID + 6).Content;
TextBox8.Text = QuestionManager.GetQues(QuesID + 7).Content;
TextBox9.Text = QuestionManager.GetQues(QuesID + 8).Content;
TextBox10.Text = QuestionManager.GetQues(QuesID + 9).Content;
Label1.Text = OptionsManager.GetQues(QuesID).A;
Label2.Text = OptionsManager.GetQues(QuesID).B;
Label3.Text = OptionsManager.GetQues(QuesID).C;
Label4.Text = OptionsManager.GetQues(QuesID).D;
Label5.Text = OptionsManager.GetQues(QuesID + 1).A;
Label6.Text = OptionsManager.GetQues(QuesID + 1).B;
Label7.Text = OptionsManager.GetQues(QuesID + 1).C;
Label8.Text = OptionsManager.GetQues(QuesID + 1).D;
Label9.Text = OptionsManager.GetQues(QuesID + 2).A;
Label10.Text = OptionsManager.GetQues(QuesID + 2).B;
Label11.Text = OptionsManager.GetQues(QuesID + 2).C;
Label12.Text = OptionsManager.GetQues(QuesID + 2).D;
Label13.Text = OptionsManager.GetQues(QuesID + 3).A;
Label14.Text = OptionsManager.GetQues(QuesID + 3).B;
Label15.Text = OptionsManager.GetQues(QuesID + 3).C;
Label16.Text = OptionsManager.GetQues(QuesID + 3).D;
Label17.Text = OptionsManager.GetQues(QuesID + 4).A;
Label18.Text = OptionsManager.GetQues(QuesID + 4).B;
Label19.Text = OptionsManager.GetQues(QuesID + 4).C;
Label20.Text = OptionsManager.GetQues(QuesID + 4).D;
Label21.Text = OptionsManager.GetQues(QuesID + 5).A;
Label22.Text = OptionsManager.GetQues(QuesID + 5).B;
Label23.Text = OptionsManager.GetQues(QuesID + 5).C;
Label24.Text = OptionsManager.GetQues(QuesID + 5).D;
Label25.Text = OptionsManager.GetQues(QuesID + 6).A;
Label26.Text = OptionsManager.GetQues(QuesID + 6).B;
Label27.Text = OptionsManager.GetQues(QuesID + 6).C;
Label28.Text = OptionsManager.GetQues(QuesID + 6).D;
Label29.Text = OptionsManager.GetQues(QuesID + 7).A;
Label30.Text = OptionsManager.GetQues(QuesID + 7).B;
Label31.Text = OptionsManager.GetQues(QuesID + 7).C;
Label32.Text = OptionsManager.GetQues(QuesID + 7).D;
Label33.Text = OptionsManager.GetQues(QuesID + 8).A;
Label34.Text = OptionsManager.GetQues(QuesID + 8).B;
Label35.Text = OptionsManager.GetQues(QuesID + 8).C;
Label36.Text = OptionsManager.GetQues(QuesID + 8).D;
Label37.Text = OptionsManager.GetQues(QuesID + 9).A;
Label38.Text = OptionsManager.GetQues(QuesID + 9).B;
Label39.Text = OptionsManager.GetQues(QuesID + 9).C;
Label40.Text = OptionsManager.GetQues(QuesID + 9).D;
}
protected void TextBox1_TextChanged(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
if (Convert.ToString(a) == QuestionManager.GetQues(QuesID).Answer)
{
int allscore = 0;
allscore++;
aaa[1] = allscore;
Label41.Text = Convert.ToString(aaa[1]);
}
}
protected void TextBox2_TextChanged(object sender, EventArgs e)
{
}
protected void RadioButton1_CheckedChanged(object sender, EventArgs e)
{
}
int a;
protected void RadioButton1_CheckedChanged1(object sender, EventArgs e)
{if (RadioButton1.Checked) a = 1;
}
protected void RadioButton2_CheckedChanged(object sender, EventArgs e)
{
if (RadioButton2.Checked) a = 2;
}
protected void RadioButton3_CheckedChanged(object sender, EventArgs e)
{
if (RadioButton2.Checked) a = 3;
}
protected void RadioButton4_CheckedChanged(object sender, EventArgs e)
{
if (RadioButton2.Checked) a = 4;
}
}
} |
using System;
using Abp.Runtime.Validation;
using SPACore.PhoneBook.Dto;
namespace SPACore.PhoneBook.PhoneBooks.Persons.Dto
{
/// <summary>
/// 查询列表
/// </summary>
public class GetPersonInput : PagedAndSortedInputDto, IShouldNormalize
{
public string FilterText { get; set; }
public void Normalize()
{
if (String.IsNullOrEmpty(Sorting))
{
Sorting = "Id";
}
}
}
} |
namespace Requestrr.WebApi.config
{
public class ChatClientsSettings
{
public DiscordSettings Discord { get; set; }
public string Language { get; set; }
}
public class DiscordSettings
{
public string BotToken { get; set; }
public string ClientId { get; set; }
public string StatusMessage { get; set; }
public string[] TvShowRoles { get; set; }
public string[] MovieRoles { get; set; }
public string[] MonitoredChannels { get; set; }
public bool EnableRequestsThroughDirectMessages { get; set; }
public bool AutomaticallyNotifyRequesters { get; set; }
public string NotificationMode { get; set; }
public string[] NotificationChannels { get; set; }
public bool AutomaticallyPurgeCommandMessages { get; set; }
}
} |
using System.IO;
using System.Threading.Tasks;
using Akka.Actor;
using Akka.TestKit.Xunit2;
using DownloadExtractLib;
using DownloadExtractLib.Interfaces;
using DownloadExtractLib.Messages;
namespace DownloadExtractLibTest
{
public class DownloadCoordinatorActorUT : TestKit, IDownloadedEvent
{
const string DOWNLOADURL = "", OUTPATH = @"C:\temp\stage";
readonly TaskCompletionSource<bool> _tcs = new TaskCompletionSource<bool>();
[Fact]
public void TestMethod1()
{
// Arrange (TestKit has already established the Actor System)
var dlca = Sys.ActorOf(Props.Create(() => new DownloadCoordinatorActor(this, OUTPATH)));
_tcs.Task.Wait(); // ensure all I/O has completed
// Act
dlca.Tell(new DownloadMessage(DOWNLOADURL, "ch029-ch03s03.htm"));
// Assert
var fileExists = File.Exists(OUTPATH + @"\ch029-ch03s03.html");
Assert.True(fileExists);
}
void IDownloadedEvent.GotItem(string parentUrl, string childUrl, int result, int totalRefs, int doneRefs)
{
System.Console.WriteLine($"\tTellMe:\tparent={parentUrl},\tchild={childUrl},\tresult={result},\ttotalRefs={totalRefs},\tdoneRefs={doneRefs}");
if (totalRefs == doneRefs)
{
System.Console.WriteLine($"TellMe:\tparent={parentUrl}\tCOMPLETED");
_tcs.SetResult(result: true); // TODO: return false if any 404, or SetException if we hit any
}
}
}
}
|
using System.Security.Cryptography;
using reverseJobsBoard.Auth;
namespace reverseJobsBoard.Auth
{
public class RSAKeyHelper
{
public static RSAParameters GenerateKey()
{
using (RSA rsa = RSA.Create())
{
return rsa.ExportParameters(true);
}
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace Pitstop
{
public class ArrowShooterFunctionning : MonoBehaviour
{
InputManager inputManager;
[SerializeField] Animator myAnim = default;
[SerializeField] GameObject interactionButton = default;
[SerializeField] GameObject whatToShoot = default;
[SerializeField] Transform fromWhereToShoot = default;
[SerializeField] float interval = 1;
bool triggerOnceCheck = false;
bool goShoot = true;
GameObject cloneProj;
private void Start()
{
inputManager = GameManager.Instance.inputManager;
}
private void Update()
{
if (!triggerOnceCheck)
{
if (interactionButton.activeInHierarchy && inputManager.interactionButton)
{
myAnim.SetTrigger("TurnOn");
interactionButton.SetActive(false);
triggerOnceCheck = true;
}
}
else if (goShoot)
{
StopCoroutine(WaitForInterval());
cloneProj = Instantiate(whatToShoot, fromWhereToShoot.position, whatToShoot.transform.rotation);
cloneProj.GetComponent<ArrowBehaviour>().isFired = true;
StartCoroutine(WaitForInterval());
}
}
private void OnTriggerEnter2D(Collider2D collision)
{
if (collision.gameObject.tag == "Player" && !triggerOnceCheck)
{
interactionButton.SetActive(true);
}
}
private void OnTriggerExit2D(Collider2D collision)
{
if (collision.gameObject.tag == "Player")
{
interactionButton.SetActive(false);
}
}
IEnumerator WaitForInterval()
{
goShoot = false;
yield return new WaitForSeconds(interval);
goShoot = true;
}
}
} |
using System;
using System.Diagnostics.CodeAnalysis;
using System.Runtime.CompilerServices;
namespace NetFabric.Hyperlinq
{
public static partial class ArrayExtensions
{
public static Option<TSource> Single<TSource>(this ReadOnlySpan<TSource> source)
=> source.Length switch
{
1 => Option.Some(source[0]),
_ => Option.None,
};
static Option<TSource> Single<TSource, TPredicate>(this ReadOnlySpan<TSource> source, TPredicate predicate)
where TPredicate : struct, IFunction<TSource, bool>
{
for (var index = 0; index < source.Length; index++)
{
if (predicate.Invoke(source[index]))
{
ref readonly var first = ref source[index];
for (index++; index < source.Length; index++)
{
if (predicate.Invoke(source[index]))
return Option.None;
}
return Option.Some(first);
}
}
return Option.None;
}
static Option<TSource> SingleAt<TSource, TPredicate>(this ReadOnlySpan<TSource> source, TPredicate predicate)
where TPredicate : struct, IFunction<TSource, int, bool>
{
for (var index = 0; index < source.Length; index++)
{
if (predicate.Invoke(source[index], index))
{
ref readonly var first = ref source[index];
for (index++; index < source.Length; index++)
{
if (predicate.Invoke(source[index], index))
return Option.None;
}
return Option.Some(first);
}
}
return Option.None;
}
static Option<TResult> Single<TSource, TResult, TSelector>(this ReadOnlySpan<TSource> source, TSelector selector)
where TSelector : struct, IFunction<TSource, TResult>
=> source.Length switch
{
1 => Option.Some(selector.Invoke(source[0])),
_ => Option.None,
};
static Option<TResult> SingleAt<TSource, TResult, TSelector>(this ReadOnlySpan<TSource> source, TSelector selector)
where TSelector : struct, IFunction<TSource, int, TResult>
=> source.Length switch
{
1 => Option.Some(selector.Invoke(source[0], 0)),
_ => Option.None,
};
static Option<TResult> Single<TSource, TResult, TPredicate, TSelector>(this ReadOnlySpan<TSource> source, TPredicate predicate, TSelector selector)
where TPredicate : struct, IFunction<TSource, bool>
where TSelector : struct, IFunction<TSource, TResult>
{
for (var index = 0; index < source.Length; index++)
{
if (predicate.Invoke(source[index]))
{
ref readonly var first = ref source[index];
for (index++; index < source.Length; index++)
{
if (predicate.Invoke(source[index]))
return Option.None;
}
return Option.Some(selector.Invoke(first));
}
}
return Option.None;
}
}
}
|
using System;
using System.Security.Cryptography;
using System.Text;
namespace TinyUrlBL
{
public class TinyUrl : ITinyUrl
{
public TinyUrl()
{
}
public string GenerateTinyUrl(string text)
{
const string chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
byte[] bytes = Encoding.UTF8.GetBytes(text);
SHA256Managed hashstring = new SHA256Managed();
byte[] hash = hashstring.ComputeHash(bytes);
char[] hash2 = new char[6];
for (int i = 0; i < hash2.Length; i++)
{
hash2[i] = chars[hash[i] % chars.Length];
}
return string.Format("{0}/{1}", "localhost:44377/api/TinyUrl/RedirectUrl", new string(hash2));
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Fornax.Net.Index.Storage
{
class Repository
{
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
//using System.IO;
//using UnityEngine;
using System.Linq;
//using System;
/**
* Copyright (c) blueback
* Released under the MIT License
* https://github.com/bluebackblue/fee/blob/master/LICENSE.txt
* http://bbbproject.sakura.ne.jp/wordpress/mitlicense
* @brief UNIVRM。
*/
/** NUniVrm
*/
namespace NUniVrm
{
/** Item
*/
public class Item
{
/** ResultType
*/
public enum ResultType
{
/** 未定義。
*/
None,
/** エラー。
*/
Error,
/** コンテキスト。
*/
Context,
}
/** result_type
*/
private ResultType result_type;
/** result_progress
*/
private float result_progress;
/** result_errorstring
*/
private string result_errorstring;
/** cancel_flag
*/
private bool cancel_flag;
/** result_context
*/
private VRM.VRMImporterContext result_context;
/** result_animetor
*/
private Animator result_animator;
/** constructor
*/
public Item()
{
//result_type
this.result_type = ResultType.None;
//result_progress
this.result_progress = 0.0f;
//result_errorstring
this.result_errorstring = null;
//cancel_flag
this.cancel_flag = false;
//result_context
this.result_context = null;
//result_animator
this.result_animator = null;
}
/** 削除。
*/
public void Delete()
{
#if(USE_UNIVRM)
if(this.result_context != null){
this.result_context.Destroy(false);
}
#endif
}
/** 処理中。チェック。
*/
public bool IsBusy()
{
if(this.result_type == ResultType.None){
return true;
}
return false;
}
/** キャンセル。設定。
*/
public void Cancel()
{
this.cancel_flag = true;
}
/** キャンセル。取得。
*/
public bool IsCancel()
{
return this.cancel_flag;
}
/** 結果。タイプ。取得。
*/
public ResultType GetResultType()
{
return this.result_type;
}
/** プログレス。設定。
*/
public void SetResultProgress(float a_result_progress)
{
this.result_progress = a_result_progress;
}
/** プログレス。取得。
*/
public float GetResultProgress()
{
return this.result_progress;
}
/** 結果。エラー文字。設定。
*/
public void SetResultErrorString(string a_error_string)
{
this.result_type = ResultType.Error;
this.result_errorstring = a_error_string;
}
/** 結果。エラー文字。取得。
*/
public string GetResultErrorString()
{
return this.result_errorstring;
}
/** 結果。コンテキスト。設定。
*/
public void SetResultContext(VRM.VRMImporterContext a_context)
{
this.result_type = ResultType.Context;
this.result_context = a_context;
this.result_animator = null;
#if(USE_UNIVRM)
if(this.result_context != null){
if(this.result_context.Root != null){
this.result_animator = this.result_context.Root.GetComponent<Animator>();
}
}
#endif
}
/** 結果。コンテキスト。取得。
*/
public VRM.VRMImporterContext GetResultContext()
{
return this.result_context;
}
/** [内部からの呼び出し]レイヤー。設定。
*/
private static void Raw_SetLayer(Transform a_transform,int a_layer)
{
GameObject t_gameobject = a_transform.gameObject;
if(t_gameobject != null){
t_gameobject.layer = a_layer;
}
foreach(Transform t_transform in a_transform){
Raw_SetLayer(t_transform,a_layer);
}
}
/** レイヤー。設定。
*/
public void SetLayer(string a_layername)
{
#if(USE_UNIVRM)
if(this.result_context != null){
Raw_SetLayer(this.result_context.Root.transform,LayerMask.NameToLayer(a_layername));
}
#endif
}
/** 表示。設定。
*/
public void SetRendererEnable(bool a_flag)
{
#if(USE_UNIVRM)
if(this.result_context != null){
for(int ii=0;ii<this.result_context.Meshes.Count;ii++){
if(this.result_context.Meshes[ii] != null){
if(this.result_context.Meshes[ii].Renderer != null){
this.result_context.Meshes[ii].Renderer.enabled = a_flag;
}
}
}
}
#endif
}
/** アニメータコントローラ。設定。
*/
public void SetAnimatorController(RuntimeAnimatorController a_animator_Controller)
{
if(this.result_animator != null){
this.result_animator.runtimeAnimatorController = a_animator_Controller;
}
}
/** アニメ。設定。
*/
public bool IsAnimeEnable()
{
if(this.result_animator != null){
return this.result_animator.enabled;
}
return false;
}
/** アニメ。設定。
*/
public void SetAnimeEnable(bool a_flag)
{
if(this.result_animator != null){
this.result_animator.enabled = a_flag;
}
}
/** アニメ。設定。
*/
public void SetAnime(int a_state_name_hash)
{
if(this.result_animator != null){
this.result_animator.Play(a_state_name_hash);
}
}
/** GetBoneTransform
*/
public Transform GetBoneTransform(UnityEngine.HumanBodyBones a_bone)
{
if(this.result_animator != null){
return this.result_animator.GetBoneTransform(a_bone);
}
return null;
}
/** GetTransform
*/
public Transform GetTransform()
{
if(this.result_context != null){
return this.result_context.Root.gameObject.transform;
}
return null;
}
/** GetForward
*/
public Vector3 GetForward()
{
if(this.result_context != null){
return this.result_context.Root.gameObject.transform.forward;
}
return Vector3.zero;
}
/** 位置。取得。
*/
public Vector3 GetPosition()
{
if(this.result_context != null){
return this.result_context.Root.gameObject.transform.position;
}
return Vector3.zero;
}
/** 位置。設定。
*/
public void SetPosition(ref Vector3 a_position)
{
if(this.result_context != null){
this.result_context.Root.gameObject.transform.position = a_position;
}
}
}
}
|
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using Microsoft.EntityFrameworkCore.TestUtilities;
namespace Microsoft.EntityFrameworkCore
{
public class FieldsOnlyLoadSqliteTest : FieldsOnlyLoadTestBase<FieldsOnlyLoadSqliteTest.FieldsOnlyLoadSqliteFixture>
{
public FieldsOnlyLoadSqliteTest(FieldsOnlyLoadSqliteFixture fixture)
: base(fixture)
{
}
public class FieldsOnlyLoadSqliteFixture : FieldsOnlyLoadFixtureBase
{
protected override ITestStoreFactory TestStoreFactory
=> SqliteTestStoreFactory.Instance;
}
}
}
|
using System;
namespace RankingsTable.EF.Entities
{
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
public class Fixture
{
[Key]
public Guid Id { get; set; }
public virtual SeasonPlayer HomePlayer { get; set; }
public virtual SeasonPlayer AwayPlayer { get; set; }
public virtual Season Season { get; set; }
[Required]
public Guid HomePlayerId { get; set; }
[Required]
public Guid AwayPlayerId { get; set; }
[Required]
public Guid SeasonId { get; set; }
public int? HomeGoals { get; set; }
public int? AwayGoals { get; set; }
}
}
|
namespace Triton.Common
{
using System;
using System.Globalization;
using System.Windows.Data;
public sealed class WpfVector2iYConverter : IValueConverter
{
private WpfVector2iSettingsDelegate wpfVector2iSettingsDelegate_0;
public WpfVector2iYConverter(WpfVector2iSettingsDelegate get)
{
this.wpfVector2iSettingsDelegate_0 = get;
}
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
WpfVector2i vectori = (WpfVector2i) value;
return vectori.Y;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
WpfVector2i vectori = this.wpfVector2iSettingsDelegate_0();
vectori.Y = int.Parse((string) value);
return vectori;
}
}
}
|
using CsvHelper;
using HubSpotIntegration.Models;
using HubSpotIntegration.Services;
using Newtonsoft.Json;
using Renci.SshNet;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace HubSpotIntegration
{
class Program
{
static void Main(string[] args)
{
var baseUrl = ConfigurationManager.AppSettings["baseUrl"]; //"https://api.hubapi.com/contacts/v1";
var baseFilePath = ConfigurationManager.AppSettings["baseFilePath"];
var ftpHost = ConfigurationManager.AppSettings["ftpHost"];
var ftpPort = int.Parse(ConfigurationManager.AppSettings["ftpPort"]);
var ftpUserName = ConfigurationManager.AppSettings["ftpUserName"];
var ftpPassword = ConfigurationManager.AppSettings["ftpPassword"];
Console.WriteLine($"Initializing...{Environment.NewLine}");
Console.WriteLine($"baseUrl: {baseUrl}");
Console.WriteLine($"baseFilePath: {baseUrl}");
Console.WriteLine($"ftpHost: {baseUrl}");
Console.WriteLine($"ftpPort: {baseUrl}");
Console.WriteLine($"ftpUserName: {baseUrl}");
Console.WriteLine($"ftpPassword: {ftpPassword}");
Console.WriteLine($"{Environment.NewLine}");
Console.Write($"hAPIKey: ");
var hapiKey = Console.ReadLine();
Console.Write($"listId: ");
int? listId = int.Parse(Console.ReadLine());
Console.WriteLine($"{Environment.NewLine}");
Console.WriteLine($"Running...");
Console.WriteLine($"{Environment.NewLine}");
var hsService = new HubSpotClientService(baseUrl, hapiKey);
string filePath = null;
if (listId != null)
{
var guid = Guid.NewGuid();
filePath = Environment.ExpandEnvironmentVariables($"{baseFilePath}contactList_{listId}_{guid}.csv");
using (var textWriter = File.CreateText(filePath))
{
using (var csv = new CsvWriter(textWriter))
{
using(var console = new CsvWriter(Console.Out))
{
var contactList = hsService.GetContactList((int)listId);
csv.WriteHeader<ContactList>();
console.WriteHeader<ContactList>();
csv.WriteRecord(contactList);
console.WriteRecord(contactList);
}
}
}
}
else
{
var guid = Guid.NewGuid();
filePath = Environment.ExpandEnvironmentVariables($"{baseFilePath}contactLists_all_{guid}.csv");
using (var textWriter = File.CreateText(filePath))
{
using (var csv = new CsvWriter(textWriter))
{
using (var console = new CsvWriter(Console.Out))
{
var contactLists = hsService.GetAllContactLists();
csv.WriteHeader<ContactList>();
console.WriteHeader<ContactList>();
foreach (var contactList in contactLists)
{
csv.WriteRecord(contactList);
console.WriteRecord(contactList);
}
}
}
}
}
//try
//{
// using (var ftpClient = new SftpClient(ftpHost, ftpPort, ftpUserName, ftpPassword))
// {
// using (FileStream fs = new FileStream(filePath, FileMode.Open))
// {
// ftpClient.UploadFile(fs, Path.GetFileName(filePath));
// }
// }
//} catch(Exception e)
//{
// Console.WriteLine($"An error occurred with attempting to transport file to {ftpHost};");
// Console.WriteLine($"Exception: {e}");
//}
Console.WriteLine($"{Environment.NewLine}");
Console.WriteLine("DONE...");
Console.ReadLine();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Diagnostics;
using Microsoft.AspNetCore.Mvc;
using eIDEAS.Models;
using eIDEAS.Models.Enums;
using eIDEAS.Data;
using Microsoft.AspNetCore.Identity;
using System.Linq;
namespace eIDEAS.Controllers
{
public class HomeController : Controller
{
private readonly ApplicationDbContext _context;
private readonly UserManager<ApplicationUser> _userManager;
public HomeController(ApplicationDbContext context, UserManager<ApplicationUser> userManager)
{
_context = context;
_userManager = userManager;
}
public IActionResult Index()
{
//Get the front page information (What's New and Success Stories)
var successStory = _context.Message
.Where(message => message.MessageType == MessageEnum.SuccessStory)
.OrderByDescending(message => message.DateCreated).FirstOrDefault();
var whatsNew = _context.Message
.Where(message => message.MessageType == MessageEnum.WhatsNew)
.OrderByDescending(message => message.DateCreated).FirstOrDefault();
var homepageViewModel = new HomePresentationViewModel();
var success = new Message {Title = "", Text = "No success stories have been set." };
var whats = new Message { Title = "", Text = "Nothing New." };
if (successStory != null)
{
success.Title = successStory.Title;
success.Text = successStory.Text;
}
if (whatsNew != null)
{
whats.Title = whatsNew.Title;
whats.Text = whatsNew.Text;
}
homepageViewModel.SuccessStory = success;
homepageViewModel.WhatsNew = whats;
return View(homepageViewModel);
}
public IActionResult FAQ()
{
return View();
}
public IActionResult Contact()
{
ViewData["Message"] = "Your contact page.";
return View();
}
public IActionResult Privacy()
{
return View();
}
public IActionResult Error(int? id)
{
return View(new ErrorViewModel { RequestId = id.ToString() });
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace FuiteAdmin.Report
{
/// <summary>
/// Contrôle présentant le résumé associé à un report
/// </summary>
public partial class ReportItem : System.Web.UI.UserControl
{
private ReportService.ReportRequest report;
protected void Page_Load(object sender, EventArgs e)
{
}
public ReportService.ReportRequest Report
{
get
{
return this.report;
}
set
{
this.report = value;
this.link.HRef += "?id=" + value.Id;
}
}
}
} |
namespace FileUploadNetCore.Models
{
public class FileOnFileSystemModel : FileModel
{
public string FilePath { get; set; }
}
}
|
using Dao;
using log4net;
using Model;
using Ninject;
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Threading;
using System.Transactions;
using System.Web;
namespace Blo
{
/// <summary>
/// Clase Base para la logica del negocio (Business Logic Layer - BLL) que
/// implementa las interfaces generales de acceso a la logica del negocio,
/// permitiendo los métodos generales de: CRUD (Create, Read, Update y Delete).
/// Implementa el control de transacciones a nivel de servicios con
/// el objetivo de mantener la integridad de las diferentes acciones
/// de persistencia.
/// </summary>
/// <typeparam name="T">Parámetro que define el objeto generico sobre el
/// cual opera la clase en tiempo de ejecución.</typeparam>
public abstract class GenericBlo<T> : IGenericBlo<T> where T : BaseEntity
{
/// <summary>
/// Propiedad para administrar el mecanismo de logeo
/// de informacion y fallas
/// </summary>
public static readonly ILog log = LogManager.GetLogger(
MethodBase.GetCurrentMethod().DeclaringType);
/// <summary>
/// Propiedad que representa el objeto principal de acceso a datos.
/// </summary>
public IGenericDao<T> _dao;
/// <summary>
/// Constructor que permite la inyección de dependencias en lo
/// referente al acceso a datos
/// </summary>
/// <param name="dao">Objeto de acceso a datos que se inyecta al
/// instanciarse la clase</param>
public GenericBlo(IGenericDao<T> dao)
{
_dao = dao;
}
/// <summary>
/// Metodo para validar si la conexion a la base de datos es correcta
/// </summary>
/// <returns>True: si la conexion a la base de datos es correcta, false:
/// en caso contrario.</returns>
public bool DatabaseIsValid()
{
bool isValid = false;
try
{
isValid = _dao.DatabaseIsValid();
}
catch (Exception e)
{
log.Error(e);
throw new Exception(e.Message);
}
return true;
}
/// <summary>
/// Método generico que permite obtener el total de registros
/// entidad
/// </summary>
/// <returns>numero de registros</returns>
public int GetCount()
{
int total = 0;
try
{
total = _dao.GetCount();
}
catch (Exception e)
{
log.Error(e.Message);
}
return total;
}
/// <summary>
/// Método generico que permite obtener todos los elementos de una
/// entidad
/// </summary>
/// <returns>un listado de objetos del tipo especificado</returns>
public IList<T> GetAll(bool relaciones = false)
{
try
{
return _dao.GetAll(relaciones);
}
catch (Exception e)
{
log.Error(e);
throw new Exception(e.Message);
}
}
/// <summary>
/// Método generico que permite obtener todos los elementos de una
/// entidad paginados ademas de retornar el total de registros existentes
/// </summary>
/// <param name="total">Total de reguistros</param>
/// <param name="page">Numero de pagina</param>
/// <param name="limit">Top de reguistros a mostrar</param>
/// <param name="sortBy">Nombre del campo a ordenar</param>
/// <param name="direction">Indica el tipo de orden (asc,desc)</param>
/// <returns>Lista de datos con paginación</returns>
public IList<T> GetDatosGrid(out int total, int? page, int? limit, string sortBy, string direction, bool relaciones = false)
{
try
{
return _dao.GetDatosGrid(out total, page, limit, sortBy, direction, relaciones);
}
catch (Exception e)
{
log.Error(e);
throw new Exception(e.Message);
}
}
/// <summary>
/// Método generico que permite obtener el detelle de una entidad
/// filtrados por el identificador del padre, paginados
/// ademas de retornar el total de registros existentes
/// </summary>
/// <param name="total">Total de reguistros</param>
/// <param name="page">Numero de pagina</param>
/// <param name="limit">Top de reguistros a mostrar</param>
/// <param name="sortBy">Nombre del campo a ordenar</param>
/// <param name="direction">Indica el tipo de orden (asc,desc)</param>
/// <param name="nombreId">Nombre del campo identificador del padre</param>
/// <param name="idPadre">Identificador del padre</param>
/// <returns>Lista de datos con paginación</returns>
public IList<T> GetDatosDetalle(out int total, int? page, int? limit, string sortBy, string direction, string nombreId, object idPadre, bool relaciones = false)
{
try
{
return _dao.GetDatosDetalle(out total, page, limit, sortBy, direction, nombreId, idPadre, relaciones);
}
catch (Exception e)
{
log.Error(e);
throw new Exception(e.Message);
}
}
/// <summary>
/// Método generico que permite obtener el detelle de una entidad
/// filtrados por el identificador del padre
/// </summary>
/// <param name="nombreId">Nombre del campo identificador del padre</param>
/// <param name="idPadre">Identificador del padre</param>
/// <returns></returns>
public IList<T> GetDatosDetalle(string nombreId, object idPadre, bool relaciones = false)
{
try
{
return _dao.GetDatosDetalle(nombreId, idPadre, relaciones);
}
catch (Exception e)
{
log.Error(e);
throw new Exception(e.Message);
}
}
/// <summary>
/// Método genérico que permite obtener una instancia de la entidad
/// especificada a traves de su respectivo Id
/// </summary>
/// <param name="id">Identificador unico de la instancia que se
/// necesita obtener</param>
/// <returns>El objeto obtenido</returns>
public T GetById(object id, bool relaciones = false)
{
try
{
return _dao.GetById(id, relaciones);
}
catch (Exception e)
{
log.Error(e);
throw new Exception(e.Message);
}
}
/// <summary>
/// Método genérico que permite agrear una nueva instancia a la entidad
/// especificada
/// </summary>
/// <param name="entity">Nueva instancia a ser persistida en la base de
/// datos</param>
public virtual void Save(T entity)
{
using (var scope = new TransactionScope(TransactionScopeOption.Required))
{
try
{
_dao.Save(entity);
scope.Complete();
}
catch (Exception e)
{
log.Error(e);
throw new Exception(e.Message);
}
}
}
/// <summary>
/// Método genérico que permite agrear una nueva instancia a la entidad
/// especificada. En este no se incluye la auditoria
/// </summary>
/// <param name="entity">Nueva instancia a ser persistida en la base de datos</param>
public void SaveNoTrack(T entity)
{
try
{
_dao.SaveNoTrack(entity);
}
catch (Exception e)
{
log.Error(e);
throw new Exception(e.Message);
}
}
/// <summary>
/// Permite cargar de manera eficiente de grandes cantidades de datos
/// una tabla de SQL Server con datos de otra fuentes
/// </summary>
/// <param name="list">Lista de datos</param>
/// <param name="TabelName">Nombre de la tabla de destino</param>
public void InsertData(List<T> list, string TabelName)
{
try
{
_dao.InsertData(list, TabelName);
}
catch (Exception e)
{
log.Error(e);
throw new Exception(e.Message);
}
}
/// <summary>
/// Método genérico que permite eliminar una instancia de la entidad
/// especificada, validando si el usuario y la opcion permite el
/// proceso de eliminacion.
/// </summary>
/// <param name="_id">Identificador único de la instancia que sera
/// removida de la base de datos.</param>
public virtual void Remove(object _id)
{
using (var scope = new TransactionScope(TransactionScopeOption.Required))
{
try
{
_dao.Remove(_id);
scope.Complete();
}
catch (Exception e)
{
log.Error(e);
throw new Exception(e.Message);
}
}
}
/// <summary>
/// Método genérico que permite eliminar una instancia de la entidad
/// especificada, validando si el usuario y la opcion permite el
/// proceso de eliminacion. En este no se incluye la auditoria
/// </summary>
/// <param name="_id"></param>
public void RemoveNoTrack(object _id)
{
try
{
_dao.RemoveNoTrack(_id);
}
catch (Exception e)
{
log.Error(e);
throw new Exception(e.Message);
}
}
/// <summary>
/// Permite reseteaar el ID de una tabla
/// </summary>
/// <param name="nombreTabla"></param>
public void ResetID(string nombreTabla)
{
try
{
_dao.ResetID(nombreTabla);
}
catch (Exception e)
{
log.Error(e);
throw new Exception(e.Message);
}
}
/// <summary>
/// Permite ejecutar consultas SQL
/// </summary>
/// <param name="sql">consulta sql</param>
public void EjecutarQuerySQL(string sql)
{
try
{
_dao.EjecutarQuerySQL(sql);
}
catch (Exception e)
{
log.Error(e);
throw new Exception(e.Message);
}
}
/// <summary>
/// Permite validar los permisos del un suario por el rol
/// </summary>
/// <param name="idPerfil">Identificador del perfil de usuario</param>
/// <param name="idOpcion">Identificador de la opcion</param>
/// <param name="accion">código del permiso</param>
/// <param name="idEmpresa">Identificador de la empresa</param>
public void ValidarPermiso(long idPerfil, long idOpcion, string accion,long idEmpresa)
{
try
{
_dao.ValidarPermiso(idPerfil,idOpcion,accion,idEmpresa);
}
catch (Exception e)
{
log.Error(e);
throw new Exception(e.Message);
}
}
/// <summary>
/// Permite validar los permisos para actualizar o agregar
/// registros esto por rol de usuario
/// </summary>
/// <param name="id">Identificador para cada tabla</param>
/// <param name="idPerfil">Identificador del perfil de usuario</param>
/// <param name="idOpcion">Identificador de la opcion</param>
/// <param name="accion">código del permiso</param>
/// <param name="idEmpresa">Identificador de la empresa</param>
public void ValidarSave(long id, long idPerfil, long idOpcion,long idEmpresa)
{
try
{
_dao.ValidarSave(id,idPerfil,idOpcion,idEmpresa);
}
catch (Exception e)
{
log.Error(e);
throw new Exception(e.Message);
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace _152802029_1
{
public class Koltuk
{
public string Ad { get; set; }
public string Soyad{ get; set; }
public int KoltukNo { get; set; }
public Koltuk Next;
public bool DolulukDurumu;
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BlackJackDudekGueguen.Model
{
class Deck
{
public List<Card> Cards { get; set; }
public Deck()
{
this.Cards = new List<Card>();
CreateDeck();
ShuffleDeck();
}
public void CreateDeck()
{
//Le nombre de paquet nécessaire
int cardPackages = 6;
//On boucle le nombre de paquet nécessaire
for (int packageNumber = 0; packageNumber < cardPackages; packageNumber++)
{
//A partir d'ici on rempli un paquet
//4 couleur, on boucle 4 fois de 1 à 4
for (int color = 1; color < 5; color++)
{
//13 cartes par couleur, on boucle 13 fois
for (int number = 1; number < 14; number++)
{
//on ajoute la carte créée dans le deck
Cards.Add(new Card(color, number));
}
}
}
}
public void ShuffleDeck()
{
//code de randomisation trouvé sur internet
//le deck de carte qui sera retourné une fois mélangé
List<Card> randomizedDeck = new List<Card>();
//notre valeur random
Random r = new Random();
//on choisi de façon random la position de la cutCard entre 50 et 80%
//Dans 6 paquets, il y a 312 cartes, donc 50% vaut 156 et 80% vaut 249,6 donc 250
int cutCard = r.Next(156, 250);
bool cutCardIsSet = false;
int randomIndex = 0;
while (this.Cards.Count > 0)
{
//Si le nouveau deck n'a pas encore de cut card
//on fait 312 - cutCard car sinon la cut card se retrouverais vers le haut du paquet
if(randomizedDeck.Count == (312 - cutCard))
{
randomizedDeck.Add(new Card(0, 0));
cutCardIsSet = true;
}
else
{
//on choisi une carte random du premier deck
randomIndex = r.Next(0, this.Cards.Count);
//on la copie dans le second
randomizedDeck.Add(this.Cards[randomIndex]);
//puis on la supprime du premier
this.Cards.RemoveAt(randomIndex);
}
}
//On brule les 5 premières cartes
for(int burn = 0; burn < 5; burn++)
{
}
//une fois que toute les cartes on été tirées,
//on remplace le premier deck par le deck mélangé
this.Cards = randomizedDeck;
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class granadaHumo : MonoBehaviour {
public GameObject avion;
public ParticleSystem humo;
public GameObject Player;
bool destruir;
// Use this for initialization
void Start ()
{
GetComponent<Rigidbody>().velocity = transform.up * 20;
GetComponent<Rigidbody>().AddForce(transform.right * 60);
StartCoroutine(llamar());
}
// Update is called once per frame
void Update ()
{
if(humo.isStopped && !destruir)
{
destruir = true;
StartCoroutine(desaparecer());
}
}
IEnumerator desaparecer()
{
yield return new WaitForSeconds(5);
Destroy(gameObject);
}
IEnumerator llamar()
{
yield return new WaitForSeconds(5);
var ataque = (GameObject)Instantiate(avion, transform.position, Quaternion.Euler(0,0,0));
ataque.GetComponent<avion>().poder = Player.GetComponent<Hero>().saludMax*ataque.GetComponent<avion>().poder/104;
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace PyFarmaceutica.Reportes.entidades
{
public class Stock
{
public int IdStock { get; set; }
public int IdSuministro { get; set; }
public string Suministro { get; set; }
public string Descripcion { get; set; }
public int StockDisponible { get; set; }
public int StockMinimo { get; set; }
}
}
|
// --------------------------------
// <copyright file="CarInventoryViewDao.cs" >
// © 2013 KarzPlus Inc.
// </copyright>
// <author>Kenneth Escobar</author>
// <summary>
// CarMake Data Layer Object.
// </summary>
// ---------------------------------
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using KarzPlus.Data.Common;
using KarzPlus.Entities;
using KarzPlus.Entities.ExtensionMethods;
namespace KarzPlus.Data
{
/// <summary>
/// This class connects to the CarInventoryView
/// </summary>
public sealed class CarInventoryViewDao : BaseDao
{
/// <summary>
/// Searches for CarMake
/// </summary>
/// <param name="item" />
/// <returns>An IEnumerable set of CarMake</returns>
public static IEnumerable<CarInventoryView> Search(CarInventoryViewSearch item)
{
List<SqlParameter> parameters
= new List<SqlParameter>
{
new SqlParameter("@InventoryId", item.InventoryId),
new SqlParameter("@ModelId", item.ModelId),
new SqlParameter("@CarYear", item.CarYear),
new SqlParameter("@Quantity", item.Quantity),
new SqlParameter("@LocationId", item.LocationId),
new SqlParameter("@Color", item.Color),
new SqlParameter("@Price", item.Price),
new SqlParameter("@InventoryDeleted", item.InventoryDeleted),
new SqlParameter("@makeid", item.MakeId),
new SqlParameter("@ModelName", item.ModelName),
new SqlParameter("@ModelDeleted", item.ModelDeleted),
new SqlParameter("@MakeName", item.MakeName),
new SqlParameter("@MakeDeleted", item.MakeDeleted),
new SqlParameter("@Manufacturer", item.Manufacturer),
new SqlParameter("@Address", item.Address),
new SqlParameter("@City", item.City),
new SqlParameter("@State", item.State),
new SqlParameter("@LocationName", item.LocationName),
new SqlParameter("@Zip", item.Zip),
new SqlParameter("@LocationDeleted", item.LocationDeleted)
};
if( item.CarImage != null)
{
parameters.Add(new SqlParameter("@CarImage", item.CarImage));
}
DataSet set = DataManager.ExecuteProcedure(KarzPlusConnectionString, "PKP_GetVKP_CarInventory", parameters);
IEnumerable<DataRow> dataRows = set.GetRowsFromDataSet();
return ConvertToEntityObject(dataRows);
}
/// <summary>
/// Converts an IEnumerable set of DataRows to an IEnumerable of CarMake
/// </summary>
/// <param name="dataRows" />
/// <returns />
private static IEnumerable<CarInventoryView> ConvertToEntityObject(IEnumerable<DataRow> dataRows)
{
return dataRows.Select(row => new CarInventoryView
{
InventoryId = row.GetValue<int?>("InventoryId"),
ModelId = row.GetValue<int?>("ModelId"),
CarYear = row.GetValue<int?>("CarYear"),
Quantity = row.GetValue<int?>("Quantity"),
LocationId = row.GetValue<int?>("LocationId"),
Color = row.GetValue<string>("Color").TrimSafely(),
Price = row.GetValue<decimal?>("Price"),
InventoryDeleted = row.GetValue<bool?>("InventoryDeleted"),
MakeId = row.GetValue<int?>("MakeId"),
ModelName = row.GetValue<string>("ModelName").TrimSafely(),
CarImage = row.GetValue<byte[]>("CarImage"),
ModelDeleted = row.GetValue<bool?>("ModelDeleted"),
MakeName = row.GetValue<string>("MakeName").TrimSafely(),
MakeDeleted = row.GetValue<bool?>("MakeDeleted"),
Manufacturer = row.GetValue<string>("Manufacturer").TrimSafely(),
Address = row.GetValue<string>("Address").TrimSafely(),
City = row.GetValue<string>("City").TrimSafely(),
State = row.GetValue<string>("State").TrimSafely(),
LocationName = row.GetValue<string>("LocationName").TrimSafely(),
Zip = row.GetValue<string>("Zip").TrimSafely(),
LocationDeleted = row.GetValue<bool?>("LocationDeleted")
});
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using TriodorArgeProject.Entities.EntityClasses;
using TriodorArgeProject.Service.Managers;
using TriodorArgeProject.WebUI.Models;
namespace TriodorArgeProject.WebUI.Controllers
{
public class DashController : Controller
{
private ProjectManager projectManager = new ProjectManager();
private PersonnelManager personnelManager = new PersonnelManager();
private SupportProjectManager supportProjectManager = new SupportProjectManager();
private SupportProjectsCostManager supportProjectCostManager = new SupportProjectsCostManager();
DashboardViewModel dashboardViewModel = new DashboardViewModel();
// GET: Dash
public ActionResult Dashboard()
{
dashboardViewModel.Projects = projectManager.List();
dashboardViewModel.SuppProjectCosts = supportProjectCostManager.List();
dashboardViewModel.SuppProjects = supportProjectManager.List();
dashboardViewModel.Personnels = personnelManager.List();
return View(dashboardViewModel);
}
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Security_System : MonoBehaviour {
public GameObject towerCenter, doorsLab, doorForest;
private bool doorsState, towers;
private Animator animDoorsLab, animDoorForest;
public Tower_System tower1, tower2, tower3;
// Start is called before the first frame update
void Start() {
doorsState = false;
towers = false;
animDoorsLab = doorsLab.GetComponent<Animator>();
animDoorForest = doorForest.GetComponent<Animator>();
}
// Update is called once per frame
void Update() {
Debug.Log(towers + " " + tower1.towerState + " " + tower2.towerState + " " + tower3.towerState + " " + doorsState);
if (towers == false) {
PanelInteraction();
} else if (towers == true) {
OpenDoors();
}
}
private void PanelInteraction () {
if (tower1.towerState == true) {
if (tower1.towerState == true) {
if (tower1.towerState == true) {
towers = true;
}
}
}
}
private void OpenDoors () {
animDoorsLab.SetBool("Open", true);
doorsState = true;
}
}
|
using System;
namespace MultiCommentCollector.Models
{
[Serializable]
public class Setting
{
#region Singleton
private static Setting instance;
public static Setting Instance => instance ??= new();
public static void SetInstance(Setting inst) => instance = inst;
#endregion
/// <summary>
/// MainWindow
/// </summary>
public WindowRect MainWindow { get; set; } = new(800, 600, 0, 0);
/// <summary>
/// LogWindow
/// </summary>
public WindowRect LogWindow { get; set; } = new(400, 300, 0, 0);
/// <summary>
/// Servers
/// </summary>
public Server Servers { get; set; } = new();
/// <summary>
/// ArrayLimits
/// </summary>
public ArrayLimit ArrayLimits { get; set; } = new();
/// <summary>
/// IsPaneOpen
/// </summary>
public Pane Pane { get; set; } = new();
/// <summary>
/// Theme
/// </summary>
public Theme Theme { get; set; } = new();
}
}
|
using System;
namespace GARITS.Models
{
public class User
{
public string username { get; set; }
public string firstname { get; set; }
public string lastname { get; set; }
public string role { get; set; }
public float rate { get; set; }
}
}
|
using System;
using System.Data;
using DevExpress.Utils;
using DevExpress.XtraEditors.Controls;
using DevExpress.XtraEditors.Repository;
using TLF.Framework.Config;
using TLF.Framework.Utility;
namespace TLF.Framework.ControlLibrary
{
/// <summary>
///
/// </summary>
public static class ControlUtil
{
#region :: MakeComboBoxCell(+4 Overloading) :: ComboBox Cell을 만듭니다.(CustomRowCellEditForEditing Event에서만 사용합니다.)
/// <summary>
/// ComboBox Cell을 만듭니다.(CustomRowCellEditForEditing Event에서만 사용합니다.)
/// </summary>
/// <param name="valueList">Value가 될 배열</param>
/// <param name="displayList">Text가 될 배열</param>
/// <returns></returns>
public static RepositoryItem MakeComboBoxCell(object[] valueList, string[] displayList)
{
return MakeComboBoxCell(valueList, displayList, false, false);
}
/// <summary>
/// ComboBox Cell을 만듭니다.(CustomRowCellEditForEditing Event에서만 사용합니다.)
/// </summary>
/// <param name="valueList">Value가 될 배열</param>
/// <param name="displayList">Text가 될 배열</param>
/// <param name="showAllItemVisible">전체선택 숨김/보임</param>
/// <param name="showCodeColumnVisible">Code Column 숨김/보임</param>
/// <remarks>
/// 2008-12-17 최초생성 : 황준혁
/// 변경내역
///
/// </remarks>
public static RepositoryItem MakeComboBoxCell(object[] valueList, string[] displayList, bool showAllItemVisible, bool showCodeColumnVisible)
{
if (valueList.Length != displayList.Length)
return null;
using (DataTable dt = new DataTable())
{
dt.Columns.Add(AppConfig.VALUEMEMBER);
dt.Columns.Add(AppConfig.DISPLAYMEMBER);
for (int idx = 0; idx < valueList.Length; idx++)
{
DataRow dr = dt.NewRow();
dr[AppConfig.VALUEMEMBER] = valueList[idx].ToString().Trim();
dr[AppConfig.DISPLAYMEMBER] = displayList[idx].Trim();
dt.Rows.Add(dr);
}
return MakeComboBoxCell(dt, showAllItemVisible, showCodeColumnVisible, AppConfig.VALUEMEMBER, AppConfig.DISPLAYMEMBER);
}
}
/// <summary>
/// ComboBox Cell을 만듭니다.(CustomRowCellEditForEditing Event에서만 사용합니다.)
/// </summary>
/// <param name="dt">Datasource 가 될 DataTable</param>
/// <remarks>
/// 2008-12-17 최초생성 : 황준혁
/// 변경내역
///
/// </remarks>
public static RepositoryItem MakeComboBoxCell(DataTable dt)
{
return MakeComboBoxCell(dt, false, false);
}
/// <summary>
/// ComboBox Cell을 만듭니다.(CustomRowCellEditForEditing Event에서만 사용합니다.)
/// </summary>
/// <param name="dt">Datasource 가 될 DataTable</param>
/// <param name="showAllItemVisible">전체선택 숨김/보임</param>
/// <param name="showCodeColumnVisible">Code Column 숨김/보임</param>
/// <remarks>
/// 2008-12-17 최초생성 : 황준혁
/// 변경내역
///
/// </remarks>
public static RepositoryItem MakeComboBoxCell(DataTable dt, bool showAllItemVisible, bool showCodeColumnVisible)
{
return MakeComboBoxCell(dt, showAllItemVisible, showCodeColumnVisible, AppConfig.VALUEMEMBER, AppConfig.DISPLAYMEMBER);
}
/// <summary>
/// ComboBox Cell을 만듭니다.(CustomRowCellEditForEditing Event에서만 사용합니다.)
/// </summary>
/// <param name="dt">Datasource 가 될 DataTable</param>
/// <param name="showAllItemVisible">전체선택 숨김/보임</param>
/// <param name="showCodeColumnVisible">Code Column 숨김/보임</param>
/// <param name="valueMember">ValueMember 명</param>
/// <param name="displayMember">DisplayMemeber 명</param>
/// <returns></returns>
public static RepositoryItem MakeComboBoxCell(DataTable dt, bool showAllItemVisible, bool showCodeColumnVisible, string valueMember, string displayMember)
{
RepositoryItemLookUpEdit edit = new RepositoryItemLookUpEdit();
DataRow dr;
if (showAllItemVisible)
{
dr = dt.NewRow();
dr[valueMember] = "";
dr[displayMember] = "";
dt.Rows.InsertAt(dr, 0);
}
edit.Appearance.Font = ControlConfig.DEFAULTFONT;
edit.NullText = "";
edit.DataSource = dt;
edit.ValueMember = valueMember;
edit.DisplayMember = displayMember;
string[] columns = AppUtil.GetColumnsFromDataTable(dt);
Array.ForEach(columns, column =>
{
edit.Columns.Add(column == valueMember ? CreateColumn(column, column, 70, HorzAlignment.Center, showCodeColumnVisible) : CreateColumn(column, column, 120, HorzAlignment.Default, true));
});
edit.ShowHeader = edit.Columns.Count < 3 ? false : true;
edit.TextEditStyle = TextEditStyles.DisableTextEditor;
return edit;
}
#endregion
#region :: MakeSpinEditCell :: SpinEdit Cell을 만듭니다.(CustomRowCellEditForEditing Event에서만 사용합니다.)
/// <summary>
/// SpinEdit Cell을 만듭니다.(CustomRowCellEditForEditing Event에서만 사용합니다.)
/// </summary>
/// <returns></returns>
public static RepositoryItem MakeSpinEditCell()
{
RepositoryItemSpinEdit edit = new RepositoryItemSpinEdit();
edit.Appearance.Font = ControlConfig.DEFAULTFONT;
edit.Mask.MaskType = DevExpress.XtraEditors.Mask.MaskType.Numeric;
//edit.Mask.EditMask = "n" + decimalPlace;
//edit.MaxLength = maxLength;
edit.Mask.UseMaskAsDisplayFormat = false;
return edit;
}
#endregion
///////////////////////////////////////////////////////////////////////////////////////////////
// Method(Private)
///////////////////////////////////////////////////////////////////////////////////////////////
#region :: CreateColumn :: LookUpColumn을 만듭니다.
/// <summary>
/// LookUpColumn을 만듭니다.
/// </summary>
/// <param name="fieldName">Field 명</param>
/// <param name="caption">Column Caption 명</param>
/// <param name="width">Column 너비</param>
/// <param name="align">Column 정렬</param>
/// <param name="visible">Column 숨김/보임</param>
/// <returns></returns>
/// <remarks>
/// 2008-12-17 최초생성 : 황준혁
/// 변경내역
///
/// </remarks>
internal static LookUpColumnInfo CreateColumn(string fieldName, string caption, int width, HorzAlignment align, bool visible)
{
LookUpColumnInfo column = new LookUpColumnInfo { FieldName = fieldName, Caption = caption, Width = width, Alignment = align, Visible = visible };
return column;
}
#endregion
}
}
|
using System;
namespace InterviewCake
{
//buy low sell highs
//getMaxProfit(stockPricesYesterday);
// returns 6 (buying for $5 and selling for $11)
public class StockPrice
{
// 10, 7 buy=10 sell=7
// 10,7,5 buy=7 sell=5
// 10,7,5,8 buy=5 sell=8
int[] stockPricesYesterday = new int[]{ 10, 7, 5, 8, 11, 9 };
public StockPrice()
{
}
int getMaxProfit(int[] stocks)
{
int low = stocks [0];
int high = stocks [1];
int profit = high - low;
Console.WriteLine("low=" + low + " high=" + high + " profit=" + profit);
for (int i = 2; i < stocks.Length - 1; i++)
{
if (stocks [i - 1] < low)
low = stocks [i - 1];
if (stocks [i] - low > profit)
{
high = stocks [i];
profit = stocks [i] - low;
}
Console.WriteLine("low=" + low + " high=" + high + " profit=" + profit);
}
return 0;
}
public void test()
{
getMaxProfit(stockPricesYesterday);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using BrainDuelsLib.widgets;
using BrainDuelsLib.web;
using UnityEngine;
using Assets;
public enum InputMethod
{
Desktop, Mobile
};
public interface IBoardScript
{
void SetOnUserTogglePoint(Action<Point> p);
void ChangeStone(int x, int y, Stone stone);
void SetLastMove(int x, int y);
void DeleteLastMove();
void Init(int size);
void SetAimBlack();
void SetAimWhite();
void SetAimInvisible();
} |
using System;
using System.Collections.Generic;
using System.Linq;
using Framework.Entities;
using Microsoft.AspNetCore.Mvc;
using Sql;
namespace WebAPI.Controllers
{
[Route("[controller]")]
public class RepositoriesController : Controller
{
private readonly GitHubRepoContext context;
public RepositoriesController(GitHubRepoContext context)
{
this.context = context;
}
// GET /repositories
/// <summary>
/// Returns all repositories stored in dbo.GitHubRepo table in SQL Server
/// </summary>
/// <returns></returns>
[HttpGet]
public IEnumerable<GitHubRepo> Get()
{
return context.GitHubRepos.ToList();
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace FPModel.Entity
{
public class CustomerGradeApp
{
public virtual Guid CustomerGradeAppId { get; set; }
public virtual Guid CustomerId { get; set; }
public virtual Grade Grade { get; set; }
public virtual App App { get; set; }
}
}
|
namespace Kraken.Services
{
public interface IOctopusAuthenticationProxy
{
bool Login(string username, string password);
string CreateApiKey();
}
} |
using System;
namespace ClassLibrary2
{
public class Veterinar : Uposlenik
{
private string fakultet;
public string Fakultet { get => fakultet; set => fakultet = value; }
public Veterinar(string i, string p, DateTime dr, string mr, string JMBG, string u, string ps, string em, DateTime datum, string faks)
: base(i, p, dr, mr, JMBG, u, ps, em, datum)
{
fakultet = faks;
}
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class ItemDescription : MonoBehaviour
{
public Text text = null;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
}
public void init(ProcedualSwordModel model)
{
text.text = "Name: " + model.name + "\n"
+ "Damage: " + model.damage;
}
}
|
namespace DoE.Quota.Repositories.BusinessServices
{
using Services.Contracts;
public class InventoryService : IInventoryService
{
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace ProyectoASPEmenic.Paginas.Servicios
{
public partial class Transporte : System.Web.UI.Page
{
Conexion conexion = new Conexion();
public object MessageBox { get; private set; }
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnLimpiarTransporte_Click(object sender, EventArgs e)
{
LimpiarTransporte();
}
protected void btnGuardarTransporte_Click(object sender, EventArgs e)
{
//recuperando entradas
Boolean Cabezal = checkCabezal.Checked;
Boolean Furgon = checkFurgon.Checked;
string Placa = txtPlaca.Text;
string Equipo = txtvehiculoequipo.Text;
string Descripcion = txtDescripcion.Text;
int Resultado_placa = 0;
string query;
if (Cabezal == false && Furgon == false)
{
ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "alertMessage", "alert('Debe seleccionar una opción')", true);
}
else if (Cabezal == true && Furgon == true)
{
ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "alertMessage", "alert('Debe seleccionar solo una opción')", true);
}
else
{
query = "SELECT COUNT(Placa) FROM transporte WHERE Placa = '" + Placa + "'";
conexion.IniciarConexion();
conexion.RecibeQuery(query);
while (conexion.reg.Read())
{
Resultado_placa = conexion.reg.GetInt32(0);
}
conexion.reg.Close();
conexion.CerrarConexion();
if (Resultado_placa == 1)
{
ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "alertMessage", "alert('El numero de Placa ya existente.')", true);
}
else
{
//consulta que se ingresa a la base de datos
query = "INSERT INTO `transporte` (`Placa`, `Descripcion`, `Equipo`, `Furgon`, `Cabezal`, `IdEmenic`) " +
"VALUES('" + Placa + "','" + Descripcion + "','" + Equipo + "'," + Furgon + "," + Cabezal + ", 1)";
//enviar consulta a Mysql
conexion.IniciarConexion();
conexion.EnviarQuery(query);
conexion.CerrarConexion();
ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "alertMessage", "alert('Se ha insertado con exito.')", true);
Response.Redirect("~/Paginas/Transporte/ListadoTransporte.aspx");
}
}
}
protected void LimpiarTransporte()
{
checkCabezal.Checked = false;
checkFurgon.Checked = false;
txtDescripcion.Text = "";
txtPlaca.Text = "";
txtvehiculoequipo.Text = "";
}
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class SidescrollManager2 : MonoBehaviour
{
// Use this for initialization
void Start()
{
BGMManager.instance.ToggleLoop();
BGMManager.instance.PlayBGM("PianoImprov");
StartCoroutine(BGMManager.instance.FadeIn());
UIManager.instance.FadeIn();
GameController.instance.TogglePlayAltSFX(true);
GameController.instance.ResetPickups();
}
// Update is called once per frame
void Update()
{
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ShootemUp
{
interface IQuadtreeElement
{
double TopBound { get; }
double LowerBound { get; }
double LeftBound { get; }
double RightBound { get; }
}
}
|
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using StoreSample.Catalog.Alpha.Exceptions;
namespace StoreSample.Catalog.Alpha.Filters
{
public class ExceptionHandlerFilter : ExceptionFilterAttribute
{
private ExceptionContext _context;
public override void OnException(ExceptionContext context)
{
_context = context;
_context.ExceptionHandled = true;
switch (_context.Exception)
{
case ProductNotFoundException productNotFound when _context.Exception is ProductNotFoundException:
SetResult(StatusCodes.Status404NotFound, productNotFound.Message);
break;
case SKUAlreadyInUseException skuInUse when _context.Exception is SKUAlreadyInUseException:
SetResult(StatusCodes.Status400BadRequest, skuInUse.Message);
break;
case OperationException operationException when _context.Exception is OperationException:
SetResult(StatusCodes.Status500InternalServerError, operationException.Message);
break;
default:
SetResult(StatusCodes.Status500InternalServerError, "Failed to perform requested operation.");
break;
}
}
private void SetResult(int statusCode, string message)
{
var response = _context.HttpContext.Response;
response.StatusCode = statusCode;
response.ContentType = "application/json";
_context.Result = new JsonResult(message);
}
}
} |
namespace Dealership.Engine.Parsers
{
using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using Contracts.Parsers;
public class CommandParser : ICommandParser
{
private const char SplitCommandSymbol = ' ';
private const string CommentOpenSymbol = "{{";
private const string CommentCloseSymbol = "}}";
private const string RegExString = "{{.+(?=}})}}";
private List<string> parameters;
private Regex regex;
public CommandParser()
{
this.regex = new Regex(RegExString);
}
public ICollection<string> Parse(string value)
{
var indexOfFirstSeparator = value.IndexOf(SplitCommandSymbol);
var indexOfOpenComment = value.IndexOf(CommentOpenSymbol);
var indexOfCloseComment = value.IndexOf(CommentCloseSymbol);
this.parameters = new List<string>();
if (indexOfFirstSeparator < 0)
{
this.parameters.Add(value);
return this.parameters;
}
this.parameters.Add(value.Substring(0, indexOfFirstSeparator));
if (indexOfOpenComment >= 0)
{
this.parameters.Add(value.Substring(indexOfOpenComment + CommentOpenSymbol.Length, indexOfCloseComment - CommentCloseSymbol.Length - indexOfOpenComment));
value = regex.Replace(value, string.Empty);
}
this.parameters.AddRange(value.Substring(indexOfFirstSeparator + 1).Split(new[] { SplitCommandSymbol }, StringSplitOptions.RemoveEmptyEntries));
return this.parameters;
}
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Kursovay
{
public partial class Form10 : Form
{
public Form10()
{
InitializeComponent();
}
string connectionString = @"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\kandr\Source\Repos\Kursovay\Kursovay\Database1.mdf;Integrated Security=True";
SqlConnection sqlconnect;
private async void button1_Click(object sender, EventArgs e)
{
try
{
DataSet ds = new DataSet();
// this.продуктыTableAdapter.Fill(this.database1DataSet1.Продукты);
sqlconnect = new SqlConnection(connectionString);
SqlDataAdapter da = new SqlDataAdapter();
// SqlCommand comand = new SqlCommand("SELECT [database1DataSet1.Продукты].Наименование,[database1DataSet1.Продукты].Калорийность FROM [database1DataSet1.Продукты] WHERE [database1DataSet1.Продукты].Калорийность<" + kkal.ToString() + "", sqlconnect);
da.SelectCommand = new SqlCommand("SELECT [Продукты].Наименование,[Продукты].Калорийность_Ккал FROM [Продукты] WHERE [Продукты].Калорийность_Ккал <" + textBox1.Text.ToString() ,sqlconnect);
sqlconnect.Open();
da.Fill(ds, "Продукты");
dataGridView1.DataSource = ds.Tables[0];
da.Dispose();
sqlconnect.Dispose();
ds.Dispose();
}
catch (FormatException)
{
MessageBox.Show("Не верный формат или не введено значение в поле!!");
}
}
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
}
private async void Form10_Load(object sender, EventArgs e)
{
}
private async void button2_Click(object sender, EventArgs e)
{
sqlconnect = new SqlConnection(connectionString);
await sqlconnect.OpenAsync();
SqlCommand comand = new SqlCommand("SELECT *FROM [Продукты],[Рецепт] WHERE [Продукты].Id=[Рецепт].Код_продукта", sqlconnect);
SqlDataReader sqlReader = comand.ExecuteReader();
List<string[]> data = new List<string[]>();
try
{
sqlReader = await comand.ExecuteReaderAsync();//считыв таблицу
while (await sqlReader.ReadAsync())
{
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message.ToString(), ex.Message.ToString(), MessageBoxButtons.OK, MessageBoxIcon.Error);
}
finally
{
if (sqlReader != null)
sqlReader.Close();
}
}
private void bindingNavigator1_RefreshItems(object sender, EventArgs e)
{
}
private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
}
private void оПрограммеToolStripMenuItem_Click(object sender, EventArgs e)
{
MessageBox.Show("Приложение представляет из себя автоматизированную информационные систему технологий создания блюд." +
"С его помощю Вы сможите удалять и добавлять данные в базу, производить поиск рецептов блюд,их авторов,выбирать рецепты из представленных категорий, искать блюда меньше заданной калорийности!");
}
private void выходToolStripMenuItem_Click(object sender, EventArgs e)
{
Close();
}
private void главноеМенюToolStripMenuItem_Click(object sender, EventArgs e)
{
Form1 newForm = new Form1();
newForm.Show(); Hide();
}
private void поставщикToolStripMenuItem_Click(object sender, EventArgs e)
{
Form2 newForm = new Form2();
newForm.Show(); Hide();
}
private void продуктыToolStripMenuItem_Click(object sender, EventArgs e)
{
Form3 newForm = new Form3();
newForm.Show(); Hide();
}
private void рецептToolStripMenuItem_Click(object sender, EventArgs e)
{
Form4 newForm = new Form4();
newForm.Show(); Hide();
}
private void авторToolStripMenuItem_Click(object sender, EventArgs e)
{
Form7 newForm = new Form7();
newForm.Show(); Hide();
}
private void ингредиентыToolStripMenuItem_Click(object sender, EventArgs e)
{
Form8 newForm = new Form8();
newForm.Show(); Hide();
}
private void группыПродуктовToolStripMenuItem_Click(object sender, EventArgs e)
{
Form5 newForm = new Form5();
newForm.Show(); Hide();
}
private void способПриготовленияToolStripMenuItem_Click(object sender, EventArgs e)
{
}
private void прайслистПоставщикаToolStripMenuItem_Click(object sender, EventArgs e)
{
Form11 newForm = new Form11();
newForm.Show(); Hide();
}
private void рецептыБлюдToolStripMenuItem_Click(object sender, EventArgs e)
{
Form12 newForm = new Form12();
newForm.Show(); Hide();
}
private void списокБлюдМинимальнойКалорийностиToolStripMenuItem_Click(object sender, EventArgs e)
{
Form10 newForm = new Form10();
newForm.Show(); Hide();
}
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Media;
using System.Net;
using System.Net.WebSockets;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace 货币价格监控
{
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
}
string path = AppDomain.CurrentDomain.BaseDirectory + "bj.wav";
SoundPlayer player = new SoundPlayer();
#region GET请求
/// <summary>
/// GET请求
/// </summary>
/// <param name="Url">网址</param>
/// <returns></returns>
public static string GetUrl(string Url, string charset)
{
try
{
//设置支持的ssl协议版本,这里我们都勾选上常用的几个
//ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3;
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url); //创建一个链接
string COOKIE = "zlan=cn; zloginStatus=; zJSESSIONID=6FE4FD3AF4111330B5DAF4564C1C0DDC";
request.UserAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.108 Safari/537.36";
request.Referer = "";
request.AllowAutoRedirect = true;
request.Headers.Add("Cookie", COOKIE);
request.KeepAlive = true;
HttpWebResponse response = request.GetResponse() as HttpWebResponse; //获取反馈
StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.GetEncoding(charset)); //reader.ReadToEnd() 表示取得网页的源码流 需要引用 using IO
string content = reader.ReadToEnd();
reader.Close();
response.Close();
return content;
}
catch (System.Exception ex)
{
MessageBox.Show(ex.ToString());
}
return "";
}
#endregion
#region 主程序
public void run()
{
try
{
if (textBox1.Text == "" || textBox2.Text == "" )
{
MessageBox.Show("请输入差值");
return;
}
string huobiHtml = GetUrl("https://www.okex.com/v3/c2c/tradingOrders/book?t=1570702053211&side=sell&baseCurrency=btc"eCurrency=cny&userType=certified&paymentMethod=all", "utf-8");
string binanceHtml = GetUrl("https://www.binance.com/api/v3/depth?symbol=MDXUSDT&limit=1000", "utf-8");
string huobiPrice = Regex.Match(huobiHtml, @"""price"":""([\s\S]*?)""").Groups[1].Value;
string binancePrice = Regex.Match(binanceHtml, @"\[\[""([\s\S]*?)""").Groups[1].Value;
if (huobiPrice != "" && binancePrice != "")
{
label6.Text = huobiPrice;
label9.Text = binancePrice;
decimal huobi = Convert.ToDecimal(huobiPrice);
decimal binance = Convert.ToDecimal(binancePrice);
if ((huobi - binance) > Convert.ToInt32(textBox1.Text))
{
textBox5.Text += DateTime.Now.ToString() + " : 火币的价格为" + huobi+ "....币安的价格为" + binance + "..火币高于币安" + (huobi - binance) + "\r\n";
player.SoundLocation = path;
player.Load();
player.Play();
}
if ((binance - huobi) > Convert.ToInt32(textBox2.Text))
{
textBox5.Text += DateTime.Now.ToString() + " : 火币的价格为" + huobi + "....币安的价格为" + binance + "..币安高于火币" + (binance - huobi) + "\r\n";
player.SoundLocation = path ;
player.Load();
player.Play();
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
#endregion
async static void ttt()
{
try
{
ClientWebSocket webSocket = new ClientWebSocket();
CancellationToken cancellation = new CancellationToken();
//建立连接
await webSocket.ConnectAsync(new Uri("wss://www.huobi.ci/-/s/pro/ws"), cancellation);
byte[] bsend = Encoding.Default.GetBytes("\"{\"sub\":\"market.mdxusdt.kline.1min\",\"id\":\"id10\"}\"");
//发送数据
await webSocket.SendAsync(new ArraySegment<byte>(bsend), WebSocketMessageType.Binary, true, cancellation);
//await webSocket.CloseAsync(WebSocketCloseStatus.NormalClosure, "1", cancellation);
//释放资源
// webSocket.Dispose();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
async static void run1()
{
ClientWebSocket cln = new ClientWebSocket();
cln.ConnectAsync(new Uri("wss://www.huobi.ci/-/s/pro/ws"), new CancellationToken()).Wait();
byte[] bytess = Encoding.Default.GetBytes("{\"sub\":\"market.mdxusdt.kline.1min\",\"id\":\"id10\"}");
cln.SendAsync(new ArraySegment<byte>(bytess), WebSocketMessageType.Text, true, new CancellationToken()).Wait();
// string returnValue = await GetAsyncValue(cln);//异步方法
string returnValue = await GetAsyncValue(cln);//异步方法
MessageBox.Show(returnValue);
}
public static async Task<string> GetAsyncValue(ClientWebSocket clientWebSocket)
{
string returnValue = null;
ArraySegment<Byte> buffer = new ArraySegment<byte>(new Byte[8192]);
WebSocketReceiveResult result = null;
using (var ms = new MemoryStream())
{
do
{
result = await clientWebSocket.ReceiveAsync(buffer, CancellationToken.None);
ms.Write(buffer.Array, buffer.Offset, result.Count);
}
while (!result.EndOfMessage);
ms.Seek(0, SeekOrigin.Begin);
if (result.MessageType == WebSocketMessageType.Text)
{
using (var reader = new StreamReader(ms, Encoding.UTF8))
{
returnValue = reader.ReadToEnd();
//Console.WriteLine(returnValue);
}
}
}
return returnValue;
}
Thread thread;
private void button1_Click(object sender, EventArgs e)
{
//if (thread == null || !thread.IsAlive)
//{
// thread = new Thread(run);
// thread.Start();
// Control.CheckForIllegalCrossThreadCalls = false;
//}
//timer1.Start();
run1();
}
private void button2_Click(object sender, EventArgs e)
{
timer1.Stop();
}
private void timer1_Tick(object sender, EventArgs e)
{
if (thread == null || !thread.IsAlive)
{
thread = new Thread(run);
thread.Start();
Control.CheckForIllegalCrossThreadCalls = false;
}
}
private void Form2_FormClosing(object sender, FormClosingEventArgs e)
{
DialogResult dr = MessageBox.Show("确定要关闭吗?", "关闭", MessageBoxButtons.OKCancel, MessageBoxIcon.Question);
if (dr == DialogResult.OK)
{
Environment.Exit(0);
//System.Diagnostics.Process.GetCurrentProcess().Kill();
}
else
{
e.Cancel = true;//点取消的代码
}
}
private void linkLabel2_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
player.Stop();
}
private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
textBox5.Text = "";
}
}
}
|
using System.Threading.Tasks;
using WeatherService.Entities;
namespace WeatherService
{
public interface IWeatherService
{
Task<WeatherForecast> GetWeatherForecastAsync(string city);
Task<WeatherForecast> GetWeatherForecastAsync(int cityId);
}
} |
using System;
using System.IO;
using System.Xml;
using System.Collections;
using System.Reflection;
using Server;
using Server.Mobiles;
using Server.Items;
using Server.Engines.Quests;
using Server.Engines.Quests.TheGraveDigger;
using Server.Commands;
namespace Server
{
public class GenerateGDQ
{
public GenerateGDQ()
{
}
public static void Initialize()
{
CommandSystem.Register( "GenGDQ", AccessLevel.Administrator, new CommandEventHandler( GenerateGDQ_OnCommand ) );
}
[Usage( "GenGDQ" )]
[Description( "Generates Grave Digger Quest" )]
public static void GenerateGDQ_OnCommand( CommandEventArgs e )
{
e.Mobile.SendMessage( "Please hold while the quest is being generated." );
GenDecore.CreateDecore();
GenMobiles.CreateMobiles();
GenSpawners.CreateSpawners();
e.Mobile.SendMessage( "Grave Digger Quest Generated." );
}
public class GenDecore
{
public GenDecore()
{
}
private static Queue m_Queue = new Queue();
public static bool FindDecore( Map map, Point3D p )
{
IPooledEnumerable eable = map.GetItemsInRange( p, 0 );
foreach ( Item item in eable )
{
if ( item is Stool )
{
int delta = item.Z - p.Z;
if ( delta >= -12 && delta <= 12 )
m_Queue.Enqueue( item );
}
}
eable.Free();
while ( m_Queue.Count > 0 )
((Item)m_Queue.Dequeue()).Delete();
return false;
}
public static void CreateDecore( Point3D pointLocation, Map mapLocation )
{
Point3D stool = new Point3D( 1545, 1768, 10 );
if ( !FindDecore( mapLocation, pointLocation ) )
{
if ( pointLocation == stool )
{
Stool sto = new Stool();
sto.Movable = false;
sto.MoveToWorld( pointLocation, mapLocation );
}
}
}
public static void CreateDecore( int xLoc, int yLoc, int zLoc, Map map )
{
CreateDecore( new Point3D( xLoc, yLoc, zLoc ), map);
}
public static void CreateDecoreFacet( Map map )
{
CreateDecore( 1545, 1768, 10, map );
}
public static void CreateDecore()
{
CreateDecoreFacet( Map.Felucca );
}
}
public class GenMobiles
{
public GenMobiles()
{
}
private static Queue m_Queue = new Queue();
public static bool FindMobile( Map map, Point3D p )
{
IPooledEnumerable eable = map.GetMobilesInRange( p, 0 );
foreach ( Mobile mob in eable )
{
if ( mob is BaseQuester )
{
int delta = mob.Z - p.Z;
if ( delta >= -12 && delta <= 12 )
m_Queue.Enqueue( mob );
}
}
eable.Free();
while ( m_Queue.Count > 0 )
((Mobile)m_Queue.Dequeue()).Delete();
return false;
}
public static void CreateMobiles( Point3D pointLocation, Map mapLocation )
{
Point3D theDrunk = new Point3D( 1432, 1734, 20 );
Point3D vincent = new Point3D( 1545, 1768, 10 );
Point3D linda = new Point3D( 2710, 2106, 0 );
Point3D boyfriend = new Point3D( 2712, 2104, 0 );
if ( !FindMobile( mapLocation, pointLocation ) )
{
TheDrunk td = new TheDrunk();
Vincent v = new Vincent();
Linda l = new Linda();
LindasBoyfriend bf = new LindasBoyfriend();
if ( pointLocation == theDrunk )
{
td.Direction = Direction.East;
td.Location = pointLocation;
td.Map = mapLocation;
World.AddMobile( td );
}
if ( pointLocation == vincent )
{
v.Direction = Direction.North;
v.Location = pointLocation;
v.Map = mapLocation;
World.AddMobile( v );
}
if ( pointLocation == boyfriend )
{
bf.Direction = Direction.South;
bf.Location = pointLocation;
bf.Map = mapLocation;
World.AddMobile( bf );
}
if ( pointLocation == linda )
{
l.Direction = Direction.East;
l.Location = pointLocation;
l.Map = mapLocation;
World.AddMobile( l );
}
l.BoyFriend = bf;
}
}
public static void CreateMobiles( int xLoc, int yLoc, int zLoc, Map map )
{
CreateMobiles( new Point3D( xLoc, yLoc, zLoc ), map);
}
public static void CreateMobilesFacet( Map map )
{
CreateMobiles( 1432, 1734, 20, map );
CreateMobiles( 1545, 1768, 10, map );
CreateMobiles( 2710, 2106, 0, map );
CreateMobiles( 2712, 2104, 0, map );
}
public static void CreateMobiles()
{
CreateMobilesFacet( Map.Felucca );
}
}
public class GenSpawners
{
//configuration
private const bool TotalRespawn = true;//Should we spawn them up right away?
private static TimeSpan MinTime = TimeSpan.FromMinutes( 3 );//min spawn time
private static TimeSpan MaxTime = TimeSpan.FromMinutes( 5 );//max spawn time
public GenSpawners()
{
}
private static Queue m_ToDelete = new Queue();
public static void ClearSpawners( int x, int y, int z, Map map )
{
IPooledEnumerable eable = map.GetItemsInRange( new Point3D( x, y, z ), 0 );
foreach ( Item item in eable )
{
if ( item is Spawner && item.Z == z )
m_ToDelete.Enqueue( item );
}
eable.Free();
while ( m_ToDelete.Count > 0 )
((Item)m_ToDelete.Dequeue()).Delete();
}
public static void CreateSpawners()
{
//Rares
PlaceSpawns( 1994, 3203, 0, "BloodLich" );
PlaceSpawns( 1185, 3608, 0, "YeastFarmer" );
PlaceSpawns( 742, 1152, 0, "LordYoshimitsu" );
PlaceSpawns( 3355, 293, 4, "Bacchus" );
}
public static void PlaceSpawns( int x, int y, int z, string types )
{
switch ( types )
{
case "BloodLich":
MakeSpawner( "BloodLich", x, y, z, Map.Felucca, true );
MinTime = TimeSpan.FromMinutes( 3 );
MaxTime = TimeSpan.FromMinutes( 5 );
break;
case "YeastFarmer":
MakeSpawner( "YeastFarmer", x, y, z, Map.Felucca, true );
MinTime = TimeSpan.FromMinutes( 3 );
MaxTime = TimeSpan.FromMinutes( 5 );
break;
case "LordYoshimitsu":
MakeSpawner( "LordYoshimitsu", x, y, z, Map.Felucca, true );
MinTime = TimeSpan.FromMinutes( 3 );
MaxTime = TimeSpan.FromMinutes( 5 );
break;
case "Bacchus":
MakeSpawner( "Bacchus", x, y, z, Map.Felucca, true );
MinTime = TimeSpan.FromMinutes( 3 );
MaxTime = TimeSpan.FromMinutes( 5 );
break;
default:
break;
}
}
private static void MakeSpawner( string types, int x, int y, int z, Map map, bool start )
{
ClearSpawners( x, y, z, map );
Spawner sp = new Spawner( types );
sp.Count = 1;
sp.Running = true;
sp.HomeRange = 15;
sp.MinDelay = MinTime;
sp.MaxDelay = MaxTime;
sp.MoveToWorld( new Point3D( x, y, z ), map );
}
}
}
}
|
namespace KPI.Model.Migrations
{
using System;
using System.Data.Entity.Migrations;
public partial class UpdateNotification : DbMigration
{
public override void Up()
{
RenameColumn(table: "dbo.Notifications", name: "DataID", newName: "KPIName");
RenameColumn(table: "dbo.Notifications", name: "CommentID", newName: "Period");
RenameColumn(table: "dbo.Notifications", name: "Content", newName: "Link");
AlterColumn("dbo.Notifications", "KPIName", c => c.String());
AlterColumn("dbo.Notifications", "Period", c => c.String());
}
public override void Down()
{
AlterColumn("dbo.Notifications", "Period", c => c.Int(nullable: false));
AlterColumn("dbo.Notifications", "KPIName", c => c.Int(nullable: false));
RenameColumn(table: "dbo.Notifications", name: "Link", newName: "Content");
RenameColumn(table: "dbo.Notifications", name: "Period", newName: "CommentID");
RenameColumn(table: "dbo.Notifications", name: "KPIName", newName: "DataID");
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.