text stringlengths 13 6.01M |
|---|
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using System;
namespace LighterApi
{
[Route("api/[controller]")]
[ApiController]
public class LogController : ControllerBase
{
private readonly ILogger<LogController> _logger;
//private readonly ILogger _myLogger;
public LogController(ILogger<LogController> logger)//ILoggerFactory loggerFactory
{
//日志的创建方式 直接注入/注入日志工厂类 再创建
_logger = logger;
//_myLogger = loggerFactory.CreateLogger("mylog");
//loggerFactory.CreateLogger<WeatherController>();
}
[HttpGet]
[Route("logtest1")]
public IActionResult Logtest1()
{
//_logger.LogTrace("LogTrace");
//_logger.LogDebug("LogDebug");
//_logger.LogInformation(new EventId(1001, "Log"), "Karl Log");
//_logger.LogWarning("LogWarning");
//_logger.LogError("LogError");
//_logger.LogCritical("LogCritical");
return Ok($"Test Log: {DateTime.Now}");
}
[HttpGet]
[Route("logtest2")]
public IActionResult Logtest2([FromQuery]string id)
{
return Ok();
//var routeInfo = ControllerContext.ToCtxString(id); _logger.LogInformation(1000, routeInfo);
//return ControllerContext.MyDisplayRouteInfo();
}
[HttpGet]
[Route("nlog")]
public IActionResult Test4()
{
//构造函数 直接注入 NLog._logger 报错
_logger.LogWarning("nlog warning");
return Ok();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
using Xamarin.Forms;
namespace CustomXamarinControls
{
public class CheckBox : View
{
/// <summary>
/// The checked state property.
/// </summary>
public static readonly BindableProperty CheckedProperty =
BindableProperty.Create(nameof(Checked), typeof(bool), typeof(CheckBox), false, BindingMode.TwoWay, propertyChanged: OnCheckedPropertyChanged);
/// <summary>
/// The checked text property.
/// </summary>
public static readonly BindableProperty CheckedTextProperty =
BindableProperty.Create(nameof(CheckedText), typeof(string), typeof(CheckBox), string.Empty, BindingMode.TwoWay);
/// <summary>
/// The unchecked text property.
/// </summary>
public static readonly BindableProperty UncheckedTextProperty =
BindableProperty.Create(nameof(UncheckedText), typeof(string), typeof(CheckBox), string.Empty);
/// <summary>
/// The default text property.
/// </summary>
public static readonly BindableProperty DefaultTextProperty =
BindableProperty.Create(nameof(DefaultText), typeof(string), typeof(CheckBox), string.Empty);
/// <summary>
/// Identifies the TextColor bindable property.
/// </summary>
///
/// <remarks/>
public static readonly BindableProperty TextColorProperty =
BindableProperty.Create(nameof(TextColor), typeof(Color), typeof(CheckBox), Color.Default);
public static readonly BindableProperty ColorProperty =
BindableProperty.Create(nameof(Color), typeof(Color), typeof(CheckBox), Color.Accent);
/// <summary>
/// The font size property
/// </summary>
public static readonly BindableProperty FontSizeProperty =
BindableProperty.Create(nameof(FontSize), typeof(double), typeof(CheckBox), -1.0);
/// <summary>
/// The font name property.
/// </summary>
public static readonly BindableProperty FontNameProperty =
BindableProperty.Create(nameof(FontName), typeof(string), typeof(CheckBox), string.Empty);
/// <summary>
/// The checked changed event.
/// </summary>
public event EventHandler<EventArgs<bool>> CheckedChanged;
/// <summary>
/// Gets or sets a value indicating whether the control is checked.
/// </summary>
/// <value>The checked state.</value>
public bool Checked
{
get
{
return this.GetValue<bool>(CheckedProperty);
}
set
{
if (this.Checked != value)
{
this.SetValue(CheckedProperty, value);
CheckedChanged?.Invoke(this, new EventArgs<bool>(value));
}
}
}
/// <summary>
/// Gets or sets a value indicating the checked text.
/// </summary>
/// <value>The checked state.</value>
/// <remarks>
/// Overwrites the default text property if set when checkbox is checked.
/// </remarks>
public string CheckedText
{
get
{
return this.GetValue<string>(CheckedTextProperty);
}
set
{
this.SetValue(CheckedTextProperty, value);
}
}
/// <summary>
/// Gets or sets a value indicating whether the control is checked.
/// </summary>
/// <value>The checked state.</value>
/// <remarks>
/// Overwrites the default text property if set when checkbox is checked.
/// </remarks>
public string UncheckedText
{
get
{
return this.GetValue<string>(UncheckedTextProperty);
}
set
{
this.SetValue(UncheckedTextProperty, value);
}
}
/// <summary>
/// Gets or sets the text.
/// </summary>
public string DefaultText
{
get
{
return this.GetValue<string>(DefaultTextProperty);
}
set
{
this.SetValue(DefaultTextProperty, value);
}
}
/// <summary>
/// Gets or sets the color of the text.
/// </summary>
/// <value>The color of the text.</value>
public Color TextColor
{
get
{
return this.GetValue<Color>(TextColorProperty);
}
set
{
this.SetValue(TextColorProperty, value);
}
}
public Color Color
{
get { return this.GetValue<Color>(ColorProperty); }
set { SetValue(ColorProperty, value); }
}
/// <summary>
/// Gets or sets the size of the font.
/// </summary>
/// <value>The size of the font.</value>
public double FontSize
{
get
{
return (double)GetValue(FontSizeProperty);
}
set
{
SetValue(FontSizeProperty, value);
}
}
/// <summary>
/// Gets or sets the name of the font.
/// </summary>
/// <value>The name of the font.</value>
public string FontName
{
get
{
return (string)GetValue(FontNameProperty);
}
set
{
SetValue(FontNameProperty, value);
}
}
/// <summary>
/// Gets the text.
/// </summary>
/// <value>The text.</value>
public string Text
{
get
{
return this.Checked
? (string.IsNullOrEmpty(this.CheckedText) ? this.DefaultText : this.CheckedText)
: (string.IsNullOrEmpty(this.UncheckedText) ? this.DefaultText : this.UncheckedText);
}
}
/// <summary>
/// Called when [checked property changed].
/// </summary>
/// <param name="bindable">The bindable.</param>
/// <param name="oldvalue">if set to <c>true</c> [oldvalue].</param>
/// <param name="newvalue">if set to <c>true</c> [newvalue].</param>
private static void OnCheckedPropertyChanged(BindableObject bindable, object oldValue, object newValue)
{
var checkBox = (CheckBox)bindable;
checkBox.Checked = (bool)newValue;
}
}
/// <summary>
/// Class BindableObjectExtensions.
/// </summary>
public static class BindableObjectExtensions
{
/// <summary>
/// Gets the value.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="bindableObject">The bindable object.</param>
/// <param name="property">The property.</param>
/// <returns>T.</returns>
public static T GetValue<T>(this BindableObject bindableObject, BindableProperty property)
{
return (T)bindableObject.GetValue(property);
}
}
/// <summary>
/// Generic event argument class
/// </summary>
/// <typeparam name="T">Type of the argument</typeparam>
public class EventArgs<T> : EventArgs
{
/// <summary>
/// Initializes a new instance of the <see cref="EventArgs"/> class.
/// </summary>
/// <param name="value">Value of the argument</param>
public EventArgs(T value)
{
this.Value = value;
}
/// <summary>
/// Gets the value of the event argument
/// </summary>
public T Value { get; private set; }
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
namespace FolderBackup.Server
{
public class User
{
public String username { get; set; }
public DirectoryInfo rootDirectory { get; set; }
static public User authUser(string username, string password, string token)
{
DatabaseManager db = DatabaseManager.getInstance();
User ret = db.getUser(username, password, token);
if (ret == null)
{
throw new Exception();
}
return ret;
}
static public string getSalt(string username)
{
DatabaseManager db = DatabaseManager.getInstance();
string salt = db.getSalt(username);
return salt;
}
static public bool register(string username, string password, string salt)
{
return DatabaseManager.getInstance().register(username, password, salt);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace HTB.Database.Views
{
public class qryAuftraggeberAction : tblAuftraggeberAktionRel
{
#region Property Declaration tblAktenIntActionType
private string _aktIntActionTypeCaption;
public string AktIntActionTypeCaption
{
get { return _aktIntActionTypeCaption; }
set { _aktIntActionTypeCaption = value; }
}
#endregion
#region Property Declaration tblAuftraggeber
private string _auftraggeberName1;
public string AuftraggeberName1
{
get { return _auftraggeberName1; }
set { _auftraggeberName1 = value; }
}
#endregion
}
}
|
using fileCrawlerWPF.Events;
using fileCrawlerWPF.Media;
using System;
using System.Windows.Controls;
namespace fileCrawlerWPF.Controls
{
/// <summary>
/// Interaction logic for FileImport.xaml
/// </summary>
public partial class FileImport : UserControl
{
private readonly string lastCheckedDirectory = null;
public event EventHandler Clear;
public event EventHandler<PathSelectedEventArgs> PathSelected;
public event EventHandler<FileSelectedEventArgs> RemoveFile;
public event EventHandler<FileSelectedEventArgs> FileSelected;
public FileImport()
{
InitializeComponent();
}
private FileDirectory? SelectedItem
=> dgFiles.SelectedItem as FileDirectory?;
private void Files_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (!SelectedItem.HasValue)
return;
FileSelected?.Invoke(this, new FileSelectedEventArgs(SelectedItem.Value));
}
private void btnSelectFolder_Click(object sender, System.Windows.RoutedEventArgs e)
{
using (var dialog = new System.Windows.Forms.FolderBrowserDialog())
{
dialog.SelectedPath = lastCheckedDirectory;
var result = dialog.ShowDialog();
if (result == System.Windows.Forms.DialogResult.OK && !string.IsNullOrWhiteSpace(dialog.SelectedPath))
{
string path = dialog.SelectedPath;
PathSelected?.Invoke(this, new PathSelectedEventArgs(path));
}
}
}
private void btnSelectFile_Click(object sender, System.Windows.RoutedEventArgs e)
{
using (var dialog = new System.Windows.Forms.OpenFileDialog())
{
dialog.InitialDirectory = lastCheckedDirectory;
var result = dialog.ShowDialog();
if (result == System.Windows.Forms.DialogResult.OK && !string.IsNullOrWhiteSpace(dialog.FileName))
{
string path = dialog.FileName;
PathSelected?.Invoke(this, new PathSelectedEventArgs(path));
}
}
}
private void btnClear_Click(object sender, System.Windows.RoutedEventArgs e)
{
Clear?.Invoke(this, EventArgs.Empty);
}
private void Image_MouseDown(object sender, System.Windows.Input.MouseButtonEventArgs e)
{
if (SelectedItem is null) return;
RemoveFile?.Invoke(this, new FileSelectedEventArgs(SelectedItem.Value.ID));
}
private void Cull_Click(object sender, System.Windows.RoutedEventArgs e)
{
}
private void UserControl_Loaded(object sender, System.Windows.RoutedEventArgs e)
{
DataContext = MediaManager.MediaCollectionInstance.Directories;
}
}
}
|
using System.ComponentModel.DataAnnotations.Schema;
using Etherama.DAL.Models.Base;
namespace Etherama.DAL.Models {
[Table("er_user_options")]
public class UserOptions : DbBaseUserEntity {
[Column("init_tfa_quest")]
public bool InitialTfaQuest { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.IO;
using System.Text.RegularExpressions;
public partial class qyrightnb : System.Web.UI.Page
{
//SQLServer数据库对象
SqlServerDataBase sdb = new SqlServerDataBase();
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
oktoedit();
string id = "";
if (Session["usertype"].ToString().Trim() == "用户")
{
id = Request["ID"];
}else{
id = Session["zlbdid"].ToString();
}
DataSet ds = new DataSet();
ds = sdb.Select("select * from zfhqyndsjsbb where qyID='" + id + "'", null);
if (ds.Tables[0].Rows.Count > 0)
{
Session["zfhzt"] = "xg";
}
else {
Session["zfhzt"] = "xz";
}
if (Session["zfhzt"].ToString() == "xz")
{
//隐藏按钮
xiugai_id.Visible = false;
querenxg.Visible = false;
}
else if (Session["zfhzt"].ToString() == "xg")
{
//隐藏按钮
btnOk.Visible = false;
//初始化数据
shuru(id);
}
}
}
void shuru(string id)
{
xiugai_id.Enabled = false;
DataSet ds = new DataSet();
ds = sdb.Select("select * from zfhqyndsjsbb where qyID='" + id + "'", null);
foreach (Control c in this.form1.Controls)
{
if (c is TextBox)
{
((TextBox)c).Text = ds.Tables[0].Rows[0][c.ID].ToString().Trim().Replace("0:00:00", "");
}
if (c is DropDownList)
{
((DropDownList)c).Text = ds.Tables[0].Rows[0][c.ID].ToString().Trim().Replace("0:00:00", "");
}
}
}
void oktoedit()
{
foreach (System.Web.UI.Control objControl in this.form1.Controls)
{
if (objControl is System.Web.UI.WebControls.TextBox)
{
((TextBox)objControl).ReadOnly = false;
}
if (objControl is System.Web.UI.WebControls.DropDownList)
{
((DropDownList)objControl).Enabled = true;
}
}
}
void notoedit()
{
foreach (System.Web.UI.Control objControl in this.form1.Controls)
{
if (objControl is System.Web.UI.WebControls.TextBox)
{
((TextBox)objControl).ReadOnly = true;
}
if (objControl is System.Web.UI.WebControls.DropDownList)
{
((DropDownList)objControl).Enabled = false;
}
}
}
//新增
protected void qrxiugai(object sender, EventArgs e)
{
string bdID = Session["zlbdid"].ToString();
string insert = "insert into zfhqyndsjsbb(qyID,";
foreach (System.Web.UI.Control objControl in this.form1.Controls)
{
if (objControl is System.Web.UI.WebControls.TextBox)
{
insert = insert + objControl.ID.ToString().Trim() + ",";
}
if (objControl is System.Web.UI.WebControls.DropDownList)
{
insert = insert + objControl.ID.ToString().Trim() + ",";
}
}
insert = insert.Substring(0, insert.Length - 1);
insert = insert + ") values(" + "'" + bdID + "',";
foreach (System.Web.UI.Control objControl in this.form1.Controls)
{
if (objControl is System.Web.UI.WebControls.TextBox)
{
if (objControl.ID.ToString() != "qymc" && objControl.ID.ToString() != "sfwlxcyz" && objControl.ID.ToString() != "synsfsqgqrd" && objControl.ID.ToString() != "sftggqrd" && objControl.ID.ToString() != "synzscqqslxhmc" && objControl.ID.ToString() != "synsjkyxmdjhmc" && objControl.ID.ToString() != "synsjgxmzjf" && objControl.ID.ToString() != "synqyxhdjhmc" && objControl.ID.ToString() != "tbr" && objControl.ID.ToString() != "tbrdh" && objControl.ID.ToString() != "bcrq" && objControl.ID.ToString() != "synqyxhgxmzjf")
{
if (((TextBox)objControl).Text.ToString().Trim() == "")
{
insert = insert + "null" + ",";
}
else
{
insert = insert + ((TextBox)objControl).Text.ToString().Trim() + ",";
}
}
else
{
insert = insert + "'" + ((TextBox)objControl).Text.ToString().Trim() + "' ,";
}
}
if (objControl is System.Web.UI.WebControls.DropDownList)
{
insert = insert + "'" + ((DropDownList)objControl).Text.ToString().Trim() + "' ,";
}
}
insert = insert.Substring(0, insert.Length - 1);
insert = insert + ");";
try
{
sdb.Insert(insert, null);
Response.Write("<script>alert('保存数据成功!');</script>");
}
catch (System.Exception ex)
{
Response.Write("<script>alert('" + ex.Message.Replace("'", "*") + "')</script>");
}
if (Session["usertype"] == "用户")
{
Response.Write("<script>opener.location.href='rightnb.aspx';</script>");
Response.Write("<script>window.opener = null;window.close();</script>");
}
else
{
xiugai_id.Visible = true;
querenxg.Visible = true;
btnOk.Visible = false;
xiugai_id.Enabled = true;
querenxg.Enabled = false;
notoedit();
}
}
//编辑
protected void xiugai(object sender, EventArgs e)
{
xiugai_id.Enabled = false;
querenxg.Enabled = true;
oktoedit();
}
//修改
protected void qrxiugai2(object sender, EventArgs e)
{
string bdID = "";
if (Session["usertype"].ToString().Trim() == "用户")
{
bdID = Request["ID"];
}
else
{
bdID = Session["zlbdid"].ToString();
}
string update = "update zfhqyndsjsbb set ";
foreach (System.Web.UI.Control objControl in this.form1.Controls)
{
if (objControl is System.Web.UI.WebControls.TextBox)
{
if (objControl.ID.ToString() != "qymc" && objControl.ID.ToString() != "sfwlxcyz" && objControl.ID.ToString() != "synsfsqgqrd" && objControl.ID.ToString() != "sftggqrd" && objControl.ID.ToString() != "synzscqqslxhmc" && objControl.ID.ToString() != "synsjkyxmdjhmc" && objControl.ID.ToString() != "synsjgxmzjf" && objControl.ID.ToString() != "synqyxhdjhmc" && objControl.ID.ToString() != "tbr" && objControl.ID.ToString() != "tbrdh" && objControl.ID.ToString() != "bcrq" && objControl.ID.ToString() != "synqyxhgxmzjf")
{
if (((TextBox)objControl).Text.ToString().Trim() == "")
{
update = update + objControl.ID.ToString().Trim() + "=" + "null" + ",";
}
else
{
update = update + objControl.ID.ToString().Trim() + "=" + ((TextBox)objControl).Text.ToString().Trim() + ",";
}
}
else
{
update = update + objControl.ID.ToString().Trim() + "=" +"'" + ((TextBox)objControl).Text.ToString().Trim() + "' ,";
}
}
if (objControl is System.Web.UI.WebControls.DropDownList)
{
update = update + objControl.ID.ToString().Trim() + "=" + "'" + ((DropDownList)objControl).Text.ToString().Trim() + "' ,";
}
}
update = update.Substring(0, update.Length - 1);
update = update + " where qyID = " + "'"+ bdID + "';";
try
{
sdb.Update(update, null);
}
catch (System.Exception ex)
{
Response.Write("<script>alert('" + ex.Message.Replace("'", "*") + "')</script>");
}
sdb.Update(update, null);
Response.Write("<script>alert('保存数据成功!');</script>");
if (Session["usertype"].ToString().Trim() == "用户")
{
Response.Write("<script>opener.location.href='rightnb.aspx';</script>");
Response.Write("<script>window.opener = null;window.close();</script>");
}
else
{
xiugai_id.Enabled = true;
querenxg.Enabled = false;
notoedit();
}
}
} |
using System.Threading.Tasks;
using Abp.Application.Services;
using Dg.fifth.Sessions.Dto;
namespace Dg.fifth.Sessions
{
public interface ISessionAppService : IApplicationService
{
Task<GetCurrentLoginInformationsOutput> GetCurrentLoginInformations();
}
}
|
namespace ServiceQuotes.Application.Filters
{
public class GetCustomersFilter : SearchStringFilter
{
public string CompanyName { get; set; }
public string VatNumber { get; set; }
}
}
|
using System;
using System.Text;
using System.Text.RegularExpressions;
using System.IO;
using BizApplication.http;
using ServerCommonLibrary;
namespace BizApplication.Http
{
/// <summary>
/// Generic helper functions for HTTP
/// </summary>
public class HttpHelper
{
/// <summary>
/// Return true if the resource is part of the static resource group
/// </summary>
/// <param name="resource">resource name</param>
/// <returns></returns>
public static bool IsStaticResource(string resource)
{
return Regex.IsMatch(resource, @"(.*?)\.(ico|css|gif|jpg|jpeg|png|js|xml)$");
}
/// <summary>
/// Return true if the resource is part of the dynamic resource group
/// </summary>
/// <param name="resource">resource name</param>
/// <returns></returns>
public static bool IsDynamicResource(string resource)
{
return Regex.IsMatch(resource, @"(.*?)\.(htm|html|xhtml|dhtml)$");
}
/// <summary>
/// return Http 404 pageHeader in byte format.
/// </summary>
/// <param name="response_data_length"></param>
/// <param name="response_data"></param>
/// <returns></returns>
public static byte[] GetHtml404Header(int response_data_length, MimeType type, string response_data = null)
{
return Encoding.UTF8.GetBytes(
"HTTP/1.1 404 Not Found" +
"\r\n" + "Date: " + String.Format("{0:r}", DateTime.Now) +
"\r\n" + "Server: my" +
(response_data != null ?
"\r\n" + "Content-Length: " + response_data_length +
"\r\n" + "Location: " + response_data +
"\r\n" + "Content-Location: " + response_data
: string.Empty) +
"\r\n" + "Content-Type: "+GetStringMimeType(type)+
"\r\n\r\n");
}
/// <summary>
/// Return a tiny Http response pageHeader in bytes format.
/// </summary>
/// <param name="lenght"></param>
/// <param name="type"></param>
/// <param name="dropConnection"></param>
/// <param name="gzip"></param>
/// <returns></returns>
public static byte[] GetHeader(int lenght, MimeType type, bool dropConnection, bool gzip)
{
string cutOffConnection = "";
if (dropConnection)
{
cutOffConnection = "\r\n" + "Connection: close";
}
string _type = GetStringMimeType(type);
string header = "HTTP/1.1 200 OK" +
"\r\n" + "Cache-Control: private" +
"\r\n" + "Server: my" +
"\r\n" + "Content-Type: " + _type +
"\r\n" + "Content-Length: " + lenght +
(gzip ? "\r\n" + "Content-Encoding: gzip" : "") +
"\r\n" + "Server: vws" +
"\r\n" + "Date: " + String.Format("{0:r}", DateTime.Now) +
// _trunoffConnection +
//"\r\n" + "Last-Modified : " + System.DateTime.Now + " GMT"+
"\r\n\r\n";
return Encoding.UTF8.GetBytes(header);
}
/// <summary>
/// This function return a byte array compressed by GZIP algorithm.
/// </summary>
/// <param name="data"></param>
/// <returns></returns>
public static byte[] CompressGZIP(byte[] data)
{
System.IO.MemoryStream streamoutput = new System.IO.MemoryStream();
System.IO.Compression.GZipStream gzip = new System.IO.Compression.GZipStream(streamoutput, System.IO.Compression.CompressionMode.Compress, false);
gzip.Write(data, 0, data.Length);
gzip.Close();
return streamoutput.ToArray();
}
/// <summary>
/// This function return the default error page as Application Response.
/// </summary>
/// <param name="request"></param>
/// <param name="ex"></param>
/// <returns></returns>
public static ApplicationResponse Generate404Page(HttpRequest request, string bodyMessage,string pageHeader,string title="Error Page")
{
//Check if the defaultPage exist
if (!File.Exists(HttpApplicationManager.RootDirectory + "\\" + HttpApplicationManager.DefaultPage))
{
//No data to sent back so the connection will be close.
return new ApplicationResponse(request) { Action = ResponseAction.Disconnect };
}
//Get the file
byte[] page = Helper.GetFile(HttpApplicationManager.RootDirectory + "\\" + HttpApplicationManager.DefaultPage);
string page_str = new String(Encoding.UTF8.GetChars(page));
//fill the page with exception information
page_str = page_str.Replace("<%ws_title%>", title);
page_str = page_str.Replace("<%ws_domain%>", HttpApplicationManager.CurrentDomain + ":" + HttpApplicationManager.ServicePort);
page_str = page_str.Replace("<%ws_header%>", pageHeader);
page_str = page_str.Replace("<%ws_message%>", bodyMessage);
page = Encoding.UTF8.GetBytes(page_str);
//Get the pageHeader
byte[] binheader = GetHeader(page.Length,MimeType.text_html,true,false);
//build the response
byte[] completeResponse = binheader.Concat(page);
ApplicationResponse response = new HttpResponse(completeResponse, request);
return response;
}
/// <summary>
/// Extract the MimeType from a resource
/// </summary>
/// <param name="request"></param>
/// <returns></returns>
public static MimeType GetResourceMime(string request)
{
if (string.IsNullOrEmpty(request)) return MimeType.none;
string[] filepats = request.Split(new string[] { "." }, StringSplitOptions.RemoveEmptyEntries);
if (filepats.Length > 0)
{
string extension = filepats[filepats.Length - 1];
return GetContentTypeByExtension(extension);
}
else
return MimeType.none;
}
public static string GetStringMimeType(MimeType mime)
{
string strMime = "";
switch (mime)
{
case MimeType.text_html: strMime = "text/html; charset=utf-8"; break;
case MimeType.text_javascript: strMime = "text/javascript"; break;
case MimeType.multipart_xmixedreplace:
strMime = "multipart/x-mixed-replace; boundary=rnA00A"; break;
case MimeType.application_xml_charsetutf8:
strMime = "application/xml; charset=utf-8";
break;
default:
strMime = mime.ToString().Replace("_", "/");
break;
}
return strMime;
}
public static MimeType GetContentTypeByExtension(string extension)
{
switch (extension)
{
case "css":
return MimeType.text_css;
case "gif":
return MimeType.image_gif;
case "jpg":
case "jpeg":
return MimeType.image_jpeg;
case "ico":
case "png":
return MimeType.image_png;
case "htm":
case "html":
case "xhtml":
case "dhtml":
return MimeType.text_html;
case "js":
return MimeType.text_javascript;
case "xml":
return MimeType.multipart_xmixedreplace;
default:
return MimeType.none;
}
}
public static string CleanJsonString(string url)
{
if (url == null) return null;
return url.Replace("%27", "\"").Replace("%35", "#").Replace("%20", " ").Replace("%61", "=").Replace("%63", "?");
}
public static string[] GetUrlQueries(string queryUrlString)
{
return queryUrlString.Split(new string[] { "&" }, StringSplitOptions.RemoveEmptyEntries);
}
#region Custom
/*
* In my demos each asynchronous ajax request have a token like : "__minute_millisecond" at the end of the string, for avoid browser cache
*/
public static string RemoveToken(string completeReq)
{
if (completeReq.Contains("__"))
{
completeReq = completeReq.Split(new string[] { "__" }, StringSplitOptions.RemoveEmptyEntries)[0];
}
string[] _pReq = completeReq.Split(new string[] { "?" }, StringSplitOptions.RemoveEmptyEntries);
if (_pReq.Length < 2) return string.Empty;
else return _pReq[1];
}
#endregion
}
}
|
using Dao;
using Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Control
{
public class ClienteCtrl
{
public Boolean SalvarClienteNoArquivo(Cliente _cliente)
{
try
{
ClienteDAO dao = new ClienteDAO();
return dao.SalvarClienteNoArquivo(_cliente);
}
catch (Exception e)
{
throw new Exception(e.Message);
}
}
public Dictionary<String, Cliente> ListarClientesDoArquivo()
{
try
{
ClienteDAO dao = new ClienteDAO();
return dao.ListarClientesDoArquivo();
}
catch (Exception e)
{
throw new Exception(e.Message);
}
}
}
}
|
using PMO2EXAMEN3;
using Examen3PMO2.controller;
using Examen3PMO2.Models;
using Examen3PMO2.ViewModel;
using SQLite;
using System;
using System.Windows.Input;
using Xamarin.Forms;
namespace Examen3PMO2.ViewModel
{
public class ViewModelPersonas : BaseViewModel
{
conexion conn = new conexion();
Crud crud = new Crud();
private int id;
private int pago;
private string descripcion;
private double monto;
private string fecha;
public int Id
{
get { return id; }
set { id = value; OnPropertyChanged(); }
}
public int Pago
{
get { return pago; }
set { pago = value; OnPropertyChanged(); }
}
public string Descripcion
{
get { return descripcion; }
set { descripcion = value; OnPropertyChanged(); }
}
public double Monto
{
get { return monto; }
set { monto = value; OnPropertyChanged(); }
}
public string Fecha
{
get { return fecha; }
set { fecha = value; OnPropertyChanged(); }
}
public async void Guardar()
{
if (string.IsNullOrEmpty(Id.ToString()))
{
await App.Current.MainPage.DisplayAlert("Alerta", "Campo de ID vacio", "Ok");
return;
}
if (string.IsNullOrEmpty(Pago.ToString()))
{
await App.Current.MainPage.DisplayAlert("Alerta", "Campo de PAGO vacio", "Ok");
return;
}
if (string.IsNullOrEmpty(Descripcion))
{
await App.Current.MainPage.DisplayAlert("Alerta", "Campo de Descripcion vacio", "Ok");
return;
}
if (string.IsNullOrEmpty(Monto.ToString()))
{
await App.Current.MainPage.DisplayAlert("Alerta", "Campo de Monto vacio", "Ok");
return;
}
if (string.IsNullOrEmpty(Fecha))
{
await App.Current.MainPage.DisplayAlert("Alerta", "Campo de fecha vacio", "Ok");
return;
}
var personas = new Personas()
{
id = Id,
pago = Pago,
descripcion = Descripcion,
monto = Monto,
fecha = Fecha
};
try
{
conn.Conn().CreateTable<Personas>();
conn.Conn().Insert(personas);
conn.Conn().Close();
await App.Current.MainPage.DisplayAlert("Success", "Datos Guardados", "Ok");
await App.Current.MainPage.Navigation.PushAsync(new Home());
}
catch (SQLiteException)
{
await App.Current.MainPage.DisplayAlert("Warning", "Correo Ya existe", "Ok");
}
}
public ICommand ClearCommand { private set; get; }
public ICommand SendEmailCommand { private set; get; }
public ViewModelPersonas()
{
ClearCommand = new Command(() => Clear());
}
public ICommand GuardarCommand
{
get { return new Command(() => Guardar()); }
}
public ICommand DeleteCommand { get { return new Command(() => eliminar()); } }
public ICommand UpdateCommand { get { return new Command(() => actualizar()); } }
void Clear()
{
pago = Convert.ToInt32(Pago.ToString());
Descripcion = string.Empty;
monto = Convert.ToDouble(Monto.ToString());
Fecha = string.Empty;
}
async void eliminar()
{
var persona = await crud.getPersonasId(Convert.ToInt32(Id));
bool conf = await App.Current.MainPage.DisplayAlert("Delete", "Eliminar Persona", "Accept", "Cancel");
if (conf)
{
if (persona != null)
{
await crud.Delete(persona);
await App.Current.MainPage.DisplayAlert("Delete", "Datos Eliminados", "ok");
Clear();
await App.Current.MainPage.Navigation.PopModalAsync();
}
}
}
async void actualizar()
{
bool conf = await App.Current.MainPage.DisplayAlert("Update", "Actualizar datos de Empleado", "Accept", "Cancel");
if (conf)
{
if (!string.IsNullOrEmpty(Id.ToString()))
{
Personas update = new Personas
{
id = Convert.ToInt32(Id.ToString()),
pago = Pago,
descripcion = Descripcion,
monto = Convert.ToDouble(Monto.ToString()),
fecha = Fecha
};
await crud.getPersonasUpdateId(update);
await App.Current.MainPage.DisplayAlert("Update", "Datos Actualizados", "ok");
await App.Current.MainPage.Navigation.PopModalAsync();
}
}
}
}
}
|
namespace CheckMkProxy
{
using JetBrains.Annotations;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Hosting;
[UsedImplicitly]
public class Program
{
public static void Main(string[] args)
{
CreateHostBuilder(args).Build().Run();
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
#if RELEASE
webBuilder.ConfigureKestrel(serverOptions =>
{
serverOptions.ListenAnyIP(5000);
serverOptions.ListenAnyIP(5001, listenOptions =>
{
listenOptions.UseHttps("CheckMkProxy.pfx", "CheckMkProxy");
});
});
#endif
webBuilder.UseStartup<Startup>();
});
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;
namespace WebAppAdvocacia.Models
{
public class Processo
{
public int ProcessoID { get; set; }
[Required(ErrorMessage = "Descrição do Processo é Obrigatório")]
[Display(Name = "Descrição do processo")]
public string Descricao { get; set; }
[Required(ErrorMessage = "Numero do Processo é Obrigatório")]
[Display(Name = "Numero do processo")]
public int NumeroProcesso { get; set; }
[Required(ErrorMessage = "Data de Abertura é Obrigatório")]
[Display(Name = "Data de Abertura")]
[DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}", ApplyFormatInEditMode = true)]
public DateTime DataAbertura { get; set; }
[Required(ErrorMessage = "Data de Conclusão é Obrigatório")]
[Display(Name = "Data de Conclusão")]
[DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}", ApplyFormatInEditMode = true)]
public DateTime? DataConclusao { get; set; }
[Required(ErrorMessage = "Situação do Processo é Obrigatório")]
[Display(Name = "Situação")]
public TipoSituacao Situacao { get; set; }
[Required(ErrorMessage = "Pessoa é Obrigatório")]
public int PessoaID { get; set; }
public virtual Pessoa Pessoa { get; set; }
[Required(ErrorMessage = "Vara é Obrigatório")]
public int VaraID { get; set; }
public virtual Vara Vara { get; set; }
public virtual ICollection<Audiencia> Audiencias { get; set; }
public virtual ICollection<Custa> Custas { get; set; }
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DataService_BpmOnline_CRUD
{
public class Id
{
public int dataValueType { get; set; }
}
public class Name
{
public int dataValueType { get; set; }
}
public class CreatedOn
{
public int dataValueType { get; set; }
}
public class Completeness
{
public int dataValueType { get; set; }
}
public class Zip
{
public int dataValueType { get; set; }
}
public class AccountType
{
public int dataValueType { get; set; }
}
public class AccountLogo
{
public int dataValueType { get; set; }
public bool isLookup { get; set; }
public string referenceSchemaName { get; set; }
}
public class RowConfig
{
public Id Id { get; set; }
public Name Name { get; set; }
public CreatedOn CreatedOn { get; set; }
public Completeness Completeness { get; set; }
public Zip Zip { get; set; }
public AccountType AccountType { get; set; }
public AccountLogo AccountLogo { get; set; }
}
public class Row
{
public string Name { get; set; }
public string Id { get; set; }
public DateTime CreatedOn { get; set; }
public int Completeness { get; set; }
public string Zip { get; set; }
public string AccountType { get; set; }
public object AccountLogo { get; set; }
}
public class RootObject
{
public RowConfig rowConfig { get; set; }
public List<Row> rows { get; set; }
public List<object> notFoundColumns { get; set; }
public int rowsAffected { get; set; }
public bool nextPrcElReady { get; set; }
public bool success { get; set; }
}
}
|
namespace XH.Commands.Catalogs
{
public class CreateRegionCommand : CreateOrUpdateRegionCommandBase
{
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class SpriteSelecting : BuildData, IBuildMode
{
Block block;
public SpriteSelecting(Block block)
{
this.block = block;
}
public void Begin()
{
BlockType type = block.GetBlockType();
int count = BlockData.Instance.spriteCount[type];
if (count < 2)
{
mode.ChangeMode(lastMode);
return;
}
spriteSelection.ShowSprites(type, Input.mousePosition);
}
public void ChangeMode(IBuildMode mode)
{
if (mode is Interacting)
return;
End();
BuildData.mode = mode;
BuildData.mode.Begin();
}
public void End()
{
hoverBlock.SetActive(false);
spriteSelection.DisableSprites();
}
public void RotateBlock() {}
public void Update()
{
if (Input.GetKeyDown(select1))
{
Block currentBlock = inv.GetSelectedBlock();
currentBlock.SetSpriteId(spriteSelection.GetHightlightId());
inv.SetSlot(inv.GetActiveSlot(), currentBlock);
bm.StartCoroutine(bm.ChangeModeOnRelease(select1));
}
if (Input.GetKeyDown(select2))
{
bm.StartCoroutine(bm.ChangeModeOnRelease(select1));
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BeeFarm
{
class Worker : Bee
{
private Honey honey = new();
public Worker() : base() { }
public Worker(Hive hv) : base(hv) { }
public int Quantity
{
get { return honey.Quantity; }
}
public List<string> Composition
{
get { return honey.Composition; }
}
public void TakePollen(Flower flower)
{
honey.AddFlower(flower);
}
public void GiveHoney(Honeycomb hc)
{
if (HomeHive.Honeycombs.Contains(hc))
{
hc.AddHoney(honey.GetHoney());
}
}
}
}
|
using System;
using System.Drawing;
using System.Windows.Forms;
namespace gView.Framework.Symbology.UI.Controls
{
public class ToolStripLineWidthPicker : ToolStripDropDownButton
{
private Control _parentControl = null;
private OfficeLineWidthPicker _lineWidthePicker;
public event EventHandler PenWidthSelected = null;
public ToolStripLineWidthPicker(Control parentControl)
{
_parentControl = parentControl;
_lineWidthePicker = new OfficeLineWidthPicker();
_lineWidthePicker.PenWidthSelected += new EventHandler(PenWidth_PenWidthSelected);
}
void PenWidth_PenWidthSelected(object sender, EventArgs e)
{
if (PenWidthSelected != null)
{
PenWidthSelected(this, EventArgs.Empty);
}
}
public int PenWidth
{
get
{
return _lineWidthePicker.PenWidth;
}
}
#region Overrides
protected override void OnClick(EventArgs e)
{
Point startPoint = GetOpenPoint();
int screenW = Screen.PrimaryScreen.Bounds.Width;
int screenH = Screen.PrimaryScreen.Bounds.Height;
if (startPoint.X + _lineWidthePicker.Width > screenW)
{
startPoint.X -= _lineWidthePicker.Width - this.Width - 5;
}
if (startPoint.Y + _lineWidthePicker.Height > screenH)
{
startPoint.Y -= this.Height + _lineWidthePicker.Height + 5;
}
_lineWidthePicker.Show(_parentControl, startPoint);
}
private Point GetOpenPoint()
{
if (this.Owner == null)
{
return new Point(5, 5);
}
int x = 0;
foreach (ToolStripItem item in this.Parent.Items)
{
if (item == this)
{
break;
}
x += item.Width;
}
return this.Owner.PointToScreen(new Point(x, 0));
}
#endregion
}
}
|
namespace TestProject.Classes
{
public class Author
{
public int AuthorIdentifier { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class climb : MonoBehaviour
{
//init vars
Transform player;
GameObject playerObj;
bool canClimb = true;
float speed = 30;
//entering the trigger collider
void OnTriggerEnter(Collider other)
{
//if we can climb the ladder
if (canClimb == true)
{
//update vars
playerObj = other.gameObject;
player = other.transform;
//set player's climbing var to false to prevent x and z movement
playerObj.GetComponent<PlayerController>().climbing = false;
//stop applying gravity to the transform
player.GetComponent<Rigidbody>().useGravity = false;
//player can no longer start climbing because player is already on a ladder
canClimb = false;
return;
}
//if we cannot climb a ladder (presumably because we are already climbing one)
else//if (canClimb == false)
{
canClimb = true;
player.GetComponent<Rigidbody>().useGravity = true;
player = null;
playerObj = null;
}
}
void OnTriggerStay(Collider other)
{
//update vars
player = other.transform;
playerObj = other.gameObject;
//if we're climbing, halt player xz position and gravity
if (canClimb == false)
{
playerObj.GetComponent<PlayerController>().climbing = true;
playerObj.GetComponent<Rigidbody>().useGravity = false;
playerObj.GetComponent<Rigidbody>().constraints = RigidbodyConstraints.FreezePositionX | RigidbodyConstraints.FreezePositionZ | RigidbodyConstraints.FreezeRotationZ | RigidbodyConstraints.FreezeRotationX;
}
//go up or down
if (Input.GetKey(KeyCode.W))
{
player.Translate(Vector3.up * Time.deltaTime * speed);
}
else if (Input.GetKey(KeyCode.S))
{
player.Translate(Vector3.down * Time.deltaTime * speed);
}
}
//push player off of the ladder
void OnTriggerExit(Collider other)
{
playerObj = other.gameObject;
player = other.transform;
//remove constraints and set player climbing to false because they are no longer climbing
playerObj.GetComponent<Rigidbody>().constraints = RigidbodyConstraints.None;
playerObj.GetComponent<Rigidbody>().constraints = RigidbodyConstraints.FreezeRotationZ | RigidbodyConstraints.FreezeRotationX;
playerObj.GetComponent<PlayerController>().climbing = false;
//gravity exists again
player.GetComponent<Rigidbody>().useGravity = true;
//push player off of the ladder
player.Translate(Vector3.forward * Time.deltaTime * 5);
canClimb = true;
player = null;
playerObj = null;
}
}
|
using System;
namespace Uintra.Features.Permissions.Models
{
public class PermissionModel
{
public Guid Id { get; }
public IntranetMemberGroup Group { get; }
public PermissionSettingValues SettingValues { get; }
public PermissionSettingIdentity SettingIdentity { get; }
public PermissionModel(
Guid id,
PermissionSettingIdentity settingIdentity,
PermissionSettingValues settingValues,
IntranetMemberGroup group)
{
Id = id;
Group = group;
SettingIdentity = settingIdentity;
SettingValues = settingValues;
}
}
} |
namespace Zesty.Core.Entities
{
public class HistoryItem
{
public User User { get; set; }
public string Resource { get; set; }
public string Text { get; set; }
public string Actor { get; set; }
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlClient;
namespace DAL
{
public class DataAccess
{
/// <summary>
/// This method returns the number of objects in the database as an integer.
/// </summary>
/// <returns></returns>
public static int TrainDBCount()
{
String connString = "Data Source=.\\SQLEXPRESS;AttachDbFilename=|DataDirectory|\\TrainDB.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True";
SqlConnection con = new SqlConnection(connString);
con.Open();
SqlCommand selectCommand = new SqlCommand("SELECT COUNT(*) FROM Table1", con);
Int32 count = (Int32)selectCommand.ExecuteScalar();
con.Close();
return count;
}
/// <summary>
/// Method creates a row in the Train DataBase by reading train object and storing each variable in the DB
/// </summary>
/// <param name="typ"></param>
/// <param name="chair1dust"></param>
/// <param name="chair1spots"></param>
/// <param name="chair1garbage"></param>
/// <param name="chair2dust"></param>
/// <param name="chair2spots"></param>
/// <param name="chair2garbage"></param>
/// <param name="chair3dust"></param>
/// <param name="chair3spots"></param>
/// <param name="chair3garbage"></param>
/// <param name="extradust"></param>
/// <param name="extraspots"></param>
/// <param name="extragarbage"></param>
/// <param name="extraname"></param>
/// <param name="wagonnumber"></param>
/// <param name="chair1"></param>
/// <param name="chair2"></param>
/// <param name="chair3"></param>
/// <param name="trainnumber"></param>
public static void createrow(string typ, int chair1dust, int chair1spots, int chair1garbage, int chair2dust, int chair2spots, int chair2garbage, int chair3dust, int chair3spots, int chair3garbage, int extradust, int extraspots, int extragarbage, string extraname, int wagonnumber, int chair1, int chair2, int chair3, string trainnumber)
{
String connString = "Data Source=.\\SQLEXPRESS;AttachDbFilename=|DataDirectory|\\TrainDB.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True";
SqlConnection con = new SqlConnection(connString);
SqlCommand selectCommand = new SqlCommand("SELECT COUNT(*) FROM Table1", con);
try
{
con.Open();
using (SqlCommand cmd = new SqlCommand("insert into Table1(ID, TYP, CHAIR1DUST, CHAIR1SPOTS, CHAIR1GARBAGE, CHAIR2DUST, CHAIR2SPOTS, CHAIR2GARBAGE, CHAIR3DUST, CHAIR3SPOTS, CHAIR3GARBAGE, EXTRADUST, EXTRASPOTS, EXTRAGARBAGE, EXTRANAME, WAGONNUMBER, CHAIR1, CHAIR2, CHAIR3, TRAINNUMBER) values (@val1, @Val2, @val3, @val4, @val5, @val6, @val7, @val8, @val9, @val10, @val11, @val12, @val13, @val14, @val15, @val16, @val17, @val18, @val19, @val20)", con))
{
int count = (int)selectCommand.ExecuteScalar();
cmd.Parameters.AddWithValue("@Val1", count + 1);
cmd.Parameters.AddWithValue("@Val2", typ);
cmd.Parameters.AddWithValue("@Val3", chair1dust);
cmd.Parameters.AddWithValue("@Val4", chair1spots);
cmd.Parameters.AddWithValue("@Val5", chair1garbage);
cmd.Parameters.AddWithValue("@Val6", chair2dust);
cmd.Parameters.AddWithValue("@Val7", chair2spots);
cmd.Parameters.AddWithValue("@Val8", chair2garbage);
cmd.Parameters.AddWithValue("@Val9", chair3dust);
cmd.Parameters.AddWithValue("@Val10", chair3spots);
cmd.Parameters.AddWithValue("@Val11", chair3garbage);
cmd.Parameters.AddWithValue("@Val12", extradust);
cmd.Parameters.AddWithValue("@Val13", extraspots);
cmd.Parameters.AddWithValue("@Val14", extragarbage);
cmd.Parameters.AddWithValue("@Val15", extraname);
cmd.Parameters.AddWithValue("@Val16", wagonnumber);
cmd.Parameters.AddWithValue("@Val17", chair1);
cmd.Parameters.AddWithValue("@Val18", chair2);
cmd.Parameters.AddWithValue("@Val19", chair3);
cmd.Parameters.AddWithValue("@Val20", trainnumber);
cmd.CommandType = System.Data.CommandType.Text;
cmd.ExecuteNonQuery();
}
}
catch
{
throw;
}
finally
{
if (con != null)
{
con.Close();
}
}
}
/// <summary>
/// method clears the Database from entries
/// </summary>
public static void deleteTrainData()
{
int antal = TrainDBCount();
String connString = "Data Source=.\\SQLEXPRESS;AttachDbFilename=|DataDirectory|\\TrainDB.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True";
SqlConnection con = new SqlConnection(connString);
for (int x = 1; x <= antal; x++)
{
SqlCommand insertCommand = new SqlCommand("DELETE Table1 WHERE ID = " + x, con);
con.Open();
insertCommand.ExecuteNonQuery();
con.Close();
}
}
/// <summary>
/// This Method reads all trains currently stored in the DataBase and sends them to the Manager wich creates
/// each one as a train object in the array.
/// </summary>
/// <param name="row"></param>
/// <param name="typ"></param>
/// <param name="chair1dust"></param>
/// <param name="chair1spots"></param>
/// <param name="chair1garbage"></param>
/// <param name="chair2dust"></param>
/// <param name="chair2spots"></param>
/// <param name="chair2garbage"></param>
/// <param name="chair3dust"></param>
/// <param name="chair3spots"></param>
/// <param name="chair3garbage"></param>
/// <param name="extradust"></param>
/// <param name="extraspots"></param>
/// <param name="extragarbage"></param>
/// <param name="extraname"></param>
/// <param name="wagonnumber"></param>
/// <param name="chair1"></param>
/// <param name="chair2"></param>
/// <param name="chair3"></param>
/// <param name="trainnumber"></param>
public static void loadTrainData(int row, out string typ, out int chair1dust, out int chair1spots, out int chair1garbage, out int chair2dust, out int chair2spots, out int chair2garbage, out int chair3dust, out int chair3spots, out int chair3garbage, out int extradust, out int extraspots, out int extragarbage, out string extraname, out int wagonnumber, out int chair1, out int chair2, out int chair3, out string trainnumber)
{
string m_typ = "";
int m_chair1dust = 0;
int m_chair1spots = 0;
int m_chair1garbage = 0;
int m_chair2dust = 0;
int m_chair2spots = 0;
int m_chair2garbage = 0;
int m_chair3dust = 0;
int m_chair3spots = 0;
int m_chair3garbage = 0;
int m_extradust = 0;
int m_extraspots = 0;
int m_extragarbage = 0;
string m_extraname = "";
int m_wagonnumber = 0;
int m_chair1 = 0;
int m_chair2 = 0;
int m_chair3 = 0;
string m_trainnumber = "";
int antal = TrainDBCount();
String connString = "Data Source=.\\SQLEXPRESS;AttachDbFilename=|DataDirectory|\\TrainDB.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True";
SqlConnection con = new SqlConnection(connString);
con.Open();
using (SqlCommand command = new SqlCommand("SELECT ID, TYP, CHAIR1DUST, CHAIR1SPOTS, CHAIR1GARBAGE, CHAIR2DUST, CHAIR2SPOTS, CHAIR2GARBAGE, CHAIR3DUST, CHAIR3SPOTS, CHAIR3GARBAGE, EXTRADUST, EXTRASPOTS, EXTRAGARBAGE, EXTRANAME, WAGONNUMBER, CHAIR1, CHAIR2, CHAIR3, TRAINNUMBER from Table1 WHERE ID = " + row, con))
{
SqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
m_typ = reader.GetString(1);
m_chair1dust = reader.GetInt32(2);
m_chair1spots = reader.GetInt32(3);
m_chair1garbage = reader.GetInt32(4);
m_chair2dust = reader.GetInt32(5);
m_chair2spots = reader.GetInt32(6);
m_chair2garbage = reader.GetInt32(7);
m_chair3dust = reader.GetInt32(8);
m_chair3spots = reader.GetInt32(9);
m_chair3garbage = reader.GetInt32(10);
m_extradust = reader.GetInt32(11);
m_extraspots = reader.GetInt32(12);
m_extragarbage = reader.GetInt32(13);
m_extraname = reader.GetString(14);
m_wagonnumber = reader.GetInt32(15);
m_chair1 = reader.GetInt32(16);
m_chair2 = reader.GetInt32(17);
m_chair3 = reader.GetInt32(18);
m_trainnumber = reader.GetString(19);
}
typ = m_typ;
chair1dust = m_chair1dust;
chair1spots = m_chair1spots;
chair1garbage = m_chair1garbage;
chair2dust = m_chair2dust;
chair2spots = m_chair2spots;
chair2garbage = m_chair2garbage;
chair3dust = m_chair3dust;
chair3spots = m_chair3spots;
chair3garbage = m_chair3garbage;
extradust = m_extradust;
extraspots = m_extraspots;
extragarbage = m_extragarbage;
extraname = m_extraname;
wagonnumber = m_wagonnumber;
chair1 = m_chair1;
chair2 = m_chair2;
chair3 = m_chair3;
trainnumber = m_trainnumber;
con.Close();
}
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class ItemShop : MonoBehaviour
{
public List<BaseShopItem> itemShopList = new List<BaseShopItem>();
public bool inShop;
Text goldText;
Text numOwned;
Transform cursor;
ItemShopMouseEvents isme;
GameObject ismeObj;
public enum ItemShopCursorStates
{
ITEMLIST,
ITEMCONFIRM,
OPTIONS
}
public ItemShopCursorStates itemShopCursorState;
public string shopMode;
bool dpadPressed;
bool confirmPressed;
int cursorOnItem;
int cursorOnOption;
float itemSpacer = 24.5f;
int tempScrollDiff = 0;
ItemShopConfirmationMouseEvents confirmationQuantityUp;
ItemShopConfirmationMouseEvents confirmationQuantityDown;
ItemShopConfirmationMouseEvents confirmationConfirm;
Color pressedColor = new Color(.4f, .4f, .4f);
Color unpressedColor = new Color(1f, 1f, 1f);
private void Start()
{
cursor = GameObject.Find("GameManager/Cursor").transform;
//set and show gold
goldText = GameObject.Find("GameManager/ShopCanvases/ItemShopCanvas/ItemShopBuyPanel/AdditionalDetailsPanel/GoldText").GetComponent<Text>();
goldText.text = GameManager.instance.gold.ToString();
//set and show number of items owned
numOwned = GameObject.Find("GameManager/ShopCanvases/ItemShopCanvas/ItemShopBuyPanel/AdditionalDetailsPanel/OwnedText").GetComponent<Text>();
numOwned.text = "-";
}
private void Update()
{
if (inShop)
{
if (itemShopCursorState == ItemShopCursorStates.ITEMLIST)
{
if (shopMode == "Buy")
{
int itemCount = GameObject.Find("GameManager/ShopCanvases/ItemShopCanvas/ItemShopBuyPanel/ItemListPanel/ItemScroller/ItemListSpacer").transform.childCount;
int scrollDiff = itemCount - 9;
if (itemCount <= 9)
{
tempScrollDiff = 0;
}
if (cursor.parent != GameObject.Find("GameManager/ShopCanvases/ItemShopCanvas").transform)
{
cursor.SetParent(GameObject.Find("GameManager/ShopCanvases/ItemShopCanvas").transform);
}
if (cursor.gameObject.GetComponent<CanvasGroup>().alpha != 1)
{
cursor.gameObject.GetComponent<CanvasGroup>().alpha = 1;
}
confirmationQuantityUp = GameObject.Find("GameManager/ShopCanvases/ItemShopCanvas/ItemShopBuyPanel/ConfirmationPanel/BuyQuantityUpButton").GetComponent<ItemShopConfirmationMouseEvents>();
confirmationQuantityDown = GameObject.Find("GameManager/ShopCanvases/ItemShopCanvas/ItemShopBuyPanel/ConfirmationPanel/BuyQuantityDownButton").GetComponent<ItemShopConfirmationMouseEvents>();
confirmationConfirm = GameObject.Find("GameManager/ShopCanvases/ItemShopCanvas/ItemShopBuyPanel/ConfirmationPanel/BuyButton").GetComponent<ItemShopConfirmationMouseEvents>();
RectTransform spacerScroll = GameObject.Find("GameManager/ShopCanvases/ItemShopCanvas/ItemShopBuyPanel/ItemListPanel/ItemScroller/ItemListSpacer").GetComponent<RectTransform>();
if (!dpadPressed && cursorOnItem == 0 && tempScrollDiff == 0)
{
if (itemCount > 1)
{
if (Input.GetAxisRaw("DpadVertical") == -1) //down
{
dpadPressed = true;
cursorOnItem = cursorOnItem + 1;
AudioManager.instance.PlaySE(AudioManager.instance.confirmSE);
}
}
if (Input.GetAxisRaw("DpadVertical") == 1) //up
{
dpadPressed = true;
AudioManager.instance.PlaySE(AudioManager.instance.confirmSE);
itemShopCursorState = ItemShopCursorStates.OPTIONS;
}
}
else if (!dpadPressed && cursorOnItem == 0 && tempScrollDiff > 0)
{
if (Input.GetAxisRaw("DpadVertical") == -1) //down
{
cursorOnItem = cursorOnItem + 1;
dpadPressed = true;
AudioManager.instance.PlaySE(AudioManager.instance.confirmSE);
}
if (Input.GetAxisRaw("DpadVertical") == 1) //up
{
spacerScroll.anchoredPosition = new Vector3(0.0f, (itemSpacer * (tempScrollDiff - 1)), 0.0f);
tempScrollDiff = tempScrollDiff - 1;
dpadPressed = true;
AudioManager.instance.PlaySE(AudioManager.instance.confirmSE);
}
}
else if (!dpadPressed && cursorOnItem > 0 && cursorOnItem < 8)
{
if (Input.GetAxisRaw("DpadVertical") == 1) //up
{
cursorOnItem = cursorOnItem - 1;
dpadPressed = true;
AudioManager.instance.PlaySE(AudioManager.instance.confirmSE);
}
if (Input.GetAxisRaw("DpadVertical") == -1) //down
{
cursorOnItem = cursorOnItem + 1;
dpadPressed = true;
AudioManager.instance.PlaySE(AudioManager.instance.confirmSE);
}
}
else if (!dpadPressed && cursorOnItem == 8 && tempScrollDiff == 0 && scrollDiff > 0)
{
if (Input.GetAxisRaw("DpadVertical") == 1) //up
{
cursorOnItem = cursorOnItem - 1;
dpadPressed = true;
AudioManager.instance.PlaySE(AudioManager.instance.confirmSE);
}
if (Input.GetAxisRaw("DpadVertical") == -1) //down
{
spacerScroll.anchoredPosition = new Vector3(0.0f, itemSpacer, 0.0f);
tempScrollDiff = tempScrollDiff + 1;
dpadPressed = true;
AudioManager.instance.PlaySE(AudioManager.instance.confirmSE);
}
}
else if (!dpadPressed && cursorOnItem == 8 && tempScrollDiff == 0 && scrollDiff == 0)
{
if (Input.GetAxisRaw("DpadVertical") == 1) //up
{
cursorOnItem = cursorOnItem - 1;
dpadPressed = true;
AudioManager.instance.PlaySE(AudioManager.instance.confirmSE);
}
}
else if (!dpadPressed && cursorOnItem == 8 && tempScrollDiff > 0 && (cursorOnItem + tempScrollDiff) < (itemCount - 1))
{
if (Input.GetAxisRaw("DpadVertical") == 1) //up
{
cursorOnItem = 8;
dpadPressed = true;
AudioManager.instance.PlaySE(AudioManager.instance.confirmSE);
}
if (Input.GetAxisRaw("DpadVertical") == -1) //down
{
spacerScroll.anchoredPosition = new Vector3(0.0f, (itemSpacer * (tempScrollDiff + 1)), 0.0f); //and use tempScrollDiff - 1 to go up
tempScrollDiff = tempScrollDiff + 1;
dpadPressed = true;
AudioManager.instance.PlaySE(AudioManager.instance.confirmSE);
}
}
else if (!dpadPressed && cursorOnItem == 8 && tempScrollDiff > 0 && (cursorOnItem + tempScrollDiff) == (itemCount - 1))
{
if (Input.GetAxisRaw("DpadVertical") == 1) //up
{
cursorOnItem = 7;
dpadPressed = true;
AudioManager.instance.PlaySE(AudioManager.instance.confirmSE);
}
}
//Debug.Log("cursorOnItem: " + cursorOnItem + ", scrollDiff: " + scrollDiff + ", tempScrollDiff: " + tempScrollDiff);
if (itemCount != 0)
{
if (cursorOnItem == itemCount)
{
cursorOnItem = itemCount - 1;
}
if (cursorOnItem == 0 && tempScrollDiff == 0)
{
cursor.localPosition = new Vector3(-249f, 67f, 0);
ismeObj = GameObject.Find("GameManager/ShopCanvases/ItemShopCanvas/ItemShopBuyPanel/ItemListPanel/ItemScroller/ItemListSpacer").transform.GetChild(0).gameObject;
}
else if (cursorOnItem == 0 && tempScrollDiff > 0)
{
cursor.localPosition = new Vector3(-249f, 67f, 0);
ismeObj = GameObject.Find("GameManager/ShopCanvases/ItemShopCanvas/ItemShopBuyPanel/ItemListPanel/ItemScroller/ItemListSpacer").transform.GetChild(tempScrollDiff).gameObject;
}
else if (cursorOnItem > 0 && tempScrollDiff > 0)
{
cursor.localPosition = new Vector3(-249f, (67f - (cursorOnItem * itemSpacer)), 0);
ismeObj = GameObject.Find("GameManager/ShopCanvases/ItemShopCanvas/ItemShopBuyPanel/ItemListPanel/ItemScroller/ItemListSpacer").transform.GetChild(cursorOnItem + tempScrollDiff).gameObject;
}
else
{
cursor.localPosition = new Vector3(-249f, (67f - (cursorOnItem * itemSpacer)), 0);
ismeObj = GameObject.Find("GameManager/ShopCanvases/ItemShopCanvas/ItemShopBuyPanel/ItemListPanel/ItemScroller/ItemListSpacer").transform.GetChild(cursorOnItem).gameObject;
}
}
isme = ismeObj.GetComponent<ItemShopMouseEvents>();
isme.ShowItemDetails();
if (Input.GetButtonDown("Confirm") && !confirmPressed)
{
confirmPressed = true;
GameManager.instance.itemShopItem = isme.GetItem(ismeObj.transform.Find("BuyShopItemNameText").GetComponent<Text>().text);
GameManager.instance.itemShopCost = int.Parse(ismeObj.transform.Find("BuyShopItemCostText").GetComponent<Text>().text);
if (confirmationConfirm.HasEnoughGold(1))
{
GameObject.Find("GameManager/Menus").GetComponent<GameMenu>().PlaySE(AudioManager.instance.confirmSE);
itemShopCursorState = ItemShopCursorStates.ITEMCONFIRM;
isme.ProcessShop();
} else
{
GameObject.Find("GameManager/Menus").GetComponent<GameMenu>().PlaySE(AudioManager.instance.cantActionSE);
}
}
}
if (shopMode == "Sell")
{
int itemCount = GameObject.Find("GameManager/ShopCanvases/ItemShopCanvas/ItemShopSellPanel/ItemListPanel/ItemScroller/ItemListSpacer").transform.childCount;
int scrollDiff = itemCount - 9;
if (itemCount <= 9)
{
tempScrollDiff = 0;
}
if (cursor.parent != GameObject.Find("GameManager/ShopCanvases/ItemShopCanvas").transform)
{
cursor.SetParent(GameObject.Find("GameManager/ShopCanvases/ItemShopCanvas").transform);
}
if (cursor.gameObject.GetComponent<CanvasGroup>().alpha != 1)
{
cursor.gameObject.GetComponent<CanvasGroup>().alpha = 1;
}
confirmationQuantityUp = GameObject.Find("GameManager/ShopCanvases/ItemShopCanvas/ItemShopSellPanel/ConfirmationPanel/SellQuantityUpButton").GetComponent<ItemShopConfirmationMouseEvents>();
confirmationQuantityDown = GameObject.Find("GameManager/ShopCanvases/ItemShopCanvas/ItemShopSellPanel/ConfirmationPanel/SellQuantityDownButton").GetComponent<ItemShopConfirmationMouseEvents>();
confirmationConfirm = GameObject.Find("GameManager/ShopCanvases/ItemShopCanvas/ItemShopSellPanel/ConfirmationPanel/SellButton").GetComponent<ItemShopConfirmationMouseEvents>();
RectTransform spacerScroll = GameObject.Find("GameManager/ShopCanvases/ItemShopCanvas/ItemShopSellPanel/ItemListPanel/ItemScroller/ItemListSpacer").GetComponent<RectTransform>();
if (!dpadPressed && cursorOnItem == 0 && tempScrollDiff == 0)
{
if (itemCount > 1)
{
if (Input.GetAxisRaw("DpadVertical") == -1) //down
{
dpadPressed = true;
cursorOnItem = cursorOnItem + 1;
AudioManager.instance.PlaySE(AudioManager.instance.confirmSE);
}
}
if (Input.GetAxisRaw("DpadVertical") == 1) //up
{
dpadPressed = true;
AudioManager.instance.PlaySE(AudioManager.instance.confirmSE);
itemShopCursorState = ItemShopCursorStates.OPTIONS;
}
}
else if (!dpadPressed && cursorOnItem == 0 && tempScrollDiff > 0)
{
if (Input.GetAxisRaw("DpadVertical") == -1) //down
{
cursorOnItem = cursorOnItem + 1;
dpadPressed = true;
AudioManager.instance.PlaySE(AudioManager.instance.confirmSE);
}
if (Input.GetAxisRaw("DpadVertical") == 1) //up
{
spacerScroll.anchoredPosition = new Vector3(0.0f, (itemSpacer * (tempScrollDiff - 1)), 0.0f);
tempScrollDiff = tempScrollDiff - 1;
dpadPressed = true;
AudioManager.instance.PlaySE(AudioManager.instance.confirmSE);
}
}
else if (!dpadPressed && cursorOnItem > 0 && cursorOnItem < 8)
{
if (Input.GetAxisRaw("DpadVertical") == 1) //up
{
cursorOnItem = cursorOnItem - 1;
dpadPressed = true;
AudioManager.instance.PlaySE(AudioManager.instance.confirmSE);
}
if (Input.GetAxisRaw("DpadVertical") == -1) //down
{
cursorOnItem = cursorOnItem + 1;
dpadPressed = true;
AudioManager.instance.PlaySE(AudioManager.instance.confirmSE);
}
}
else if (!dpadPressed && cursorOnItem == 8 && tempScrollDiff == 0 && scrollDiff > 0)
{
if (Input.GetAxisRaw("DpadVertical") == 1) //up
{
cursorOnItem = cursorOnItem - 1;
dpadPressed = true;
AudioManager.instance.PlaySE(AudioManager.instance.confirmSE);
}
if (Input.GetAxisRaw("DpadVertical") == -1) //down
{
spacerScroll.anchoredPosition = new Vector3(0.0f, itemSpacer, 0.0f);
tempScrollDiff = tempScrollDiff + 1;
dpadPressed = true;
AudioManager.instance.PlaySE(AudioManager.instance.confirmSE);
}
}
else if (!dpadPressed && cursorOnItem == 8 && tempScrollDiff == 0 && scrollDiff == 0)
{
if (Input.GetAxisRaw("DpadVertical") == 1) //up
{
cursorOnItem = cursorOnItem - 1;
dpadPressed = true;
AudioManager.instance.PlaySE(AudioManager.instance.confirmSE);
}
}
else if (!dpadPressed && cursorOnItem == 8 && tempScrollDiff > 0 && (cursorOnItem + tempScrollDiff) < (itemCount - 1))
{
if (Input.GetAxisRaw("DpadVertical") == 1) //up
{
cursorOnItem = 8;
dpadPressed = true;
AudioManager.instance.PlaySE(AudioManager.instance.confirmSE);
}
if (Input.GetAxisRaw("DpadVertical") == -1) //down
{
spacerScroll.anchoredPosition = new Vector3(0.0f, (itemSpacer * (tempScrollDiff + 1)), 0.0f); //and use tempScrollDiff - 1 to go up
tempScrollDiff = tempScrollDiff + 1;
dpadPressed = true;
AudioManager.instance.PlaySE(AudioManager.instance.confirmSE);
}
}
else if (!dpadPressed && cursorOnItem == 8 && tempScrollDiff > 0 && (cursorOnItem + tempScrollDiff) == (itemCount - 1))
{
if (Input.GetAxisRaw("DpadVertical") == 1) //up
{
cursorOnItem = 7;
dpadPressed = true;
AudioManager.instance.PlaySE(AudioManager.instance.confirmSE);
}
}
//Debug.Log("cursorOnItem: " + cursorOnItem + ", scrollDiff: " + scrollDiff + ", tempScrollDiff: " + tempScrollDiff);
if (itemCount != 0)
{
if (cursorOnItem == itemCount)
{
cursorOnItem = itemCount - 1;
}
if (cursorOnItem == 0 && tempScrollDiff == 0)
{
cursor.localPosition = new Vector3(-249f, 67f, 0);
ismeObj = GameObject.Find("GameManager/ShopCanvases/ItemShopCanvas/ItemShopSellPanel/ItemListPanel/ItemScroller/ItemListSpacer").transform.GetChild(0).gameObject;
}
else if (cursorOnItem == 0 && tempScrollDiff > 0)
{
cursor.localPosition = new Vector3(-249f, 67f, 0);
ismeObj = GameObject.Find("GameManager/ShopCanvases/ItemShopCanvas/ItemShopSellPanel/ItemListPanel/ItemScroller/ItemListSpacer").transform.GetChild(tempScrollDiff).gameObject;
}
else if (cursorOnItem > 0 && tempScrollDiff > 0)
{
cursor.localPosition = new Vector3(-249f, (67f - (cursorOnItem * itemSpacer)), 0);
ismeObj = GameObject.Find("GameManager/ShopCanvases/ItemShopCanvas/ItemShopSellPanel/ItemListPanel/ItemScroller/ItemListSpacer").transform.GetChild(cursorOnItem + tempScrollDiff).gameObject;
}
else
{
cursor.localPosition = new Vector3(-249f, (67f - (cursorOnItem * itemSpacer)), 0);
ismeObj = GameObject.Find("GameManager/ShopCanvases/ItemShopCanvas/ItemShopSellPanel/ItemListPanel/ItemScroller/ItemListSpacer").transform.GetChild(cursorOnItem).gameObject;
}
isme = ismeObj.GetComponent<ItemShopMouseEvents>();
isme.ShowItemDetails();
} else
{
cursorOnItem = 0;
shopMode = "Buy";
GameObject.Find("GameManager/ShopCanvases/ItemShopCanvas/ShopOptionsPanel/BuyOptionButton").GetComponent<ItemShopMouseEvents>().DisplayItemShopBuyGUI();
}
if (Input.GetButtonDown("Confirm") && !confirmPressed)
{
confirmPressed = true;
GameManager.instance.itemShopItem = isme.GetItem(ismeObj.transform.Find("SellShopItemNameText").GetComponent<Text>().text);
GameManager.instance.itemShopCost = isme.GetItem(ismeObj.transform.Find("SellShopItemNameText").GetComponent<Text>().text).sellValue;
GameObject.Find("GameManager/Menus").GetComponent<GameMenu>().PlaySE(AudioManager.instance.confirmSE);
itemShopCursorState = ItemShopCursorStates.ITEMCONFIRM;
isme.ProcessShop();
}
cursor.localPosition = new Vector3(-249f, 67f - (cursorOnItem * itemSpacer), 0);
}
if (Input.GetButtonDown("Cancel"))
{
//clear items from list
ClearBuyList();
HideItemShopGUI();
inShop = false;
cursor.SetParent(GameObject.Find("GameManager").transform);
cursor.gameObject.GetComponent<CanvasGroup>().alpha = 0;
cursorOnItem = 0;
cursorOnOption = 0;
}
}
if (itemShopCursorState == ItemShopCursorStates.ITEMCONFIRM)
{
if (Input.GetAxisRaw("DpadHorizontal") == -1 && !dpadPressed) //left
{
dpadPressed = true;
confirmationQuantityDown.gameObject.GetComponent<Image>().color = pressedColor;
AudioManager.instance.PlaySE(AudioManager.instance.confirmSE);
confirmationQuantityDown.DecreaseQuantity(shopMode);
}
if (Input.GetAxisRaw("DpadHorizontal") == 1 && !dpadPressed) //right
{
dpadPressed = true;
confirmationQuantityUp.gameObject.GetComponent<Image>().color = pressedColor;
AudioManager.instance.PlaySE(AudioManager.instance.confirmSE);
confirmationQuantityUp.IncreaseQuantity(shopMode);
}
if (Input.GetButtonDown("Confirm") && !confirmPressed)
{
confirmPressed = true;
AudioManager.instance.PlaySE(AudioManager.instance.confirmSE);
itemShopCursorState = ItemShopCursorStates.ITEMLIST;
if (shopMode == "Buy")
{
confirmationConfirm.ConfirmPurchase();
ClearBuyList();
ShowItemListInBuyGUI();
} else if (shopMode == "Sell")
{
confirmationConfirm.ConfirmSell();
}
}
if (Input.GetButtonDown("Cancel"))
{
if (shopMode == "Buy")
{
confirmationConfirm.CancelPurchase();
} else if (shopMode == "Sell")
{
confirmationConfirm.CancelSell();
}
AudioManager.instance.PlaySE(AudioManager.instance.backSE);
itemShopCursorState = ItemShopCursorStates.ITEMLIST;
}
}
if (itemShopCursorState == ItemShopCursorStates.OPTIONS)
{
GameObject.Find("GameManager/ShopCanvases/ItemShopCanvas/ItemDescriptionPanel/ItemDescriptionText").GetComponent<Text>().text = "";
if (Input.GetAxisRaw("DpadHorizontal") == -1 && !dpadPressed && cursorOnOption == 1) //left
{
dpadPressed = true;
AudioManager.instance.PlaySE(AudioManager.instance.confirmSE);
cursorOnOption = cursorOnOption - 1;
}
if (Input.GetAxisRaw("DpadHorizontal") == 1 && !dpadPressed && cursorOnOption == 0) //right
{
dpadPressed = true;
AudioManager.instance.PlaySE(AudioManager.instance.confirmSE);
cursorOnOption = cursorOnOption + 1;
}
if (Input.GetAxisRaw("DpadVertical") == -1 && !dpadPressed) //down
{
dpadPressed = true;
itemShopCursorState = ItemShopCursorStates.ITEMLIST;
AudioManager.instance.PlaySE(AudioManager.instance.confirmSE);
}
if (Input.GetButtonDown("Confirm") && !confirmPressed)
{
confirmPressed = true;
cursorOnItem = 0;
if (cursorOnOption == 0) //buy
{
GameObject.Find("GameManager/ShopCanvases/ItemShopCanvas/ShopOptionsPanel/BuyOptionButton").GetComponent<ItemShopMouseEvents>().DisplayItemShopBuyGUI();
} else if (cursorOnOption == 1) //sell
{
GameObject.Find("GameManager/ShopCanvases/ItemShopCanvas/ShopOptionsPanel/SellOptionButton").GetComponent<ItemShopMouseEvents>().DisplayItemShopSellGUI();
}
}
if (Input.GetButtonDown("Cancel"))
{
//clear items from list
ClearBuyList();
HideItemShopGUI();
inShop = false;
cursor.SetParent(GameObject.Find("GameManager").transform);
cursor.gameObject.GetComponent<CanvasGroup>().alpha = 0;
cursorOnItem = 0;
cursorOnOption = 0;
}
if (cursorOnOption == 0)
{
cursor.localPosition = new Vector3(-169f, 138, 0);
shopMode = "Buy";
} else if (cursorOnOption == 1)
{
cursor.localPosition = new Vector3(89, 138, 0);
shopMode = "Sell";
}
}
if (Input.GetAxisRaw("DpadVertical") == 0 && Input.GetAxisRaw("DpadHorizontal") == 0)
{
dpadPressed = false;
confirmationQuantityDown.gameObject.GetComponent<Image>().color = unpressedColor;
confirmationQuantityUp.gameObject.GetComponent<Image>().color = unpressedColor;
}
if (confirmPressed && Input.GetButtonUp("Confirm"))
{
confirmPressed = false;
}
}
}
public void DisplayItemShopGUI()
{
GameObject.Find("GameManager/ShopCanvases/ItemShopCanvas/ShopOptionsPanel/BuyOptionButton/BuyOptionButtonText").GetComponent<Text>().fontStyle = FontStyle.Bold;
GameObject.Find("GameManager/ShopCanvases/ItemShopCanvas/ShopOptionsPanel/SellOptionButton/SellOptionButtonText").GetComponent<Text>().fontStyle = FontStyle.Normal;
GameObject.Find("GameManager/ShopCanvases/ItemShopCanvas").GetComponent<CanvasGroup>().alpha = 1;
GameObject.Find("GameManager/ShopCanvases/ItemShopCanvas").GetComponent<CanvasGroup>().interactable = true;
GameObject.Find("GameManager/ShopCanvases/ItemShopCanvas").GetComponent<CanvasGroup>().blocksRaycasts = true;
GameObject.Find("GameManager/ShopCanvases/ItemShopCanvas/ItemShopBuyPanel").GetComponent<CanvasGroup>().alpha = 1;
GameObject.Find("GameManager/ShopCanvases/ItemShopCanvas/ItemShopBuyPanel").GetComponent<CanvasGroup>().interactable = true;
GameObject.Find("GameManager/ShopCanvases/ItemShopCanvas/ItemShopBuyPanel").GetComponent<CanvasGroup>().blocksRaycasts = true;
GameObject.Find("GameManager/ShopCanvases/ItemShopCanvas/ItemShopSellPanel").GetComponent<CanvasGroup>().alpha = 0;
GameObject.Find("GameManager/ShopCanvases/ItemShopCanvas/ItemShopSellPanel").GetComponent<CanvasGroup>().interactable = false;
GameObject.Find("GameManager/ShopCanvases/ItemShopCanvas/ItemShopSellPanel").GetComponent<CanvasGroup>().blocksRaycasts = false;
DisablePlayerInput();
GameObject.Find("GameManager/Menus").GetComponent<GameMenu>().PauseBackground(true);
GameObject.Find("GameManager/Menus").GetComponent<GameMenu>().disableMenu = true;
}
public void HideItemShopGUI()
{
if (!GameManager.instance.inConfirmation)
{
GameObject.Find("GameManager/ShopCanvases/ItemShopCanvas").GetComponent<CanvasGroup>().alpha = 0;
GameObject.Find("GameManager/ShopCanvases/ItemShopCanvas").GetComponent<CanvasGroup>().interactable = false;
GameObject.Find("GameManager/ShopCanvases/ItemShopCanvas").GetComponent<CanvasGroup>().blocksRaycasts = false;
GameObject.Find("GameManager/ShopCanvases/ItemShopCanvas/ItemShopBuyPanel").GetComponent<CanvasGroup>().alpha = 0;
GameObject.Find("GameManager/ShopCanvases/ItemShopCanvas/ItemShopBuyPanel").GetComponent<CanvasGroup>().interactable = false;
GameObject.Find("GameManager/ShopCanvases/ItemShopCanvas/ItemShopBuyPanel").GetComponent<CanvasGroup>().blocksRaycasts = false;
GameObject.Find("GameManager/ShopCanvases/ItemShopCanvas/ItemShopSellPanel").GetComponent<CanvasGroup>().alpha = 0;
GameObject.Find("GameManager/ShopCanvases/ItemShopCanvas/ItemShopSellPanel").GetComponent<CanvasGroup>().interactable = false;
GameObject.Find("GameManager/ShopCanvases/ItemShopCanvas/ItemShopSellPanel").GetComponent<CanvasGroup>().blocksRaycasts = false;
EnablePlayerInput();
GameObject.Find("GameManager/Menus").GetComponent<GameMenu>().PauseBackground(false);
GameObject.Find("GameManager/Menus").GetComponent<GameMenu>().disableMenu = false;
AudioManager.instance.PlaySE(AudioManager.instance.backSE);
}
}
public void ShowItemListInBuyGUI()
{
goldText.text = GameManager.instance.gold.ToString();
//generate item prefab for each item in item shop list
foreach (BaseShopItem shopItem in itemShopList)
{
GameObject shopItemPanel = Instantiate(PrefabManager.Instance.shopBuyItemPrefab);
shopItemPanel.transform.Find("BuyShopItemNameText").GetComponent<Text>().text = shopItem.item.name;
shopItemPanel.transform.Find("BuyShopItemIcon").GetComponent<Image>().sprite = shopItem.item.icon;
shopItemPanel.transform.Find("BuyShopItemCostText").GetComponent<Text>().text = shopItem.cost.ToString();
shopItemPanel.transform.SetParent(GameObject.Find("GameManager/ShopCanvases").GetComponent<ShopObjectHolder>().shopItemBuyListSpacer, false);
if (shopItem.cost > GameManager.instance.gold)
{
shopItemPanel.transform.Find("BuyShopItemNameText").GetComponent<Text>().color = Color.gray;
} else
{
shopItemPanel.transform.Find("BuyShopItemNameText").GetComponent<Text>().color = Color.white;
}
}
}
void ClearBuyList()
{
foreach (Transform child in GameObject.Find("GameManager/ShopCanvases").GetComponent<ShopObjectHolder>().shopItemBuyListSpacer.transform)
{
Destroy (child.gameObject);
}
}
//-----------------------------
void DisablePlayerInput()
{
GameObject.Find("Player").GetComponent<PlayerController2D>().enabled = false;
GameObject.Find("Player").GetComponent<BoxCollider2D>().enabled = false;
}
void EnablePlayerInput()
{
GameObject.Find("Player").GetComponent<PlayerController2D>().enabled = true;
GameObject.Find("Player").GetComponent<BoxCollider2D>().enabled = true;
}
}
|
using PhobiaX.Graphics;
using PhobiaX.Physics;
using PhobiaX.SDL2;
using System;
using System.Collections.Generic;
using System.Text;
namespace PhobiaX.Game.GameObjects
{
public class MapGameObject : StaticGameObject
{
public MapGameObject(IRenderableObject renderableObject, ICollidableObject collidableObjet) : base(renderableObject, collidableObjet)
{
}
}
}
|
using System;
namespace Algorithms.LeetCode
{
public class MaxAreaOfIslandTask
{
public int MaxAreaOfIsland(int[][] grid)
{
int n = grid.Length;
int m = grid[0].Length;
var visited = new bool[n][];
for (int i = 0; i < n; ++i)
visited[i] = new bool[m];
int max = 0;
for (int i = 0; i < n; i++)
{
for (int j = 0; j < m; ++j)
{
if (!visited[i][j] && grid[i][j] == 0)
{
visited[i][j] = true;
}
if (visited[i][j])
{
continue;
}
max = Math.Max(max, FindIsland(i, j, visited, grid));
}
}
return max;
}
private int FindIsland(int i, int j, bool[][] visited, int[][] grid)
{
visited[i][j] = true;
var res = 1;
if (i - 1 >= 0 && !visited[i - 1][j] && grid[i - 1][j] == 1)
{
res += FindIsland(i - 1, j, visited, grid);
}
if (j - 1 >= 0 && !visited[i][j - 1] && grid[i][j - 1] == 1)
{
res += FindIsland(i, j - 1, visited, grid);
}
if (i + 1 < grid.Length && !visited[i + 1][j] && grid[i + 1][j] == 1)
{
res += FindIsland(i + 1, j, visited, grid);
}
if (j + 1 < grid[0].Length && !visited[i][j + 1] && grid[i][j + 1] == 1)
{
res += FindIsland(i, j + 1, visited, grid);
}
return res;
}
}
} |
using System.Linq;
using static TriangleCollector.Models.Triangle;
namespace TriangleCollector.Models
{
public static class ProfitPercentCalculator
{
public static decimal GetProfitPercent(Triangle triangle)
{
//use the direction list to understand what trades to make at each step
if (triangle.Direction == Directions.BuySellSell)
{
var firstTrade = 1 / triangle.FirstOrderBook.Keys.Min();
var secondTrade = firstTrade * triangle.SecondOrderBook.Keys.Max(); //sell
var thirdTrade = secondTrade * triangle.ThirdOrderBook.Keys.Max(); //sell
return thirdTrade - 1;
}
else if (triangle.Direction == Directions.BuyBuySell)
{
var firstTrade = 1 / triangle.FirstOrderBook.Keys.Min();
var secondTrade = firstTrade / triangle.SecondOrderBook.Keys.Min(); //buy
var thirdTrade = secondTrade * triangle.ThirdOrderBook.Keys.Max(); //sell
return thirdTrade - 1;
}
else //Sell Buy Sell
{
var firstTrade = 1 * triangle.FirstOrderBook.Keys.Max();
var secondTrade = firstTrade / triangle.SecondOrderBook.Keys.Min();
var thirdTrade = secondTrade * triangle.ThirdOrderBook.Keys.Max();
return thirdTrade - 1;
}
}
}
} |
using System;
using System.IO;
using System.Net;
using System.Data.Services.Client;
namespace DataService_BpmOnline_CRUD
{
class LoginClass
{
private readonly static Uri serverUri = new Uri("http://178.206.68.64:82/0/ServiceModel/EntityDataService.svc/");
private const string baseUri = "http://178.206.68.64:82/";
public static CookieContainer AuthCookie = new CookieContainer();
private const string authServiceUri = baseUri + @"/ServiceModel/AuthService.svc/Login";
private const string selectQueryUri = baseUri + @"/0/DataService/json/SyncReply/SelectQuery";
private const string deleteQueryUri = baseUri + @"/0/DataService/json/SyncReply/DeleteQuery";
private const string updateQueryUri = baseUri + @"/0/DataService/json/SyncReply/UpdateQuery";
private const string insertQueryUri = baseUri + @"/0/DataService/json/SyncReply/InsertQuery";
public static bool TryLogin(string userName, string userPassword)
{
var authRequest = HttpWebRequest.Create(authServiceUri) as HttpWebRequest;
authRequest.Method = "POST";
authRequest.ContentType = "application/json";
authRequest.CookieContainer = AuthCookie;
using (var requestStream = authRequest.GetRequestStream())
{
using (var writer = new StreamWriter(requestStream))
{
writer.Write(@"{
""UserName"":""" + userName + @""",
""UserPassword"":""" + userPassword + @"""
}");
}
}
ResponseStatus status = null;
using (var response = (HttpWebResponse)authRequest.GetResponse())
{
using (var reader = new StreamReader(response.GetResponseStream()))
{
string responseText = reader.ReadToEnd();
status = new System.Web.Script.Serialization.JavaScriptSerializer().Deserialize<ResponseStatus>(responseText);
}
}
if (status != null)
{
if (status.Code == 0)
{
return true;
}
Console.WriteLine(status.Message);
}
return false;
}
public static void OnSendingRequestCookie(object sender, SendingRequestEventArgs e)
{
var req = e.Request as HttpWebRequest;
req.CookieContainer = AuthCookie;
CookieCollection cookieCollection = AuthCookie.GetCookies(serverUri);
string csrfToken = cookieCollection["BPMCSRF"].Value;
((HttpWebRequest)e.Request).Headers.Add("BPMCSRF", csrfToken);
e.Request = req;
}
public static void CreateHttpRequest(out HttpWebRequest request, string collectionName, Guid id, string requestMethod)
{
request = (HttpWebRequest)HttpWebRequest.Create(serverUri
+ collectionName + "(guid'" + id + "')");
request.Method = requestMethod;
request.Accept = "application/atom+xml";
request.ContentType = "application/atom+xml;type=entry";
request.CookieContainer = AuthCookie;
CookieCollection cookieCollection = AuthCookie.GetCookies(serverUri);
string csrfToken = cookieCollection["BPMCSRF"].Value;
request.Headers.Add("BPMCSRF", csrfToken);
}
public static void CreateAndSendHttpRequestDataService(out HttpWebRequest request, Configuration.RequestType type)
{
string requestUri=String.Empty;
switch(type)
{
case Configuration.RequestType.Insert:
requestUri = insertQueryUri;
break;
case Configuration.RequestType.Update:
requestUri = updateQueryUri;
break;
case Configuration.RequestType.Delete:
requestUri = deleteQueryUri;
break;
case Configuration.RequestType.Select:
requestUri = selectQueryUri;
break;
default:
break;
}
request = HttpWebRequest.Create(requestUri) as HttpWebRequest;
request.Method = ReqestMethod.Post;
request.ContentType = "application/json";
request.CookieContainer = LoginClass.AuthCookie;
CookieCollection cookieCollection = LoginClass.AuthCookie.GetCookies(serverUri);
string csrfToken = cookieCollection["BPMCSRF"].Value;
request.Headers.Add("BPMCSRF", csrfToken);
}
}
}
|
using System;
using System.Xml.Linq;
using System.Globalization;
namespace DesignMaterial
{
class Movimentacao
{
XElement Cadastro = XElement.Load(@"Cadastro.xml");
public string Codigo { get;}
public double Valor { get; set; }
public string Descricao { get; set; }
public string Data { get; set; }
public string Natureza { get; set; }
public string Cliente { get; set; }
public Movimentacao()
{
Guid x = Guid.NewGuid();
Codigo = x.ToString().Substring(14, 7);
}
}
class Dados
{
XElement Cadastro = XElement.Load(@"Cadastro.xml");
public void AdicionarNovo(Movimentacao x)
{
XElement NovoCad = new XElement("Registro",
new XElement("Codigo", x.Codigo),
new XElement("Data", x.Data),
new XElement("Natureza", x.Natureza),
new XElement("Descricao", x.Descricao),
new XElement("Valor", x.Valor)
);
Cadastro.Add(NovoCad);
try
{
Cadastro.Save(@"Cadastro.xml");
}
catch (UnauthorizedAccessException ex)
{
System.Windows.MessageBox.Show("Por favor, execute o programa como administrador para utilizar essa função!", ex.Message);
System.Windows.Application.Current.Shutdown();
}
}
}
class Operacoes
{
public bool ValidarData(string Date)
{
try
{
DateTime.ParseExact(Date, "dd/MM/yyyy", DateTimeFormatInfo.InvariantInfo);
}
catch
{
return false;
}
return true;
}
public void ValidarString(string x,string y, string z)
{
if (x == "" || y == "" || z == "")
{
throw new FormatException("O valor de algum campo está vazio");
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Linq;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using System.Drawing.Printing;
using System.Data.SqlClient;
using System.IO;
using Restuarnt.Bl;
using System.Windows.Input;
namespace Restuarnt.PL
{
public partial class Frm_Setting : DevExpress.XtraEditors.XtraForm
{
SettingPrint st = new SettingPrint();
public Frm_Setting()
{
InitializeComponent();
}
private void radioButton1_CheckedChanged(object sender, EventArgs e)
{
}
private void radioButton4_CheckedChanged(object sender, EventArgs e)
{
}
//call to show orderdata in DB
private void showOrderData()
{
try
{
tbl.Clear();
tbl = st.SelectSettingPrintOrder();
if (tbl.Rows.Count >0)
{
byte[] image = (byte[])tbl.Rows[0][0];
MemoryStream f = new MemoryStream(image);
pictureLogo.Image = Image.FromStream(f);
txtAddress.Text = tbl.Rows[0][1].ToString();
txtDescription.Text = tbl.Rows[0][2].ToString();
txtPhone1.Text = tbl.Rows[0][3].ToString();
txtPhone2.Text = tbl.Rows[0][4].ToString();
Txt_DeliveryService.Text = Properties.Settings.Default.DeliveryService.ToString();
if (Properties.Settings.Default.OrderType=="صالة")
{
Rdb_Sala.Checked = true;
}
if (Properties.Settings.Default.OrderType == "دليفرى")
{
Rdb_Deleviry.Checked = true;
}
if (Properties.Settings.Default.OrderType == "تيك اواى")
{
Rdb_TakeAway.Checked = true;
}
/////////////////
if (Properties.Settings.Default.PrintCheckenInHold == "true")
{
check_checkenInHold.Checked = true;
}
if (Properties.Settings.Default.PrintCheckenInHold == "false")
{
check_checkenInHold.Checked = false;
}
////////////////////////
if (Properties.Settings.Default.PrintOrderInHold == "true")
{
check_OrderInhold.Checked = true;
}
if (Properties.Settings.Default.PrintOrderInHold == "false")
{
check_OrderInhold.Checked = false;
}
////////////////////////////
if (Properties.Settings.Default.PrintCheckenInSave == "true")
{
check_CheckenInSave.Checked = true;
}
if (Properties.Settings.Default.PrintCheckenInSave == "false")
{
check_CheckenInSave.Checked = false;
}
/////////////////////////////
///
if (Properties.Settings.Default.PrintOrderInSave == "true")
{
check_OrderInSave.Checked = true;
}
if (Properties.Settings.Default.PrintOrderInSave == "false")
{
check_OrderInSave.Checked = false;
}
///////////////////////
/////////////////////////
if (Properties.Settings.Default.CheckenType == "collect")
{
Rdb_Collect.Checked = true;
}
if (Properties.Settings.Default.CheckenType == "seperator")
{
Rdb_Seperator.Checked = true;
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
string printerName = "";
//call to show printers name in combo
private void showPrinters()
{
try
{
for (int i = 0; i < PrinterSettings.InstalledPrinters.Count; i++)
{
printerName = PrinterSettings.InstalledPrinters[i];
cbxPrinterClient.Items.Add(printerName);
Cmb_PrintChecken.Items.Add(printerName);
Cmb_PrintDrinks.Items.Add(printerName);
}
if (Properties.Settings.Default.PrinterOrderClient == "")
{
cbxPrinterClient.SelectedIndex = 0;
}
else
{
cbxPrinterClient.Text = Properties.Settings.Default.PrinterOrderClient;
}
if (Properties.Settings.Default.PrinterChecken == "")
{
Cmb_PrintChecken.SelectedIndex = 0;
}
else
{
Cmb_PrintChecken.Text = Properties.Settings.Default.PrinterChecken;
}
if (Properties.Settings.Default.PrinterDrinks == "")
{
Cmb_PrintDrinks.SelectedIndex = 0;
}
else
{
Cmb_PrintDrinks.Text = Properties.Settings.Default.PrinterDrinks;
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void Frm_Setting_Load(object sender, EventArgs e)
{
try
{
showPrinters();
}
catch (Exception) { }
try
{
showOrderData();
}
catch (Exception) { }
}
private void btnSavePrinter_Click(object sender, EventArgs e)
{
//try
//{
//if (cbxPrinter.Text == "")
//{
// MessageBox.Show("من فضلك تاكد من بيانات طابعة الفواتير", "تاكيد");
// return;
//}
//Properties.Settings.Default.PrinterName = cbxPrinter.Text;
//Properties.Settings.Default.Save();
////Properties.Settings.Default.PrintBarcode = cbx_printBarcode.Text;
////Properties.Settings.Default.Save();
//MessageBox.Show("تم الحفظ بنجاح", "تاكيد", MessageBoxButtons.OK, MessageBoxIcon.Information);
//}
//catch (Exception ex)
//{
// MessageBox.Show(ex.Message);
//}
}
//function to convert image to byte and save it in DB
private void saveImage(string stmt, string paramaterName, string message)
{
}
DataTable tbl = new DataTable();
private void btnSaveOrder_Click(object sender, EventArgs e)
{
try
{
//if (txtName.Text == "")
//{
// MessageBox.Show("من فضلك اكتب اسم الشركة", "تاكيد", MessageBoxButtons.OK, MessageBoxIcon.Information);
// return;
//}
if (cbxPrinterClient.Text == "")
{
MessageBox.Show("من فضلك تاكد من اختيار طابعة فاتورة العميل", "تاكيد");
return;
}
if (Cmb_PrintChecken.Text == "")
{
MessageBox.Show("من فضلك تاكد من اختيار طابعة للمطبخ ", "تاكيد");
return;
}
if (Cmb_PrintDrinks.Text == "")
{
MessageBox.Show("من فضلك تاكد من اختيار طابعة للمشروبات ", "تاكيد");
return;
}
Properties.Settings.Default.PrinterOrderClient = cbxPrinterClient.Text;
Properties.Settings.Default.Save();
Properties.Settings.Default.PrinterChecken = (Cmb_PrintChecken.Text);
Properties.Settings.Default.Save();
Properties.Settings.Default.PrinterDrinks = (Cmb_PrintDrinks.Text);
Properties.Settings.Default.Save();
Properties.Settings.Default.DeliveryService = Convert.ToDecimal(Txt_DeliveryService.Text);
Properties.Settings.Default.Save();
//////////////////////////
if (check_checkenInHold.Checked == true)
{
Properties.Settings.Default.PrintCheckenInHold = "true";
Properties.Settings.Default.Save();
}
if (check_checkenInHold.Checked == false)
{
Properties.Settings.Default.PrintCheckenInHold = "false";
Properties.Settings.Default.Save();
}
////////////////////////
if (check_OrderInhold.Checked == true)
{
Properties.Settings.Default.PrintOrderInHold = "true";
Properties.Settings.Default.Save();
}
if (check_OrderInhold.Checked == false)
{
Properties.Settings.Default.PrintOrderInHold = "false";
Properties.Settings.Default.Save();
}
////////////////////////////
if (check_CheckenInSave.Checked == true)
{
Properties.Settings.Default.PrintCheckenInSave = "true";
Properties.Settings.Default.Save();
}
if (check_CheckenInSave.Checked == false)
{
Properties.Settings.Default.PrintCheckenInSave = "false";
Properties.Settings.Default.Save();
}
/////////////////////////////
///
if (check_OrderInSave.Checked == true)
{
Properties.Settings.Default.PrintOrderInSave = "true";
Properties.Settings.Default.Save();
}
if (check_OrderInSave.Checked == false)
{
Properties.Settings.Default.PrintOrderInSave = "false";
Properties.Settings.Default.Save();
}
///////////////////////
/////////////////////////
if (Rdb_Collect.Checked == true)
{
Properties.Settings.Default.CheckenType ="collect";
Properties.Settings.Default.Save();
}
if (Rdb_Seperator.Checked == true)
{
Properties.Settings.Default.CheckenType = "seperator";
Properties.Settings.Default.Save();
}
////////////////////////////////////////
if (Rdb_Deleviry.Checked==true)
{
Properties.Settings.Default.OrderType ="دليفرى";
Properties.Settings.Default.Save();
}
if (Rdb_Sala.Checked==true)
{
Properties.Settings.Default.OrderType ="صالة";
Properties.Settings.Default.Save();
}
if (Rdb_TakeAway.Checked == true)
{
Properties.Settings.Default.OrderType ="تيك اواى";
Properties.Settings.Default.Save();
}
tbl.Clear();
tbl = st.SelectSettingPrintOrder();
if (tbl.Rows.Count > 0)
{
if (imagePath == "")
{
st.UpdateSettingPrint((byte[])tbl.Rows[0][0], txtAddress.Text, txtDescription.Text, txtPhone1.Text, txtPhone2.Text);
// m.UpdateMenu(txt_name.Text, Convert.ToDecimal(txt_seeling.Text), Convert.ToInt32(lable_num.Text), Convert.ToInt32(comboBox1.SelectedValue), (byte[])layoutView1.GetFocusedRowCellValue("Images"));
}
else
{
FileStream filestream = new FileStream(imagePath, FileMode.Open, FileAccess.Read);
Byte[] bytestream = new Byte[filestream.Length];
filestream.Read(bytestream, 0, bytestream.Length);
filestream.Close();
st.UpdateSettingPrint(bytestream, txtAddress.Text, txtDescription.Text, txtPhone1.Text, txtPhone2.Text);
}
}
else
{
if (imagePath == "")
{
imagePath = Application.StartupPath + @"\Resources" + @"\image-not-found-scaled-1150x6471.png";
}
//convert image to byte save in db
FileStream filestream = new FileStream(imagePath, FileMode.Open, FileAccess.Read);
Byte[] bytestream = new Byte[filestream.Length];
filestream.Read(bytestream, 0, bytestream.Length);
filestream.Close();
st.AddSettingPrint(bytestream, txtAddress.Text, txtDescription.Text, txtPhone1.Text, txtPhone2.Text);
}
MessageBox.Show("تم الحفظ بنجاح", "تاكيد", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void btnSaveGenralSetting_Click(object sender, EventArgs e)
{
}
private void txtName_TextChanged(object sender, EventArgs e)
{
}
private void label2_Click(object sender, EventArgs e)
{
}
private void Txt_DeliveryService_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar == '.' && Txt_DeliveryService.Text.ToString().IndexOf('.') > -1)
{
e.Handled = true;
}
else if (!char.IsDigit(e.KeyChar) && e.KeyChar != 8 && e.KeyChar != Convert.ToChar((System.Globalization.CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator)))
{
e.Handled = true;
}
}
private void txtPhone1_KeyPress(object sender, KeyPressEventArgs e)
{
}
private void label5_Click(object sender, EventArgs e)
{
}
private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
}
private void checkBox4_CheckedChanged(object sender, EventArgs e)
{
}
private void checkBox3_CheckedChanged(object sender, EventArgs e)
{
}
private void label8_Click(object sender, EventArgs e)
{
}
private void checkBox2_CheckedChanged(object sender, EventArgs e)
{
}
private void Txt_DeliveryService_Click(object sender, EventArgs e)
{
Txt_DeliveryService.SelectAll();
}
private void btnChoose_Click(object sender, EventArgs e)
{
OpenFileDialog openFileDialog = new OpenFileDialog();
openFileDialog.Filter = "All Files (*.*) | *.*";
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
imagePath = openFileDialog.FileName.ToString();
pictureLogo.Image = null;
pictureLogo.ImageLocation = imagePath;
}
}
string imagePath = "";
private void btndelete_Click(object sender, EventArgs e)
{
pictureLogo.BackgroundImage = Properties.Resources.image_not_found_scaled_1150x647;
pictureLogo.Image = Properties.Resources.image_not_found_scaled_1150x647;
imagePath = Application.StartupPath + @"\Resources" + @"\image-not-found-scaled-1150x6471.png";
}
private void groupBox1_Enter(object sender, EventArgs e)
{
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace PrimeNumberTest.Common
{
public class PrimeNumberProvider
{
public static long[] GetPrimeNumbers()
{
return new long[] { 2, 3, 5, 7, 11,13, 17, 19, 23, 29, 73, 79, 83, 1861, 2003, 3463, 5000000000129, 1000023423521231521, 1000023423521231513 };
}
public static long[] GetNotPrimeNumbers()
{
return new long[] { 0, 1, 4, 6, 8, 9, 10, 12, 14, 15, 2000, 5000000000122 };
}
public static Dictionary<long,long> GetValueFirstPrimeDicionary()
{
var d = new Dictionary<long, long>();
d.Add(1, 2);
d.Add(2, 3);
d.Add(3, 5);
d.Add(4, 5);
d.Add(5, 7);
d.Add(6, 7);
d.Add(11, 13);
d.Add(12, 13);
d.Add(823, 827);
d.Add(825, 827);
d.Add(3100, 3109);
d.Add(3120, 3121);
d.Add(5000000000122, 5000000000129);
d.Add(1000023423521231513, 1000023423521231521);
return d;
}
}
}
|
using Microsoft.SharePoint;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
namespace YFVIC.DMS.Model.Models.Distribute
{
public class BorrowFileEntity
{
/// <summary>
/// 编号
/// </summary>
[DataMember]
public string Id;
/// <summary>
/// 文档名称
/// </summary>
[DataMember]
public string FileName;
/// <summary>
/// 存放地址GUID
/// </summary>
[DataMember]
public string FilePath;
/// <summary>
///文件地址
/// </summary>
[DataMember]
public string Path;
/// <summary>
/// 项目ep号码
/// </summary>
[DataMember]
public string ProjectNumber;
/// <summary>
/// 当前版本号
/// </summary>
[DataMember]
public string VersionNum;
/// <summary>
/// 项目名称
/// </summary>
[DataMember]
public string ProjectName;
/// <summary>
/// 产品线
/// </summary>
[DataMember]
public string ProjectLine;
/// <summary>
/// 客户
/// </summary>
[DataMember]
public string Customer;
/// <summary>
/// 文件编号
/// </summary>
[DataMember]
public string FileId;
/// <summary>
///文件是否存在
/// </summary>
[DataMember]
public string FileIsExist;
/// <summary>
/// 关联标签
/// </summary>
[DataMember]
public string AssTag;
/// <summary>
///sharepoint版本号
/// </summary>
[DataMember]
public string SPVersion;
/// <summary>
/// 文件类别
/// </summary>
[DataMember]
public string FileType;
/// <summary>
///文件类别
/// </summary>
[DataMember]
public string FileClass;
/// <summary>
/// 组
/// </summary>
[DataMember]
public string FunctionGroup;
/// <summary>
/// 过程类型
/// </summary>
[DataMember]
public string ProcessType;
/// <summary>
/// 当前版本号
/// </summary>
[DataMember]
public string Sample;
/// <summary>
/// 数字组
/// </summary>
[DataMember]
public string NumberGroup;
/// <summary>
/// 文件标签
/// </summary>
[DataMember]
public string FileLable;
/// <summary>
/// RTCAprovalId
/// </summary>
[DataMember]
public string RTCAprovalId;
/// <summary>
///ReleasePurpose
/// </summary>
[DataMember]
public string ReleasePurpose;
/// <summary>
/// SW
/// </summary>
[DataMember]
public string SW;
/// <summary>
/// Micro
/// </summary>
[DataMember]
public string Micro;
/// <summary>
/// SWRevision
/// </summary>
[DataMember]
public string SWRevision;
/// <summary>
/// OEM
/// </summary>
[DataMember]
public string OEM;
/// <summary>
/// OEM关键字
/// </summary>
[DataMember]
public string OEMKey;
/// <summary>
/// 文件大类
/// </summary>
[DataMember]
public string BigClass;
/// <summary>
/// 文件小类
/// </summary>
[DataMember]
public string SmallClass;
/// <summary>
/// 资产分类
/// </summary>
[DataMember]
public string FileLevel;
/// <summary>
/// 文件保存地址
/// </summary>
[DataMember]
public string FileArea;
/// <summary>
/// 是否更新
/// </summary>
[DataMember]
public string IsUpdata;
/// <summary>
/// 借阅编号
/// </summary>
[DataMember]
public string BorrowId;
}
}
|
using System.ComponentModel.DataAnnotations;
using System.Xml.Serialization;
namespace BO
{
public class Competitor : Personne
{
[XmlIgnore]
[Display(Name = "Inscrit à la course")]
public Race Race { get; set; }
}
} |
using IWorkFlow.DataBase;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace IWorkFlow.ORM
{
[Serializable]
[DataTableInfo("B_OA_Email_Mark", "id")]
public class B_OA_Email_Mark : QueryInfo
{
#region Model
private int _id;
[DataField("id", "B_OA_Email_Mark",false)]
public int id
{
set { _id = value; }
get { return _id; }
}
private string _markName;
[DataField("markName", "B_OA_Email_Mark")]
public string markName
{
set { _markName = value; }
get { return _markName; }
}
private string _userid;
[DataField("userid", "B_OA_Email_Mark")]
public string userid
{
set { _userid = value; }
get { return _userid; }
}
#endregion
}
}
|
using System;
namespace TrainAPI
{
public class API
{
}
}
|
using NUnit.Framework;
using OpenQA.Selenium;
using System;
namespace Training
{
public class Task7 : Base
{
[Test]
public void Task_7()
{
driver.Navigate().GoToUrl("http://localhost/litecart/admin/");
driver.FindElement(By.Name("username")).SendKeys("admin");
driver.FindElement(By.Name("password")).SendKeys("admin");
driver.FindElement(By.Name("login")).Click();
var elementsCount = driver.FindElements(By.CssSelector("#box-apps-menu-wrapper li")).Count;
for (var i = 1; i <= elementsCount; i++)
{
var element = driver.FindElement(By.XPath($"//li[@id='app-'][{i}]"));
element.Click();
if (driver.IsElementPresent(By.CssSelector(".docs li")))
{
var subCount = driver.FindElements(By.CssSelector(".docs li")).Count;
for (var k = 1; k <= subCount; k++)
{
var subFolder = driver.FindElement(By.XPath($"//ul[@class='docs']/li[{k}]"));
subFolder.Click();
Assert.True(driver.FindElement(By.CssSelector("h1")).Displayed);
Console.WriteLine(driver.FindElement(By.CssSelector("h1")).Text);
}
}
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
using FSDP.DATA.EF;
namespace FSDP.UI.MVC.Controllers
{
[Authorize]
public class CourseCompletionsController : Controller
{
//private FSDPEntities1 db = new FSDPEntities1();
UnitOfWork uow = new UnitOfWork();
// GET: CourseCompletions
public ActionResult Index()
{
var courseCompletions = uow.CourseCompletionsRepository.Get(includeProperties: "Cours");
if (User.IsInRole("Employee"))
{
var employeeOnly = uow.CourseCompletionsRepository.Get(includeProperties: "Cours").Where(x => x.UserID == User.Identity.Name);
return View(employeeOnly.ToList());
}
return View(courseCompletions.ToList());
}
// GET: CourseCompletions/Details/5
public ActionResult Details(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
CourseCompletion courseCompletion = uow.CourseCompletionsRepository.Find(id);
if (courseCompletion == null)
{
return HttpNotFound();
}
return View(courseCompletion);
}
// GET: CourseCompletions/Create
[Authorize(Roles = "Admin")]
public ActionResult Create()
{
ViewBag.UserID = new SelectList(uow.AspNetUsersRepository.Get(), "Id", "Email");
ViewBag.CourseID = new SelectList(uow.CoursesRepository.Get(), "CourseID", "CourseName");
return View();
}
// POST: CourseCompletions/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.
[Authorize(Roles = "Admin")]
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "CourseCompletionID,UserID,CourseID,DateCompleted")] CourseCompletion courseCompletion)
{
if (ModelState.IsValid)
{
uow.CourseCompletionsRepository.Add(courseCompletion);
uow.Save();
return RedirectToAction("Index");
}
ViewBag.UserID = new SelectList(uow.AspNetUsersRepository.Get(), "Id", "Email");
ViewBag.CourseID = new SelectList(uow.CoursesRepository.Get(), "CourseID", "CourseName");
return View(courseCompletion);
}
// GET: CourseCompletions/Edit/5
[Authorize(Roles = "Admin")]
public ActionResult Edit(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
CourseCompletion courseCompletion = uow.CourseCompletionsRepository.Find(id);
if (courseCompletion == null)
{
return HttpNotFound();
}
ViewBag.UserID = new SelectList(uow.AspNetUsersRepository.Get(), "Id", "Email");
ViewBag.CourseID = new SelectList(uow.CoursesRepository.Get(), "CourseID", "CourseName");
return View(courseCompletion);
}
// POST: CourseCompletions/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.
[Authorize(Roles = "Admin")]
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit([Bind(Include = "CourseCompletionID,UserID,CourseID,DateCompleted")] CourseCompletion courseCompletion, AspNetUser aspNetUser)
{
if (ModelState.IsValid)
{
uow.CourseCompletionsRepository.Update(courseCompletion);
uow.Save();
return RedirectToAction("Index");
}
ViewBag.UserID = new SelectList(uow.AspNetUsersRepository.Get(), "UserID", "Email");
ViewBag.CourseID = new SelectList(uow.CoursesRepository.Get(), "CourseID", "CourseName");
return View(courseCompletion);
}
// GET: CourseCompletions/Delete/5
[Authorize(Roles = "Admin")]
public ActionResult Delete(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
CourseCompletion courseCompletion = uow.CourseCompletionsRepository.Find(id);
if (courseCompletion == null)
{
return HttpNotFound();
}
return View(courseCompletion);
}
// POST: CourseCompletions/Delete/5
[Authorize(Roles = "Admin")]
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public ActionResult DeleteConfirmed(int id)
{
CourseCompletion courseCompletion = uow.CourseCompletionsRepository.Find(id);
uow.CourseCompletionsRepository.Remove(courseCompletion);
uow.Save();
return RedirectToAction("Index");
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
uow.Dispose();
}
base.Dispose(disposing);
}
}
}
|
using Microsoft.VisualStudio.TestTools.UnitTesting;
using OpenQA.Selenium;
using System;
using System.Collections.Generic;
using System.Linq;
namespace PW.InternalMoney.Tests
{
public sealed class LinkCliker : ILinkCliker
{
private readonly IBrowserNavigator _browser;
public LinkCliker(IBrowserNavigator browser)
{
_browser = browser;
}
public void ClickOnLinkWithText(string linkText)
{
var linkWithText = FindIsLinkWithText(linkText);
Assert.IsNotNull(linkWithText, $"Can't find [{linkText}] link in page. Existed links is: [{GetExistedLinks()}]");
linkWithText.Click();
}
public void CheckThatLinkWithTextExist(string linkText)
{
var linkWithText = FindIsLinkWithText(linkText);
Assert.IsNotNull(linkWithText, $"Can't find [{linkText}] link in page. Existed links is: [{GetExistedLinks()}]");
}
public void CheckThatLinkWithTextNotExist(string linkText)
{
var linkWithText = FindIsLinkWithText(linkText);
Assert.IsNull(linkWithText, $"Found [{linkText}] link in page. But should not.");
}
private IWebElement FindIsLinkWithText(string linkText)
{
IList<IWebElement> links = _browser.GetDriver().FindElements(By.TagName("a"));
return links.SingleOrDefault(element => element.Text.Equals(linkText, StringComparison.OrdinalIgnoreCase));
}
private string GetExistedLinks()
{
var existedLinks = _browser.GetDriver().FindElements(By.TagName("a"));
return string.Join(", ", existedLinks.Select(link => $"[Tag: {link.TagName}, Text: {link.Text}]"));
}
}
}
|
using Terraria;
using Terraria.ID;
using Terraria.ModLoader;
namespace Caserraria.Items.Accessories
{
public class GraniteCore : ModItem
{
public override void SetStaticDefaults()
{
DisplayName.SetDefault("Granite Core");
Tooltip.SetDefault("+5 defense if under 50% HP");
}
public override void SetDefaults()
{
item.width = 20;
item.height = 20;
item.value = 10000;
item.rare = 1;
item.accessory = true;
}
public override void UpdateAccessory(Player player, bool hideVisual)
{
if (player.statLife < player.statLifeMax/2)
{
player.statDefense += 5;
}
}
}
}
|
// ReSharper disable MemberCanBePrivate.Global
using System;
using System.Collections.Generic;
using System.Linq;
namespace iSukces.Code.Interfaces
{
public interface ICsCodeWriter : ICodeWriter
{
}
public static class CsCodeWriterExtensions
{
public static void AddNamespaces(this ICsCodeWriter src, string namespaceName)
{
src.WriteLine("using {0};", namespaceName);
}
public static void AddNamespaces(this ICsCodeWriter src, IEnumerable<string> namespaceName)
{
foreach (var x in namespaceName)
src.AddNamespaces(x);
}
public static void CloseCompilerIf(this ICsCodeWriter self, string directive)
{
if (!string.IsNullOrEmpty(directive))
self.WritelineNoIndent("#endif");
}
public static void CloseCompilerIf(this ICsCodeWriter self, IConditional conditional)
{
self.CloseCompilerIf(conditional?.CompilerDirective);
}
public static T EmptyLine<T>(this T self, bool skip = false)
where T : ICodeWriter
{
if (!skip)
self.Append("\r\n");
return self;
}
public static string GetIndent(this ICodeWriter self)
{
return self.Indent > 0 ? new string(' ', self.Indent * 4) : "";
}
public static void OpenCompilerIf(this ICsCodeWriter self, string directive)
{
if (!string.IsNullOrEmpty(directive))
self.WritelineNoIndent("#if " + directive);
}
public static void OpenCompilerIf(this ICsCodeWriter self, IConditional conditional)
{
self.OpenCompilerIf(conditional?.CompilerDirective);
}
public static ICodeWriter OpenConstructor(this ICodeWriter self, string x, string baseOrThis = null)
{
self.WriteLine(x);
if (!string.IsNullOrEmpty(baseOrThis))
{
self.Indent++;
self.WriteLine(": " + baseOrThis);
self.Indent--;
}
self.WriteLine("{");
self.Indent++;
return self;
}
public static T OpenIf<T>(this T src, string condition)
where T : ICsCodeWriter
{
src.Open($"if ({condition})");
return src;
}
public static T OpenSwitch<T>(this T src, string expression)
where T : ICsCodeWriter
{
src.Open($"switch ({expression})");
return src;
}
public static T SingleLineIf<T>(this T src, string condition, string statement, string elseStatement = null)
where T : ICsCodeWriter
{
src.WriteLine("if (" + condition + ")");
src.IncIndent();
src.WriteLine(statement);
src.DecIndent();
if (string.IsNullOrEmpty(elseStatement))
return src;
src.WriteLine("else");
src.IncIndent();
src.WriteLine(elseStatement);
src.DecIndent();
return src;
}
public static void WriteComment(this ICsCodeWriter writer, ICommentable c)
{
var comment = c?.GetComments()?.Trim();
if (string.IsNullOrEmpty(comment))
return;
var lines = comment.Replace("\r\n", "\n").Split('\n');
if (lines.Length == 1)
{
writer.WriteLine("// " + lines[0]);
}
else
{
writer.WriteLine("/*");
foreach (var line in lines)
writer.WriteLine(line);
writer.WriteLine("*/");
}
}
public static T WriteIndent<T>(this T self)
where T : ICodeWriter
{
if (self.Indent > 0)
self.Append(new string(' ', self.Indent * CodeFormatting.IndentSpaces));
return self;
}
public static void WriteLambda(this ICsCodeWriter writer, string header, string expression, int maxLineLength,
bool addSemiColon)
{
var emptyHeader = string.IsNullOrEmpty(header);
if (emptyHeader)
{
writer.WriteLine($"=> {expression};");
return;
}
if (addSemiColon)
expression += ";";
header = $"{header} => ";
var lineLength = header.Length + expression.Length + writer.Indent * CodeFormatting.IndentSpaces;
if (lineLength <= maxLineLength)
writer.WriteLine(header + expression);
else
writer.WriteLine(header).IncIndent().WriteLine(expression).DecIndent();
}
public static void WriteLambda(this ICsCodeWriter writer, string header, IReadOnlyList<string> expression, int maxLineLength)
{
switch (expression.Count)
{
case 0:
throw new InvalidOperationException("No expression lines");
case 1:
WriteLambda(writer, header, expression.Single(), maxLineLength, true);
return;
}
WriteLambda(writer, header, expression[0], maxLineLength, false);
writer.IncIndent();
for (var index = 1; index < expression.Count; index++)
{
var line = expression[index];
if (index == expression.Count - 1)
line += ";";
writer.WriteLine(line);
}
writer.DecIndent();
}
public static T WriteMultiLineSummary<T>(this T src, IReadOnlyList<string> lines, bool skipIfEmpty = false)
where T : ICsCodeWriter
{
lines = lines ?? XArray.Empty<string>();
if (lines.Count == 0 && skipIfEmpty)
return src;
src.WriteLine("/// <summary>");
foreach (var line in lines)
src.WriteSummary(line);
src.WriteLine("/// </summary>");
return src;
}
public static T WriteNewLineAndIndent<T>(this T self)
where T : ICodeWriter
{
self.WriteLine();
if (self.Indent > 0)
self.Append(new string(' ', self.Indent * CodeFormatting.IndentSpaces));
return self;
}
public static T WriteSingleLineSummary<T>(this T src, string x, bool skipIfEmpty = false)
where T : ICsCodeWriter
{
if (x == null)
{
if (skipIfEmpty)
return src;
return WriteMultiLineSummary(src, XArray.Empty<string>());
}
var lines = x.Split('\r', '\n').Where(q => !string.IsNullOrEmpty(q?.Trim()))
.ToArray();
return WriteMultiLineSummary(src, lines, skipIfEmpty);
}
public static T WriteSummary<T>(this T src, string x)
where T : ICsCodeWriter
{
// System.Xml.Linq.XObject el = new XElement("param", new XAttribute("name", p.Name), p.Description);
// cs.Writeln("/// {0}", el);
src.WriteLine("/// {0}", x);
return src;
}
}
}
|
using Core;
using System;
namespace Tms_18_UnixTests
{
class Program
{
static void Main(string[] args)
{
// Название - [тестируемый метод] [сценарий] [ожидаемое поведение]
// Стиль ARRANGE(данные для входа), ACT(действие), ASSERT(проверка и взаимодействие)
// тестируется одна вещь за один раз
// Stabs (попытка) и mock (пародировать)
Calc calc = new Calc();
var summ = calc.Add(1, 2);
Console.WriteLine(summ);
// 1. Создали проект Untest
// 2. Сделали ссылку на проект
// 3. Написали наш патерн ARRANGE, ACT, ASSERT
Console.ReadLine();
}
}
}
|
namespace CarDealer.Data.Models
{
using System.Data.Entity;
using CarDealer.Models;
using Interfaces;
public class CustomerRepository : Repository<Customer>, ICustomerRepository
{
public CustomerRepository(DbContext context) : base(context)
{
}
}
} |
using System.Drawing;
using System.Windows.Forms;
using DelftTools.TestUtils;
using NUnit.Framework;
using SharpMap.UI.Tools;
namespace SharpMap.UI.Tests
{
[TestFixture]
public class ScaleBarTest
{
/// <summary>
/// This image shows a short bit of text with all 9 different alignment combinations around 9 different points.
/// The alignment point is at the intersection of the blue lines. The code is below:
/// </summary>
/// <param name="graphics"></param>
/// <param name="ctrl"></param>
private static void DrawPointText(Graphics graphics, Control ctrl)
{
float xDelta = ctrl.ClientRectangle.Size.Width/4f;
float yDelta = ctrl.ClientRectangle.Size.Height/4f;
var f = new StringFormat();
graphics.DrawLine(Pens.Blue, xDelta, 0f, xDelta,
ctrl.ClientRectangle.Height);
graphics.DrawLine(Pens.Blue, xDelta*2f, 0f, xDelta*2f,
ctrl.ClientRectangle.Height);
graphics.DrawLine(Pens.Blue, xDelta*3f, 0f, xDelta*3f,
ctrl.ClientRectangle.Height);
graphics.DrawLine(Pens.Blue, 0, yDelta,
ctrl.ClientRectangle.Width, yDelta);
graphics.DrawLine(Pens.Blue, 0, yDelta*2f,
ctrl.ClientRectangle.Width, yDelta*2f);
graphics.DrawLine(Pens.Blue, 0, yDelta*3f,
ctrl.ClientRectangle.Width, yDelta*3f);
f.Alignment = StringAlignment.Near;
f.LineAlignment = StringAlignment.Near;
graphics.DrawString("Near, Near Line", ctrl.Font, Brushes.Black,
xDelta*3, yDelta, f);
f.LineAlignment = StringAlignment.Center;
graphics.DrawString("Near, Center Line", ctrl.Font, Brushes.Black,
xDelta*3, yDelta*2, f);
f.LineAlignment = StringAlignment.Far;
graphics.DrawString("Near, Far Line", ctrl.Font, Brushes.Black,
xDelta*3, yDelta*3, f);
f.Alignment = StringAlignment.Center;
f.LineAlignment = StringAlignment.Near;
graphics.DrawString("Center, Near Line", ctrl.Font, Brushes.Black,
xDelta*2, yDelta, f);
f.LineAlignment = StringAlignment.Center;
graphics.DrawString("Center, Center Line", ctrl.Font, Brushes.Black,
xDelta*2, yDelta*2f, f);
f.LineAlignment = StringAlignment.Far;
graphics.DrawString("Center, Far Line", ctrl.Font, Brushes.Black,
xDelta*2, yDelta*3f, f);
f.Alignment = StringAlignment.Far;
f.LineAlignment = StringAlignment.Near;
graphics.DrawString("Far, Near Line", ctrl.Font, Brushes.Black,
xDelta, yDelta, f);
f.LineAlignment = StringAlignment.Center;
graphics.DrawString("Far, Center Line", ctrl.Font, Brushes.Black,
xDelta, yDelta*2f, f);
f.LineAlignment = StringAlignment.Far;
graphics.DrawString("Far, Far Line", ctrl.Font, Brushes.Black,
xDelta, yDelta*3f, f);
}
/// <summary>
/// The other nine combinations are created by aligning the text inside a bounding rectangle.
/// This image shows the same text aligned inside the window rectangle, using all 9 alignment combinations.
/// </summary>
/// <param name="graphics"></param>
/// <param name="control"></param>
private static void DrawRectText(Graphics graphics, Control control)
{
var f = new StringFormat();
var bounds = new RectangleF(
control.ClientRectangle.X,
control.ClientRectangle.Y,
control.ClientRectangle.Width,
control.ClientRectangle.Height);
f.Alignment = StringAlignment.Near;
f.LineAlignment = StringAlignment.Near;
graphics.DrawString("Near, Near", control.Font, Brushes.Black,
bounds, f);
f.Alignment = StringAlignment.Center;
f.LineAlignment = StringAlignment.Near;
graphics.DrawString("Center, Near", control.Font, Brushes.Black,
bounds, f);
f.Alignment = StringAlignment.Far;
f.LineAlignment = StringAlignment.Near;
graphics.DrawString("Far, Near", control.Font, Brushes.Black,
bounds, f);
f.Alignment = StringAlignment.Near;
f.LineAlignment = StringAlignment.Center;
graphics.DrawString("Near, Center", control.Font, Brushes.Black,
bounds, f);
f.Alignment = StringAlignment.Center;
f.LineAlignment = StringAlignment.Center;
graphics.DrawString("Center, Center", control.Font, Brushes.Black,
bounds, f);
f.Alignment = StringAlignment.Far;
f.LineAlignment = StringAlignment.Center;
graphics.DrawString("Far, Center", control.Font, Brushes.Black,
bounds, f);
f.Alignment = StringAlignment.Near;
f.LineAlignment = StringAlignment.Far;
graphics.DrawString("Near, Far", control.Font, Brushes.Black,
bounds, f);
f.Alignment = StringAlignment.Center;
f.LineAlignment = StringAlignment.Far;
graphics.DrawString("Center, Far", control.Font, Brushes.Black,
bounds, f);
f.Alignment = StringAlignment.Far;
f.LineAlignment = StringAlignment.Far;
graphics.DrawString("Far, Far", control.Font, Brushes.Black,
bounds, f);
}
private static void DrawRectangles(Graphics g)
{
g.PageUnit=GraphicsUnit.Pixel;
var p=new Pen(Color.Black, 3); //this pen will be 3 pixels wide
g.DrawRectangle(p,10,10,200,100); //draw a rectangle in Pixel mode (the default)
p.Dispose();
g.PageUnit=GraphicsUnit.Inch;
p=new Pen(Color.Blue,0.05f); //this pen will be 1/20th of an inch wide
g.DrawRectangle(p,0.1f,1.5f,4f,1f); // draw a rectangle 4" by 1"
p.Dispose();
g.PageUnit=GraphicsUnit.Millimeter;
p=new Pen(Color.Green,1f); //this pen will be 1 millimeter wide
g.DrawRectangle(p,4f,80f,80f,60f); // draw a rectangle 80 by 60 mm
p.Dispose();
}
[Test, Ignore("just for demonstration purposes")]
public void DrawRectanglesForDifferentUnits()
{
using (var control = new UserControl())
{
control.Paint +=
((sender, e) => DrawRectangles(e.Graphics));
WindowsFormsTestHelper.ShowModal(control);
}
}
[Test, Ignore("just for demonstration purposes")]
public void DrawTextInRectangle()
{
using (var control = new UserControl())
{
control.Paint +=
((sender, e) => DrawRectText(e.Graphics, (UserControl) sender));
WindowsFormsTestHelper.ShowModal(control);
}
}
[Test, Ignore("just for demonstration purposes")]
public void DrawTextNearPoint()
{
using (var control = new UserControl())
{
control.Paint +=
((sender, e) => DrawPointText(e.Graphics, (UserControl) sender));
WindowsFormsTestHelper.ShowModal(control);
}
}
[Test,Category(TestCategory.WindowsForms)]
public void ShowScaleBar()
{
var rectangle = new Rectangle(5,5,300,50);
var bar = new ScaleBar();
bar.BorderVisible = false;
bar.TransparentBackground = true;
bar.BorderVisible = true;
//bar.BarColor2 = Color.Yellow;
bar.SetScale(20, 40);
// bar.MapUnit = MapUnits.ws_muMeter;
// bar.BarUnit = MapUnits.ws_muMeter;
//bar.SetCustomUnit(4,"test","test");
// bar.MapUnit = MapUnits.ws_muCustom;
using (var control = new UserControl())
{
control.Paint +=
delegate(object sender, PaintEventArgs e)
{
// rectangle = new Rectangle(new Point(0, 0), ((Control) sender).Size);
bar.DrawTheControl(e.Graphics, rectangle);
};
WindowsFormsTestHelper.ShowModal(control);
}
}
[Test]
public void ToFormattedString()
{
double value = 1520000;
Assert.AreEqual(1.5.ToString()+"E+6", value.ToFormattedString(0.000001));
value = .0000012344;
Assert.AreEqual(1.2.ToString()+ "E-6", value.ToFormattedString(0.000001));
value = 100.2298234048243240294234320948234324032984;
Assert.AreEqual(100.23.ToString(), value.ToFormattedString(0.000001));
value = 1e10;
Assert.AreEqual("1E+10", value.ToFormattedString(0.000001));
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace Model.APIModels.Parameter
{
/// <summary>
/// 获取 销货单数据列表
/// </summary>
public class E_getSaleOutList
{
/// <summary>
/// 开始时间
/// </summary>
public DateTime? beginDate { get; set; }
/// <summary>
/// 结束时间
/// </summary>
public DateTime? endDate { get; set; }
/// <summary>
/// 客户代码
/// </summary>
public string customerCode { get; set; }
}
} |
using JetBrains.Annotations;
using Microsoft.Extensions.Configuration;
namespace Thinktecture.Extensions.Configuration.Legacy
{
/// <summary>
/// Configuration source for App.config and Web.config.
/// </summary>
public class LegacyConfigurationSource : FileConfigurationSource
{
/// <inheritdoc />
[NotNull]
public override IConfigurationProvider Build(IConfigurationBuilder builder)
{
EnsureDefaults(builder);
return new LegacyConfigurationProvider(this);
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class DiscoBall : MonoBehaviour
{
public float rotationSpeed = 15.0f;
public MeshRenderer mesh;
private Material material;
private static string IntensityOccStr = "_IntensityOcc";
private int maxDisco;
private int currDisco;
private float failTime = -5f;
void Awake()
{
maxDisco = 100;
material = mesh.GetComponent<MeshRenderer>().materials[0];
}
void Update()
{
transform.Rotate(Vector3.up * rotationSpeed * Time.deltaTime, Space.Self);
float failRatio = failTime - Time.time;
if (failRatio > 0f)
transform.localPosition = new Vector3(Random.Range(-failRatio * 0.5f, failRatio * 0.5f), Random.Range(-failRatio * 0.3f, failRatio * 0.3f), 0f);
else
transform.localPosition = Vector3.zero;
}
public void FailAnimation()
{
failTime = Time.time + 0.5f;
}
public void SetRotationSpeed(float speed)
{
rotationSpeed = speed;
}
public void SetMaxDisco(int val)
{
maxDisco = val;
}
public void SetDisco(int val)
{
currDisco = val;
float r = (float)currDisco / maxDisco;
SetDiscoBallIntensity(r);
}
private void SetDiscoBallIntensity(float intensity)
{
material.SetFloat(IntensityOccStr, intensity);
}
public void SetDissolveColor(Color color)
{
material.SetColor("_EdgeColor", color);
}
public void SetDissolveRatio(float ratio)
{
material.SetFloat("_AlphaThreshold", ratio);
}
}
|
using System;
using UnityEngine;
public interface IMouseService
{
event Action<Vector3> OnEnvironmentClick;
event Action<Vector3> OnEnvironmentRightClick;
event Action<GameObject> OnAttackableClick;
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace LinQ_Operation_Using_collections
{
class StateCollection
{
public int stateId { get; set; }
public string stateName { get; set; }
public double stateArea { get; set; }
public long statePopulation { get; set; }
public double stateGenderEqualityRatio { get; set; }
public List<string> stateCities { get; set; }
public List<string> stateRivers { get; set; }
public static List<StateCollection> GetStateCollections()
{
List<StateCollection> stateCollections = new List<StateCollection>();
stateCollections.Add(new StateCollection
{
stateId = 101,
stateName ="Maharashtra",
statePopulation = 1500,
stateArea = 150.2,
stateCities = new List<string> {"nasik","pune","mumbai"},
stateGenderEqualityRatio = 0.7,
stateRivers = new List<string> {"Godawari","Tapi","Wasundhara"}
});
stateCollections.Add(new StateCollection
{
stateId = 102,
stateName = "Panjab",
statePopulation = 1520,
stateArea = 50.2,
stateCities = new List<string> { "gurgaon", "hariyana", "cahna" },
stateGenderEqualityRatio = 0.2,
stateRivers = new List<string> { "ganga", "trupti", "delta" }
});
stateCollections.Add(new StateCollection
{
stateId = 103,
stateName = "Asam",
statePopulation = 150,
stateArea = 60.285,
stateCities = new List<string> { "nasik", "pune", "mumbai" },
stateGenderEqualityRatio = 0.3,
});
stateCollections.Add(new StateCollection
{
stateId = 104,
stateName = "Gujrat",
statePopulation = 1000,
stateArea = 120.2,
stateCities = new List<string> { "hara", "bhara", "kabab" },
stateGenderEqualityRatio = 0.3,
stateRivers = new List<string> { "jasusi", "nadi", "pani" }
});
stateCollections.Add(new StateCollection
{
stateId = 105,
stateName = "kerala",
statePopulation = 1300,
stateArea = 30.22,
stateCities = new List<string> { "natu", "chaitri", "rajarampur" },
stateGenderEqualityRatio = 1.7,
stateRivers = new List<string> { "nillu", "kantham", "wishwashwari" }
});
return stateCollections;
}
}
}
|
using IconCreator.Core.Domain.Enums;
using IconCreator.Core.Models;
using IconCreator.WPF.UI.Models;
using IconCreator.WPF.UI.ViewModel;
using Microsoft.Practices.ServiceLocation;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Configuration;
using System.Windows;
using System.Windows.Media;
namespace IconCreator.WPF.UI
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
///
public partial class MainWindow
{
readonly IconCreatorSettings IconCreatorSettings;
public MainWindow()
{
InitializeComponent();
Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
IconCreatorSettings = new IconCreatorSettings
{
Database = config.AppSettings.Settings["Database"].Value,
WorkIcons = config.AppSettings.Settings["Workicons"].Value,
Omschrijving = (Omschrijving)Int32.Parse(config.AppSettings.Settings["Omschrijving"].Value),
Opties = (Opties)Int32.Parse(config.AppSettings.Settings["Opties"].Value),
ImageStyles = (ImageStyles)Int32.Parse(config.AppSettings.Settings["ImageStyles"].Value),
IconSizes = (IconSize)Int32.Parse(config.AppSettings.Settings["IconSizes"].Value),
IsAlfatouch = Convert.ToBoolean(config.AppSettings.Settings["IsAlfatouch"].Value),
IsAlfaRetail = Convert.ToBoolean(config.AppSettings.Settings["IsAlfaRetail"].Value),
FontSize = Convert.ToInt32(config.AppSettings.Settings["FontSize"].Value),
Typeface = new Typeface(new FontFamily(config.AppSettings.Settings["FontFamily"].Value), FontStyles.Normal, FontWeights.Normal, FontStretches.Normal)
};
}
}
}
|
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System;
using Mio.TileMaster;
namespace Achievement {
public class AchievementManager {
// activation rules
public const string ACTIVE_IF_GREATER_THAN = ">";
public const string ACTIVE_IF_LESS_THAN = "<";
public const string ACTIVE_IF_EQUALS_TO = "=";
public event Action<Achievement> OnAchievementUnlocked;
#region Add/Remove Achievements
//a list of all achievements' name, used when traversed through all achievement. Since list has better performance than dictionary when doing such operation
private List<string> m_AchievementsIDs;
private Dictionary<string, Achievement> m_Achievements;
public Dictionary<string, Achievement> Achievements {
get { return m_Achievements; }
set { m_Achievements = value; }
}
private Dictionary<string, List<Achievement>> m_AchievementsByTag;
public List<AchievementModel> GetAllAchievementsData() {
List<AchievementModel> res = new List<AchievementModel>(m_AchievementsIDs.Count);
//foreach (string id in m_AchievementsIDs) {
// res.Add(Achievements[id].Data);
//}
for(int i = 0; i < m_AchievementsIDs.Count; i++) {
res.Add(Achievements[m_AchievementsIDs[i]].Data);
}
return res;
}
public List<AchievementModel> GetAllAchievementsDataWithTag (string tag) {
List<AchievementModel> res = new List<AchievementModel>(m_AchievementsIDs.Count);
//Debug.Log("getting achievement with tag: " + tag);
for(int i = 0; i < m_AchievementsIDs.Count; i++) {
if(string.IsNullOrEmpty(tag) && string.IsNullOrEmpty(Achievements[m_AchievementsIDs[i]].Data.tag)) {
res.Add(Achievements[m_AchievementsIDs[i]].Data);
//Debug.Log("Added for " + tag + " with achievement " + Achievements[m_AchievementsIDs[i]].Data.title);
}
else if (!string.IsNullOrEmpty(tag) && Achievements[m_AchievementsIDs[i]].Data.tag.Contains(tag)) {
res.Add(Achievements[m_AchievementsIDs[i]].Data);
//Debug.Log("Added for " + tag + " with achievement " + Achievements[m_AchievementsIDs[i]].Data.title);
}
}
return res;
}
private void AddAchievement(AchievementModel data) {
if (data != null) {
if (!Achievements.ContainsKey(data.ID)) {
Achievement ach = Achievement.CreateAchievement(data, this);
if (ach != null) {
ach.OnAchievementCompleted += OnAchievementCompleted;
Achievements.Add(data.ID, ach);
m_AchievementsIDs.Add(data.ID);
//save reference for tagged properties
if (!string.IsNullOrEmpty(data.tag)) {
if (!m_AchievementsByTag.ContainsKey(data.tag)) {
m_AchievementsByTag.Add(data.tag, new List<Achievement>(10));
}
m_AchievementsByTag[data.tag].Add(ach);
}
}
}
else {
Debug.Log("Trying to add new achievement, but the collection already contains the same property: " + data.ID);
}
}
else {
Debug.Log("Trying to add new achievement with NULL data, skipping...");
}
}
private void OnAchievementCompleted(Achievement ach) {
Debug.Log("Achievement Completed: " + ach.DisplayName);
if(OnAchievementUnlocked != null) {
OnAchievementUnlocked(ach);
}
}
private Achievement GetAchievement(string id) {
if (Achievements.ContainsKey(id)) {
return Achievements[id];
}
Debug.Log("Could NOT found achievement: " + id + ", returning null...");
return null;
}
#endregion
#region Add/Remove Operators
private List<string> m_OperatorsIDs;
private Dictionary<string, Operator> m_Operators;
public Dictionary<string, Operator> Operators {
get { return m_Operators; }
private set { m_Operators = value; }
}
internal Operator AddOperator(OperatorModel data) {
if (data != null) {
data.ID = data.propertyID + data.expressionString + data.targetValue.ToString();
if (!Operators.ContainsKey(data.ID)) {
Property prop = GetProperty(data.propertyID);
if (prop == null) {
Debug.Log("Could not find property: " + data.propertyID + ", can't add operator..." + data.ID);
return null;
}
else {
//Debug.Log("Creating new operator " + data.ID);
Operator op = new Operator(data, prop);
Operators.Add(data.ID, op);
m_OperatorsIDs.Add(data.ID);
return op;
}
}
else {
//Debug.Log("Trying to add new Operator, but the collection already contains the same property: " + data.ID + ", returning existed one...");
return Operators[data.ID];
}
}
else {
Debug.LogError("Trying to add new operator with NULL data, returning NULL...");
return null;
}
}
internal float GetAchievementProgress(string achievementID) {
if (Achievements.ContainsKey(achievementID)) {
return Achievements[achievementID].GetCurrentProgress();
}
return 0;
}
#endregion
#region Add/Remove Properties
//a list of all properties' name, used when traversed through all achievement. Since list has better performance than dictionary when doing such operation
private List<string> m_PropertiesIDs;
private Dictionary<string, List<Property>> m_PropertiesByTag;
private Dictionary<string, Property> m_Properties;
public Dictionary<string, Property> Properties {
get { return m_Properties; }
set { m_Properties = value; }
}
/// <summary>
/// Add new achievement property, based on specified model
/// </summary>
/// <param name="propData">Model data of achievement property</param>
/// <returns>The newly created property, or the existed one</returns>
private Property AddAchievementProperty(PropertyModel propData) {
if (propData != null) {
if (!Properties.ContainsKey(propData.ID)) {
Property property = new Property(propData);
Properties.Add(propData.ID, property);
m_PropertiesIDs.Add(propData.ID);
//save reference for tagged properties
if (!string.IsNullOrEmpty(propData.tag)) {
if (!m_PropertiesByTag.ContainsKey(propData.tag)) {
m_PropertiesByTag.Add(propData.tag, new List<Property>(10));
}
m_PropertiesByTag[propData.tag].Add(property);
}
//Debug.Log("Added property: " + propData.ID + " initial value: " + propData.initValue);
return property;
}
else {
Debug.Log("Trying to add new achievement property, but the collection already contains the same property: " + propData.ID + ", returning existed one.");
return Properties[propData.ID];
}
}
else {
Debug.LogWarning("Trying to add new achievement property with NULL data, returning NULL");
return null;
}
}
/// <summary>
/// Get a List of all properties' data
/// </summary>
public List<PropertyModel> GetAllPropertiesData() {
List<PropertyModel> res = new List<PropertyModel>(m_PropertiesIDs.Count);
for(int i = 0; i < m_PropertiesIDs.Count; i++) {
res.Add(Properties[m_PropertiesIDs[i]].Data);
}
return res;
}
private Property GetProperty(string id) {
if (Properties.ContainsKey(id)) {
return Properties[id];
}
Debug.LogWarning("Could NOT found achievement property: " + id + ", returning null...");
return null;
}
public int GetPropertyValue(string propertyID) {
if (Properties.ContainsKey(propertyID)) {
return Properties[propertyID].Value;
}
Debug.Log("Trying to get value of not-existing property: " + propertyID + " returning -1");
return -1;
}
/// <summary>
/// Increase a property's value
/// </summary>
/// <param name="propertyID">The property to manipulate</param>
/// <param name="value">The value to increase</param>
/// <param name="noCallback">Currently not in use, will do in un-forseeable future</param>
public void IncreaseAchievementProperty(string propertyID, int value = 1, bool noCallback = false) {
if (Properties.ContainsKey(propertyID)) {
//Debug.Log("Increasing value of property: " + propertyID + " by " + value);
Properties[propertyID].Value += value;
}
else {
Debug.Log("Trying to increase value of not-existing property: " + propertyID + ", skipping...");
}
}
public void SetPropertyValue(string propertyID, int value) {
if (Properties.ContainsKey(propertyID)) {
Properties[propertyID].Value = value;
}
else {
Debug.Log("Trying to set value of not-existing property: " + propertyID + ", skipping...");
}
}
internal void SetPropertyValue(List<string> propertiesIDs, List<int> values) {
if (propertiesIDs.Count != values.Count) {
Debug.LogError(string.Format("Size mismatched: List of properties ({0}) and list of values ({1}) are not identical in size, skipping...", propertiesIDs.Count, values.Count));
return;
}
for (int i = 0; i < propertiesIDs.Count; i++) {
SetPropertyValue(propertiesIDs[i], values[i]);
}
}
#endregion
public AchievementManager() {
}
internal void Initialize(List<PropertyModel> props, List<AchievementModel> achs) {
Achievements = new Dictionary<string, Achievement>(50);
m_AchievementsIDs = new List<string>(50);
Operators = new Dictionary<string, Operator>(50);
m_OperatorsIDs = new List<string>(50);
Properties = new Dictionary<string, Property>(10);
m_PropertiesIDs = new List<string>(10);
m_PropertiesByTag = new Dictionary<string, List<Property>>(10);
m_AchievementsByTag = new Dictionary<string, List<Achievement>>(20);
InitializeProperties(props);
InitializeAchievements(achs);
}
private void InitializeProperties(List<PropertyModel> props) {
for(int i = 0; i < props.Count; i++) {
//Debug.Log("Adding property: " + props[i].ID);
AddAchievementProperty(props[i]);
}
////Test purpose only.
//PropertyModel p1 = new PropertyModel();
//p1.ID = "songfinished";
//p1.initValue = 0;
//p1.currentValue = 0;
//AddAchievementProperty(p1);
//PropertyModel p2 = new PropertyModel();
//p2.ID = "songowned";
//p2.initValue = 2;
//p2.currentValue = 2;
//AddAchievementProperty(p2);
//PropertyModel p3 = new PropertyModel();
//p3.ID = "5star";
//p3.initValue = 0;
//p3.currentValue = 0;
//AddAchievementProperty(p3);
}
private void InitializeAchievements(List<AchievementModel> achs) {
for(int i = 0; i < achs.Count; i++) {
//Debug.Log("Adding achievement: " + achs[i].title);
AddAchievement(achs[i]);
}
//OperatorModel buy5song = new OperatorModel();
//buy5song.expressionString = AchievementManager.ACTIVE_IF_EQUALS_TO;
//buy5song.targetValue = 5;
//buy5song.propertyID = "songowned";
//OperatorModel own3song = new OperatorModel();
//own3song.expressionString = AchievementManager.ACTIVE_IF_EQUALS_TO;
//own3song.targetValue = 3;
//own3song.propertyID = "songowned";
//OperatorModel play3song = new OperatorModel();
//play3song.expressionString = AchievementManager.ACTIVE_IF_EQUALS_TO;
//play3song.targetValue = 3;
//play3song.propertyID = "songfinished";
//OperatorModel get3songfullstar = new OperatorModel();
//get3songfullstar.expressionString = AchievementManager.ACTIVE_IF_EQUALS_TO;
//get3songfullstar.targetValue = 3;
//get3songfullstar.propertyID = "5star";
//AchievementModel a1 = new AchievementModel();
//a1.title = "Buy 5 song";
//a1.ID = "buy5song";
//a1.isActive = true;
//a1.isUnlocked = false;
//a1.listConditions = new List<OperatorModel>() { buy5song };
//AddAchievement(a1);
//AchievementModel a2 = new AchievementModel();
//a2.title = "Get 5 stars in 3 songs";
//a2.ID = "5star3song";
//a2.isActive = true;
//a2.isUnlocked = false;
//a2.listConditions = new List<OperatorModel>() { get3songfullstar };
//AddAchievement(a2);
//AchievementModel a3 = new AchievementModel();
//a3.title = "One by one";
//a3.ID = "1by1";
//a3.isActive = true;
//a3.isUnlocked = false;
//a3.listConditions = new List<OperatorModel>() { own3song, play3song };
//AddAchievement(a3);
}
public void MarkAchievementAsUnlocked(string id) {
if (Achievements.ContainsKey(id)) {
Achievements[id].Data.isUnlocked = true;
}
}
public void MarkAchievementAsClaimed(string id) {
if (Achievements.ContainsKey(id)) {
Achievements[id].Data.isClaimed = true;
//Debug.Log("Marking achievement as claimed with hashcode: " + Achievements[id].Data.GetHashCode());
}
}
/// <summary>
/// Check all achievements to see if there are any newly completed one
/// </summary>
/// <returns>A list of newly unlocked achievements</returns>
public List<Achievement> CheckAllAchievements() {
List<Achievement> unlockedAchs = new List<Achievement>(5);
////traverse through all achievements currently in list
//for (int i = 0; i < m_AchievementsIDs.Count; i++) {
// var ach = Achievements[m_AchievementsIDs[i]];
// //only check if the achievement is not unlocked already
// if (!ach.IsUnlocked) {
// //an achievement is unlocked only when all of its related properties are activated
// int numPropertiesActivated = 0;
// //so, we check for them
// for (int j = 0; j < ach.Properties.Count; j++) {
// var property = Properties[ach.Properties[j].ID];
// //if (property.IsActive()) {
// // ++numPropertiesActivated;
// //}
// }
// //newly unlocked achievement will be added into list of result
// if (numPropertiesActivated == ach.Properties.Count) {
// ach.IsUnlocked = true;
// unlockedAchs.Add(ach);
// }
// }
//}
return unlockedAchs;
}
/// <summary>
/// Reset value of all properties has a specified tag
/// </summary>
/// <param name="tag">The tag of properties to reset value</param>
public void ResetPropertiesByTag(string tag) {
if (m_PropertiesByTag.ContainsKey(tag)) {
List<Property> props = m_PropertiesByTag[tag];
if(props != null) {
for(int i = 0; i< props.Count; i++) {
props[i].Reset();
}
}
}
}
public void ResetAchievementsByTag (string tag) {
//Debug.Log("Trying to reset achievement with tag: " + tag);
if (m_AchievementsByTag.ContainsKey(tag)) {
List<Achievement> achievements = m_AchievementsByTag[tag];
if (achievements != null) {
for (int i = 0; i < achievements.Count; i++) {
achievements[i].Reset();
}
}
}
}
}
} |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class AddAlbum : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (Session["user"] == null)
Response.Redirect("Login.aspx");
}
protected void btnUpload_Click(object sender, EventArgs e)
{
string FullName = myFileUpload.PostedFile.FileName;//获取图片物理地址
if (FullName == "")
{
this.lbImage.Visible = true;
this.lbImage.Text = "请选择图片";
}
else
{
FileInfo fi = new FileInfo(FullName);
string name = fi.Name;//获取图片名称
string type = fi.Extension;//获取图片类型
if (type == ".jpg" || type == ".gif" || type == ".bmp" || type == ".png")
{
string SavePath = Server.MapPath("~\\image");//图片保存到文件夹下
this.myFileUpload.PostedFile.SaveAs(SavePath + "\\" + name);//保存路径
this.Image.Visible = true;
this.Image.ImageUrl = "~\\image" + "\\" + name;//界面显示图片
Session["photoname"] = name;
}
else
{
this.lbImage.Visible = true;
this.lbImage.Text = "请选择正确的格式图片";
}
}
}
protected void btnSave_Click(object sender, EventArgs e)
{
Users user = (Users)Session["user"];
string name = Session["photoname"].ToString();
DateTime time = DateTime.Now;
if(txtName.Text.Length == 0)
Response.Write("<script>alert('输入不能为空!')</script>");
else
{
string sql = "insert into Album values('" + user.Userid + "',N'" + txtName.Text + "','image/" + name + "','" + time + "')";
DataClass.Save(sql);
Response.Write("<script>alert('创建成功!');location='Album.aspx'</script>");
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Data;
using System.ComponentModel.DataAnnotations;
using MiniProjectMVC.Models;
using System.Dynamic;
using System.Text.RegularExpressions;
namespace MiniProjectMVC.Controllers
{
public class HomeController : Controller
{
dbLinQtoSQLDataContext db = new dbLinQtoSQLDataContext();
tblDemo d = new tblDemo();
#region Actions For Index/Home
// GET: /Home/
public ActionResult Index()
{
MainModel modelAll = new MainModel();
modelAll.ModelMy = GetModelMy();
modelAll.ModelDemo = GettlblDemo();
if (Session["id"] != null)
{
}
else
{
return RedirectToAction("Index", "LogIn");
}
return View(modelAll);
}
//==================Post action for Index========================
[HttpPost]
public ActionResult Index(ModelMy m)
{
return View();
}
#endregion
#region Actions For LogOutButton\Home
//====================Post action for LogOut========================
[HttpPost]
public ActionResult LogOut()
{
Session.Abandon();
return RedirectToAction("Index", "LogIn");
}
#endregion
#region Action For link Edit
//===================Post action for Grid Edit=========================
[HttpGet]
public ActionResult GridEdit(int id)
{
Session["id"] = id;
return RedirectToAction("EditForm", "Home");
}
#endregion
#region Action For Link Delete
//===================Post action for Grid Delete=======================
public ActionResult GridDelete(int id)
{
var uniq = db.tblDemos.Single(x => x.id == id);
db.tblDemos.DeleteOnSubmit(uniq);
db.SubmitChanges();
return RedirectToAction("Index", "Home");
}
#endregion
#region Functions For Get Models
//==================Method for Get Models===============================
//*********** 1 Method For tblDemo *************
public List<tblDemo> GettlblDemo()
{
Modeldemo dm = new Modeldemo();
MainModel mm = new MainModel();
// dm.ld = db.tblDemos.ToList();
mm.ModelDemo = db.tblDemos.ToList();
return mm.ModelDemo;
}
//********** 2 Method For ModelMy **************
public ModelMy GetModelMy()
{
ModelMy m = new ModelMy();
return m;
}
#endregion
#region Action For EditForm Get & Post EditForm\Home
//============Get Action for EditForm =================
[HttpGet]
public ActionResult EditForm()
{
ModelMy m = new ModelMy();
MainModel mm = new MainModel();
if (Session["id"] != null)
{
//=============Filter Data ================
int id = Convert.ToInt32(Session["id"]);
var data = from x in db.tblDemos where x.id == id select x;
foreach (var item in data)
{
m.Name = item.name;
m.id = item.id;
m.Email = item.email;
}
mm.ModelMy = m;
return View("EditForm", mm);
}
else
{
return View("Index", "LogIn");
}
return View("Index", "Home");
}
//==========Post Action for EditForm ===================
[HttpPost]
public ActionResult EditForm(MainModel mm)
{
//============Filter user entered details=============
if (string.IsNullOrEmpty(mm.ModelMy.Name))
{
ModelState.AddModelError("Name", "Please Enter Name !");
}
if (string.IsNullOrEmpty(mm.ModelMy.Email))
{
ModelState.AddModelError("Email", "Please Enter Email !");
}
else
{
Regex rg = new Regex(@"^([\w\.\-]+)@([\w\-]+)((\.(\w){2,3})+)$");
Match mt = rg.Match(mm.ModelMy.Email);
if (!mt.Success)
{
ModelState.AddModelError("Email", "Invalid Email Address !");
}
}
if (ModelState.IsValid)
{
int id= Convert.ToInt32(Session["id"]);
var vid = db.tblDemos.Single(x => x.id == id);
vid.name = mm.ModelMy.Name;
vid.email = mm.ModelMy.Email;
db.SubmitChanges();
return RedirectToAction("Index", "Home");
}
return RedirectToAction("EditForm", "Home");
}
#endregion
}
}
|
namespace Profiling2.Domain.Prf.Sources
{
using System;
using System.Collections.Generic;
using System.Linq;
using NHibernate.Envers.Configuration.Attributes;
using Profiling2.Domain.Prf.Events;
using Profiling2.Domain.Prf.Organizations;
using Profiling2.Domain.Prf.Persons;
using Profiling2.Domain.Prf.Units;
using SharpArch.Domain.DomainModel;
/// <summary>
/// Principal entity for storing binary contents of documents. There are two binary columns: FileData and OriginalFileData,
/// for those sources which have undergone OCR.
///
/// Loading this entity can in some cases fail if the binary data is large enough (NHibernate is not meant to handle this use case).
/// Rather than set the binary attributes as lazy, which caused problems with Envers auditing, there exists SourceDTO which in
/// most cases satisifies what is needed without having to load the binary contents of a Source into memory.
/// </summary>
public class Source : Entity
{
/// <summary>
/// This list is replicated in the console utility DocumentImportConsole's config file, used when importing sources from file shares.
/// </summary>
public static string[] IGNORED_FILE_EXTENSIONS = { "avi", "mpg", "m4a", "mov", "mp3", "wmv", "db", "sql", "dll", "exe", "lnk", "tmp", "ini",
"onet", // this should be 'onetoc2', but table column stores it as 'onet' since it only stores 4 bytes
"nsf" };
public static string[] IMAGE_FILE_EXTENSIONS = { "jpg", "jpeg", "png", "bmp", "gif", "tiff" };
/// <summary>
/// The file name, including file extension.
/// </summary>
public virtual string SourceName { get; set; }
/// <summary>
/// Seems to be defunct.
/// </summary>
public virtual string FullReference { get; set; }
/// <summary>
/// The full path to the original location from which this Source was imported. Includes the file name.
/// </summary>
public virtual string SourcePath { get; set; }
/// <summary>
/// The date when this source was imported.
/// </summary>
public virtual DateTime? SourceDate { get; set; }
/// <summary>
/// Once archived, a Source doesn't appear in searches. It stays in the database as its SourcePath is still useful in preventing
/// the source from being automatically re-imported.
/// </summary>
[Audited]
public virtual Boolean Archive { get; set; }
public virtual string Notes { get; set; }
/// <summary>
/// Used by the MSSQL full-text indexer to determine which text filter to use when indexing; for OCR'd documents for example, it's value should be txt.
/// It's recommended to use FileUtil.GetExtension() or Path.GetExtension() on the SourceName instead to get an OCR'd file's true extension.
/// </summary>
public virtual string FileExtension { get; set; }
/// <summary>
/// MSSQL's full-text indexer can be customised based on language, but this has not been exploited: this field isn't really used.
/// </summary>
public virtual Language FileLanguage { get; set; }
/// <summary>
/// Binary contents of the file. Target of full-text indexer (both MSSQL and Lucene).
/// </summary>
public virtual byte[] FileData { get; set; }
/// <summary>
/// A classification level above those sources for which this is not true.
/// </summary>
public virtual Boolean IsRestricted { get; set; }
/// <summary>
/// The Last Modified Date of the file at the time of import.
/// </summary>
public virtual DateTime? FileDateTimeStamp { get; set; }
/// <summary>
/// Binary contents of the file if it has undergone OCR. Not indexed.
/// </summary>
public virtual byte[] OriginalFileData { get; set; }
/// <summary>
/// JHRO case number, if detected to be a JHRO case or one of its related attachments.
/// </summary>
public virtual JhroCase JhroCase { get; set; }
/// <summary>
/// Designates extra warning levels to the user in the interface, but is not a classification level:
/// Sources marked 'read only' are generally a subset of those marked 'restricted'.
/// </summary>
public virtual bool IsReadOnly { get; set; }
/// <summary>
/// MD5 hash of the file's binary contents (according to the SQL Server function master.sys.fn_repl_hash_binary).
/// Populated by insert trigger. See Profiling2.Migrations.Migrations.PopulateSourceHash.cs for the initial populate SQL
/// (large Sources were not hashed).
///
/// NOTE: Another algorithm may have been used that allowed for better collision detection (i.e. different files generating
/// the same hash), but MD5 proved simpler and faster to implement based on the convenience of master.sys.fn_repl_hash_binary.
/// </summary>
public virtual byte[] Hash { get; set; }
public virtual bool IsPublic { get; set; }
/// <summary>
/// Log of when this Source was originally imported, if exists.
/// </summary>
public virtual IList<AdminSourceImport> AdminSourceImports { get; set; }
/// <summary>
/// Log of every instance where this Source has appeared as a search result, and the actions by the user thereafter.
/// </summary>
public virtual IList<AdminReviewedSource> AdminReviewedSources { get; set; }
public virtual IList<PersonSource> PersonSources { get; set; }
public virtual IList<OrganizationSource> OrganizationSources { get; set; }
public virtual IList<EventSource> EventSources { get; set; }
public virtual IList<UnitSource> UnitSources { get; set; }
public virtual IList<OperationSource> OperationSources { get; set; }
public virtual IList<SourceRelationship> SourceRelationshipsAsParent { get; set; }
public virtual IList<SourceRelationship> SourceRelationshipsAsChild { get; set; }
/// <summary>
/// Before a file becomes a Source, it may be uploaded for approval as a FeedingSource. There should only be
/// one FeedingSource per Source. The FeedingSource contains useful attributes like UploadedBy and ApprovedBy.
/// </summary>
public virtual IList<FeedingSource> FeedingSources { get; set; }
public virtual IList<SourceAuthor> SourceAuthors { get; set; }
public virtual IList<SourceOwningEntity> SourceOwningEntities { get; set; }
public Source()
{
this.AdminSourceImports = new List<AdminSourceImport>();
this.AdminReviewedSources = new List<AdminReviewedSource>();
this.PersonSources = new List<PersonSource>();
this.EventSources = new List<EventSource>();
this.OrganizationSources = new List<OrganizationSource>();
this.UnitSources = new List<UnitSource>();
this.OperationSources = new List<OperationSource>();
this.SourceRelationshipsAsParent = new List<SourceRelationship>();
this.SourceRelationshipsAsChild = new List<SourceRelationship>();
this.FeedingSources = new List<FeedingSource>();
this.SourceAuthors = new List<SourceAuthor>();
this.SourceOwningEntities = new List<SourceOwningEntity>();
}
public virtual bool HasOcrText()
{
return this.OriginalFileData != null && this.OriginalFileData.Length > 0;
}
public virtual Source GetParentSource()
{
if (this.SourceRelationshipsAsChild != null && this.SourceRelationshipsAsChild.Any())
return this.SourceRelationshipsAsChild.First().ParentSource;
return null;
}
public virtual IList<Source> GetChildSources()
{
if (this.SourceRelationshipsAsParent != null && this.SourceRelationshipsAsParent.Any())
return this.SourceRelationshipsAsParent.Select(x => x.ChildSource).ToList<Source>();
return null;
}
public virtual bool HasUploadedBy()
{
return this.FeedingSources != null && this.FeedingSources.Any() && this.FeedingSources.First().UploadedBy != null;
}
public virtual AdminUser GetUploadedBy()
{
if (this.HasUploadedBy())
return this.FeedingSources.First().UploadedBy;
return null;
}
/// <summary>
/// Return SourcePath, but without the filename (not including directory separator).
/// </summary>
/// <returns></returns>
public virtual string GetSourcePathOnly()
{
// SourcePath includes filename, we index only the folder.
// Not using Path.GetDirectoryName since it has a char length limitation.
if (!string.IsNullOrEmpty(this.SourcePath))
{
int i = this.SourcePath.LastIndexOf(System.IO.Path.DirectorySeparatorChar);
if (i > -1)
return this.SourcePath.Substring(0, i);
}
return this.SourcePath;
}
/// <summary>
/// Uploading user's User ID. Only to be set when indexing, as the indexer uses a stateless session which cannot
/// use traverse the attached collections referenced in HasUploadedBy() and GetUploadedBy().
/// </summary>
protected internal virtual string _uploadedByHorsSession { get; set; }
public virtual string GetUploadedByHorsSession()
{
return this._uploadedByHorsSession;
}
public virtual void SetUploadedByHorsSession(string uploadedByUserId)
{
this._uploadedByHorsSession = uploadedByUserId;
}
protected internal virtual IList<string> _authorsHorsSession { get; set; }
public virtual IList<string> GetAuthorsHorsSession()
{
return this._authorsHorsSession;
}
public virtual void SetAuthorsHorsSession(IList<string> authors)
{
this._authorsHorsSession = authors;
}
protected internal virtual IList<string> _ownersHorsSession { get; set; }
public virtual IList<string> GetOwnersHorsSession()
{
return this._ownersHorsSession;
}
public virtual void SetOwnersHorsSession(IList<string> owners)
{
this._ownersHorsSession = owners;
}
protected internal virtual string _jhroCaseNumber { get; set; }
public virtual string GetJhroCaseNnumberHorsSession()
{
return this._jhroCaseNumber;
}
public virtual void SetJhroCaseNumberHorsSession(string jhroCaseNumber)
{
this._jhroCaseNumber = jhroCaseNumber;
}
protected internal virtual long _fileSize { get; set; }
public virtual long GetFileSizeHorsSession()
{
return this._fileSize;
}
public virtual void SetFileSizeHorsSession(long fileSize)
{
this._fileSize = fileSize;
}
public virtual PersonSource GetPersonSource(Person person)
{
IList<PersonSource> personSources = (from ps in this.PersonSources
where ps.Person.Id == person.Id && !ps.Archive
select ps).ToList<PersonSource>();
return (personSources != null && personSources.Count > 0 ? personSources[0] : null);
}
public virtual void AddPersonSource(PersonSource ps)
{
if (this.PersonSources.Contains(ps))
return;
this.PersonSources.Add(ps);
}
public virtual void RemovePersonSource(PersonSource ps)
{
this.PersonSources.Remove(ps);
}
public virtual void AddEventSource(EventSource es)
{
if (this.EventSources.Contains(es))
return;
this.EventSources.Add(es);
}
public virtual EventSource GetEventSource(Event ev)
{
IList<EventSource> eventSources = (from es in this.EventSources
where es.Event.Id == ev.Id && !es.Archive
select es).ToList<EventSource>();
return (eventSources != null && eventSources.Count > 0 ? eventSources[0] : null);
}
public virtual void RemoveEventSource(EventSource es)
{
this.EventSources.Remove(es);
}
public virtual void AddOrganizationSource(OrganizationSource os)
{
if (this.OrganizationSources.Contains(os))
return;
this.OrganizationSources.Add(os);
}
public virtual void RemoveOrganizationSource(OrganizationSource os)
{
this.OrganizationSources.Remove(os);
}
public virtual UnitSource GetUnitSource(Unit unit)
{
IList<UnitSource> unitSources = (from us in this.UnitSources
where us.Unit.Id == unit.Id && !us.Archive
select us).ToList<UnitSource>();
return (unitSources != null && unitSources.Count > 0 ? unitSources[0] : null);
}
public virtual void AddUnitSource(UnitSource us)
{
if (this.UnitSources.Contains(us))
return;
this.UnitSources.Add(us);
}
public virtual void RemoveUnitSource(UnitSource us)
{
this.UnitSources.Remove(us);
}
public virtual OperationSource GetOperationSource(Operation operation)
{
IList<OperationSource> operationSources = (from os in this.OperationSources
where os.Operation.Id == operation.Id && !os.Archive
select os).ToList<OperationSource>();
return (operationSources != null && operationSources.Count > 0 ? operationSources[0] : null);
}
public virtual void AddOperationSource(OperationSource os)
{
if (this.OperationSources.Contains(os))
return;
this.OperationSources.Add(os);
}
public virtual void RemoveOperationSource(OperationSource os)
{
this.OperationSources.Remove(os);
}
public virtual void AddSourceAuthor(SourceAuthor sa)
{
if (this.SourceAuthors.Contains(sa))
return;
this.SourceAuthors.Add(sa);
}
public virtual void AddSourceOwningEntity(SourceOwningEntity e)
{
if (this.SourceOwningEntities.Contains(e))
return;
this.SourceOwningEntities.Add(e);
}
public virtual void AddFeedingSource(FeedingSource fs)
{
if (this.FeedingSources.Contains(fs))
return;
this.FeedingSources.Add(fs);
}
public override string ToString()
{
return this.SourceName + " (ID=" + this.Id + ")";
}
}
} |
namespace Thingy.WebServerLite
{
public interface IKnownUser
{
string IpAddress { get; set; }
string Password { get; }
string[] Roles { get; }
string UserId { get; }
}
} |
using System;
using System.Collections.Generic;
using System.Text;
namespace Big_Bank_Inc
{
public static class Validator
{
private static bool IsInputGivenNumeric(string userInput)
{
bool intInString = Int32.TryParse(userInput, out int result);
return intInString;
}
public static string ValidateNameGiven(string guide)
{
var inputName = "";
bool isNumber;
do
{
if (guide == "fn")
{
inputName = Menu.PromptFirstName();
}
else if (guide == "ln")
{
inputName = Menu.PromptLastName();
}
isNumber = IsInputGivenNumeric(inputName);
Console.WriteLine();
} while (inputName.Length < 2 || isNumber == true);
return inputName;
}
public static string ValidateUserSsn()
{
var ssn = "";
var isNumber = false;
do
{
ssn = Menu.PromptSSN();
isNumber = IsInputGivenNumeric(ssn);
Console.WriteLine();
} while (ssn.Length < 9 || isNumber == false);
return ssn;
}
public static decimal IsInitialInvestmentDecimal()
{
var enteredAmount = Console.ReadLine();
decimal openingAmount;
bool amountIsInt;
do
{
amountIsInt = Decimal.TryParse(enteredAmount, out openingAmount);
} while (amountIsInt == false);
return openingAmount;
}
}
}
|
using Library.DataTransferObjects.Enum;
using System;
using System.Collections.Generic;
using System.Text;
namespace Library.DataTransferObjects.Dto
{
public class BookDto : BaseDto
{
public string Name { get; set; }
public int GenreId { get; set; }
public string GenreName { get; set; }
}
}
|
using System;
using Compent.CommandBus;
using Uintra.Core;
using Uintra.Core.Activity;
using Uintra.Features.Likes.CommandBus.Commands;
using Uintra.Features.Likes.Services;
using Uintra.Infrastructure.Extensions;
namespace Uintra.Features.Likes.CommandBus
{
public class LikeHandle : IHandle<AddLikeCommand>, IHandle<RemoveLikeCommand>
{
private readonly ILikesService _likesService;
private readonly IActivitiesServiceFactory _activitiesServiceFactory;
public LikeHandle(ILikesService likesService, IActivitiesServiceFactory activitiesServiceFactory)
{
_likesService = likesService;
_activitiesServiceFactory = activitiesServiceFactory;
}
public BroadcastResult Handle(AddLikeCommand command)
{
var likeTargetEntityId = command.EntityId;
_likesService.Add(command.Author, likeTargetEntityId);
UpdateCache(command.EntityType, likeTargetEntityId);
return BroadcastResult.Success;
}
public BroadcastResult Handle(RemoveLikeCommand command)
{
var likeTargetEntityId = command.EntityId;
_likesService.Remove(command.Author, likeTargetEntityId);
UpdateCache(command.EntityType, likeTargetEntityId);
return BroadcastResult.Success;
}
private void UpdateCache(Enum commentsTargetType, Guid commentsTargetEntityId)
{
if (!commentsTargetType.Is(IntranetEntityTypeEnum.News, IntranetEntityTypeEnum.Social, IntranetEntityTypeEnum.Events)) return;
var activityService = _activitiesServiceFactory.GetCacheableIntranetActivityService(commentsTargetEntityId);
activityService.UpdateActivityCache(commentsTargetEntityId);
}
}
} |
namespace CheckIt.Tests.CheckSources
{
using Xunit;
public class CheckClassHaveInterface
{
[Fact]
public void Should_class_have_interface_When_when()
{
}
}
}
|
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
namespace LMS.App_Code
{
public class CommonFunctions
{
string connection_string = ConfigurationManager.ConnectionStrings["db_connectionstring"].ConnectionString;
public string getCurrentDate()
{
var remoteTimeZone = TimeZoneInfo.FindSystemTimeZoneById("Sri Lanka Standard Time");
var remoteTime = TimeZoneInfo.ConvertTime(DateTime.Now, remoteTimeZone);
return remoteTime.ToString("yyyy-MM-dd");
}
public string getCurrentDateTime()
{
var remoteTimeZone = TimeZoneInfo.FindSystemTimeZoneById("Sri Lanka Standard Time");
var remoteTime = TimeZoneInfo.ConvertTime(DateTime.Now, remoteTimeZone);
return remoteTime.ToString("yyyy-MM-dd HH:mm");
}
public string getServerDate()
{
string dt = "";
DateTime d;
SqlConnection con = new SqlConnection(connection_string);
string sql = "select CONVERT(date,GETDATE()) as currDate";
SqlCommand cmd = new SqlCommand(sql, con);
con.Open();
SqlDataReader rdr = cmd.ExecuteReader();
while (rdr.Read())
{
//dt = rdr["currDate"].ToString();
d = Convert.ToDateTime(rdr["currDate"]);
dt = d.ToString("yyyy-MM-dd");
}
con.Close();
return dt;
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using strange.extensions.mediation.impl;
namespace Ghostpunch.OnlyDown.Common.Views
{
public abstract class ViewBase : View
{
internal virtual void Initialize() { }
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;
namespace GDS.Comon
{
public class HttpRuntimeCache
{
private const int DefaultExpireTime = 30;
public static void Add(string key, object value, bool isExpire = true)
{
var absoluteExpiration = DateTime.Now.AddMinutes(DefaultExpireTime);
if (isExpire == false)
{
absoluteExpiration = DateTime.Now.Add(TimeSpan.MaxValue);
}
HttpRuntime.Cache.Insert(key, value, null, absoluteExpiration, TimeSpan.Zero);
}
public static void Add(string key, object value, int DefaultExpireTime)
{
var absoluteExpiration = DateTime.Now.AddMinutes(DefaultExpireTime);
HttpRuntime.Cache.Insert(key, value, null, absoluteExpiration, TimeSpan.Zero);
}
public static void Add(string key, object value, TimeSpan timeSpan)
{
HttpRuntime.Cache.Insert(key, value, null, DateTime.Now.Add(timeSpan), TimeSpan.Zero);
}
public static void Update(string key, object value)
{
Add(key, value);
}
public static T Get<T>(string key)
{
return (T)HttpRuntime.Cache.Get(key);
}
public static object Get(string key)
{
return HttpRuntime.Cache.Get(key);
}
public static object GetClone<T>(string key)
{
return JsonHelper.Deserialize<T>(JsonHelper.Serializer(HttpRuntime.Cache.Get(key)));
}
public static bool Exists(string key)
{
return HttpRuntime.Cache.Get(key) != null;
}
public static void Remove(string key)
{
HttpRuntime.Cache.Remove(key);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace SynchronizationPrimitive
{
class SpinLockTest
{
private const string s = "";
private int _participantNumber = Environment.ProcessorCount;
private Barrier _barrier;
private Task[] _tasks;
public void SpinLockMethod()
{
this._tasks = new Task[this._participantNumber];
this._barrier = new Barrier(this._participantNumber, (barrier) =>
{
Console.WriteLine($"Current phase :{barrier.CurrentPhaseNumber}");
});
var sl = new SpinLock(false);
var sb = new StringBuilder();
for (int i = 0; i < this._participantNumber; i++)
{
this._tasks[i] = Task.Factory.StartNew((num) =>
{
var participantNumber = (int)num;
for (int j = 0; j < 10; j++)
{
this.CreatePlanets(participantNumber);
this._barrier.SignalAndWait();
this.CreateStarts(participantNumber);
this._barrier.SignalAndWait();
this.CheckCollisionsBetweenPlanets(participantNumber);
this._barrier.SignalAndWait();
this.CheckCollisionsBetweenStars(participantNumber);
this._barrier.SignalAndWait();
this.RenderCollisions(participantNumber);
this._barrier.SignalAndWait();
var logLine = $"Time: {DateTime.Now.TimeOfDay}, Phase: {this._barrier.CurrentPhaseNumber}, Participant: {participantNumber}, Phase completed OK";
bool lockTaken = false;
try
{
sl.Enter(ref lockTaken);
sb.Append(logLine);
}
finally
{
if (lockTaken)
{
sl.Exit(false);
}
}
}
}, i);
}
var finalTask = Task.Factory.ContinueWhenAll(this._tasks, (tasks) =>
{
Task.WaitAll(this._tasks);
Console.WriteLine("All the phase were executed.");
Console.WriteLine(sb);
this._barrier.Dispose();
});
finalTask.Wait();
Console.ReadKey();
}
private void CreatePlanets(int participantNum)
{
Console.WriteLine($"Creating planets. Participant #{participantNum}");
}
private void CreateStarts(int participantNum)
{
Console.WriteLine($"Creating starts. Participant #{participantNum}");
}
private void CheckCollisionsBetweenPlanets(int participantNum)
{
Console.WriteLine($"Checking collisions between planets .Participant # {participantNum}");
}
private void CheckCollisionsBetweenStars(int participantNum)
{
Console.WriteLine($"Checking collisions between stars. Participant # {participantNum}");
}
private void RenderCollisions(int participantNum)
{
Console.WriteLine($"Rendering collisions . Participant # {participantNum}");
}
}
}
|
using Microsoft.AspNetCore.SignalR;
using Microsoft.Extensions.Configuration;
using Newtonsoft.Json;
using RabbitMQ.Client;
using RabbitMQ.Client.Events;
using Rexxar.Chat.Dtos;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Rexxar.Chat.Extensions
{
public class MsgSender
{
public MsgSender(IConfiguration configuration)
{
factory = new ConnectionFactory();
factory.HostName = configuration.GetValue<string>("RabbitMQ:Host");
factory.UserName = configuration.GetValue<string>("RabbitMQ:User");
factory.Password = configuration.GetValue<string>("RabbitMQ:Password");
}
ConnectionFactory factory;
public void Send(MsgDto msg)
{
using (var connection = factory.CreateConnection())
{
using (var channel = connection.CreateModel())
{
channel.QueueDeclare("chat_queue", false, false, false, null);//创建一个名称为hello的消息队列
var body = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(msg));
channel.BasicPublish("", "chat_queue", null, body); //开始传递
}
}
}
}
public class MsgHandler : IDisposable
{
public MsgHandler(IConfiguration configuration, IHubContext<MessageHub> hubContext)
{
factory = new ConnectionFactory();
factory.HostName = configuration.GetValue<string>("RabbitMQ:Host");
factory.UserName = configuration.GetValue<string>("RabbitMQ:User");
factory.Password = configuration.GetValue<string>("RabbitMQ:Password");
this.hubContext = hubContext;
connection = factory.CreateConnection();
channel = connection.CreateModel();
}
ConnectionFactory factory;
// 注入SignalR的消息处理器上下文,用以发送消息到客户端
IHubContext<MessageHub> hubContext;
IConnection connection;
IModel channel;
public void BeginHandleMsg()
{
channel.QueueDeclare("chat_queue", false, false, false, null);
var consumer = new EventingBasicConsumer(channel);
channel.BasicConsume("chat_queue", false, consumer);
consumer.Received += (model, arg) =>
{
var body = arg.Body;
var message = Encoding.UTF8.GetString(body);
var msg = JsonConvert.DeserializeObject<MsgDto>(message);
// 通过消息处理器上下文发送消息到客户端
hubContext.Clients?.Client(msg.ToUser.ConnectionId)
?.SendAsync("Receive", msg);
channel.BasicAck(arg.DeliveryTag, false);
};
}
public void Dispose()
{
channel?.Dispose();
connection?.Dispose();
}
}
}
|
using UBaseline.Core.Node;
using Uintra.Features.Groups.Helpers;
using Uintra.Features.Groups.Models;
namespace Uintra.Features.Groups.Converters
{
public class UintraMyGroupsPageViewModelConverter : INodeViewModelConverter<UintraMyGroupsPageModel, UintraMyGroupsPageViewModel>
{
private readonly IGroupHelper _groupHelper;
public UintraMyGroupsPageViewModelConverter(IGroupHelper groupHelper)
{
_groupHelper = groupHelper;
}
public void Map(UintraMyGroupsPageModel node, UintraMyGroupsPageViewModel viewModel)
{
viewModel.Navigation = _groupHelper.GroupNavigation();
}
}
} |
using FluentValidation;
using SFA.DAS.ProviderCommitments.Web.Models.Apprentice.Edit;
namespace SFA.DAS.ProviderCommitments.Web.Validators.Apprentice
{
public class ChangeVersionViewModelValidator : AbstractValidator<ChangeVersionViewModel>
{
public ChangeVersionViewModelValidator()
{
RuleFor(x => x.SelectedVersion).NotEmpty().WithMessage("Select a version");
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework.Audio;
namespace DevEngine.Sound {
public class SoundHandler {
public SoundHandler() {
}
public void Tick() {
}
}
} |
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Senparc.Areas.Admin.Models.VD;
using Senparc.Areas.Admin.NopiUtil;
using Senparc.CO2NET.Extensions;
using Senparc.Core.Enums;
using Senparc.Core.Models;
using Senparc.Mvc;
using Senparc.Mvc.Filter;
using Senparc.Service;
using Senparc.Utility;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
namespace Senparc.Areas.Admin.Controllers
{
[MenuFilter("AdminUserInfo")]
public class AdminUserInfoController : BaseAdminController
{
private readonly AdminUserInfoService _adminUserInfoService;
public AdminUserInfoController(AdminUserInfoService adminUserInfoService)
{
_adminUserInfoService = adminUserInfoService;
}
public ActionResult Index(int pageIndex = 1)
{
var seh = new SenparcExpressionHelper<AdminUserInfo>();
seh.ValueCompare.AndAlso(true, z => !string.IsNullOrEmpty(z.Note) &&!string.IsNullOrEmpty(z.RealName));
var where = seh.BuildWhereExpression();
var admins = _adminUserInfoService.GetObjectList(pageIndex, 1000, where, z => z.Id, OrderingType.Ascending);
var vd = new AdminUserInfo_IndexVD()
{
AdminUserInfoList = admins
};
return View(vd);
}
public ActionResult Edit(int id = 0)
{
bool isEdit = id > 0;
var vd = new AdminUserInfo_EditVD();
if (isEdit)
{
var userInfo = _adminUserInfoService.GetAdminUserInfo(id);
if (userInfo == null)
{
return RenderError("信息不存在!");
}
vd.UserName = userInfo.UserName;
vd.Note = userInfo.Note;
vd.RealName = userInfo.RealName;
vd.Id = userInfo.Id;
}
vd.IsEdit = isEdit;
return View(vd);
}
[HttpPost]
public async Task<IActionResult> Edit(AdminUserInfo_EditVD model)
{
bool isEdit = model.Id > 0;
this.Validator(model.UserName, "用户名", "UserName", false)
.IsFalse(z => this._adminUserInfoService.CheckUserNameExisted(model.Id, z), "用户名已存在!", true);
if (!isEdit || !model.Password.IsNullOrEmpty())
{
this.Validator(model.Password, "密码", "Password", false).MinLength(6);
}
if (!ModelState.IsValid)
{
return View(model);
}
AdminUserInfo userInfo = null;
if (isEdit)
{
userInfo = _adminUserInfoService.GetAdminUserInfo(model.Id);
if (userInfo == null)
{
return RenderError("信息不存在!");
}
}
else
{
var passwordSalt = DateTime.Now.Ticks.ToString();
userInfo = new AdminUserInfo()
{
PasswordSalt = passwordSalt,
LastLoginTime = DateTime.Now,
ThisLoginTime = DateTime.Now,
AddTime = DateTime.Now,
};
}
if (!model.Password.IsNullOrEmpty())
{
userInfo.Password = this._adminUserInfoService.GetPassword(model.Password, userInfo.PasswordSalt, false);//生成密码
}
userInfo.RealName = model.RealName;
await this.TryUpdateModelAsync(userInfo, "", z => z.Note,z=>z.RealName ,z => z.UserName);
this._adminUserInfoService.SaveObject(userInfo);
base.SetMessager(MessageType.success, $"{(isEdit ? "修改" : "新增")}成功!");
return RedirectToAction("Index");
}
[HttpPost]
public ActionResult Delete(List<int> ids)
{
var userInfoList = _adminUserInfoService.GetAdminUserInfo(ids);
_adminUserInfoService.DeleteAll(userInfoList);
SetMessager(MessageType.success, "删除成功!");
return RedirectToAction("Index");
}
//[Route("UploadFiles")]
[HttpPost]
public async Task<IActionResult> Post(List<IFormFile> files)
{
long size = files.Sum(f => f.Length);
// full path to file in temp location
var filePath = Path.GetTempFileName();
try
{
foreach (var formFile in files)
{
if (formFile.Length > 0)
{
using (var stream = formFile.OpenReadStream())
{
ExcelHelper excelHelper = new ExcelHelper();
string fileExtension = Path.GetExtension(formFile.FileName);
DataTable table = excelHelper.ExcelImport(stream, fileExtension, 0);
if (table != null)
{
foreach (DataRow row in table.Rows)
{
if (row.ItemArray.Length != 6)
{
continue;
}
var passwordSalt = DateTime.Now.Ticks.ToString();
AdminUserInfo model = null;
var userName = row.ItemArray[4].ToString();
var password = row.ItemArray[5].ToString();
if (string.IsNullOrEmpty(userName) || string.IsNullOrEmpty(password))
{
continue;
}
var existModel = _adminUserInfoService.GetUserInfo(userName);
if (existModel != null)
{
model = existModel;
}
else
{
model = new AdminUserInfo()
{
PasswordSalt = passwordSalt,
LastLoginTime = DateTime.Now,
ThisLoginTime = DateTime.Now,
AddTime = DateTime.Now,
};
}
if (!password.IsNullOrEmpty())
{
model.Password = this._adminUserInfoService.GetPassword(password, model.PasswordSalt, false);//生成密码
}
model.RealName = row.ItemArray[3].ToString();
model.Note = row.ItemArray[1].ToString();
model.UserName = userName;
await this.TryUpdateModelAsync(model, "", z => z.Note, z => z.RealName, z => z.UserName);
this._adminUserInfoService.SaveObject(model);
}
}
await Task.Delay(10);
// await formFile.CopyToAsync(stream);
}
}
}
}
catch (Exception ex)
{
var error = ex.Message;
}
// process uploaded files
// Don't rely on or trust the FileName property without validation.
return Ok(new { count = files.Count, size, filePath });
}
}
}
|
using PhobiaX.Assets.Models;
using System;
using System.Collections.Generic;
using System.Text;
namespace PhobiaX.Physics
{
class CollidableObject : ICollidableObject
{
public CollissionMetadata Metadata { get; }
public int X { get; set; }
public int Y { get; set; }
public int MiddleX => X + Width / 2;
public int MiddleY => Y + Height / 2;
public int Width { get; }
public int Height { get; }
public CollidableObject(int width, int height, CollissionMetadata collissionMetadata)
{
this.Width = width;
this.Height = height;
this.Metadata = collissionMetadata ?? new CollissionMetadata();
}
public bool IsColliding(ICollidableObject collidableObject)
{
if (collidableObject is null)
{
return false;
}
var x = X + Metadata.OffsetX;
var y = Y + Metadata.OffsetY;
var width = Width - 2 * Metadata.OffsetX;
var height = Height - 2 * Metadata.OffsetY;
var targetX = collidableObject.X + collidableObject.Metadata.OffsetX;
var targetY = collidableObject.Y + collidableObject.Metadata.OffsetY;
var targetWidth = collidableObject.Width - 2 * collidableObject.Metadata.OffsetX;
var targetHeight = collidableObject.Height - 2 * collidableObject.Metadata.OffsetY;
var isCollissionX = x + width >= targetX && x <= targetX + targetWidth;
var isCollissionY = y + height >= targetY && y <= targetY + targetHeight;
var isCollission = isCollissionX && isCollissionY;
return isCollission;
}
}
}
|
/// <summary>
/// Ben Redahan, redahanb@gmail.com, 2015
/// </summary>
using UnityEngine;
using System.Collections;
public class EnemySight : MonoBehaviour {
public float fieldOfView = 90f;
public bool playerInSight;
public float visionRange = 12.0f;
public bool patrolling;
public bool alerted;
public Vector3 lastPlayerSighting;
private SphereCollider coll;
private GameObject player;
private PlayerController playerController;
private AudioSource guardCry;
private bool canCry = true;
private float timeInSight;
private Vector3 direction;
private float distanceToPlayer;
private float angle;
private RaycastHit hit;
public int visionCount;
// Public function used by alarm systems and noisemaker items to alert the guard from a distance
public void globalAlert(Vector3 alertLocation) {
patrolling = false;
alerted = true;
lastPlayerSighting = alertLocation;
}
public void returnPatrol() {
alerted = false;
patrolling = true;
}
// Use this for initialization
void Start () {
coll = GetComponent<SphereCollider> ();
guardCry = GetComponent<AudioSource> ();
player = GameObject.FindWithTag ("Player");
playerController = player.GetComponent<PlayerController> ();
patrolling = true;
alerted = false;
visionCount = 0;
timeInSight = 0.0f;
}
// Update is called once per frame
void Update () {
// if (!player && GameObject.FindWithTag("Player")) {
// player = GameObject.FindWithTag ("Player");
// //pcc = player.GetComponent<PlayerColorChanger> ();
// } else {
// //print( pcc.isBlending);
// }
//
// if(!playerController && GameObject.FindWithTag("Player")){
// playerController = player.GetComponent<PlayerController> ();
// }
/// TESTING ALTERNATE IMPLEMENTATION: No Trigger Collider ///
if (player) {
checkSight ();
}
if (patrolling) {
if (playerInSight) {
if (visionCount >= 60) {
patrolling = false;
alerted = true;
visionCount = 120;
} else {
visionCount += 3;
}
} else {
if (visionCount > 0) {
visionCount--;
}
}
}
else {
// check distance from last known sighting of player, if player is not seen in area, return to patrol
float huntRange = Vector3.Distance(transform.position, lastPlayerSighting);
if (playerInSight == false && huntRange <= 1.0f ){
if (visionCount > 0) {
visionCount--;
}
else {
GuardAI guardAI = GetComponent<GuardAI>();
guardAI.alerted = false;
returnPatrol();
NavMeshPatrolv3 patrol = GetComponent<NavMeshPatrolv3>();
patrol.nextAlertPoint();
}
}
}
}
void resetCanCry(){
canCry = true;
}
void checkSight() {
// Performed every frame to report whether or not the player can be seen by the guard
distanceToPlayer = Vector3.Distance (transform.position, player.transform.position);
if (distanceToPlayer < visionRange && (player.transform.position.y - transform.position.y < 0.1))
{
//print ("player in range");
playerInSight = false;
// calculate angle between guard forward vector and player
direction = player.transform.position - transform.position;
angle = Vector3.Angle (direction, transform.forward); // v3.angle returns acute angle always
if (angle <= 50.0f) {
// if player is within +-50 degrees of forward vector, cast a ray to player
//print("player in field of view");
if (Physics.Raycast (transform.position + Vector3.up, direction, out hit, visionRange)) {
if (hit.collider.gameObject.tag == "Player")
{
// if ray hits player, check player camoflage
if(playerController.isVisible)
{
playerInSight = true;
// record last sighting coordinates for chasing
lastPlayerSighting = player.transform.position;
// play guard cry sound
if(canCry)
{
AudioSource.PlayClipAtPoint(guardCry.clip, transform.position);
// put canCry on cooldown
canCry = false;
Invoke("resetCanCry", 5);
}
}
}
}
}
}
else
{
playerInSight = false;
}
// HEARING //
// If player is running withing the guard's sphere of hearing, the guard will hear them
// if((distanceToPlayer < 4.0f) && playerController.currentMoveState == PlayerController.MoveState.Run){
// // Investigate the noise at the location the noise came from
// print ("Heard player running");
// patrolling = false;
// alerted = true;
// lastPlayerSighting = player.transform.position;
// GetComponent<NavMeshPatrolv3>().Investigate(lastPlayerSighting);
// } // If the player is moving at any speed too close to the guard the guard will detect them
// else if (distanceToPlayer < 2.0f && playerController.currentMoveState != PlayerController.MoveState.Blend_Stand){
// print ("Heard player in vicinity");
// patrolling = false;
// alerted = true;
// lastPlayerSighting = player.transform.position;
// GetComponent<NavMeshPatrolv3>().Investigate(lastPlayerSighting);
// }
} // end of checkSight
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xunit;
using Xunit.Abstractions;
namespace Terminal.Gui.ViewTests {
public class PanelViewTests {
readonly ITestOutputHelper output;
public PanelViewTests (ITestOutputHelper output)
{
this.output = output;
}
[Fact]
public void Constructor_Defaults ()
{
var pv = new PanelView ();
Assert.False (pv.CanFocus);
Assert.False (pv.Visible);
Assert.False (pv.UsePanelFrame);
Assert.Null (pv.Child);
pv = new PanelView (new Label ("This is a test."));
Assert.False (pv.CanFocus);
Assert.True (pv.Visible);
Assert.False (pv.UsePanelFrame);
Assert.NotNull (pv.Child);
Assert.NotNull (pv.Border);
Assert.NotNull (pv.Child.Border);
}
[Fact]
public void Child_Sets_To_Null_Remove_From_Subviews_PanelView ()
{
var pv = new PanelView (new Label ("This is a test."));
Assert.NotNull (pv.Child);
Assert.Single (pv.Subviews [0].Subviews);
pv.Child = null;
Assert.Null (pv.Child);
Assert.Empty (pv.Subviews [0].Subviews);
}
[Fact]
public void Add_View_Also_Sets_Child ()
{
var pv = new PanelView ();
Assert.Null (pv.Child);
Assert.Empty (pv.Subviews [0].Subviews);
pv.Add (new Label ("This is a test."));
Assert.NotNull (pv.Child);
Assert.Single (pv.Subviews [0].Subviews);
}
[Fact]
public void Add_More_Views_Remove_Last_Child_Before__Only_One_Is_Allowed ()
{
var pv = new PanelView (new Label ("This is a test."));
Assert.NotNull (pv.Child);
Assert.Single (pv.Subviews [0].Subviews);
Assert.IsType<Label> (pv.Child);
pv.Add (new TextField ("This is a test."));
Assert.NotNull (pv.Child);
Assert.Single (pv.Subviews [0].Subviews);
Assert.IsNotType<Label> (pv.Child);
Assert.IsType<TextField> (pv.Child);
}
[Fact]
public void Remove_RemoveAll_View_Also_Sets_Child_To_Null ()
{
var pv = new PanelView (new Label ("This is a test."));
Assert.NotNull (pv.Child);
Assert.Single (pv.Subviews [0].Subviews);
pv.Remove (pv.Child);
Assert.Null (pv.Child);
Assert.Empty (pv.Subviews [0].Subviews);
pv = new PanelView (new Label ("This is a test."));
Assert.NotNull (pv.Child);
Assert.Single (pv.Subviews [0].Subviews);
pv.RemoveAll ();
Assert.Null (pv.Child);
Assert.Empty (pv.Subviews [0].Subviews);
}
[Fact]
[AutoInitShutdown]
public void AdjustContainer_Without_Border ()
{
var top = Application.Top;
var win = new Window ();
var pv = new PanelView (new Label ("This is a test."));
win.Add (pv);
top.Add (win);
Application.Begin (top);
Assert.Equal (new Rect (0, 0, 15, 1), pv.Frame);
Assert.Equal (new Rect (0, 0, 15, 1), pv.Child.Frame);
}
[Fact]
[AutoInitShutdown]
public void AdjustContainer_With_Border_Absolute_Values ()
{
var top = Application.Top;
var win = new Window ();
var pv = new PanelView (new Label ("This is a test.") {
Border = new Border () {
BorderStyle = BorderStyle.Double,
BorderThickness = new Thickness (1, 2, 3, 4),
Padding = new Thickness (1, 2, 3, 4)
}
});
win.Add (pv);
top.Add (win);
Application.Begin (top);
Assert.False (pv.Child.Border.Effect3D);
Assert.Equal (new Rect (0, 0, 25, 15), pv.Frame);
Assert.Equal (new Rect (0, 0, 15, 1), pv.Child.Frame);
pv.Child.Border.Effect3D = true;
Assert.True (pv.Child.Border.Effect3D);
Assert.Equal (new Rect (0, 0, 25, 15), pv.Frame);
Assert.Equal (new Rect (0, 0, 15, 1), pv.Child.Frame);
pv.Child.Border.Effect3DOffset = new Point (-1, -1);
Assert.Equal (new Point (-1, -1), pv.Child.Border.Effect3DOffset);
Assert.Equal (new Rect (0, 0, 25, 15), pv.Frame);
Assert.Equal (new Rect (0, 0, 15, 1), pv.Child.Frame);
}
[Fact]
[AutoInitShutdown]
public void AdjustContainer_With_Border_Computed_Values ()
{
var top = Application.Top;
var win = new Window ();
var pv = new PanelView (new TextView () {
Width = Dim.Fill (),
Height = Dim.Fill (),
Border = new Border () {
BorderStyle = BorderStyle.Double,
BorderThickness = new Thickness (1, 2, 3, 4),
Padding = new Thickness (1, 2, 3, 4)
}
});
var pv1 = new PanelView (new TextView () {
Width = Dim.Fill (1),
Height = Dim.Fill (1),
Border = new Border () {
BorderStyle = BorderStyle.Double,
BorderThickness = new Thickness (1, 2, 3, 4),
Padding = new Thickness (1, 2, 3, 4)
}
});
var pv2 = new PanelView (new TextView () {
Width = Dim.Fill (2),
Height = Dim.Fill (2),
Border = new Border () {
BorderStyle = BorderStyle.Double,
BorderThickness = new Thickness (1, 2, 3, 4),
Padding = new Thickness (1, 2, 3, 4)
}
});
win.Add (pv, pv1, pv2);
top.Add (win);
Application.Begin (top);
Assert.Equal (new Rect (0, 0, 78, 23), pv.Frame);
Assert.Equal (new Rect (0, 0, 68, 9), pv.Child.Frame);
Assert.Equal (new Rect (0, 0, 77, 22), pv1.Frame);
Assert.Equal (new Rect (0, 0, 65, 6), pv1.Child.Frame);
Assert.Equal (new Rect (0, 0, 76, 21), pv2.Frame);
Assert.Equal (new Rect (0, 0, 62, 3), pv2.Child.Frame);
pv.Child.Border.Effect3D = pv1.Child.Border.Effect3D = pv2.Child.Border.Effect3D = true;
Assert.True (pv.Child.Border.Effect3D);
Assert.Equal (new Rect (0, 0, 78, 23), pv.Frame);
Assert.Equal (new Rect (0, 0, 68, 9), pv.Child.Frame);
Assert.Equal (new Rect (0, 0, 77, 22), pv1.Frame);
Assert.Equal (new Rect (0, 0, 65, 6), pv1.Child.Frame);
Assert.Equal (new Rect (0, 0, 76, 21), pv2.Frame);
Assert.Equal (new Rect (0, 0, 62, 3), pv2.Child.Frame);
pv.Child.Border.Effect3DOffset = pv1.Child.Border.Effect3DOffset = pv2.Child.Border.Effect3DOffset = new Point (-1, -1);
Assert.Equal (new Point (-1, -1), pv.Child.Border.Effect3DOffset);
Assert.Equal (new Rect (0, 0, 78, 23), pv.Frame);
Assert.Equal (new Rect (0, 0, 68, 9), pv.Child.Frame);
Assert.Equal (new Rect (0, 0, 77, 22), pv1.Frame);
Assert.Equal (new Rect (0, 0, 65, 6), pv1.Child.Frame);
Assert.Equal (new Rect (0, 0, 76, 21), pv2.Frame);
Assert.Equal (new Rect (0, 0, 62, 3), pv2.Child.Frame);
}
[Fact]
[AutoInitShutdown]
public void UsePanelFrame_False_PanelView_Always_Respect_The_PanelView_Upper_Left_Corner_Position_And_The_Child_Size ()
{
var top = Application.Top;
var win = new Window ();
var pv = new PanelView (new Label ("This is a test.")) {
X = 2,
Y = 4,
Width = 20,
Height = 10
};
var pv1 = new PanelView (new TextField (3, 4, 15, "This is a test.")) {
X = 2,
Y = 4,
Width = 20,
Height = 10
};
var pv2 = new PanelView (new TextView () {
X = 5,
Y = 6,
Width = Dim.Fill (),
Height = Dim.Fill ()
}) {
X = 2,
Y = 4,
Width = 20,
Height = 10
};
win.Add (pv, pv1, pv2);
top.Add (win);
Application.Begin (top);
Assert.False (pv.UsePanelFrame);
Assert.False (pv.Border.Effect3D);
Assert.Equal (pv.Child.Border, pv.Border);
Assert.False (pv1.UsePanelFrame);
Assert.False (pv1.Border.Effect3D);
Assert.Equal (pv1.Child.Border, pv1.Border);
Assert.False (pv2.UsePanelFrame);
Assert.False (pv2.Border.Effect3D);
Assert.Equal (pv2.Child.Border, pv2.Border);
Assert.Equal (new Rect (2, 4, 15, 1), pv.Frame);
Assert.Equal (new Rect (0, 0, 15, 1), pv.Child.Frame);
Assert.Equal (new Rect (2, 4, 18, 5), pv1.Frame);
Assert.Equal (new Rect (3, 4, 15, 1), pv1.Child.Frame);
Assert.Equal (new Rect (2, 4, 76, 19), pv2.Frame);
Assert.Equal (new Rect (5, 6, 71, 13), pv2.Child.Frame);
pv.Border.Effect3D = pv1.Border.Effect3D = pv2.Border.Effect3D = true;
Assert.Equal (new Rect (2, 4, 15, 1), pv.Frame);
Assert.Equal (new Rect (0, 0, 15, 1), pv.Child.Frame);
Assert.Equal (new Rect (2, 4, 18, 5), pv1.Frame);
Assert.Equal (new Rect (3, 4, 15, 1), pv1.Child.Frame);
Assert.Equal (new Rect (2, 4, 76, 19), pv2.Frame);
Assert.Equal (new Rect (5, 6, 71, 13), pv2.Child.Frame);
pv.Border.Effect3DOffset = pv1.Border.Effect3DOffset = pv2.Border.Effect3DOffset = new Point (-1, -1);
Assert.Equal (new Rect (2, 4, 15, 1), pv.Frame);
Assert.Equal (new Rect (0, 0, 15, 1), pv.Child.Frame);
Assert.Equal (new Rect (2, 4, 18, 5), pv1.Frame);
Assert.Equal (new Rect (3, 4, 15, 1), pv1.Child.Frame);
Assert.Equal (new Rect (2, 4, 76, 19), pv2.Frame);
Assert.Equal (new Rect (5, 6, 71, 13), pv2.Child.Frame);
}
[Fact]
[AutoInitShutdown]
public void UsePanelFrame_True_PanelView_Position_And_Size_Are_Used_Depending_On_Effect3DOffset ()
{
var top = Application.Top;
var win = new Window ();
var pv = new PanelView (new TextView () {
X = 2,
Y = 4,
Width = 20,
Height = 10
}) {
X = 5,
Y = 6,
Width = Dim.Fill (),
Height = Dim.Fill (),
UsePanelFrame = true
};
var pv1 = new PanelView (new TextView () {
X = 5,
Y = 6,
Width = Dim.Fill (),
Height = Dim.Fill ()
}) {
X = 2,
Y = 4,
Width = 20,
Height = 10,
UsePanelFrame = true
};
win.Add (pv, pv1);
top.Add (win);
Application.Begin (top);
Assert.Equal (new Rect (5, 6, 73, 17), pv.Frame);
Assert.Equal (new Rect (2, 4, 20, 10), pv.Child.Frame);
Assert.Equal (new Rect (2, 4, 20, 10), pv1.Frame);
Assert.Equal (new Rect (5, 6, 15, 4), pv1.Child.Frame);
pv.Border.Effect3D = pv1.Border.Effect3D = true;
Assert.Equal (new Rect (5, 6, 73, 17), pv.Frame);
Assert.Equal (new Rect (2, 4, 20, 10), pv.Child.Frame);
Assert.Equal (new Rect (2, 4, 20, 10), pv1.Frame);
Assert.Equal (new Rect (5, 6, 15, 4), pv1.Child.Frame);
pv.Border.Effect3DOffset = pv1.Border.Effect3DOffset = new Point (-1, -1);
Assert.Equal (new Rect (6, 7, 73, 17), pv.Frame);
Assert.Equal (new Rect (2, 4, 20, 10), pv.Child.Frame);
Assert.Equal (new Rect (3, 5, 20, 10), pv1.Frame);
Assert.Equal (new Rect (5, 6, 15, 4), pv1.Child.Frame);
}
[Fact, AutoInitShutdown]
public void Setting_Child_Size_Disable_AutoSize ()
{
var top = Application.Top;
var win = new Window ();
var label = new Label () {
ColorScheme = Colors.TopLevel,
Text = "This is a test\nwith a \nPanelView",
TextAlignment = TextAlignment.Centered,
Width = 24,
Height = 13,
AutoSize = false
};
var pv = new PanelView (label) {
Width = 24,
Height = 13,
Border = new Border () {
BorderStyle = BorderStyle.Single,
DrawMarginFrame = true,
BorderThickness = new Thickness (2),
BorderBrush = Color.Red,
Padding = new Thickness (2),
Background = Color.BrightGreen,
Effect3D = true
},
};
win.Add (pv);
top.Add (win);
Application.Begin (top);
Assert.False (label.AutoSize);
Assert.Equal (new Rect (0, 0, 24, 13), label.Frame);
Assert.Equal (new Rect (0, 0, 34, 23), pv.Frame);
Assert.Equal (new Rect (0, 0, 80, 25), win.Frame);
Assert.Equal (new Rect (0, 0, 80, 25), Application.Top.Frame);
var expected = @"
┌──────────────────────────────────────────────────────────────────────────────┐
│ │
│ │
│ │
│ │
│ ┌────────────────────────┐ │
│ │ This is a test │ │
│ │ with a │ │
│ │ PanelView │ │
│ │ │ │
│ │ │ │
│ │ │ │
│ │ │ │
│ │ │ │
│ │ │ │
│ │ │ │
│ │ │ │
│ │ │ │
│ │ │ │
│ └────────────────────────┘ │
│ │
│ │
│ │
│ │
└──────────────────────────────────────────────────────────────────────────────┘
";
var pos = TestHelpers.AssertDriverContentsWithFrameAre (expected, output);
Assert.Equal (new Rect (0, 0, 80, 25), pos);
}
[Fact, AutoInitShutdown]
public void Not_Setting_Child_Size_Default_AutoSize_True ()
{
var top = Application.Top;
var win = new Window ();
var label = new Label () {
ColorScheme = Colors.TopLevel,
Text = "This is a test\nwith a \nPanelView",
TextAlignment = TextAlignment.Centered
};
var pv = new PanelView (label) {
Width = 24,
Height = 13,
Border = new Border () {
BorderStyle = BorderStyle.Single,
DrawMarginFrame = true,
BorderThickness = new Thickness (2),
BorderBrush = Color.Red,
Padding = new Thickness (2),
Background = Color.BrightGreen,
Effect3D = true
},
};
win.Add (pv);
top.Add (win);
Application.Begin (top);
Assert.True (label.AutoSize);
Assert.False (pv.UsePanelFrame);
Assert.Equal (new Rect (0, 0, 14, 3), label.Frame);
Assert.Equal (new Rect (0, 0, 24, 13), pv.Frame);
Assert.Equal (new Rect (0, 0, 80, 25), win.Frame);
Assert.Equal (new Rect (0, 0, 80, 25), Application.Top.Frame);
var expected = @"
┌──────────────────────────────────────────────────────────────────────────────┐
│ │
│ │
│ │
│ │
│ ┌──────────────┐ │
│ │This is a test│ │
│ │ with a │ │
│ │ PanelView │ │
│ └──────────────┘ │
│ │
│ │
│ │
│ │
│ │
│ │
│ │
│ │
│ │
│ │
│ │
│ │
│ │
│ │
└──────────────────────────────────────────────────────────────────────────────┘
";
var pos = TestHelpers.AssertDriverContentsWithFrameAre (expected, output);
Assert.Equal (new Rect (0, 0, 80, 25), pos);
}
}
}
|
using System;
namespace Euler_Logic.Problems.AdventOfCode.Y2017 {
public class Problem01 : AdventOfCodeBase {
public override string ProblemName {
get { return "Advent of Code 2017: 1"; }
}
public override string GetAnswer2() {
return Answer2(Input()[0]);
}
public override string GetAnswer() {
return Answer1(Input()[0]);
}
private string Answer1(string text) {
int sum = 0;
for (int index = 0; index < text.Length; index++) {
string character = text.Substring(index, 1);
if (index == text.Length - 1) {
if (character == text.Substring(0, 1)) {
sum += Convert.ToInt32(character);
}
} else if (character == text.Substring(index + 1, 1)) {
sum += Convert.ToInt32(character);
}
}
return sum.ToString();
}
private string Answer2(string text) {
int sum = 0;
for (int index = 0; index < text.Length; index++) {
int next = ((text.Length / 2) + index) % text.Length;
if (text.Substring(index, 1) == text.Substring(next, 1)) {
sum += Convert.ToInt32(text.Substring(index, 1));
}
}
return sum.ToString();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
namespace DiagramDesigner
{
public class FullyCreatedConnectorInfo : ConnectorInfoBase
{
private bool showConnectors = false;
public FullyCreatedConnectorInfo(DesignerItemViewModelBase dataItem, ConnectorOrientation orientation)
: base(orientation)
{
this.DataItem = dataItem;
}
public DesignerItemViewModelBase DataItem { get; private set; }
public bool ShowConnectors
{
get
{
return showConnectors;
}
set
{
if (showConnectors != value)
{
showConnectors = value;
NotifyChanged("ShowConnectors");
}
}
}
}
}
|
// Loads the next level
using UnityEngine;
using System.Collections;
public class NextLevel : MonoBehaviour {
public GameScript load;
// Use this for initialization
void Start () {
// Finds the game manager object
load = GameObject.Find ("GameManager").GetComponent<GameScript>();
}
void OnMouseDown () {
// Get the last level loaded by LevelLoader and adds 1, loading the next level
Application.LoadLevel(load.lastLevelPlayed + 1);
}
}
|
using System.Threading.Tasks;
using KitStarter.Server.Library.Configuration;
using KitStarter.Server.Models;
namespace KitStarter.Server.Tools.EmailSender
{
public abstract class EmailSender
{
protected STMPConnection settings;
public EmailSender(STMPConnection settings)
{
this.settings = settings;
}
public abstract Task SendEmailAsync(CredentialsDTO credentials, string subject, string message);
}
} |
using Allyn.Domain.Models.Basic;
using System;
using System.Collections.Generic;
namespace Allyn.Domain.Models.Basic
{
/// <summary>
/// 表示"角色"聚合根类型.
/// </summary>
public class Role : AggregateRoot
{
/// <summary>
/// 获取或设置父级.
/// </summary>
public Role Parent { get; set; }
/// <summary>
/// 获取或设置角色代码.
/// </summary>
public string Code { get; set; }
/// <summary>
/// 获取或设置角色名.
/// </summary>
public string Name { get; set; }
/// <summary>
/// 获取或设置备注信息.
/// </summary>
public string Description { get; set; }
/// <summary>
/// 获取或设置排序
/// </summary>
public int Sort { get; set; }
/// <summary>
/// 获取或设置创建时间.
/// </summary>
public DateTime CreateDate { get; set; }
/// <summary>
/// 获取或设置更新时间.
/// </summary>
public DateTime UpdateDate { get; set; }
/// <summary>
/// 获取或设置锁定标识.
/// </summary>
public bool Disabled { get; set; }
/// <summary>
/// 获取或设置创建人.
/// </summary>
public Guid Creater { get; set; }
/// <summary>
/// 获取或设置修改者.
/// </summary>
public Guid Modifier { get; set; }
/// <summary>
/// 获取或设置子角色.
/// </summary>
public List<Role> Children { get; set; }
}
}
|
namespace IdentityServer3.Shaolinq
{
public class ShaolinqServiceOptions
{
/// <summary>
/// The name of the config section to use for this data model (if null or empty defaults to the type name of the data access model)
/// </summary>
public string DataAccessModelConfigSection { get; set; }
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public enum MarkerType {
In,
Up,
Down,
Out
}
public class SingleMarker : OnRailRechargeMarker {
MarkerType MarkerType;
private SpriteRenderer spriteRenderer;
private static Sprite InMarkerSprite;
private static Sprite DownMarkerSprite;
private static Sprite OutMarkerSprite;
// Use this for initialization
public override void Awake () {
base.Awake();
spriteRenderer = GetComponent<SpriteRenderer>();
}
// Update is called once per frame
void Update () {
}
public override void Init() {
MarkerType = (MarkerType)Random.Range(0, 4);
switch (MarkerType) {
case MarkerType.In:
InMarkerSprite = InMarkerSprite ?? Resources.Load<Sprite>("Sprites/arrow_in");
spriteRenderer.sprite = InMarkerSprite;
Value = 10f;
break;
case MarkerType.Up:
DownMarkerSprite = DownMarkerSprite ?? Resources.Load<Sprite>("Sprites/down_arrow_out");
spriteRenderer.sprite = DownMarkerSprite;
spriteRenderer.flipY = true;
Value = 20f;
break;
case MarkerType.Down:
DownMarkerSprite = DownMarkerSprite ?? Resources.Load<Sprite>("Sprites/down_arrow_out");
spriteRenderer.sprite = DownMarkerSprite;
spriteRenderer.flipY = false;
Value = 20f;
break;
default:
case MarkerType.Out:
OutMarkerSprite = OutMarkerSprite ?? Resources.Load<Sprite>("Sprites/both_arrow_out");
spriteRenderer.sprite = OutMarkerSprite;
Value = 15f;
break;
}
}
public new static SingleMarker Create() {
var name = "Single-Marker";
PoolManager pm = PoolManager.Instance;
if (!pm.ContainsKey(name)) {
SingleMarker prefab = Resources.Load<SingleMarker>($"Prefabs/{name}");
prefab.Key = name;
pm.CreatePool(prefab);
}
SingleMarker seg = pm.Next<SingleMarker>(name);
return seg;
}
public override bool IsConditionMet(bool jumping, bool attachedToRail, float direction) {
if(!jumping || !attachedToRail) return false;
switch (MarkerType) {
case MarkerType.In:
return Mathf.Abs(direction) < 0.3f;
case MarkerType.Up:
return direction > 0.5f;
case MarkerType.Down:
return direction < -0.5f;
case MarkerType.Out:
return Mathf.Abs(direction) > 0.5f;
default:
return true;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Exercicio14
{
class Xis
{
static void Main(string[] args)
{
{
const char Caract = 'X';
const char Ponto = '.';
int Dimensao = 12; Console.Clear();
for (int Linha = 1; Linha <= Dimensao; Linha++)
{
for (int Coluna = 1; Coluna <= Dimensao; Coluna++)
{
if ((Linha == Coluna) || (Coluna == Dimensao - Linha + 1))
Console.Write(Caract);
else
Console.Write(Ponto);
}
Console.WriteLine(); Console.WriteLine();
}
}
}
}
}
|
using System.Collections.Generic;
namespace TechnicalSupport
{
public class SettingsJSON
{
public DB DataBase { get; set; }
}
public class DB
{
public problem Problem { get; set; }
public tarif Tarif { get; set; }
public communication Communication { get; set; }
}
public class problem
{
public List<string> nameProblem { get; set; }
public List<List<string>> ListReshProblem { get; set; }
}
public class tarif
{
public List<string> nameTarif { get; set; }
public List<List<string>> ListTextTarif { get; set; }
}
public class communication
{
public List<string> phone { get; set; }
public List<string> email { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;
using Microsoft.WindowsAzure;
using Microsoft.WindowsAzure.StorageClient;
using WCFServiceWebRole1.Database;
using WCFServiceWebRole1.Helpers;
using System.Net;
using System.IO;
using HtmlAgilityPack;
using System.Text.RegularExpressions;
namespace WCFServiceWebRole1
{
public class Service1 : IService1
{
public string GetHello()
{
// Retrieve storage account from connection string
CloudStorageAccount storageAccount = CloudStorageAccount.Parse(
CloudConfigurationManager.GetSetting("StorageConnectionString"));
// Create the table client
CloudTableClient tableClient = storageAccount.CreateCloudTableClient();
// Create the table if it doesn't exist
string tableName = "users1";
tableClient.CreateTableIfNotExist(tableName);
// Get the data service context
TableServiceContext serviceContext = tableClient.GetDataServiceContext();
return "Hello from my WCF service in Windows Azure!";
}
/// <summary>
///
/// </summary>
/// <param name="loginUrl">Login url</param>
/// <param name="userName">User's login name</param>
/// <param name="password">User's password</param>
/// <param name="formParams">Optional string which contains any additional form params</param>
/// <returns></returns>
public bool LoginToSite(String userName, String password)
{
//////////////////////////////////////////////////////////////////////////////
//
// local variables
// TODO: Review if there is a better solution to hard-coding these
//
string formParams = string.Format("language=en&affiliateName=espn&parentLocation=®istrationFormId=espn");
string loginUrl = "https://r.espn.go.com/members/util/loginUser";
CookieCollection cookies;
string leagueId = "";
string teamId = "";
string season = "";
string userTable = "ausers00";
string teamTable = "ateams00";
string cookieTable = "acookies00";
bool newUser = true;
/////////////////////////////////////////////////////////////////////////////
//
// Lookup / Store user in storage.
//
// Encrypt the user password for safe persistence
// TODO: Store the key somewhere safe. Also, it may be better to store password on the device?
//
string passwordHash = Crypto.EncryptStringAES(password, "foobar");
// Retrieve storage account from connection string
CloudStorageAccount storageAccount = CloudStorageAccount.Parse(
CloudConfigurationManager.GetSetting("StorageConnectionString"));
//
// Create the table client
//
CloudTableClient tableClient = storageAccount.CreateCloudTableClient();
//
// Create the user/team/cookie tables if they don't exist
//
tableClient.CreateTableIfNotExist(userTable);
tableClient.CreateTableIfNotExist(teamTable);
tableClient.CreateTableIfNotExist(cookieTable);
// Get the data service context
TableServiceContext serviceContext = tableClient.GetDataServiceContext();
//
// Look up the user in the storage tables
//
UserEntity specificEntity =
(from e in serviceContext.CreateQuery<UserEntity>(userTable)
where e.RowKey == userName
select e).FirstOrDefault();
//
// Check to see if password is correct
//
if (specificEntity != null)
{
string userPassword = Crypto.DecryptStringAES(specificEntity.PasswordHash, "foobar");
if (userPassword == password)
{
newUser = false;
}
}
//
// If this is a new user add them to the users databse
//
if (newUser)
{
//
// Setup formUrl string
//
string formUrl = "";
if (!String.IsNullOrEmpty(formParams))
{
formUrl = formParams + "&";
}
formUrl += string.Format("username={0}&password={1}", userName, password);
//
// Now setup the POST request
//
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(loginUrl);
req.CookieContainer = new CookieContainer();
req.ContentType = "application/x-www-form-urlencoded";
req.Method = "POST";
byte[] bytes = Encoding.ASCII.GetBytes(formUrl);
req.ContentLength = bytes.Length;
using (Stream os = req.GetRequestStream())
{
os.Write(bytes, 0, bytes.Length);
}
//
// Read the response
//
string respString = "";
using (HttpWebResponse resp = (HttpWebResponse)req.GetResponse())
{
//
// Gather cookie info
//
cookies = resp.Cookies;
//
// Read the response stream to determine if login was successful.
//
using (StreamReader reader = new StreamReader(resp.GetResponseStream()))
{
Char[] buffer = new Char[256];
int count = reader.Read(buffer, 0, 256);
while (count > 0)
{
respString += new String(buffer, 0, count);
count = reader.Read(buffer, 0, 256);
}
} // reader is disposed here
}
//writeLog(respString);
//
// If response string contains "login":"true" this indicates success
//
if (!respString.Contains("{\"login\":\"true\"}"))
{
throw new InvalidOperationException("Failed to login with given credentials");
}
//
// Login success - Now save user to databse
// TODO: Figure out a better partition key other than "key"
//
UserEntity user = new UserEntity("key", userName);
user.PasswordHash = passwordHash;
// Add the new team to the teams table
serviceContext.AddObject(userTable, user);
//////////////////////////////////////////////////////////////////////////////////
//
// Now that we have logged in, extract user info from the page
//
string url2 = "http://games.espn.go.com/frontpage/football";
HttpWebRequest req2 = (HttpWebRequest)WebRequest.Create(url2);
req2.CookieContainer = new CookieContainer();
req2.ContentType = "application/x-www-form-urlencoded";
req2.Method = "POST";
//
// Add the login cookies
//
foreach (Cookie cook in cookies)
{
//writeLog("**name = " + cook.Name + " value = " + cook.Value);
CookieEntity newCook = new CookieEntity(userName, cook.Name);
newCook.Value = cook.Value;
newCook.Path = cook.Path;
newCook.Domain = cook.Domain;
// Add the new cookie to the cookies table
serviceContext.AddObject(cookieTable, newCook);
req2.CookieContainer.Add(cook);
}
//
// Read the response
//
using (HttpWebResponse resp = (HttpWebResponse)req2.GetResponse())
{
//
// Do something with the response stream. As an example, we'll
// stream the response to the console via a 256 character buffer
using (StreamReader reader = new StreamReader(resp.GetResponseStream()))
{
HtmlDocument doc = new HtmlDocument();
doc.Load(reader);
//
// Build regEx for extracting legue info from link address
//
string pattern = @"(clubhouse\?leagueId=)(\d+)(&teamId=)(\d+)(&seasonId=)(\d+)";
Regex rgx = new Regex(pattern, RegexOptions.IgnoreCase);
foreach (HtmlNode hNode in doc.DocumentNode.SelectNodes("//a[@href]"))
{
HtmlAttribute att = hNode.Attributes["href"];
Match match = rgx.Match(att.Value);
//
// If our regEx finds a match then we have leagueId, teamId, and seasonId
//
if (match.Success)
{
//writeLog("NODE> Name: " + hNode.Name + ", ID: " + hNode.Id + "attr: " + att.Value);
GroupCollection groups = match.Groups;
leagueId = groups[2].Value;
teamId = groups[4].Value;
season = groups[6].Value;
//
// Create a new team entity
//
TeamEntity team = new TeamEntity(leagueId, teamId);
team.Season = season;
team.UserId = userName;
// Add the new team to the teams table
serviceContext.AddObject(teamTable, team);
}
}
} // reader is disposed here
}
// Submit the operation to the table service
serviceContext.SaveChangesWithRetries();
}
return true;
}
}
}
|
using Alabo.Datas.UnitOfWorks;
using Alabo.Domains.Entities;
using Alabo.Domains.Repositories;
using Alabo.Domains.Services;
using Alabo.Extensions;
using Alabo.Framework.Basic.Relations.Domain.Entities;
using Alabo.Framework.Basic.Relations.Domain.Repositories;
using Alabo.Framework.Core.Reflections.Interfaces;
using System.Collections.Generic;
using System.Linq;
namespace Alabo.Framework.Basic.Relations.Domain.Services {
public class RelationIndexService : ServiceBase<RelationIndex, long>, IRelationIndexService {
public RelationIndexService(IUnitOfWork unitOfWork, IRepository<RelationIndex, long> repository) : base(
unitOfWork, repository) {
}
public ServiceResult AddUpdateOrDelete(string fullName, long entityId, string relationIds) {
var result = ServiceResult.Success;
var list = GetList(r => r.Type == fullName && r.EntityId == entityId).Select(r => r.RelationId).ToList();
var addList = new List<RelationIndex>();
var temp = relationIds.ToLongList();
var deleteList = list.Except(relationIds.ToLongList()).ToList();
temp.Except(list).Foreach(o => {
addList.Add(new RelationIndex {
Type = fullName,
EntityId = entityId,
RelationId = o
});
});
//foreach (var item in relationIds.ToSplitList()) {
// var relationId = item.ToInt16();
// if (relationId > 0) {
// if (!list.Contains(relationId)) {
// RelationIndex index = new RelationIndex();
// index.Type = type;
// index.EntityId = entityId;
// index.RelationId = item.ToInt16();
// addList.Add(index);
// }
// //else {
// // deleteList.Add(relationId);
// //}
// }
//}
//删除级联数据
Delete(r => deleteList.Contains(r.RelationId) && r.EntityId == entityId && r.Type == fullName);
//添加级联数据
AddMany(addList);
return result;
}
/// <summary>
/// 批量更新RealtionIndex
/// 批量更新分类、标签等,包括删除、添加、更新操作
/// </summary>
/// <typeparam name="T">级联类型</typeparam>
/// <param name="entityId">实体Id</param>
/// <param name="relationIds">级联ID字符串,多个Id 用逗号隔开,格式:12,13,14,15</param>
public ServiceResult AddUpdateOrDelete<T>(long entityId, string relationIds) where T : class, IRelation {
return AddUpdateOrDelete(typeof(T).FullName, entityId, relationIds);
}
/// <summary>
/// 获取Id字符串列表,返回格式逗号隔开
/// 示列数据:12,13,14,15
/// </summary>
/// <typeparam name="T">级联类型</typeparam>
/// <param name="entityId">实体Id</param>
public string GetRelationIds<T>(long entityId) where T : class, IRelation {
var type = typeof(T).FullName;
var list = GetList(r => r.Type == type && r.EntityId == entityId).Select(r => r.RelationId).ToList();
var ids = list.JoinToString(",");
return ids;
}
public string GetRelationIds(string type, long entityId) {
var list = GetList(r => r.Type == type && r.EntityId == entityId).Select(r => r.RelationId).ToList();
var ids = list.JoinToString(",");
return ids;
}
public List<RelationIndex> GetEntityIds(string ids) {
var query = Repository<IRelationIndexRepository>().GetList();
var tags = ids.ToIntList();
var list = (from t in query join i in tags on t.RelationId equals i select t).ToList();
return list;
}
public ServiceResult AddUpdateOrDelete(long entityId, string relationIds, string type) {
var result = ServiceResult.Success;
var list = GetList(r => r.Type == type && r.EntityId == entityId).Select(r => r.RelationId).ToList();
var addList = new List<RelationIndex>();
var temp = relationIds.ToLongList();
var deleteList = list.Except(relationIds.ToLongList()).ToList();
temp.Except(list).Foreach(o => {
addList.Add(new RelationIndex {
Type = type,
EntityId = entityId,
RelationId = o
});
});
//删除级联数据
Delete(r => deleteList.Contains(r.RelationId) && r.EntityId == entityId && r.Type == type);
//添加级联数据
AddMany(addList);
return result;
}
}
} |
using UnityEngine;
using UnityEditor;
using Thesis;
using System.Collections.Generic;
using System;
using Object = UnityEngine.Object;
public class Builder : EditorWindow
{
// dimensions stuff
private Vector2 _p1 = Vector2.zero;
private Vector2 _p2 = Vector2.zero;
private Vector2 _p3 = Vector2.zero;
private Vector2 _p4 = Vector2.zero;
private float _width = 0f, _depth = 0f, _height = 0f;
private int _floors = 0;
private enum Area { noChoice, dimensions, points }
private Area choice1 = Area.noChoice;
private enum Heights
{
noChoice,
floorCount,
floorHeight,
floorCountAndHeight
}
private Heights choice2 = Heights.noChoice;
// component stuff
private bool inputCompCount = false;
private float compDist = 0f;
private bool windowFoldout = false;
private float windowHeight = 0f;
private float windowWidth = 0f;
private bool setWindowWidth = false;
private bool setWindowHeight = false;
private bool doorFoldout = false;
private float doorHeight = 0f;
private float doorWidth = 0f;
private bool setDoorWidth = false;
private bool setDoorHeight = false;
private bool balconyFoldout = false;
private bool setBalconyWidth = false;
private float balconyWidth = 0f;
private bool setBalconyHeight = false;
private float balconyHeight = 0f;
// roof stuff
private enum myRType
{
noChoice,
Flat,
SinglePeak,
DoublePeak
}
private myRType rtype = myRType.noChoice;
private bool inputRoofDecor = false;
private Object roofDecorTexture;
private bool inputRoof = false;
private Object roofTexture;
private bool inputRoofBase = false;
private Object roofBaseTexture;
private static Building _building;
[MenuItem ("Window/Builder")]
static void Init ()
{
ColorManager.Instance.Init();
TextureManager.Instance.Init();
MaterialManager.Instance.Init();
_building = new Building();
EditorWindow.GetWindow(typeof(Builder), false, "Builder");
}
void OnGUI ()
{
GUILayout.Space(20);
EditorGUILayout.BeginHorizontal();
if (GUILayout.Button("Destroy"))
_building.Destroy();
if (GUILayout.Button("Create"))
{
_building.Destroy();
_building.Init();
_building.CreateBuilding();
_building.Draw();
}
EditorGUILayout.EndHorizontal();
GUILayout.Space(20);
BuildingDimensions();
GUILayout.Space(10);
ComponentParams();
GUILayout.Space(10);
RoofParams();
}
void OnDestroy ()
{
_building.Destroy();
ColorManager.Instance.Unload();
TextureManager.Instance.Unload();
MaterialManager.Instance.Unload();
}
private void BuildingDimensions ()
{
EditorGUILayout.LabelField("Dimensions", EditorStyles.boldLabel);
choice1 = (Area) EditorGUILayout.EnumPopup("Area", choice1);
switch (choice1)
{
case Area.dimensions:
_building.startingPoints = null;
_width = EditorGUILayout.FloatField("Width", _width);
_depth = EditorGUILayout.FloatField("Depth", _depth);
_building.width0 = _width;
_building.width1 = _depth;
break;
case Area.points:
_building.width0 = 0f;
_building.width1 = 0f;
_p1 = EditorGUILayout.Vector2Field("point 1", _p1);
_p2 = EditorGUILayout.Vector2Field("point 2", _p2);
_p3 = EditorGUILayout.Vector2Field("point 3", _p3);
_p4 = EditorGUILayout.Vector2Field("point 4", _p4);
if (_p1 != _p2 && _p1 != _p3 && _p1 != _p4 && _p2 != _p3 &&
_p2 != _p4 && _p3 != _p4)
{
_building.startingPoints = new Vector3[4];
_building.startingPoints[0] = new Vector3(_p1.x, 0f, _p1.y);
_building.startingPoints[1] = new Vector3(_p2.x, 0f, _p2.y);
_building.startingPoints[2] = new Vector3(_p3.x, 0f, _p3.y);
_building.startingPoints[3] = new Vector3(_p4.x, 0f, _p4.y);
}
break;
default:
_building.width0 = 0f;
_building.width1 = 0f;
_building.startingPoints = null;
break;
}
choice2 = (Heights) EditorGUILayout.EnumPopup("Height", choice2);
switch (choice2)
{
case Heights.floorCount:
_floors = EditorGUILayout.IntField("Floor Count", _floors);
_building.floorCount = _floors;
_building.floorHeight = 0f;
break;
case Heights.floorHeight:
_height = EditorGUILayout.FloatField("Floor Height", _height);
_building.floorHeight = _height;
_building.floorCount = 0;
break;
case Heights.floorCountAndHeight:
_floors = EditorGUILayout.IntField("Floor Count", _floors);
_height = EditorGUILayout.FloatField("Floor Height", _height);
_building.floorHeight = _height;
_building.floorCount = _floors;
break;
default:
_building.floorHeight = 0f;
_building.floorCount = 0;
break;
}
}
private void ComponentParams ()
{
EditorGUILayout.LabelField("Components", EditorStyles.boldLabel);
EditorGUILayout.BeginHorizontal();
EditorGUILayout.LabelField("Component distance");
inputCompCount = EditorGUILayout.Toggle(inputCompCount);
if (inputCompCount)
{
compDist = EditorGUILayout.FloatField(compDist, GUILayout.Width(30));
_building.componentDistance = compDist;
}
else
{
compDist = 0;
_building.componentDistance = 0;
}
EditorGUILayout.EndHorizontal();
//EditorGUILayout.BeginHorizontal();
//EditorGUILayout.LabelField("Component distance");
//inputCompDistance = EditorGUILayout.Toggle(inputCompDistance);
//if (inputCompDistance)
//{
// distance = EditorGUILayout.FloatField(distance, GUILayout.Width(25));
// _building.distance = distance;
//}
//else
//{
// distance = 0f;
// _building.distance = 0f;
//}
//EditorGUILayout.EndHorizontal();
// Window
windowFoldout = EditorGUILayout.Foldout(windowFoldout, "Window");
if (windowFoldout)
{
// width
EditorGUILayout.BeginHorizontal();
EditorGUILayout.LabelField("Width");
setWindowWidth = EditorGUILayout.Toggle(setWindowWidth);
if (setWindowWidth)
windowWidth = EditorGUILayout.FloatField(windowWidth, GUILayout.Width(30));
else
windowWidth = 0f;
EditorGUILayout.EndHorizontal();
_building.windowWidth = windowWidth;
// height
EditorGUILayout.BeginHorizontal();
EditorGUILayout.LabelField("Height");
setWindowHeight = EditorGUILayout.Toggle(setWindowHeight);
if (setWindowHeight)
windowHeight = EditorGUILayout.FloatField(windowHeight, GUILayout.Width(30));
else
windowHeight = 0f;
EditorGUILayout.EndHorizontal();
_building.windowHeight = windowHeight;
// material
//EditorGUILayout.BeginHorizontal();
//EditorGUILayout.LabelField("Texture");
//setWindowTexture = EditorGUILayout.Toggle(setWindowTexture);
//if (setWindowTexture)
// windowTexture = EditorGUILayout.ObjectField(windowTexture,
// typeof(Texture),
// false,
// GUILayout.Height(55));
//else
// windowTexture = null;
//EditorGUILayout.EndHorizontal();
// find material by windowtexture name
}
// Door
doorFoldout = EditorGUILayout.Foldout(doorFoldout, "Door");
if (doorFoldout)
{
// width
EditorGUILayout.BeginHorizontal();
EditorGUILayout.LabelField("Width");
setDoorWidth = EditorGUILayout.Toggle(setDoorWidth);
if (setDoorWidth)
doorWidth = EditorGUILayout.FloatField(doorWidth, GUILayout.Width(30));
else
doorWidth = 0f;
EditorGUILayout.EndHorizontal();
_building.doorWidth = doorWidth;
// height
EditorGUILayout.BeginHorizontal();
EditorGUILayout.LabelField("Height");
setDoorHeight = EditorGUILayout.Toggle(setDoorHeight);
if (setDoorHeight)
doorHeight = EditorGUILayout.FloatField(doorHeight, GUILayout.Width(30));
else
doorHeight = 0f;
EditorGUILayout.EndHorizontal();
_building.doorHeight = doorHeight;
// material
//EditorGUILayout.BeginHorizontal();
//EditorGUILayout.LabelField("Texture");
//setDoorTexture = EditorGUILayout.Toggle(setDoorTexture);
//if (setDoorTexture)
// doorTexture = EditorGUILayout.ObjectField(doorTexture,
// typeof(Texture),
// false,
// GUILayout.Height(55));
//else
// doorTexture = null;
//EditorGUILayout.EndHorizontal();
// find material by windowtexture name
}
// balcony
balconyFoldout = EditorGUILayout.Foldout(balconyFoldout, "Balcony");
if (balconyFoldout)
{
// width
EditorGUILayout.BeginHorizontal();
EditorGUILayout.LabelField("Width");
setBalconyWidth = EditorGUILayout.Toggle(setBalconyWidth);
if (setBalconyWidth)
balconyWidth = EditorGUILayout.FloatField(balconyWidth, GUILayout.Width(30));
else
balconyWidth = 0f;
EditorGUILayout.EndHorizontal();
_building.balconyWidth = balconyWidth;
// height
EditorGUILayout.BeginHorizontal();
EditorGUILayout.LabelField("Height");
setBalconyHeight = EditorGUILayout.Toggle(setBalconyHeight);
if (setBalconyHeight)
balconyHeight = EditorGUILayout.FloatField(balconyHeight, GUILayout.Width(30));
else
balconyHeight = 0f;
EditorGUILayout.EndHorizontal();
_building.balconyHeight = balconyHeight;
}
}
private void RoofParams ()
{
EditorGUILayout.LabelField("Roof", EditorStyles.boldLabel);
rtype = (myRType) EditorGUILayout.EnumPopup("Roof type", rtype);
switch (rtype)
{
case myRType.Flat:
_building.roofType = Type.GetType(GetFullType(myRType.Flat));
EditorGUILayout.BeginHorizontal();
EditorGUILayout.LabelField("Roof decor texture");
inputRoofDecor = EditorGUILayout.Toggle(inputRoofDecor);
if (inputRoofDecor)
{
roofDecorTexture = EditorGUILayout.ObjectField(roofDecorTexture,
typeof(Texture),
false,
GUILayout.Height(55));
if (roofDecorTexture != null)
_building.roofDecorMaterial = MaterialManager.Instance.
FindByTextureName(roofDecorTexture.name);
}
else
{
_building.roofDecorMaterial = null;
roofDecorTexture = null;
}
EditorGUILayout.EndHorizontal();
break;
case myRType.SinglePeak:
_building.roofType = Type.GetType(GetFullType(myRType.SinglePeak));
inputRoofDecor = false;
_building.roofDecorMaterial = null;
break;
case myRType.DoublePeak:
_building.roofType = Type.GetType(GetFullType(myRType.DoublePeak));
inputRoofDecor = false;
_building.roofDecorMaterial = null;
break;
default:
_building.roofType = null;
inputRoofDecor = false;
_building.roofDecorMaterial = null;
break;
}
// roof texture
EditorGUILayout.BeginHorizontal();
EditorGUILayout.LabelField("Roof texture");
inputRoof = EditorGUILayout.Toggle(inputRoof);
if (inputRoof)
{
roofTexture = EditorGUILayout.ObjectField(roofTexture,
typeof(Texture),
false,
GUILayout.Height(55));
if (roofTexture != null)
_building.roofMaterial = MaterialManager.Instance.
FindByTextureName(roofTexture.name);
}
else
{
_building.roofMaterial = null;
roofTexture = null;
}
EditorGUILayout.EndHorizontal();
// roof base texture
EditorGUILayout.BeginHorizontal();
EditorGUILayout.LabelField("Roof base texture");
inputRoofBase = EditorGUILayout.Toggle(inputRoofBase);
if (inputRoofBase)
{
roofBaseTexture = EditorGUILayout.ObjectField(roofBaseTexture,
typeof(Texture),
false,
GUILayout.Height(55));
if (roofBaseTexture != null)
_building.roofBaseMaterial = MaterialManager.Instance.
FindByTextureName(roofBaseTexture.name);
}
else
{
_building.roofBaseMaterial = null;
roofBaseTexture = null;
}
EditorGUILayout.EndHorizontal();
}
private string GetFullType (myRType t)
{
return "Thesis." + t.ToString() + "Roof,Assembly-CSharp-firstpass";
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace MerchantRPG.Simulation
{
public enum BuildPurpose
{
MinHpLoss,
MinTurns,
MaxDefense,
MaxEffectiveHp
}
}
|
namespace Senparc.Core.Models
{
/// <summary>
/// 软删除接口
/// </summary>
public interface ISoftDelete
{
/// <summary>
/// 是否删除
/// </summary>
bool Flag { get; set; }
}
}
|
using System;
using System.Net.Http;
using System.Net.Http.Headers;
namespace CPlanner.Client
{
public class BaseWebClient
{
public HttpClient Client = new HttpClient();
public BaseWebClient()
{
Client.BaseAddress = new Uri("https://plannersp.azurewebsites.net/api/");
Client.DefaultRequestHeaders.Clear();
Client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
Client.DefaultRequestHeaders.TryAddWithoutValidation("Content-Type", "application/json; charset=utf-8");
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using CommonFunctions;
namespace AggregatorAPI.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class AggregateController : ControllerBase
{
// PUT api/aggregate/5
[HttpPut("{count}")]
public void Put(int count)
{
DSOperations datastore = new DSOperations();
datastore.AddResponse(count);
}
[HttpGet]
public string Get()
{
return "Test Agregate";
}
}
}
|
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Text.RegularExpressions;
using Epic.Training.Project.Inventory;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace Epic.Training.Project.UnitTest
{
/// <summary>
/// Verifies Epic naming conventions
/// </summary>
[TestClass]
public class NameConventionTests
{
#region Helper and support members
/// <summary>
/// Used to verify camel case
/// </summary>
private static readonly Regex CamelCase = new Regex("^[a-z]+(?:[A-Z][a-z]+)*$");
/// <summary>
/// Used to verify pascal case
/// </summary>
private static readonly Regex PascalCase = new Regex("^[A-Z][a-z]+(?:[A-Z][a-z]+)*$");
/// <summary>
/// Method used to look up members of a type
/// </summary>
/// <typeparam name="TMemberInfo">The type of member to look up</typeparam>
/// <param name="flags">Flags used to indicate static vs. instance and public vs. non-public members</param>
/// <returns></returns>
private delegate TMemberInfo[] MemberLookup<TMemberInfo>(BindingFlags flags);
/// <summary>
/// Returns all members of every with every combination of Public/NonPublic and Instance/Static
/// </summary>
/// <typeparam name="TMemberInfo">The type of member to look up</typeparam>
/// <param name="lookupMethod">The method used to lookup the member information</param>
/// <returns>A list of all members of the given type</returns>
private static List<TMemberInfo> GetAllMembers<TMemberInfo>(MemberLookup<TMemberInfo> lookupMethod)
{
var allMembers = new List<TMemberInfo>();
allMembers.AddRange(lookupMethod(BindingFlags.Instance | BindingFlags.Public));
allMembers.AddRange(lookupMethod(BindingFlags.Instance | BindingFlags.NonPublic));
allMembers.AddRange(lookupMethod(BindingFlags.Static | BindingFlags.Public));
allMembers.AddRange(lookupMethod(BindingFlags.Static | BindingFlags.NonPublic));
return allMembers;
}
/// <summary>
/// Types that need to be examined
/// </summary>
private static List<Type> _typesInAssembly;
/// <summary>
/// Returns all relevent types, filtering out those that were auto-generated.
/// </summary>
/// <param name="context">From unit test framework</param>
[ClassInitialize]
public static void GetTypesInItemAssembly(TestContext context)
{
_typesInAssembly = new List<Type>();
Assembly assemblyInfo = Assembly.GetAssembly(typeof(Epic.Training.Project.Inventory.Item));
foreach (Type t in assemblyInfo.DefinedTypes)
{
// Skip the two classes already tested, along with auto-generated classes that come from IEnumerable results.
if (t.Name[0] == '<' || t.Name.Contains("GetEnumerator>"))
{
continue;
}
_typesInAssembly.Add(t);
}
}
#endregion
#region Tests
/// <summary>
/// Verifies that class and struct names are in Pascal case, and interfaces are in IPascalCase
/// </summary>
[TestMethod]
public void TestTypeNames()
{
foreach (Type t in _typesInAssembly)
{
// Skip the two classes already tested, along with auto-generated classes that come from IEnumerable results.
string name = t.Name;
if (t.IsGenericType)
{
name = name.Split('`')[0];
}
if (t.IsInterface)
{
Assert.IsFalse(name[0] != 'I' || !PascalCase.IsMatch(name.Substring(1)),
string.Format("Your interface \"{0}\" does not match the pattern IPascalCase", t.Name));
}
else
{
Assert.IsFalse(!PascalCase.IsMatch(name),
string.Format("Your class \"{0}\" is not in Pascal case", t.Name));
}
}
}
/// <summary>
/// Verifies that all methods are in pascal case
/// </summary>
[TestMethod]
public void TestMethodNames()
{
foreach (Type t in _typesInAssembly)
{
foreach (MethodInfo m in GetAllMembers<MethodInfo>(t.GetMethods))
{
string name = m.Name;
// Exclude property getter/setter, event adder/remover and overloaded operators
if (name.StartsWith("get_") || name.StartsWith("set_")) { continue; }
// Exclude event adder/remover
if (name.StartsWith("add_") || name.StartsWith("remove_")) { continue; }
// Exclude overloaded operators
if (name.StartsWith("op_")) { continue; }
// Exclude explicitly implemented interfaces
if (name.Contains(".")) { continue; }
// Look for Linq
Assert.IsFalse(name.Contains("AnonymousMethodDelegate") || name.Contains("<"),
string.Format("The class \"{0}\" contains a method named {1}. Are you using Linq? Linq hides the implementation details and is not recommended except when used very carefully. See: http://wiki.epic.com/main/Coding_Standards/.NET/3.0_Features#LINQ", t.Name, m.Name));
Assert.IsFalse(!PascalCase.IsMatch(m.Name),
string.Format("The method \"{0}\" of class \"{1}\" is not in Pascal case", m.Name, t.Name));
}
}
}
/// <summary>
/// Verifies that all properties are in Pascal case
/// </summary>
[TestMethod]
public void TestPropertyNames()
{
foreach (Type t in _typesInAssembly)
{
foreach (PropertyInfo p in GetAllMembers<PropertyInfo>(t.GetProperties))
{
// HResult is a property inherited from System.Exception. If they create a
// custom exception class, we may encounter it.
if (p.Name == "HResult") { continue; }
// Exclude explicitly implemented interfaces
if (p.Name.Contains(".")) { continue; }
Assert.IsFalse(!PascalCase.IsMatch(p.Name),
string.Format("The property \"{0}\" of class \"{1}\" is not in Pascal case", p.Name, t.Name));
}
}
}
/// <summary>
/// Verifies that events follow Epic name conventions
/// </summary>
[TestMethod]
public void TestEventNames()
{
foreach (Type t in _typesInAssembly)
{
foreach (EventInfo e in GetAllMembers<EventInfo>(t.GetEvents))
{
Assert.IsFalse(!PascalCase.IsMatch(e.Name),
string.Format("The event \"{0}\" of class \"{1}\" is not in Pascal case", e.Name, t.Name));
}
}
}
/// <summary>
/// Verifies that fields follow Epic name conventions
/// </summary>
[TestMethod]
public void TestFieldNames()
{
foreach (Type t in _typesInAssembly)
{
if (t.IsSubclassOf(typeof(Delegate)))
{
return;
}
var eventNames = new HashSet<string>();
foreach (EventInfo e in GetAllMembers<EventInfo>(t.GetEvents))
{
eventNames.Add(e.Name);
}
foreach (FieldInfo f in GetAllMembers<FieldInfo>(t.GetFields))
{
// Filter out backing field of enums
if (f.Name == "value__") { continue; }
// Filter out events
if (eventNames.Contains(f.Name)) { continue; }
// Filter out auto-implemented fields
if (f.Name.Contains("__BackingField")) { continue; }
// Filter out _HResult from Exception
if (f.Name == "_HResult") { continue; }
// Look for Linq
Assert.IsFalse(f.Name.Contains("AnonymousMethodDelegate") || f.Name.Contains("<"),
string.Format("The class \"{0}\" contains a field named {1}. Are you using Linq? Linq hides the implementation details and is not recommended except when used very carefully. See: http://wiki.epic.com/main/Coding_Standards/.NET/3.0_Features#LINQ", t.Name, f.Name));
if (f.IsLiteral || f.IsStatic && f.IsInitOnly)
{
if (t.IsEnum)
{
Assert.IsFalse(!PascalCase.IsMatch(f.Name),
string.Format("The member \"{0}\" of enum \"{1}\" is not in Pascal case", f.Name, t.Name));
}
else
{
Assert.IsFalse(!PascalCase.IsMatch(f.Name),
string.Format("The constant or static readonly field \"{0}\" of class \"{1}\" is not in Pascal case", f.Name, t.Name));
}
}
else
{
if (f.IsPublic || f.IsAssembly || f.IsFamilyOrAssembly) // public, internal, or protected internal
{
Assert.IsFalse(!PascalCase.IsMatch(f.Name),
string.Format("The field \"{0}\" of class \"{1}\" is public, internal or protected internal and is not in Pascal case", f.Name, t.Name));
}
else if (f.IsPrivate || f.IsFamily) // protected or private
{
if (f.IsStatic)
{
Assert.IsFalse(f.IsPrivate && !f.Name.StartsWith("s_") && !CamelCase.IsMatch(f.Name.Substring(2)),
string.Format("The static field \"{0}\" of class \"{1}\" is private or protected and doesn't match the pattern \"s_camelCase\"", f.Name, t.Name));
}
else
{
Assert.IsTrue(f.IsPrivate && !f.IsStatic && f.Name.StartsWith("_") && CamelCase.IsMatch(f.Name.Substring(1)),
string.Format("The field \"{0}\" of class \"{1}\" is private or protected and doesn't match the pattern \"_camelCase\"", f.Name, t.Name));
}
}
}
}
}
}
#endregion
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Bag : MonoBehaviour {
private List<Product> listItem;
private float total=0;
void Start () {
listItem = new List<Product>();
}
public void addProToBag(Product pro)
{
total += pro.Price;
listItem.Add(pro);
}
public int numberItem()
{
return listItem.Count;
}
public float totalMoney()
{
return total;
}
}
|
using BDTest.Test;
namespace BDTest.Interfaces.Internal;
internal interface IScenarioRetryManager
{
Task CheckIfAlreadyExecuted(Scenario scenario);
} |
using Lab2.Properties;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Lab2.Generating;
using Lab2.Services.Filter;
using Lab2.Services;
using Lab2.Areas;
using Lab2.Services.TurnAgent;
using Lab2.Services.Sensor;
using Lab2.Services.Statistic;
namespace Lab2.World
{
// дії, які агент може виконати
public enum AgentAction
{
Move,
Eat,
TurnRight,
TurnLeft
}
public class WorldSimulation : ISimulation
{
private const int reproductionLevel = 90;
private const double criticalRate = 0.1;
public int WorldSize;
public Generate generator;
public List<Agent> allAgents;
private Agent currentAgent;
// сервіси
private FilterService filterService;
private LocationServiceBuilder locationBuilder;
private TurnService turnService;
public SensorService sensorService;
private Random rand;
public StatisticService statistic;
public WorldSimulation()
{
WorldSize = Convert.ToInt32(Settings.Default.WorldSize);
generator = new Generate(WorldSize);
AddAllAgents(generator.GenerateAgents());
// ініціалізація сервісів
filterService = new FilterService();
locationBuilder = new LocationServiceBuilder();
turnService = new TurnService();
sensorService = new SensorService();
statistic = new StatisticService();
rand = new Random();
}
// додати всіх агентів
public void AddAllAgents(List<Agent> agents)
{
allAgents = agents;
}
// змінюємо координати агента якщо є вільні чарунки
private void MoveAgent()
{
var locationService = locationBuilder.getLocationService(currentAgent.AgentLocation, currentAgent.Direction);
// Якщо можливо переміститись у вільний чарунок, то переміщаємо агента
Point dest = locationService.getPositionToMove();
var agents = allAgents.Where(a => a.AgentLocation.X == dest.X && a.AgentLocation.Y == dest.Y);
if (agents.Count() >= 2)
{
TurnAgentLeft();
}
else if (agents.Where(a => a.AgentType == AgentTypes.Plant).Count() >= 1)
{
TurnAgentLeft();
}
else
{
currentAgent.MoveAgent(dest);
}
}
// повернути агента вліво
private void TurnAgentLeft()
{
currentAgent.Direction = turnService.getSightDirectionLeft(currentAgent.Direction);
}
// повернути агента вправо
private void TurnAgentRight()
{
currentAgent.Direction = turnService.getSightDirectionRight(currentAgent.Direction);
}
// з'їсти іншого агента відповідно до харчового ланцюгу
private void EatAgent()
{
var locationService = locationBuilder.getLocationService(currentAgent.AgentLocation, currentAgent.Direction);
var points = locationService.getProximityPoints().ToList();
var agentToEat = sensorService.getAgentToEat(allAgents, points, currentAgent);
if (agentToEat != null)
{
currentAgent.Eat();
allAgents.Remove(agentToEat);
// якщо з'їджений агент - це рослина, то генеруємо автоматично нову
if(agentToEat.AgentType == AgentTypes.Plant)
allAgents.Add(generator.GenerateNewPlant(allAgents));
}
else
{
TurnAgentLeft();
}
}
// функція відтворення
private void Reproduce()
{
currentAgent.Reproduction();
var newAMigratingAgent = generator.GenerateNewMigratingAgent(allAgents, currentAgent);
newAMigratingAgent.GetNetwork().Mutation();
allAgents.Add(newAMigratingAgent);
}
// агент вибирає, яку дію виконати
private void TakeAgentAction()
{
var locationService = locationBuilder.getLocationService(currentAgent.AgentLocation, currentAgent.Direction);
var inputs = sensorService.GetInputsForNetwork(allAgents, currentAgent, locationService);
AgentAction action = currentAgent.GetNetwork().ChooseAction(inputs);
switch (action)
{
case AgentAction.Move:
{
MoveAgent();
break;
}
case AgentAction.Eat:
{
EatAgent();
break;
}
case AgentAction.TurnRight:
{
TurnAgentRight();
break;
}
case AgentAction.TurnLeft:
{
TurnAgentLeft();
break;
}
default:
break;
}
}
// метаболізм
private void Metabolism()
{
currentAgent.ReduceEnergy();
}
// змінюємо поточного агента
private void setCurrentAgent()
{
var migratingAll = filterService.getMigratingAgents(allAgents);
int index = rand.Next(0, migratingAll.Count);
currentAgent = migratingAll.ElementAt(index);
}
// збільшуємо вік мігруючих агентів, які прожили поточну ітерацію і вижили
private void IncreaseAge()
{
var migratingAll = filterService.getMigratingAgents(allAgents);
for(int i = 0; i < migratingAll.Count; i++)
migratingAll[i].IncreseAge();
}
// перевірка, чи відсоток популяції одного з типів мігруючих агентів менше 10 %
private bool ContinueAlgorithm()
{
var allHerbivirous = allAgents.Where(a => a.AgentType == AgentTypes.Herbivorous);
var allPredators = allAgents.Where(a => a.AgentType == AgentTypes.Predator);
double herbivirousRate = (double)allHerbivirous.Count() / (double)allAgents.Count();
double predatorsRate = (double)allPredators.Count() / (double)allAgents.Count();
if (herbivirousRate < criticalRate || predatorsRate < criticalRate)
return false;
return true;
}
// запуск симуляції
public void RunSimulation()
{
while (ContinueAlgorithm())
{
setCurrentAgent();
RunIteration();
statistic.IncreaseIterations();
if (statistic.Iterations % 100 == 0)
{
statistic.AddAgentsCount(allAgents, statistic.Iterations);
statistic.AddAgentsRate(allAgents, statistic.Iterations);
}
}
}
// запуск ітерації для поточного мігруючого агента
public void RunIteration()
{
TakeAgentAction();
if (currentAgent.GetEnergyLevel() >= reproductionLevel)
{
Reproduce();
statistic.IncreaseReproduction(currentAgent);
}
else
Metabolism();
if (currentAgent.IsAlive() == false)
allAgents.Remove(currentAgent);
IncreaseAge();
statistic.SetMaxAge(allAgents);
}
}
}
|
using System;
namespace FeriaVirtual.Application.Services.Users.Commands.Update
{
public class UpdateUserCommandBuilder
{
private readonly UpdateUserCommand _command;
private UpdateUserCommandBuilder() =>
_command = new UpdateUserCommand();
public static UpdateUserCommandBuilder GetInstance() =>
new();
public UpdateUserCommandBuilder UserId(string userid)
{
_command.UserId = new Guid(userid);
return this;
}
public UpdateUserCommandBuilder Firstname(string firstname)
{
_command.Firstname = firstname;
return this;
}
public UpdateUserCommandBuilder Lastname(string lastname)
{
_command.Lastname = lastname;
return this;
}
public UpdateUserCommandBuilder Dni(string dni)
{
_command.Dni = dni;
return this;
}
public UpdateUserCommandBuilder ProfileId(int profileid)
{
_command.ProfileId = profileid;
return this;
}
public UpdateUserCommandBuilder CredentialId(string credentialid)
{
_command.CredentialId = new Guid(credentialid);
return this;
}
public UpdateUserCommandBuilder Username(string username)
{
_command.Username = username;
return this;
}
public UpdateUserCommandBuilder Password(string password)
{
_command.Password = password;
return this;
}
public UpdateUserCommandBuilder Email(string email)
{
_command.Email = email;
return this;
}
public UpdateUserCommandBuilder IsActive(int isactive)
{
_command.IsActive = isactive;
return this;
}
public UpdateUserCommand Build() =>
_command;
}
}
|
using AutoMapper;
using DAL.Context;
using Models;
using ServiceLayer.Contracts;
using ServiceLayer.Translations;
using System;
using System.Collections.Generic;
using System.Linq;
namespace ServiceLayer.DB
{
public class DbCatalogService : ICatalogService, IDisposable
{
private readonly IDalUnitOfWork _dalUnitOfWork;
private IMapper _mapper;
public DbCatalogService(IDalUnitOfWork dalUnitOfWork)
{
_dalUnitOfWork = dalUnitOfWork;
LoadMapper();
}
void LoadMapper()
{
var config = new MapperConfiguration(cfg => cfg.AddProfile(new MappingProfile()));
_mapper = config.CreateMapper();
}
public IEnumerable<Movie> GetMovies()
{
return _dalUnitOfWork.MoviesRepo.All().Select(m => m.ToModel(_mapper));
}
public Movie GetMovie(int id)
{
return _dalUnitOfWork.MoviesRepo.Find(m => m.Id == id).ToModel(_mapper);
}
public Movie InsertMovie(Movie movie)
{
var movy = _dalUnitOfWork.MoviesRepo.Create(movie.ToEntity(_mapper));
_dalUnitOfWork.SaveChanges();
return movy.ToModel(_mapper);
}
public Movie UpdateMovie(Movie movie)
{
var movy = _dalUnitOfWork.MoviesRepo.Find(m => m.Id == movie.Id);
return movie.MapTo(movy, _mapper).ToModel(_mapper);
}
public int DeleteMovie(int id)
{
var delCount = _dalUnitOfWork.MoviesRepo.Delete(m => m.Id == id);
_dalUnitOfWork.SaveChanges();
return delCount;
}
public void Dispose()
{
_dalUnitOfWork?.Dispose();
}
public IEnumerable<Customer> GetCustomers()
{
return _dalUnitOfWork.CustomersRepo.All().Select(c => c.ToModel(_mapper));
}
public IEnumerable<Genre> GetGenres()
{
return _dalUnitOfWork.GenreRepository.All().Select(g => g.ToModel(_mapper));
}
}
}
|
namespace Blackjack21.Game.Model
{
/// <summary>
/// Card Symbol Enumerate
/// </summary>
public enum CardSymbol : int
{
CLUBS = 1,
SPADES = 2,
HEARTS = 3,
DIAMONDS = 4
}
}
|
using UnityEngine;
#if UNITY_EDITOR
using UnityEditor;
#endif
using System.Collections;
namespace AlmenaraGames
{
public class MLPASAboutWindow : EditorWindow
{
private Texture logoTex;
#if UNITY_EDITOR
[MenuItem("Almenara Games/MLPAS/About", false, +4)]
public static void ShowWindow()
{
GetWindow<MLPASAboutWindow>(false, "MLPAS About", true);
}
void OnEnable()
{
logoTex = Resources.Load("MLPASImages/logoSmall") as Texture;
}
void OnGUI()
{
maxSize = new Vector2(390f, 200f);
minSize = new Vector2(390f, 200f);
GUILayout.Space(15f);
var centeredStyle = new GUIStyle(GUI.skin.GetStyle("Label"));
centeredStyle.alignment = TextAnchor.UpperCenter;
GUILayout.Label(logoTex, centeredStyle);
GUILayout.Space(5f);
GUIStyle versionStyle = new GUIStyle(EditorStyles.miniLabel);
versionStyle.alignment = TextAnchor.MiddleCenter;
EditorGUILayout.LabelField("Version: " + AlmenaraGames.MultiAudioManager.Version, versionStyle);
GUIStyle webPageStyle = new GUIStyle(EditorStyles.label);
webPageStyle.alignment = TextAnchor.MiddleCenter;
webPageStyle.fontStyle = FontStyle.Bold;
GUIStyle aboutStyle = new GUIStyle(EditorStyles.label);
aboutStyle.alignment = TextAnchor.MiddleCenter;
GUILayout.Space(10f);
EditorGUILayout.LabelField("An asset created by: ALMENARA GAMES", aboutStyle);
GUILayout.Space(10f);
Color restoreColor = GUI.contentColor;
GUI.color = EditorGUIUtility.isProSkin? Color.cyan : Color.blue;
if (GUILayout.Button("Documentation", webPageStyle))
{
Application.OpenURL("https://almenaragames.github.io");
}
if (GUILayout.Button("Author Webpage", webPageStyle))
{
Application.OpenURL("https://almenara-games.itch.io/");
}
GUI.contentColor = restoreColor;
}
#endif
}
} |
using NUnit.Framework;
using BugunNeYesem.Logic;
namespace BugunNeYesem.Test
{
[TestFixture]
public class LocationServiceTests
{
[Test]
public void LocationService_GetLocation_ReturnsLocationResponse()
{
//arrange
const string argesetLatitude = "41.010305";
const string argesetLongitude = "29.074330";
var locationService = new LocationService();
//act
var result = locationService.GetLocation();
//assert
Assert.AreEqual(result.Latitude, argesetLatitude);
Assert.AreEqual(result.Longitude, argesetLongitude);
}
}
} |
using System;
using System.Collections.Generic;
using System.Text;
namespace Bolletta
{
public class Bolletta
{
public double Kwh { get; set; }
public Utente Utente { get; set; }
public decimal Conto { get; set; }
const decimal quotaFissa= 40;
public Bolletta()
{
Utente = new Utente();
}
public Bolletta(double kwh)
{
Kwh = kwh;
}
public string StampaDati()
{
return $"Nome: {Utente.Nome} \nCognome: {Utente.Cognome} \nkwh consumate:{Kwh}, \nTotale da pagare: {Conto} euro";
}
public decimal CalcoloBolletta()
{
Conto= quotaFissa + (decimal)(Kwh * 10);
return Conto;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Otiport.API.Contract.Models;
using Otiport.API.Contract.Response.Medicines;
using Otiport.API.Data.Entities.Medicine;
namespace Otiport.API.Repositories
{
public interface IMedicineRepository
{
Task<IEnumerable<MedicineEntity>> GetMedicinesAsync();
Task<bool> AddMedicineAsync(MedicineEntity entity);
Task<bool> DeleteMedicineAsync(MedicineEntity entity);
Task<MedicineEntity> GetMedicineById(int id);
Task<bool> UpdateMedicinesAsync(MedicineEntity entity);
}
}
|
using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
namespace DBDiff.Schema.Sybase.Model
{
public class Tables:List<Table>
{
private Hashtable hash = new Hashtable();
private Database parent;
private string sqlScript;
public Tables(Database parent)
{
this.parent = parent;
}
/// <summary>
/// Devuelve la base perteneciente a la coleccion de tablas.
/// </summary>
public Database Parent
{
get { return parent; }
}
/// <summary>
/// Indica si el nombre de la tabla existe en la coleccion de tablas del objeto.
/// </summary>
/// <param name="table">
/// Nombre de la tabla a buscar.
/// </param>
/// <returns></returns>
public Boolean Find(string table)
{
return hash.ContainsKey(table);
}
public Table this[string name]
{
get { return (Table)hash[name]; }
}
public new void Add(Table table)
{
if (table != null)
{
hash.Add(table.FullName, table);
base.Add(table);
}
else
throw new ArgumentNullException("table");
}
public string ToSQL()
{
if (sqlScript == null)
{
StringBuilder sql = new StringBuilder();
for (int index = 0; index < this.Count; index++)
{
sql.Append(this[index].ToSQL());
}
sqlScript = sql.ToString();
}
return sqlScript;
}
public SQLScriptList ToSQLDiff()
{
SQLScriptList listDiff = new SQLScriptList();
int index;
for (index = 0; index < this.Count; index++)
{
listDiff.Add(this[index].ToSQLDiff());
}
return listDiff;
}
public new void Sort()
{
BuildDependenciesTree();
base.Sort(); //Ordena las tablas en funcion de su dependencias
}
/// <summary>
/// Reordena la tabla en funcion de sus dependencias.
/// </summary>
private void BuildDependenciesTree()
{
int index;
for (index = 0; index < this.Count; index++)
{
this[index].DependenciesCount += FindDependenciesCount(this[index].Id);
}
}
private int FindDependenciesCount(int tableId)
{
int count = 0;
int relationalTableId;
/*Constraints constraints = ((Database)Parent).ConstraintDependencies.FindNotOwner(tableId);
for (int index = 0; index < constraints.Count; index++)
{
Constraint cons = constraints[index];
relationalTableId = constraints[index].RelationalTableId; //((Table)constraints[index].Parent).Id;
if ((cons.Type == Constraint.ConstraintType.ForeignKey) && (relationalTableId == tableId))
count += 1+FindDependenciesCount(((Table)cons.Parent).Id);
}*/
return count;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Unidade8.ExercicioSlides
{
class _3forWhile
{
static void Main111(string[] args)
{
int x = 1;
do
{
if (x % 3 != 0)
{
Console.WriteLine(x);
}
x++;
} while (x <= 100);
}
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.