text stringlengths 13 6.01M |
|---|
using mec.Model.Apps;
using mec.Model.Entities;
using mec.Model.Packs;
using mec.Model.Plans;
using mec.Model.Processes;
using mec.Model.Systems;
using mec.Model.WareHouse;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace mec.Database
{
public class OracleDbContext : DbContext
{
public OracleDbContext(string connectName)
: base(connectName)
{
}
public DbSet<User> Users { get; set; }
public DbSet<Bin> Bins { get; set; }
public DbSet<BinDetail> BinDetails { get; set; }
public DbSet<PlanPackDelivery> PlanPackDeliveries { get; set; }
public DbSet<Material> Materials { get; set; }
public DbSet<FlowCard> FlowCards { get; set; }
public DbSet<FlowCardDetail> FlowCardDetails { get; set; }
/// <summary>
/// MES.ERP_PACKING_NOTICE
/// </summary>
public DbSet<PackingNotice> PackingNoticies { get; set; }
/// <summary>
/// A_BARCODE
/// </summary>
public DbSet<Barcode> Barcodes { get; set; }
public DbSet<BarcodeDetail> BarcodeDetails { get; set; }
public DbSet<ProductInstore> ProductInstores { get; set; }
public DbSet<SubComponent> SubComponents { get; set; }
public DbSet<RouteMain> RouteMains { get; set; }
public DbSet<RouteDetail> RouteDetails { get; set; }
public DbSet<NoticeRecord> NoticeRecords { get; set; }
public DbSet<NoticeOption> NoticeOptions { get; set; }
public DbSet<NoticeRule> NoticeRules { get; set; }
public DbSet<ProcessStockMain> ProcessStockMains { get; set; }
public DbSet<ProcessStockDetail> ProcessStockDetails { get; set; }
public DbSet<Misc> Miscs { get; set; }
public DbSet<MiscDetail> MiscDetails { get; set; }
public DbSet<MiscRecord> MiscRecords { get; set; }
public DbSet<Serial> Serials { get; set; }
#region WareHouse
public DbSet<Stock> Stocks { get; set; }
#endregion
#region System
public DbSet<Menu> Menus { get; set; }
#endregion
}
}
|
using Aranda.Users.BackEnd.Repositories.Definition;
using Aranda.Users.BackEnd.Repositories.Implementation;
using Aranda.Users.BackEnd.Services.Definition;
using Aranda.Users.BackEnd.Services.Implementation;
using Microsoft.Extensions.DependencyInjection;
namespace Aranda.Users.BackEnd
{
public static class ServiceCollectionExtension
{
public static void DependencyInjectionRepositories(this IServiceCollection service)
{
service.AddScoped<IUserRepository, UserRepository>();
service.AddScoped<IRoleRepository, RoleRepository>();
}
public static void DependencyInjectionServices(this IServiceCollection service)
{
service.AddScoped<IAuthService, AuthService>();
service.AddScoped<IUserService, UserService>();
service.AddScoped<IRoleService, RoleService>();
}
}
}
|
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Xml;
using System.Xml.Linq;
// ReSharper disable once CheckNamespace
namespace Aquarium.Util.Extension.StringExtension
{
public static class StringExtension
{
#region 格式化
/// <summary>
/// 用指定对象的字符串表示形式替换指定字符串中的一个或多个格式项
/// </summary>
/// <param name="format">A composite format string.</param>
/// <param name="arg0">The object to format.</param>
/// <returns>A copy of in which any format items are replaced by the string representation of .</returns>
public static string Format(this string format, object arg0)
{
return string.Format(format, arg0);
}
/// <summary>
/// 去除首尾空格,如果字符为Null则返回空字符
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
public static string TrimSafe(this string str)
{
var result = string.IsNullOrWhiteSpace(str) ? string.Empty : str.Trim();
return result;
}
#endregion 格式化
#region 计算
/// <summary>
/// 指定超长字符使用指定字符代替
/// </summary>
/// <param name="this">The @this to act on.</param>
/// <param name="maxLength">The maximum length.</param>
/// <param name="suffix">The suffix.</param>
/// <returns>A string.</returns>
public static string Truncate(this string @this, int maxLength, string suffix = "...")
{
if (@this == null || @this.Length <= maxLength) return @this;
var strLength = maxLength - suffix.Length;
return @this.Substring(0, strLength) + suffix;
}
/// <summary>
/// 得到字符串长度,一个汉字长度为2
/// </summary>
/// <param name="inputString">参数字符串</param>
/// <returns></returns>
public static int GetLength(string inputString)
{
var ascii = new ASCIIEncoding();
var tempLen = 0;
var s = ascii.GetBytes(inputString);
foreach (var t in s)
if (t == 63)
tempLen += 2;
else
tempLen += 1;
return tempLen;
}
/// <summary>
/// 获取指定字符之后的所有字符
/// </summary>
/// <param name="this">The @this to act on.</param>
/// <param name="value">The value to search.</param>
/// <returns>The string after the specified value.</returns>
public static string GetAfter(this string @this, string value)
{
return @this.IndexOf(value, StringComparison.Ordinal) == -1
? ""
: @this.Substring(@this.IndexOf(value, StringComparison.Ordinal) + value.Length);
}
/// <summary>
/// 获取指定字符之前的所有字符
/// </summary>
/// <param name="this">The @this to act on.</param>
/// <param name="value">The value to search.</param>
/// <returns>The string before the specified value.</returns>
public static string GetBefore(this string @this, string value)
{
return @this.IndexOf(value, StringComparison.Ordinal) == -1
? ""
: @this.Substring(0, @this.IndexOf(value, StringComparison.Ordinal));
}
/// <summary>
/// 获取指定字符之间的字符
/// </summary>
/// <param name="this">The @this to act on.</param>
/// <param name="before">The string before to search.</param>
/// <param name="after">The string after to search.</param>
/// <returns>The string between the two specified string.</returns>
public static string GetBetween(this string @this, string before, string after)
{
var beforeStartIndex = @this.IndexOf(before, StringComparison.Ordinal);
var startIndex = beforeStartIndex + before.Length;
var afterStartIndex = @this.IndexOf(after, startIndex, StringComparison.Ordinal);
if (beforeStartIndex == -1 || afterStartIndex == -1) return "";
return @this.Substring(startIndex, afterStartIndex - startIndex);
}
#endregion 计算
#region 判断
/// <summary>
/// 判断字符串是否空字符串
/// </summary>
/// <param name="this">The @this to act on.</param>
/// <returns>true if a not is empty, false if not.</returns>
public static bool IsNotEmpty(this string @this)
{
return @this != string.Empty;
}
/// <summary>
/// 判断字符串是否不是NULL或者空字符串
/// </summary>
/// <param name="this">The @this to act on.</param>
/// <returns>true if '@this' is not (null or empty), false if not.</returns>
public static bool IsNotNullOrEmpty(this string @this)
{
return !string.IsNullOrEmpty(@this);
}
/// <summary>
/// 判断字符串是否是NULL或者空字符串
/// </summary>
/// <param name="this">The @this to act on.</param>
/// <returns>true if '@this' is null or is empty, false if not.</returns>
public static bool IsNullOrEmpty(this string @this)
{
return string.IsNullOrEmpty(@this);
}
/// <summary>
/// 判断指定字符是否是空格
/// </summary>
/// <param name="s">A string.</param>
/// <param name="index">The position of the character to evaluate in .</param>
/// <returns>true if the character at position in is white space; otherwise, false.</returns>
public static bool IsWhiteSpace(this string s, int index)
{
return char.IsWhiteSpace(s, index);
}
/// <summary>
/// 判断字符串是否Like目标字符串
/// </summary>
/// <param name="this">The @this to act on.</param>
/// <param name="pattern">The pattern to use. Use '*' as wildcard string.</param>
/// <returns>true if '@this' satisfy the specified pattern, false if not.</returns>
public static bool IsLike(this string @this, string pattern)
{
// Turn the pattern into regex pattern, and match the whole string with ^$
var regexPattern = "^" + Regex.Escape(pattern) + "$";
// Escape special character ?, #, *, [], and [!]
regexPattern = regexPattern.Replace(@"\[!", "[^")
.Replace(@"\[", "[")
.Replace(@"\]", "]")
.Replace(@"\?", ".")
.Replace(@"\*", ".*")
.Replace(@"\#", @"\d");
return Regex.IsMatch(@this, regexPattern);
}
/// <summary>
/// 判断字符串是否在目标字符串类包含
/// </summary>
/// <param name="this">The object to be compared.</param>
/// <param name="values">The value list to compare with the object.</param>
/// <returns>true if the values list contains the object, else false.</returns>
public static bool IsIn(this string @this, params string[] values)
{
return Array.IndexOf(values, @this) != -1;
}
/// <summary>
/// 判断指定字符串是否不为Null
/// </summary>
/// <param name="this">The @this to act on.</param>
/// <returns>true if not null, false if not.</returns>
public static bool IsNotNull(this string @this)
{
return @this != null;
}
/// <summary>
/// 判断指定字符串是否为Null
/// </summary>
/// <param name="this">The @this to act on.</param>
/// <returns>true if null, false if not.</returns>
public static bool IsNull(this string @this)
{
return @this == null;
}
/// <summary>
/// 判断指定字符是否在字符串内
/// </summary>
/// <param name="this">The object to be compared.</param>
/// <param name="values">The value list to compare with the object.</param>
/// <returns>true if the values list doesn't contains the object, else false.</returns>
public static bool IsNotIn(this string @this, params string[] values)
{
return Array.IndexOf(values, @this) == -1;
}
/// <summary>
/// 判断除去空格字符串是否为Null或者空
/// </summary>
/// <param name="value">The string to test.</param>
/// <returns>true if the parameter is null or , or if consists exclusively of white-space characters.</returns>
public static bool IsNullOrWhiteSpace(this string value)
{
return string.IsNullOrWhiteSpace(value);
}
/// <summary>
/// 判断除去空格字符串是否不为Null或者空
/// </summary>
/// <param name="value">The string to test.</param>
/// <returns>true if the parameter is null or , or if consists exclusively of white-space characters.</returns>
public static bool IsNotNullOrWhiteSpace(this string value)
{
return !string.IsNullOrWhiteSpace(value);
}
/// <summary>
/// 判断字符串是否满足正则表达式
/// </summary>
/// <param name="input">The string to search for a match.</param>
/// <param name="pattern">The regular expression pattern to match.</param>
/// <returns>true if the regular expression finds a match; otherwise, false.</returns>
public static bool IsMatch(this string input, string pattern)
{
return Regex.IsMatch(input, pattern);
}
/// <summary>
/// 判断字符串是否满足正则表达式
/// </summary>
/// <param name="input">The string to search for a match.</param>
/// <param name="pattern">The regular expression pattern to match.</param>
/// <param name="options">A bitwise combination of the enumeration values that provide options for matching.</param>
/// <returns>true if the regular expression finds a match; otherwise, false.</returns>
public static bool IsMatch(this string input, string pattern, RegexOptions options)
{
return Regex.IsMatch(input, pattern, options);
}
#endregion 判断
#region 字符串操作
/// <summary>
/// 按照指定分割符生成字符串数组
/// </summary>
/// <param name="this">The @this to act on.</param>
/// <param name="separator">A string that delimit the substrings in this string.</param>
/// <param name="option">
/// (Optional) Specify RemoveEmptyEntries to omit empty array elements from the array returned,
/// or None to include empty array elements in the array returned.
/// </param>
/// <returns>
/// An array whose elements contain the substrings in this string that are delimited by the separator.
/// </returns>
public static string[] Split(this string @this, string separator,
StringSplitOptions option = StringSplitOptions.None)
{
return @this.Split(new[] { separator }, option);
}
/// <summary>
/// 获取右边指定长度所有字符(最大值为字符串长度)
/// </summary>
/// <param name="this">The @this to act on.</param>
/// <param name="length">The length.</param>
/// <returns>A string.</returns>
public static string RightSafe(this string @this, int length)
{
return @this.Substring(Math.Max(0, @this.Length - length));
}
/// <summary>
/// 获取右边指定长度所有字符
/// </summary>
/// <param name="this">The @this to act on.</param>
/// <param name="length">The length.</param>
/// <returns>The right part.</returns>
public static string Right(this string @this, int length)
{
return @this.Substring(@this.Length - length);
}
/// <summary>
/// 字符串反排序
/// </summary>
/// <param name="this">The @this to act on.</param>
/// <returns>The string reversed.</returns>
public static string Reverse(this string @this)
{
if (@this.Length <= 1) return @this;
var chars = @this.ToCharArray();
Array.Reverse(chars);
return new string(chars);
}
/// <summary>
/// 替换最后一个指定字符
/// </summary>
/// <param name="this">The @this to act on.</param>
/// <param name="oldValue">The old value.</param>
/// <param name="newValue">The new value.</param>
/// <returns>The string with the last occurence of old value replace by new value.</returns>
public static string ReplaceLast(this string @this, string oldValue, string newValue)
{
var startindex = @this.LastIndexOf(oldValue, StringComparison.Ordinal);
if (startindex == -1) return @this;
return @this.Remove(startindex, oldValue.Length).Insert(startindex, newValue);
}
/// <summary>
/// 替换最后若干个指定字符
/// </summary>
/// <param name="this">The @this to act on.</param>
/// <param name="number">Number of.</param>
/// <param name="oldValue">The old value.</param>
/// <param name="newValue">The new value.</param>
/// <returns>The string with the last numbers occurences of old value replace by new value.</returns>
public static string ReplaceLast(this string @this, int number, string oldValue, string newValue)
{
var list = @this.Split(oldValue).ToList();
var old = Math.Max(0, list.Count - number - 1);
var listStart = list.Take(old);
var listEnd = list.Skip(old);
return string.Join(oldValue, listStart) +
(old > 0 ? oldValue : "") +
string.Join(newValue, listEnd);
}
/// <summary>
/// 替换首个字符
/// </summary>
/// <param name="this">The @this to act on.</param>
/// <param name="oldValue">The old value.</param>
/// <param name="newValue">The new value.</param>
/// <returns>The string with the first occurence of old value replace by new value.</returns>
public static string ReplaceFirst(this string @this, string oldValue, string newValue)
{
var startindex = @this.IndexOf(oldValue, StringComparison.Ordinal);
if (startindex == -1) return @this;
return @this.Remove(startindex, oldValue.Length).Insert(startindex, newValue);
}
/// <summary>
/// 替换开始若干个字符
/// </summary>
/// <param name="this">The @this to act on.</param>
/// <param name="number">Number of.</param>
/// <param name="oldValue">The old value.</param>
/// <param name="newValue">The new value.</param>
/// <returns>The string with the numbers of occurences of old value replace by new value.</returns>
public static string ReplaceFirst(this string @this, int number, string oldValue, string newValue)
{
var list = @this.Split(oldValue).ToList();
var old = number + 1;
var listStart = list.Take(old);
var listEnd = list.Skip(old);
var enumerable = listEnd.ToList();
return string.Join(newValue, listStart) +
(enumerable.Any() ? oldValue : string.Empty) +
string.Join(oldValue, enumerable);
}
/// <summary>
/// 替换指定字符为空字符
/// </summary>
/// <param name="this">The @this to act on.</param>
/// <param name="values">A variable-length parameters list containing values.</param>
/// <returns>A string with all specified values replaced by an empty string.</returns>
public static string ReplaceByEmpty(this string @this, params string[] values)
{
return values.Aggregate(@this, (current, value) => current.Replace(value, string.Empty));
}
/// <summary>
/// 移除首个空格
/// </summary>
/// <param name="this">The @this to act on.</param>
/// <returns>A string with all specified values replaced by an empty string.</returns>
public static string RemoveFirstWhiteSpace(this string @this)
{
if (!@this.IsNotNullOrEmpty()) return @this;
return char.IsWhiteSpace(@this[0]) ? @this.Right(@this.Length - 1) : @this;
}
/// <summary>替换指定位置指定长度的字符为目标字符</summary>
/// <param name="this">The @this to act on.</param>
/// <param name="startIndex">The start index.</param>
/// <param name="length">The length.</param>
/// <param name="value">The value.</param>
/// <returns>A string.</returns>
public static string Replace(this string @this, int startIndex, int length, string value)
{
@this = @this.Remove(startIndex, length).Insert(startIndex, value);
return @this;
}
/// <summary>
/// 重复生成字符
/// </summary>
/// <param name="this">The @this to act on.</param>
/// <param name="repeatCount">Number of repeats.</param>
/// <returns>The repeated string.</returns>
public static string Repeat(this string @this, int repeatCount)
{
if (@this.Length == 1) return new string(@this[0], repeatCount);
var sb = new StringBuilder(repeatCount * @this.Length);
while (repeatCount-- > 0) sb.Append(@this);
return sb.ToString();
}
/// <summary>
/// 按输入条件移除字符串中的字符
/// </summary>
/// <param name="this">The @this to act on.</param>
/// <param name="predicate">The predicate.</param>
/// <returns>A string.</returns>
public static string RemoveWhere(this string @this, Func<char, bool> predicate)
{
return new string(@this.ToCharArray().Where(x => !predicate(x)).ToArray());
}
/// <summary>
/// 移除小写字符
/// </summary>
/// <param name="this">The @this to act on.</param>
/// <returns>A string.</returns>
public static string RemoveLetter(this string @this)
{
return new string(@this.ToCharArray().Where(x => !char.IsLetter(x)).ToArray());
}
/// <summary>
/// A string extension method that return the left part of the string.
/// </summary>
/// <param name="this">The @this to act on.</param>
/// <param name="length">The length.</param>
/// <returns>The left part.</returns>
public static string Left(this string @this, int length)
{
return @this.Substring(0, length);
}
/// <summary>
/// 从左边获取指定长度的字符串
/// </summary>
/// <param name="this">The @this to act on.</param>
/// <param name="length">The length.</param>
/// <returns>A string.</returns>
public static string LeftSafe(this string @this, int length)
{
return @this.Substring(0, Math.Min(length, @this.Length));
}
/// <summary>
/// 提取指定字符
/// </summary>
/// <param name="this">The @this to act on.</param>
/// <param name="predicate">The predicate.</param>
/// <returns>A string.</returns>
public static string Extract(this string @this, Func<char, bool> predicate)
{
return new string(@this.ToCharArray().Where(predicate).ToArray());
}
/// <summary>
/// 提取小写字符
/// </summary>
/// <param name="this">The @this to act on.</param>
/// <returns>The extracted letter.</returns>
public static string ExtractLetter(this string @this)
{
return new string(@this.ToCharArray().Where(char.IsLetter).ToArray());
}
/// <summary>
/// 提取数字
/// </summary>
/// <param name="this">The @this to act on.</param>
/// <returns>The extracted number.</returns>
public static string ExtractNumber(this string @this)
{
return new string(@this.ToCharArray().Where(char.IsNumber).ToArray());
}
/// <summary>
/// 串联两个字符串
/// </summary>
/// <param name="str0">The first string to concatenate.</param>
/// <param name="str1">The second string to concatenate.</param>
/// <returns>The concatenation of and .</returns>
public static string ConcatTo(this string str0, string str1)
{
return string.Concat(str0, str1);
}
/// <summary>
/// 串联字符串数组
/// </summary>
/// <param name="str0">The first string to concatenate.</param>
/// <param name="strings"></param>
/// <returns>The concatenation of , , and .</returns>
public static string ConcatWith(this string str0, string[] strings)
{
var result = str0;
foreach (var concatString in strings) result.ConcatTo(concatString);
return result;
}
/// <summary>
/// 拷贝字符串
/// </summary>
/// <param name="str">The string to copy.</param>
/// <returns>A new string with the same value as .</returns>
public static string Copy(this string str)
{
return string.Copy(str);
}
/// <summary>
/// 用指定分割付连接若干字符串
/// </summary>
/// <param name="separator">
/// The string to use as a separator. is included in the returned string only if has more
/// than one element.
/// </param>
/// <param name="value">An array that contains the elements to concatenate.</param>
/// <returns>
/// A string that consists of the elements in delimited by the string. If is an empty array, the method
/// returns .
/// </returns>
public static string Join(this string separator, string[] value)
{
return string.Join(separator, value);
}
/// <summary>
/// 用指定分割付连接若干字符串
/// </summary>
/// <typeparam name="T">Generic type parameter.</typeparam>
/// <param name="separator">
/// The string to use as a separator. is included in the returned string only if has more
/// than one element.
/// </param>
/// <param name="values">An array that contains the elements to concatenate.</param>
/// <returns>A String.</returns>
public static string Join<T>(this string separator, IEnumerable<T> values)
{
return string.Join(separator, values);
}
/// <summary>
/// 用指定分割付连接若干字符串
/// </summary>
/// <param name="separator">
/// The string to use as a separator. is included in the returned string only if has more
/// than one element.
/// </param>
/// <param name="values">An array that contains the elements to concatenate.</param>
/// <returns>
/// A string that consists of the elements in delimited by the string. If is an empty array, the method
/// returns .e
/// </returns>
public static string Join(this string separator, IEnumerable<string> values)
{
return string.Join(separator, values);
}
/// <summary>
/// 删除最后结尾的指定字符后的字符
/// </summary>
public static string RemoveLastChar(string str, string strchar)
{
return str.Substring(0, str.LastIndexOf(strchar, StringComparison.Ordinal));
}
#endregion 字符串操作
#region 类型转换
/// <summary>
/// 转换字符串为byte数组
/// </summary>
/// <param name="this">The @this to act on.</param>
/// <returns>@this as a byte[].</returns>
public static byte[] ToByteArray(this string @this)
{
Encoding encoding = Activator.CreateInstance<ASCIIEncoding>();
return encoding.GetBytes(@this);
}
/// <summary>
/// 转换字符串为文件目录对象
/// </summary>
/// <param name="this">The @this to act on.</param>
/// <returns>@this as a DirectoryInfo.</returns>
public static DirectoryInfo ToDirectoryInfo(this string @this)
{
return new DirectoryInfo(@this);
}
/// <summary>
/// 转换字符串为枚举项
/// </summary>
/// <typeparam name="T">Generic type parameter.</typeparam>
/// <param name="this">The @this to act on.</param>
/// <returns>@this as a T.</returns>
public static T ToEnum<T>(this string @this)
{
var enumType = typeof(T);
return (T)Enum.Parse(enumType, @this);
}
/// <summary>
/// 转换字符串为文件对象
/// </summary>
/// <param name="this">The @this to act on.</param>
/// <returns>@this as a FileInfo.</returns>
public static FileInfo ToFileInfo(this string @this)
{
return new FileInfo(@this);
}
/// <summary>
/// 转换字符串为内存流
/// </summary>
/// <param name="this">The @this to act on.</param>
/// <param name="encoding"></param>
/// <returns>@this as a MemoryStream.</returns>
public static Stream ToStream(this string @this, Encoding encoding = null)
{
if (encoding == null)
encoding = Encoding.UTF8;
return new MemoryStream(encoding.GetBytes(@this));
}
/// <summary>
/// 转换字符串为XDocument
/// </summary>
/// <param name="this">The @this to act on.</param>
/// <returns>@this as an XDocument.</returns>
public static XDocument ToXDocument(this string @this)
{
Encoding encoding = Activator.CreateInstance<ASCIIEncoding>();
using (var ms = new MemoryStream(encoding.GetBytes(@this)))
{
return XDocument.Load(ms);
}
}
/// <summary>
/// 转换字符串为XmlDocument
/// </summary>
/// <param name="this">The @this to act on.</param>
/// <returns>@this as an XmlDocument.</returns>
public static XmlDocument ToXmlDocument(this string @this)
{
var doc = new XmlDocument();
doc.LoadXml(@this);
return doc;
}
#endregion 类型转换
}
} |
using System;
using System.Collections.Generic;
using System.Diagnostics.Tracing;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;
using UnityEngine;
/// <summary>
/// The center of all stimuli in the game. Whenever a stimulus occurs, it should go through this
/// </summary>
class EventHub
{
public delegate void GameTimeChangeDelegate(float time);
public static event GameTimeChangeDelegate GameTimeChange;
public static void GameTimeChangeBroadcast(float time)
{
GameTimeChange?.Invoke(time);
}
public delegate void PlayerChangeStoryDelegate(PlayerCharacter playerCharacter);
public static event PlayerChangeStoryDelegate PlayerChangeStory;
public static void PlayerChangeStoryBroadcast(PlayerCharacter playerCharacter)
{
PlayerChangeStory?.Invoke(playerCharacter);
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine.UI;
using UnityEngine;
using UnityEngine.EventSystems;
public class CarPartsSelect : MonoBehaviour {
[SerializeField] private GameObject body, cluster, frame, frontBumper, frontLeftFender,
frontRightFender, glass, hood, interior, leftFrontdoor, leftHeadlight, leftSideskirt,
leftTaillight, lod, rearBumper, rearDoorLeft, rearDoorRight, rearLeftFender,
rearRightFender, rightFrontDoor, rightHeadlight, rightSideskirt, rightTaillight,
rollcage, spacer, spoiler, trunk, wheels;
public void ClickSelection()
{
EventSystem.current.currentSelectedGameObject.GetComponent<Image>().color = Color.yellow;
PlayerPrefs.SetString("PartsSelected", PlayerPrefs.GetString("PartsSelected") + EventSystem.current.currentSelectedGameObject.name + ";");
switch (EventSystem.current.currentSelectedGameObject.name)
{
case "Body": body.gameObject.tag = "Selected";
break;
case "Cluster": cluster.gameObject.tag = "Selected";
break;
case "Frame": frame.gameObject.tag = "Selected";
break;
case "Front Bumper": frontBumper.gameObject.tag = "Selected";
break;
case "Front Left Fender": frontLeftFender.gameObject.tag = "Selected";
break;
case "Front Right Fender": frontRightFender.gameObject.tag = "Selected";
break;
case "Glass": glass.gameObject.tag = "Selected";
break;
case "Hood": hood.gameObject.tag = "Selected";
break;
case "Interior": interior.gameObject.tag = "Selected";
break;
case "Left Front Door": leftFrontdoor.gameObject.tag = "Selected";
break;
case "Left Headlight": leftHeadlight.gameObject.tag = "Selected";
break;
case "Left Sideskirt": leftSideskirt.gameObject.tag = "Selected";
break;
case "Left Taillight":leftTaillight.gameObject.tag = "Selected";
break;
case "LOD": lod.gameObject.tag = "Selected";
break;
case "Rear Bumper": rearBumper.gameObject.tag = "Selected";
break;
case "Rear Door Left": rearDoorLeft.gameObject.tag = "Selected";
break;
case "Rear Door Right": rearDoorRight.gameObject.tag = "Selected";
break;
case "Rear Left Fender": rearLeftFender.gameObject.tag = "Selected";
break;
case "Rear Right Fender": rearRightFender.gameObject.tag = "Selected";
break;
case "Right Front Door": rightFrontDoor.gameObject.tag = "Selected";
break;
case "Right Headlight": rightHeadlight.gameObject.tag = "Selected";
break;
case "Right Sideskirt": rightSideskirt.gameObject.tag = "Selected";
break;
case "Right Taillight": rightTaillight.gameObject.tag = "Selected";
break;
case "Rollcage": rollcage.gameObject.tag = "Selected";
break;
case "Spacer": spacer.gameObject.tag = "Selected";
break;
case "Spoiler": spoiler.gameObject.tag = "Selected";
break;
case "Trunk": trunk.gameObject.tag = "Selected";
break;
case "Wheels": wheels.gameObject.tag = "Selected";
break;
}
}
}
|
namespace Groundwork.Domain
{
using System.ComponentModel;
using System.Runtime.Serialization;
[DataContract]
public abstract class BaseEntity<TopLevelDomain> : IEntity<TopLevelDomain>
{
private TopLevelDomain _id;
private string _name;
protected BaseEntity(TopLevelDomain id, string name)
{
_id = id;
_name = name;
}
public bool IsModified { get; private set; }
public void SetModified(bool modified)
{
if(IsModified != modified)
{
IsModified = modified;
}
}
public event PropertyChangedEventHandler PropertyChanged;
public event PropertyChangingEventHandler PropertyChanging;
protected virtual void OnPropertyChanged(string propertyName)
=> PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
protected virtual void OnPropertyChanging(string propertyName)
=> PropertyChanging?.Invoke(this, new PropertyChangingEventArgs(propertyName));
[DataMember]
public virtual string Name
{
get => _name;
set
{
if(!Equals(_name, value))
{
OnPropertyChanging(nameof(Name));
_name = value;
SetModified(true);
OnPropertyChanged(nameof(Name));
}
}
}
[DataMember]
public TopLevelDomain Id
{
get => _id;
set
{
if(!Equals(_id, value))
{
OnPropertyChanging(nameof(Id));
_id = value;
SetModified(true);
OnPropertyChanged(nameof(Id));
}
}
}
}
}
|
using GHCIQuizSolution.DBContext;
using GHCIQuizSolution.Models.FromDBContext;
using Newtonsoft.Json;
using NLog;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using System.Web;
using System.Web.Http;
namespace GHCIQuizSolution.Controllers
{
public class BaseQuizController : BaseAPIController
{
protected static Logger logger = LogManager.GetCurrentClassLogger();
protected static class QUIZ_STATUS {
public static String IN_PROGRESS = "IN_PROGRESS";
public static String COMPLETED_SUCCESS = "COMPLETED_SUCCESS";
public static String COMPLETED_FAIL = "COMPLETED_FAIL";
}
private Dictionary<String, int> COMPLEXITY_POINT = new Dictionary<string, int> {
{ "EASY", 1 },
{ "MEDIUM", 2 },
{ "COMPLEX", 3 },
{ "GROUP", 1 }
};
protected String[] QUESTION_COMPLEXITITES = { "COMPLEX", "MEDIUM", "EASY", "GROUP" };
protected String[] QUESTION_OPTION_TYPE = { "Radio", "Checkbox", "Text" };
protected List<Action> SetImageUrl(IFileBased sourceQuestion, IFileBased targetQuestion)
{
List<Action> fileListToDelete = new List<Action>();
if (sourceQuestion.file != null)
{
if (!sourceQuestion.file.isDeleted)
{
if (String.IsNullOrWhiteSpace(targetQuestion.id))
{
targetQuestion.id = Guid.NewGuid().ToString();
}
fileListToDelete.Add(() => File.Delete(FILE_IMAGE_PATH + "/" + targetQuestion.id + sourceQuestion.file.ext));
fileListToDelete.Add(() => File.Move(FILE_TEMP_PATH + "/" + sourceQuestion.file.fileName, FILE_IMAGE_PATH + "/" + targetQuestion.id + sourceQuestion.file.ext));
targetQuestion.imageUrl = targetQuestion.id + sourceQuestion.file.ext;
}
else
{
if (targetQuestion.imageUrl != null)
{
fileListToDelete.Add(() => File.Delete(FILE_IMAGE_PATH + "/" + targetQuestion.imageUrl));
targetQuestion.imageUrl = null;
}
}
}
else
{
targetQuestion.imageUrl = sourceQuestion.imageUrl;
}
return fileListToDelete;
}
protected void SetNextQuestion(QuizUser quizUser)
{
UserQuestion userQuestion;
if(quizUser.CurrentUserQuiz == null) {
return;
}
if (quizUser.CurrentUserQuestion == null)
{
userQuestion = quizUser.CurrentUserQuiz.UserQuestions
.OrderBy(q => q.index)
.FirstOrDefault();
}
else
{
userQuestion = quizUser.CurrentUserQuiz.UserQuestions
.OrderBy(q => q.index)
.Where(q => q.index > quizUser.CurrentUserQuestion.index)
.FirstOrDefault();
}
//quizUser.isLastQuestionForCurrentQuiz = userQuestion == null;
quizUser.CurrentUserQuestion = userQuestion;
if(quizUser.CurrentUserQuestion == null) {
this.SetQuizStatus(quizUser);
}
}
private void SetQuizStatus(QuizUser quizUser) {
int passPoint = quizUser.CurrentUserQuiz.Quiz.passpoint.GetValueOrDefault();
int acquiredPoint = quizUser.CurrentUserQuiz.UserQuestions.Sum(q => {
if(q.isCorrect.GetValueOrDefault() && COMPLEXITY_POINT.ContainsKey(q.Question.complexity)) {
return COMPLEXITY_POINT[q.Question.complexity];
}
else {
return 0;
}
});
quizUser.CurrentUserQuiz.status = acquiredPoint >= passPoint ? QUIZ_STATUS.COMPLETED_SUCCESS.ToString() : QUIZ_STATUS.COMPLETED_FAIL.ToString();
}
protected void SetNextQuiz(QuizUser quizUser)
{
Quiz quiz;
int attemptNo = 0;
if (quizUser.CurrentUserQuiz == null)
{
quiz = QuizDB.Quizs.OrderBy(q => q.level).FirstOrDefault();
}
else if(quizUser.CurrentUserQuiz.status == QUIZ_STATUS.COMPLETED_SUCCESS)
{
quiz = QuizDB.Quizs
.OrderBy(q => q.level)
.Where(q => q.level > quizUser.CurrentUserQuiz.Quiz.level)
.FirstOrDefault();
}
else if (quizUser.CurrentUserQuiz.status == QUIZ_STATUS.COMPLETED_FAIL)
{
// Reset the CurrentQuiz;
quiz = quizUser.CurrentUserQuiz.Quiz;
attemptNo = quizUser.CurrentUserQuiz.attempt.GetValueOrDefault() + 1;
}
else {
throw new NotImplementedException();
}
if (quiz == null)
{
quizUser.isLastQuiz = true;
quizUser.CurrentUserQuiz = null;
quizUser.CurrentUserQuestion = null;
return;
}
//quizUser.isLastQuiz = quizList.Count() == 1;
quizUser.CurrentUserQuiz = new UserQuiz()
{
Quiz = quiz,
status = QUIZ_STATUS.IN_PROGRESS.ToString(),
attempt = attemptNo
};
quizUser.UserQuizs.Add(quizUser.CurrentUserQuiz);
this.GenerateQuizQuestions(quizUser.CurrentUserQuiz);
}
public class ComplexityComposition {
public String level;
public int nos;
}
private void GenerateQuizQuestions(UserQuiz userQuiz) {
Random random = new Random();
var complexityCompArr = JsonConvert.DeserializeObject<ComplexityComposition[]>(userQuiz.Quiz.complexityComposition);
List<Question> questionList = new List<Question>();
List<Question> randomList = new List<Question>();
// Apply Group logic
if(complexityCompArr.Any(c => "GROUP".Equals(c.level))) {
var questionGroup = userQuiz.Quiz.Questions.GroupBy(q => q.groupName);
var index = random.Next(0, questionGroup.Count());
randomList = questionGroup.ElementAt(index).OrderBy(q => q.index).ToList();
}
else {
foreach (var comp in complexityCompArr)
{
questionList.AddRange(userQuiz.Quiz.Questions
.Where(q => q.complexity == comp.level)
.OrderBy(x => Guid.NewGuid())
.Take(comp.nos));
}
while (questionList.Count != 0)
{
var index = random.Next(0, questionList.Count);
randomList.Add(questionList[index]);
questionList.RemoveAt(index);
}
}
int indexCounter = 0;
foreach (var item in randomList)
{
userQuiz.UserQuestions.Add(new UserQuestion()
{
index = indexCounter++,
Question = item,
});
}
}
protected Object GetCurrentUserQuestionForReturn(QuizUser user)
{
if(user.CurrentUserQuestion != null) {
return new
{
user.CurrentUserQuestion.id,
user.CurrentUserQuestion.index,
user.CurrentUserQuestion.isCorrect,
Question = new
{
user.CurrentUserQuestion.Question.description,
user.CurrentUserQuestion.Question.id,
user.CurrentUserQuestion.Question.optionType,
user.CurrentUserQuestion.Question.imageUrl,
QuizOptions = user.CurrentUserQuestion.Question.QuizOptions.Select(quizOption => new
{
quizOption.description,
quizOption.id,
quizOption.isCorrect,
quizOption.index
})
.OrderBy(quizOption => quizOption.index)
},
user.CurrentUserQuestion.questionId,
user.CurrentUserQuestion.selectedOptionIds
};
}
else {
return null;
}
}
protected void CheckLength(String value, int len, String message, List<String> messageList)
{
if (String.IsNullOrWhiteSpace(value) || value.Length < len)
{
messageList.Add(message);
}
}
protected void CheckInArray(String value, String[] arr, String message, List<String> messageList)
{
if (!arr.Contains(value))
{
messageList.Add(message);
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
using Windows.UI.Core;
using Windows.System;
using System.Diagnostics;
namespace VéloMax.pages
{
public sealed partial class CommandesMainUI : Page
{
public CommandesMainUI()
{
this.InitializeComponent();
NavViewCommandes.SelectedItem = NavViewCommandes_Default;
NavigationContentFrame.Navigate(typeof(CommandesEncoursUI));
}
private void NavView_SelectionChanged(NavigationView sender, NavigationViewSelectionChangedEventArgs args)
{
switch (((NavigationViewItem)args.SelectedItem).Tag)
{
case "commandesEncours":
NavigationContentFrame.Navigate(typeof(CommandesEncoursUI));
break;
case "commandesEnvoyee":
NavigationContentFrame.Navigate(typeof(CommandesEnvoyeeUI));
break;
}
}
private readonly List<(string Tag, Type Page)> _pages = new List<(string Tag, Type Page)>{
("commande1", typeof(VéloMax.pages.CommandesEncoursUI)),
("commande2", typeof(VéloMax.pages.CommandesEnvoyeeUI)),
("commande3", typeof(VéloMax.pages.AjouterCommandeUI))
};
private void NavView_ItemInvoked(NavigationView sender, NavigationViewItemInvokedEventArgs args)
{
if (args.InvokedItemContainer != null)
{
var navItemTag = args.InvokedItemContainer.Tag.ToString();
NavView_Navigate(navItemTag, args.RecommendedNavigationTransitionInfo);
}
}
private void NavView_Navigate(
string navItemTag,
Windows.UI.Xaml.Media.Animation.NavigationTransitionInfo transitionInfo)
{
Type _page = null;
var item = _pages.FirstOrDefault(p => p.Tag.Equals(navItemTag));
_page = item.Page;
// Get the page type before navigation so you can prevent duplicate
// entries in the backstack.
var preNavPageType = NavigationContentFrame.CurrentSourcePageType;
// Only navigate if the selected page isn't currently loaded.
if (!(_page is null) && !Type.Equals(preNavPageType, _page))
{
NavigationContentFrame.Navigate(_page, null, transitionInfo);
}
}
private void NavView_BackRequested(NavigationView sender,
NavigationViewBackRequestedEventArgs args)
{
TryGoBack();
}
private bool TryGoBack()
{
if (!NavigationContentFrame.CanGoBack)
return false;
// Don't go back if the nav pane is overlayed.
if (NavViewCommandes.IsPaneOpen &&
(NavViewCommandes.DisplayMode == NavigationViewDisplayMode.Compact ||
NavViewCommandes.DisplayMode == NavigationViewDisplayMode.Minimal))
return false;
NavigationContentFrame.GoBack();
return true;
}
}
}
|
using System;
using System.Collections.Generic;
namespace Warehouse.Infrastructure.Entities
{
public partial class LogOrder
{
public int Id { get; set; }
public int OrderId { get; set; }
public string Sku { get; set; }
public int Quantity { get; set; }
public DateTime Modified { get; set; }
public int UserId { get; set; }
public short Status { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.Xml.Linq;
using System.Xml.XPath;
using System.Windows.Browser;
namespace Lite
{
/// <summary>
/// The service agent that talks to the OSM Service Provider to use its
/// GeoLocator service.
/// </summary>
public class LiteOsmGeoLocatorServiceAgent : LiteWebGeoLocatorServiceAgentBase
{
#region Constructors
/// <summary>
/// Constructs the OSM GeoLocator Service Agent
/// </summary>
public LiteOsmGeoLocatorServiceAgent()
: base("osm", "OpenStreetMap")
{
GeoLocatorUri = new Uri(@"http://nominatim.openstreetmap.org/search.php");
}
#endregion
#region Implementation
/// <summary>
/// Return the Query for the GeoLocate service call
/// </summary>
protected override string GeoLocateServiceQuery(string searchString, int maximumNumberOfResults)
{
return HttpUtility.UrlEncode(String.Format("q={0}&format=xml&limit={1}", searchString, maximumNumberOfResults));
}
/// <summary>
/// Get the result for the GeoLocate service call.
/// The document parameter is the result from the service call, which is assumed
/// to be an XML structure
/// </summary>
protected override IList<WebGeoLocatorResultAddress> GetGeoLocateServiceResult(XDocument document)
{
var result = new List<WebGeoLocatorResultAddress>();
if (document != null)
{
var navi = document.CreateNavigator();
var iter = navi.SelectDescendants("place", string.Empty, false);
while (iter.MoveNext())
{
var name = iter.Current.GetAttribute("display_name", string.Empty);
var bb = iter.Current.GetAttribute("boundingbox", string.Empty);
if (!String.IsNullOrEmpty(bb) && !String.IsNullOrEmpty(name))
{
var coords = GetDoublesFromString(bb);
if (coords.Count == 4)
{
var env = CreateWGS84Envelope(coords[2], coords[0], coords[3], coords[1]);
if (env != null)
{
result.Add(new WebGeoLocatorResultAddress { Name = name, Bounds = env });
}
}
}
}
}
return result;
}
#endregion
}
}
|
using System.Collections;
using System.Collections.Generic;
using NUnit.Framework;
using UnityEngine;
using UnityEngine.TestTools;
namespace Tests
{
public class TestMove
{
MoveController moveController;
[OneTimeSetUp]
public void TestSetUp()
{
moveController = new GameObject().AddComponent<MoveController>();
}
[Test]
public void TestMovePassesForHorizontalAxis()
{
float h = 1f;
float deltaTime = 1f;
float actualSpeed = moveController.SpeedByFrame(h, deltaTime);
Assert.AreEqual(actualSpeed, 20f);
}
[Test]
public void TestMovePassesForVerticalAxis()
{
float v = 0.3f;
float deltaTime = 0.7f;
float actualSpeed = moveController.SpeedByFrame(v, deltaTime);
Assert.That(Mathf.Approximately(actualSpeed, 4.2f));
}
[Test]
public void TestNewPositionHasNoChangeOverDirection()
{
float x = 0f;
float z = 0f;
Vector3 position = new Vector3(3f, 4f, 5f);
Vector3 newPosition = moveController.CalculatePosition(position, x, z);
Assert.AreEqual(position, newPosition);
}
[Test]
public void TestNewPositionHasChangedOnX()
{
float x = 1f;
float z = 0f;
Vector3 position = new Vector3(3f, 4f, 5f);
Vector3 newPosition = moveController.CalculatePosition(position, x, z);
Assert.AreEqual(new Vector3(4f,4f,5f) , newPosition);
}
[Test]
public void TestNewPositionHasChangedOnXAndZ()
{
float x = 3f;
float z = 5f;
Vector3 position = new Vector3(3f, 4f, 5f);
Vector3 newPosition = moveController.CalculatePosition(position, x, z);
Assert.AreEqual(new Vector3(6f, 4f, 10f), newPosition);
}
[Test]
public void TestNewPositionHasChangedNegativelyOnZ()
{
float x = 0f;
float z = -3f;
Vector3 position = new Vector3(3f, 4f, 5f);
Vector3 newPosition = moveController.CalculatePosition(position, x, z);
Assert.AreEqual(new Vector3(3f, 4f, 2f), newPosition);
}
}
}
|
using DigitalFormsSteamLeak.Entity.IModels;
using DigitalFormsSteamLeak.Entity.Models;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DigitalFormsSteamLeak.Entity.Models
{
[Table("T_User")]
public class LeakUser : ILeakUser
{
[Key]
[Column("User_Id")]
public Guid UserId { get; set; }
[Required]
[Column("User_Name")]
public string UserName { get; set; }
public virtual ICollection<LeakDetails> leakDetails { get; set; }
}
}
|
using POSServices.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace POSServices.Data
{
public interface IAuthRepository
{
Task<UserLogin> Register(UserLogin login, string password);
Task<UserLogin> Login(string username, string password);
Task<bool> UserExists(string username);
}
}
|
//
// InstrumentationProvider.cs
//
// Author:
// nofanto ibrahim <nofanto.ibrahim@gmail.com>
//
// Copyright (c) 2011 sejalan
//
// This library is free software; you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as
// published by the Free Software Foundation; either version 2.1 of the
// License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
using System;
using Sejalan.Framework.Instrumentation;
using System.IO;
namespace Sejalan.Framework.Instrumentation.SimpleLog
{
public class InstrumentationProvider : InstrumentationProviderBase
{
public virtual string LogFileName
{
get{
return this.Parameters["logFileName"];
}
}
#region implemented abstract members of Sejalan.Framework.Instrumentation.InstrumentationProviderBase
public override void WriteLog (string message)
{
using(StreamWriter fs = new StreamWriter(LogFileName,true))
{
fs.Write(message);
}
}
#endregion
public InstrumentationProvider ()
{
}
}
}
|
using Microsoft.AspNet.SignalR.Messaging;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Orleans.Host;
using OrleansR.GrainInterfaces;
using OrleansR.MessageBus;
using System;
using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;
namespace OrleansR.UnitTests
{
[TestClass]
public class GrainTests
{
[TestMethod]
public async Task SingleGrainTest()
{
Message[] messages = null;
var grain = PubSubGrainFactory.GetGrain(0, "");
await grain.Subscribe(await MessageObserverFactory.CreateObjectReference(new MessageObserver(x => messages = x)));
await grain.Publish(new Message[] { new Message("x", "y", "Hello World") });
Thread.Sleep(50);
Assert.IsNotNull(messages);
Assert.AreEqual(1, messages.Length);
Assert.AreEqual("x", messages[0].Source);
Assert.AreEqual("y", messages[0].Key);
}
[TestMethod]
public async Task DoubleGrainTest()
{
Message[] messages = null;
var grain1 = PubSubGrainFactory.GetGrain(1);
await grain1.Subscribe(await MessageObserverFactory.CreateObjectReference(new MessageObserver(x => messages = x)));
var grain2 = PubSubGrainFactory.GetGrain(2);
await grain2.Publish(new Message[] { new Message("a", "b", "Hello World") });
Thread.Sleep(10);
Assert.IsNotNull(messages);
Assert.AreEqual(1, messages.Length);
Assert.AreEqual("a", messages[0].Source);
Assert.AreEqual("b", messages[0].Key);
}
// code to initialize and clean up an Orleans Silo
static OrleansSiloHost siloHost;
static AppDomain hostDomain;
static void InitSilo(string[] args)
{
siloHost = new OrleansSiloHost("test");
siloHost.ConfigFileName = "DevTestServerConfiguration.xml";
siloHost.DeploymentId = "1";
siloHost.InitializeOrleansSilo();
var ok = siloHost.StartOrleansSilo();
if (!ok) throw new SystemException(string.Format("Failed to start Orleans silo '{0}' as a {1} node.", siloHost.SiloName, siloHost.SiloType));
}
[ClassInitialize]
public static void GrainTestsClassInitialize(TestContext testContext)
{
hostDomain = AppDomain.CreateDomain("OrleansHost", null, new AppDomainSetup
{
AppDomainInitializer = InitSilo,
ApplicationBase = AppDomain.CurrentDomain.SetupInformation.ApplicationBase,
});
Orleans.OrleansClient.Initialize("DevTestClientConfiguration.xml");
}
[ClassCleanup]
public static void GrainTestsClassCleanUp()
{
try
{
hostDomain.DoCallBack(() =>
{
siloHost.Dispose();
siloHost = null;
//AppDomain.Unload(hostDomain);
});
// vstest execution engine must die
var startInfo = new ProcessStartInfo
{
FileName = "taskkill",
Arguments = "/F /IM vstest.executionengine.x86.exe",
UseShellExecute = false,
WindowStyle = ProcessWindowStyle.Hidden,
};
//Process.Start(startInfo);
}
catch
{ }
}
}
}
|
using AutoMapper;
using GigHub.Core.Dto;
using GigHub.Core.Models;
namespace GigHub
{
public class MappingProfile:Profile
{
public MappingProfile()
{
var config = new MapperConfiguration(cfg => {
cfg.CreateMap<ApplicationUser, UserDto>();
cfg.CreateMap<Gig,GigDto>();
cfg.CreateMap<Notification, NotificationDto>();
});
}
}
} |
using System;
using System.Collections;
using System.ComponentModel;
using System.ComponentModel.Design;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Data;
using System.Windows.Forms;
using System.Drawing.Design;
using System.Security.Permissions;
using System.Runtime.InteropServices;
using System.Diagnostics;
using System.IO;
using AC.ExtendedRenderer.Toolkit.Utils;
using AC.ExtendedRenderer.Toolkit.Drawing;
namespace AC.ExtendedRenderer.Toolkit.Navigator
{
#region ... KryptonNavigatorButton ...
[System.Drawing.ToolboxBitmapAttribute(typeof(System.Windows.Forms.Button)), ToolboxItem(false)]
public class CustomNavigatorButton : AC.StdControls.Toolkit.Buttons.CustomButton
{
public CustomNavigatorButton(Color BorderColor, Color GradientStartColor, Color GradientEndColor, Color TextColor)
{
this.AutoSize = false;
this.GradientBorderColor = BorderColor;
this.GradientTop = GradientStartColor;
this.GradientBottom = GradientEndColor;
this.Size = new System.Drawing.Size(23, 23);
this.ForeColor = TextColor;
this.TextAlign = ContentAlignment.MiddleCenter;
this.Font = new System.Drawing.Font("Marlett", 11.25f, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, (byte)2);
}
public CustomNavigatorButton()
{
this.AutoSize = false;
this.Size = new System.Drawing.Size(23, 23);
this.TextAlign = ContentAlignment.MiddleCenter;
this.Font = new System.Drawing.Font("Marlett", 11.25f, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, (byte)2);
}
protected override void OnPaint(PaintEventArgs pevent)
{
base.OnPaint(pevent);
}
protected override void Dispose(bool disposing)
{
base.Dispose(disposing);
}
#endregion
}
}
|
using System;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Http;
using LoginRegister.Models;
namespace LoginRegister.Controllers
{
public class LoginRegisterController : Controller
{
[HttpGet("")]
public ViewResult Index()
{
return View();
}
[HttpPost("login")]
public IActionResult Login(LogUser user)
{
if (ModelState.IsValid)
{
return RedirectToAction("LoggedIn", user);
}
else
{
return View("Index");
}
}
[HttpPost("register")]
public IActionResult Register(RegUser user)
{
if (ModelState.IsValid)
{
return RedirectToAction("Registered", user);
}
else
{
return View("Index");
}
}
[HttpGet("loggedin")]
public IActionResult LoggedIn(LogUser user)
{
return View(user);
}
[HttpGet("registered")]
public IActionResult Registered(RegUser user)
{
return View(user);
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Docller.Core.Common;
namespace Docller.UI.Models
{
public class ShareFolderEmailViewModel:InviteUserEmailViewModel
{
public string Folder { get; set; }
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data;
namespace PROG1_PROYECTO_FINAL
{
class C_Clientes : Cliente
{
private S_Cliente obj = new S_Cliente();
public DataTable MostrarClientes()
{
DataTable tabla = new DataTable();
tabla = obj.Mostrar(tabla);
return tabla;
}
public DataTable MostrarCategoriasClientes()
{
DataTable tabla = new DataTable();
tabla = obj.MostrarCategorias(tabla);
return tabla;
}
public void InsertarClient(string nombre, string cedula, string telefono, string email, int categoria)
{
obj.Insertar(nombre, cedula, telefono, email, categoria);
}
public void EditarClient(int id, string nombre, string cedula, string telefono, string email, int categoria)
{
obj.Editar(id, nombre, cedula, telefono, email, categoria);
}
public void EliminarClient(string id)
{
obj.Eliminar(Convert.ToInt32(id));
}
}
}
|
using Microsoft.EntityFrameworkCore;
namespace Thuisbegymmen
{
class TmpData
{
public static void AddDataDb()
{
// using(Context _context = new Context())
// {
// _context.Database.EnsureCreated();
// _context.Account.Add(new Account
// {
// Id = 1,
// Gebruikersnaam = "Admin",
// Wachtwoord = "Admin",
// Naam = "Admin",
// Tussenvoegsel = "Admin",
// Achternaam = "Admin",
// StraatHuisnr = "AdminStraat 99",
// Postcode = "9999AD",
// IsAdmin = true,
// EmailAdres = "admin@thuisbegymmen.nl",
// Telefoonnummer = null,
// VerwijderAccount = true,
// VerwijderProduct = true,
// ToevoegenProduct = true,
// VerwijderCategorie = true,
// ToevoegenCategorie = true,
// Rechten = true,
// });
// _context.Product.Add(new Product
// {
// ProductId = 1,
// Productnaam = "Muscle Power Barbell",
// Productbeschrijving = "Merk: Muscle Power, Lengte: 183cm, Kleur: Zwart",
// ProductFoto = "Wordt nog gevuld",
// Prijs = 100,
// Categorie = "Free Weight",
// Inventaris = 99,
// VerzendTijd = 3
// });
// _context.Product.Add(new Product
// {
// ProductId = 2,
// Productnaam = "Dumbbell 25kg",
// Productbeschrijving = "Merk: Tunturi, Gewicht: 25kg, Kleur: Zwart, ",
// ProductFoto = "Wordt nog gevuld",
// Prijs = 199,
// Categorie = "Free Weight",
// Inventaris = 100,
// VerzendTijd = 10
// });
// _context.SaveChanges();
// }
}
}
} |
using Microsoft.VisualBasic;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using System.Windows.Forms;
using System.Text;
namespace AC.ExtendedRenderer.Toolkit
{
public class TreeGridNodeParentBuilder
{
}
}
|
using UnityEngine;
namespace UnityAtoms.BaseAtoms
{
/// <summary>
/// Variable of type `int`. Inherits from `EquatableAtomVariable<int, IntPair, IntEvent, IntPairEvent, IntIntFunction>`.
/// </summary>
[EditorIcon("atom-icon-lush")]
[CreateAssetMenu(menuName = "Unity Atoms/Variables/Int", fileName = "IntVariable")]
public sealed class IntVariable : EquatableAtomVariable<int, IntPair, IntEvent, IntPairEvent, IntIntFunction>
{
/// <summary>
/// Add value to Variable.
/// </summary>
/// <param name="value">Value to add.</param>
public void Add(int value) => Value += value;
/// <summary>
/// Add variable value to Variable.
/// </summary>
/// <param name="variable">Variable with value to add.</param>
public void Add(AtomBaseVariable<int> variable) => Add(variable.Value);
/// <summary>
/// Subtract value from Variable.
/// </summary>
/// <param name="value">Value to subtract.</param>
public void Subtract(int value) => Value -= value;
/// <summary>
/// Subtract variable value from Variable.
/// </summary>
/// <param name="variable">Variable with value to subtract.</param>
public void Subtract(AtomBaseVariable<int> variable) => Subtract(variable.Value);
/// <summary>
/// Multiply variable by value.
/// </summary>
/// <param name="value">Value to multiple by.</param>
public void MultiplyBy(int value) => Value *= value;
/// <summary>
/// Multiply variable by Variable value.
/// </summary>
/// <param name="variable">Variable with value to multiple by.</param>
public void MultiplyBy(AtomBaseVariable<int> variable) => MultiplyBy(variable.Value);
/// <summary>
/// Divide Variable by value.
/// </summary>
/// <param name="value">Value to divide by.</param>
public void DivideBy(int value) => Value /= value;
/// <summary>
/// Divide Variable by Variable value.
/// </summary>
/// <param name="variable">Variable value to divide by.</param>
public void DivideBy(AtomBaseVariable<int> variable) => DivideBy(variable.Value);
}
}
|
using System;
namespace Oefening3
{
class Program
{
static void Main(string[] args)
{
double far, cel;
Console.Write("Hoeveel grade Fahrenheit is het momenteel: ");
far = Convert.ToDouble(Console.ReadLine());
cel = Math.Round((far - 32) / (5/9));
Console.WriteLine($"Het is momenteel {cel} graden Celcius ");
Console.ReadLine();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DesignPattern_AbstractFactory
{
class Car
{
Motor motor;
Wheel wheel;
public Wheel getWheel()
{
return wheel;
}
public void setWheel(Wheel wheel)
{
this.wheel = wheel;
}
public Motor getMotor()
{
return motor;
}
public void setMotor(Motor motor)
{
this.motor = motor;
}
public void information()
{
Console.WriteLine("Wheel: " + wheel.type + " || " + "Motor: " + motor.type);
}
}
}
|
using UnityEngine;
using DG.Tweening;
public class Door : MonoBehaviour
{
private Sound _sound;
private bool _open;
private void Start()
{
_sound = GetComponent<Sound>();
}
public void Open()
{
if (_open == false)
{
transform.DORotate(new Vector3(0, 84, 0), 5);
_sound.Play();
_open = true;
}
}
public void OpenReset()
{
_open = false;
}
}
|
using Microsoft.Data.SqlClient;
using System;
using System.Collections.Generic;
using System.Text;
namespace SalesDbToSqlLib
{
public class OrdersController
{
private static Connection connection { get; set; }
public OrdersController(Connection connection)
{
OrdersController.connection = connection;
}
private Order FillOrderForSqlRow(SqlDataReader sqldatareader)
{
var order = new Order()
{
Id = Convert.ToInt32(sqldatareader["Id"]),
CustomerId = Convert.ToInt32(sqldatareader["CustomerId"]),
Date = Convert.ToDateTime(sqldatareader["Date"]),
Description = Convert.ToString(sqldatareader["Description"])
};
return order;
}
private void FillParametersForSql(SqlCommand cmd, Order order)
{
cmd.Parameters.AddWithValue("@CustomerId", order.CustomerId);
cmd.Parameters.AddWithValue("@Date", order.Date);
cmd.Parameters.AddWithValue("@Description", order.Description);
}
public List<Order> GetAll()
{
var sql = " Select * from Orders; ";
var cmd = new SqlCommand(sql, connection.sqlconn);
var sqldatareader = cmd.ExecuteReader();
var orders = new List<Order>();
while (sqldatareader.Read())
{
var order = FillOrderForSqlRow(sqldatareader);
orders.Add(order);
}
sqldatareader.Close();
foreach(var o in orders)
{
GetCustomerForOrder(o);
}
return orders;
}
private void GetCustomerForOrder(Order order)
{
var custyCntrl = new CustomersController(connection);
order.customer = custyCntrl.GetByPK(order.CustomerId);
}
public Order GetByPk(int id)
{
var sql = $" Select * from Orders Where @Id = {id}; ";
var cmd = new SqlCommand(sql, connection.sqlconn);
cmd.Parameters.AddWithValue("@Id", id);
var sqldatareader = cmd.ExecuteReader();
if (!sqldatareader.HasRows)
{
sqldatareader.Close();
return null;
}
sqldatareader.Read();
var order = FillOrderForSqlRow(sqldatareader);
sqldatareader.Close();
return order;
}
//CREATE BY CUSTOMER ID
public bool Create(Order order)
{
var sql = $" Insert into Orders " +
" ( CustomerId, Date, Description) " +
" VALUES " +
" (@CustomerId, @Date, @Description) ; ";
var cmd = new SqlCommand(sql, connection.sqlconn);
FillParametersForSql(cmd, order);
var rowsAffected = cmd.ExecuteNonQuery();
return (rowsAffected == 1);
}
// CREATE BY CUSTOMER NAME
public bool Create( Order order, string CustomerName)
{
var custyCntrl = new CustomersController(connection);
var custy = custyCntrl.GetByCustomerName(CustomerName);
{
order.CustomerId = custy.Id;
return Create(order);
}
}
public bool Change(Order order)
{
var sql = " UPDATE Orders set " +
" CustomerId = @CustomerId, " +
" Date = @Date, " +
" Description = @Description " +
" Where Id = @Id; ";
var cmd = new SqlCommand(sql, connection.sqlconn);
FillParametersForSql(cmd, order);
var rowsAffected = cmd.ExecuteNonQuery();
return (rowsAffected == 1);
}
public bool Delete(Order order)
{
var sql = " Delete from Orders where Id = @Id; ";
var cmd = new SqlCommand(sql, connection.sqlconn);
cmd.Parameters.AddWithValue("@Id", order.Id);
var rowsAffected = cmd.ExecuteNonQuery();
return (rowsAffected == 1);
}
}
}
|
// -----------------------------------------------------------------------
// <copyright file="LocalizationDefinitionAttribute.cs">
// Copyright (c) Michal Pokorný. All Rights Reserved.
// </copyright>
// -----------------------------------------------------------------------
namespace Pentagon.Extensions.Localization
{
using System;
using JetBrains.Annotations;
[PublicAPI]
[AttributeUsage(AttributeTargets.Class, Inherited = false)]
public sealed class LocalizationDefinitionAttribute : Attribute { }
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace CentricTeam2.Models
{
public class EmployeeRecognition
{
[Key]
public int EmployeeRecognitionID { get; set; }
[Display(Name = "Date Recognition is Given")]
[DataType(DataType.DateTime)]
[DisplayFormat(DataFormatString = "{0:d}", ApplyFormatInEditMode = true)]
public DateTime CurentDateTime { get; set; }
[Display(Name = "Comments")]
public string RecognitionComments { get; set; }
[Display(Name = "Employee Giving Recognition")]
[Required]
public Guid EmployeeGivingRecog { get; set; }
[ForeignKey("EmployeeGivingRecog")]
public virtual UserDetails Giver { get; set; }
[Required]
[Display(Name = "Centric Core Value")]
public int RecognitionId { get; set; }
public virtual Recognition Recognition { get; set; }
[Required]
[Display(Name = "Employee Being Recognized")]
public Guid ID { get; set; }
[ForeignKey("ID")]
public virtual UserDetails UserDetails { get; set; }
}
} |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Data;
using System.Security.Principal;
using DrasCommon.Datalayer;
using DrasCommon.Utilities;
using System.Text;
namespace DrasCommon.Classes
{
[Serializable]
public class SSAUser : ISecurity
{
//Fields from database record
public String userPinNbr { get; private set; }
public String firstName { get; private set; }
public String lastName { get; private set; }
public String eMail { get; private set; }
public String phone { get; private set; }
public int componentUid { get; private set; }
public int? pgmAreaUid { get; private set; }
public String region { get; private set; }
public String ocd { get; private set; }
public bool? isActive { get; private set; }
public DateTime insertTmstmp { get; private set; }
public DateTime lastUpdTmstmp { get; private set; }
public String lastUpdUserPin { get; private set; }
//All security tokens currently available for this user
public List<Dictionary<String, String>> securityTokens { get; private set; }
public Boolean isSuperUser { get; private set; }
public String domain { get; private set; }
public String componentName { get; private set; }
public String pgmAreaName { get; private set; }
//*******************************************************************
//* Get User information from database and build User object *
//*******************************************************************
public Boolean AuthenticateUser(String _pin, string appName)
{
ExecStoredProcedure spAuthenticateUser = null;
DataTable spResult = new DataTable();
Boolean isOK = false;
try
{
spAuthenticateUser = new ExecStoredProcedure(SharedConstants.SPAUTHENTICATE_USER, new ConnectionManager().GetConnection(), "SPAUTHENTICATE_USER");
spAuthenticateUser.SPAddParm("@userPin", SqlDbType.NVarChar, _pin, ParameterDirection.Input);
spAuthenticateUser.SPAddParm("@appname", SqlDbType.NVarChar, appName, ParameterDirection.Input);
spResult = spAuthenticateUser.SPselect();
//Set User properties from result set
if (spResult.Rows.Count > 0)
{
isOK = true;
// need this for super users that have no roles (rasta)
if (spResult.Rows[0]["roleName"].ToString().Equals("Super User"))
this.isSuperUser = true;
}
}
catch (Exception ex)
{
throw ex;
}
finally
{
if (spResult != null)
{
spResult.Dispose();
}
}
return isOK;
}
//*********************************************************************
//* Check if user is in AD group OQRALL *
//*********************************************************************
public Boolean IsMemberOf(String _domain, String _pin)
{
bool retVal = false;
String newIdentity = _pin + "@" + _domain;
using (var identity = new WindowsIdentity(newIdentity.Trim()))
{
var principal = new WindowsPrincipal(identity);
retVal = principal.IsInRole(SharedConstants.AD_GROUP_OQRALL);
}
return retVal;
}
//*******************************************************************
//* Get User information from database and build User object *
//*******************************************************************
public SSAUser GetUser(String _domain, String _pin)
{
userPinNbr = _pin;
ExecStoredProcedure spGetUser = null;
DataTable spResult = new DataTable();
try
{
spGetUser = new ExecStoredProcedure(SharedConstants.SPGET_USER, new ConnectionManager().GetConnection(), "SPGET_USER");
spGetUser.SPAddParm("@userPin", SqlDbType.NVarChar, userPinNbr, ParameterDirection.Input);
spResult = spGetUser.SPselect();
//Set User properties from result set
if (spResult.Rows.Count > 0)
{
this.firstName = spResult.Rows[0]["firstName"].ToString();
this.lastName = spResult.Rows[0]["lastName"].ToString();
this.eMail = spResult.Rows[0]["userEmail"].ToString();
this.phone = spResult.Rows[0]["userPhone"].ToString();
this.componentUid = Convert.ToInt32(spResult.Rows[0]["componentUid"]);
this.componentName = spResult.Rows[0]["componentName"].ToString();
this.pgmAreaUid = Convert.ToInt32(spResult.Rows[0]["programAreaUid"]); //null value in integer datatype converted to zero in SQL
this.pgmAreaName = spResult.Rows[0]["programAreaName"].ToString();
this.region = spResult.Rows[0]["region"].ToString();
this.ocd = spResult.Rows[0]["officeCode"].ToString();
this.isActive = Convert.ToBoolean(spResult.Rows[0]["activeSw"]); //null value in bit datatype converted to "true" in SQL
this.domain = _domain;
}
}
catch (Exception ex)
{
throw ex;
}
finally
{
if (spResult != null)
{
spResult.Dispose();
}
}
return this;
}
//*******************************************************************
//* Load security tokens for this user *
//*******************************************************************
public List<Dictionary<String, String>> GetSecurityTokens(string appName)
{
ExecStoredProcedure spGetUserSecurity = null;
DataTable spResult = new DataTable();
try
{
spGetUserSecurity = new ExecStoredProcedure(SharedConstants.SPGET_USERSECURITY, new ConnectionManager().GetConnection(), "SPGET_USERSECURITY");
spGetUserSecurity.SPAddParm("@userPin", SqlDbType.NVarChar, userPinNbr, ParameterDirection.Input);
spGetUserSecurity.SPAddParm("@appname", SqlDbType.NVarChar, appName, ParameterDirection.Input);
spResult = spGetUserSecurity.SPselect();
securityTokens = new List<Dictionary<String, String>>();
if (spResult.Rows.Count > 0)
{
foreach (DataRow row in spResult.Rows)
{
Dictionary<String, String> tcol = new Dictionary<String, String>();
foreach (DataColumn col in spResult.Columns)
{
switch (col.ColumnName.ToString())
{
case "roleName":
tcol.Add(SharedConstants.ROLE, row["roleName"].ToString());
break;
case "resourceName":
tcol.Add(SharedConstants.RESOURCE, row["resourceName"].ToString());
break;
case "privilegeName":
tcol.Add(SharedConstants.PRIVILEGE, row["privilegeName"].ToString());
break;
case "filterPropertyName":
tcol.Add(SharedConstants.FILTER_PROPERTYNAME, row["filterPropertyName"].ToString());
break;
case "filterValueUid":
tcol.Add(SharedConstants.FILTER_VALUE_UID, row["filterValueUid"].ToString());
break;
}
}
securityTokens.Add(tcol);
}
}
}
catch (Exception ex)
{
throw ex;
}
finally
{
if (spResult != null)
{
spResult.Dispose();
}
}
return securityTokens;
}
//*******************************************************************
//* Check to see if user has a certain key-value pair defined *
//*******************************************************************
//* KEY VALUE
//* -------- ----------
//* Role User, Administrator, Security Administrator, Super User
//* Resource Report, Recommendation, Security, Reference File
//* Privilege Alter, View, All
//*
public Boolean IsUserAuthorized(String key, String value)
{
//If a Super User, no need to check anything else
if (isSuperUser)
{
return true;
}
try
{
foreach (Dictionary<String, String> dictionary in securityTokens)
{
foreach (KeyValuePair<string, String> KV in dictionary)
{
switch (key.Trim())
{
case SharedConstants.ROLE:
break;
case SharedConstants.RESOURCE:
break;
case SharedConstants.PRIVILEGE:
if (KV.Value == SharedConstants.PRIVILEGE_ALTER || KV.Value == SharedConstants.PRIVILEGE_ALL)
{
return true;
}
break;
default:
break;
}
if (KV.Key == key.Trim() && KV.Value == value.Trim())
{
return true;
}
}
}
}
catch (KeyNotFoundException)
{
return false;
}
return false;
}
//************************************************************************************
//* Check to see if user is authorized using match on specific role-resource-privilege
//* Check for privilege "Alter" in addition to "View" since alter includes view
//************************************************************************************
public Boolean IsUserAuthorized(string role, string resource = null, string privilege = null)
{
//If a Super User, no need to check anything else
if (isSuperUser)
{
return true;
}
//Loop thru security to find an exact match on all tokens provided
try
{
foreach (Dictionary<string, string> dictionary in securityTokens)
{
if ((dictionary.ContainsKey(SharedConstants.ROLE) && dictionary.ContainsValue(role.Trim()))
&& (resource == null ? true : (dictionary.ContainsKey(SharedConstants.RESOURCE) && dictionary.ContainsValue(resource.Trim()))))
{
if (privilege != null)
{
String privilegeName = dictionary.GetValueOrDefault(SharedConstants.PRIVILEGE);
if (!String.IsNullOrEmpty(privilegeName) && (privilegeName == privilege.Trim() || privilegeName == SharedConstants.PRIVILEGE_ALTER || privilegeName == SharedConstants.PRIVILEGE_ALL))
{
return true;
}
}
}
}
}
catch (KeyNotFoundException)
{
return false;
}
return false;
}
//*******************************************************************
//* Pass in role, resource & privilege - return available filters *
//*******************************************************************
//* Privilege Type = View, Alter, All
//*
public NameValueCollection GetFiltersForResourcePrivilege(String role, String resource, String privilege)
{
NameValueCollection filters = new NameValueCollection();
//If a Super User, no need to check anything else
if (isSuperUser)
{
return filters;
}
foreach (Dictionary<String, String> dictionary in securityTokens)
{
if ((dictionary.ContainsKey(SharedConstants.ROLE) && dictionary.ContainsValue(role.Trim())) &&
(dictionary.ContainsKey(SharedConstants.RESOURCE) && dictionary.ContainsValue(resource.Trim())) &&
(dictionary.ContainsKey(SharedConstants.PRIVILEGE) && (dictionary.ContainsValue(privilege.Trim()) || dictionary.ContainsValue(SharedConstants.PRIVILEGE_ALTER) || dictionary.ContainsValue(SharedConstants.PRIVILEGE_ALL))))
{
String filterName = dictionary.GetValueOrDefault(SharedConstants.FILTER_PROPERTYNAME);
if (!String.IsNullOrEmpty(filterName))
{
String uid = dictionary.GetValueOrDefault(SharedConstants.FILTER_VALUE_UID);
String value = dictionary.GetValueOrDefault(SharedConstants.FILTER_VALUE);
String filterValue = String.IsNullOrEmpty(uid) ? (String.IsNullOrEmpty(value) ? String.Empty : value) : uid;
filters.Add(filterName, filterValue);
}
}
}
return filters;
}
public Boolean CheckSuperUser()
{
isSuperUser = IsUserAuthorized(SharedConstants.ROLE, SharedConstants.ROLE_SUPER_USER);
return isSuperUser;
}
public void GetSecurity(string appName)
{
string currentUser = HttpContext.Current.Session[SharedConstants.SESSION_CURRENTUSERPIN] == null ? String.Empty : HttpContext.Current.Session[SharedConstants.SESSION_CURRENTUSERPIN].ToString();
//SSAUser user = (SSAUser)HttpContext.Current.Session[SharedConstants.SESSION_USER];
String[] tmpUser = HttpContext.Current.User.Identity.Name.Split('\\');
string domain = tmpUser[0].Trim();
if (!String.IsNullOrEmpty(currentUser))
{
BuildUser(domain, currentUser, appName);
//HttpContext.Current.Session[SharedConstants.SESSION_CURRENTUSERPIN] = this.Pin;
}
else
{
throw new HttpException(500, "User Identity cannot be established from Active Directory");
}
}
public void GetAlias(string appName, string domain, string pin)
{
if (!String.IsNullOrEmpty(pin))
{
BuildUser(domain, pin, appName);
}
else
{
throw new HttpException(500, "User Identity cannot be established from Active Directory");
}
}
private void BuildUser(string _domain, string _pin, string appName)
{
//SSAUser user = new SSAUser();
// Build User record if authenticated with at least one security Role
if (this.AuthenticateUser(_pin, appName) == false)
{
if (this.IsMemberOf(_domain, _pin) == false) //Is user in OQR?
{
throw new HttpException(403, "User not authorized to use system until added to User table");
}
else
{
_pin = SharedConstants.OQRALL_USERPIN;
}
}
this.GetUser(_domain, _pin);
// If User is not in the database, then Authentication fails
if (String.IsNullOrEmpty(this.firstName) || String.IsNullOrEmpty(this.lastName))
{
throw new HttpException(403, "User not authorized to use system until added to User table");
}
else
{
// get all security tokens for this user
this.GetSecurityTokens(appName);
// gsd: revisit super user stuff
// need this for super users that have no roles (rasta)
if ((this.securityTokens.Count > 0) || (this.isSuperUser) )
{
// Check if Super User and set flag
this.CheckSuperUser();
// Store User and Security data in this session
//HttpContext.Current.Session[SharedConstants.SESSION_USER] = user;
}
else
{
throw new HttpException(403, "User not authorized to use system until a role is added");
}
}
//return user;
}
public string GetSecurityAttributes(HttpContextBase httpContext)
{
// Get security parameters from [SecurityAccess] attribute to pass for security authorization
string role = httpContext.Items[SharedConstants.ROLE].ToString();
string resource = httpContext.Items[SharedConstants.RESOURCE].ToString();
string privilege = httpContext.Items[SharedConstants.PRIVILEGE].ToString();
string securityAccess = (String.IsNullOrEmpty(role) ? " " : role.Trim()) + ',' +
(String.IsNullOrEmpty(resource) ? " " : resource.Trim()) + ',' +
(String.IsNullOrEmpty(privilege) ? " " : privilege.Trim());
return securityAccess;
}
public NameValueCollection GetSecurityFilters(HttpContextBase httpContext)
{
string securityAccess = GetSecurityAttributes(httpContext);
//Split out the security parameters that were annotated on the Controller method
string[] securityParams = securityAccess.Split(new Char[] { ',' });
string role = securityParams[0];
string resource = securityParams[1];
string privilege = securityParams[2];
NameValueCollection securityFilters = GetFiltersForResourcePrivilege(role, resource, privilege);
return securityFilters;
}
public NameValueCollection GetSecurityFilters(string securityAccess)
{
//Split out the security parameters that were annotated on the Controller method
string[] securityParams = securityAccess.Split(new Char[] { ',' });
string role = securityParams[0];
string resource = securityParams[1];
string privilege = securityParams[2];
NameValueCollection securityFilters = GetFiltersForResourcePrivilege(role, resource, privilege);
return securityFilters;
}
public Boolean CompareSecurityFilters(string securityAccess, SSAUser _user, List<KeyValuePair<string, string>> compareItems)
{
if (_user.isSuperUser)
{
return true;
}
NameValueCollection securityFilters = GetSecurityFilters(securityAccess);
//If User has no security filters then no need to compare. No filter means get all data.
bool hasKey = securityFilters.HasKeys();
if (!hasKey)
{
return true;
}
//If User has security filters then compare them to the actual screen/database values.
var filters = securityFilters.AllKeys.SelectMany(securityFilters.GetValues, (k, v) => new { key = k, value = v });
foreach (var filterValue in filters)
{
foreach (var compare in compareItems)
{
if (filterValue.key == compare.Key && filterValue.value == compare.Value)
{
return true;
}
}
}
return false;
}
}
}
|
using EBS.Domain.ValueObject;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace EBS.Domain.Entity
{
/// <summary>
/// 盘点单
/// </summary>
public class Stocktaking:BaseEntity
{
public Stocktaking()
{
this.Items = new List<StocktakingItem>();
this.CreatedOn = DateTime.Now;
}
/// <summary>
/// 盘点单据号
/// </summary>
public string Code { get; set; }
/// <summary>
/// 盘点类型
/// </summary>
public StocktakingType StocktakingType { get; set; }
/// <summary>
/// 货架码
/// </summary>
public string ShelfCode { get; set; }
/// <summary>
/// 盘点计划编号
/// </summary>
public int StocktakingPlanId { get; set; }
/// <summary>
/// 创建时间
/// </summary>
public DateTime CreatedOn { get; set; }
/// <summary>
/// 创建人ID
/// </summary>
public int CreatedBy { get; set; }
/// <summary>
/// 创建人
/// </summary>
public string CreatedByName { get; set; }
/// <summary>
/// 部门ID
/// </summary>
public int StoreId { get; set; }
/// <summary>
/// 备注
/// </summary>
public string Note { get; set; }
/// <summary>
/// 状态
/// </summary>
public StocktakingStatus Status { get; set; }
public virtual List<StocktakingItem> Items { get; set; }
public void Cancel()
{
if (this.Status != StocktakingStatus.Audited)
{
this.Status = StocktakingStatus.Cancel;
}
else {
throw new Exception("已审单据不能作废");
}
}
}
}
|
using MyForum.Domain;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace MyForum.Web.Models.Threads
{
public class ThreadsListCategoriesViewModel
{
public string Title { get; set; }
public string Content { get; set; }
public List<Category> Categories { get; set; }
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace POSServices.WebAPIInforModel
{
public class InforArticle
{
/*
public string STAT { get; set; }
public string ITNO { get; set; }
public string ITDS { get; set; }
public string FUDS { get; set; }
public string DWNO { get; set; }
public string RESP { get; set; }
public string RENM { get; set; }
public string UNMS { get; set; }
public string DS01 { get; set; }
public string ITGR { get; set; }
public string DS02 { get; set; }
public string ITCL { get; set; }
public string DS03 { get; set; }
public string BUAR { get; set; }
public string DS04 { get; set; }
public string ITTY { get; set; }
public string DS05 { get; set; }
public string TPCD { get; set; }
public string MABU { get; set; }
public string CHCD { get; set; }
public string STCD { get; set; }
public string BACD { get; set; }
public string VOL3 { get; set; }
public string NEWE { get; set; }
public string GRWE { get; set; }
public string PPUN { get; set; }
public string DS06 { get; set; }
public string BYPR { get; set; }
public string WAPC { get; set; }
public string QACD { get; set; }
public string EPCD { get; set; }
public string POCY { get; set; }
public string ACTI { get; set; }
public string HIE1 { get; set; }
public string HIE2 { get; set; }
public string HIE3 { get; set; }
public string HIE4 { get; set; }
public string HIE5 { get; set; }
public string GRP1 { get; set; }
public string GRP2 { get; set; }
public string GRP3 { get; set; }
public string GRP4 { get; set; }
public string GRP5 { get; set; }
public string CFI1 { get; set; }
public string CFI2 { get; set; }
public string CFI3 { get; set; }
public string CFI4 { get; set; }
public string CFI5 { get; set; }
public string TXID { get; set; }
public string ECMA { get; set; }
public string PRGP { get; set; }
public string DS07 { get; set; }
public string INDI { get; set; }
public string PUUN { get; set; }
public string DS08 { get; set; }
public string ALUC { get; set; }
public string IEAA { get; set; }
public string EXPD { get; set; }
public string GRMT { get; set; }
public string HAZI { get; set; }
public string SALE { get; set; }
public string TAXC { get; set; }
public string DS09 { get; set; }
public string ATMO { get; set; }
public string ATMN { get; set; }
public string TPLI { get; set; }
public string FCU1 { get; set; }
public string ALUN { get; set; }
public string IACP { get; set; }
public string HDPR { get; set; }
public string AAD0 { get; set; }
public string AAD1 { get; set; }
public string CHCL { get; set; }
public string ITRC { get; set; }
public string VTCP { get; set; }
public string DS10 { get; set; }
public string VTCS { get; set; }
public string DS11 { get; set; }
public string LMDT { get; set; }
public string DCCD { get; set; }
public string PDCC { get; set; }
public string SPUN { get; set; }
public string CAWP { get; set; }
public string CWUN { get; set; }
public string CPUN { get; set; }
public string ITRU { get; set; }
public string TECR { get; set; }
public string EXCA { get; set; }
public string ACCG { get; set; }
public string CCCM { get; set; }
public string CCI1 { get; set; }
public string CRI1 { get; set; }
public string HVMT { get; set; }
public string ITNE { get; set; }
public string SPGV { get; set; }
public string PDLN { get; set; }
public string CPGR { get; set; }
public string SUME { get; set; }
public string SUMP { get; set; }
public string EVGR { get; set; }
public string QMGP { get; set; }
public string POPN { set; get; }
*/
public string ITNO { get; set; }
public string ITDS { get; set; }
public string BUAR { get; set; }
public string DS04 { get; set; }
public string FUDS { get; set; }
public string ITGR { get; set; }
public string DS02 { get; set; }
public string ITCL { get; set; }
public string DS03 { get; set; }
public string POPN { get; set; }
public string SIZE { get; set; }
public string COLO { get; set; }
}
public class ResultArticle
{
public string transaction { get; set; }
public IList<InforArticle> records { get; set; }
}
public class InforArticleAPI
{
public IList<ResultArticle> results { get; set; }
public bool wasTerminated { get; set; }
public int nrOfSuccessfullTransactions { get; set; }
public int nrOfFailedTransactions { get; set; }
}
}
|
using Microsoft.AspNetCore.Identity;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using GradConnect.Models;
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
namespace GradConnect.Data
{
public class DatabaseSeed
{
public async static void Seed(ApplicationDbContext context, RoleManager<Role> roleManager, UserManager<User> userManager)
{
// if no users exist in database
if (!context.Users.Any())
{
if(!await roleManager.RoleExistsAsync("Admin"))
{
await roleManager.CreateAsync(new Role("Admin"));
}
if(!await roleManager.RoleExistsAsync("Moderator"))
{
await roleManager.CreateAsync(new Role("Moderator"));
}
if (!await roleManager.RoleExistsAsync("Staff"))
{
await roleManager.CreateAsync(new Role("Staff"));
}
if (!await roleManager.RoleExistsAsync("Employer"))
{
await roleManager.CreateAsync(new Role("Employer"));
}
if (!await roleManager.RoleExistsAsync("User"))
{
await roleManager.CreateAsync(new Role("User"));
}
}
if (await userManager.FindByNameAsync("admin@gradconnect.network") == null)
{
var admin = new User()
{
Forename = "Admin",
Surname = "",
Email = "admin@gradconnect.network",
EmailConfirmed = true,
UserName = "admin@gradconnect.network",
StudentEmial = "",
StudentEmailConfirmed = false,
DateOfBirth = DateTime.Parse("01/01/1990"),
About = "Admin at GradConect",
InstitutionName = "GradConnect",
CourseName = "GradConnect"
};
var result = await userManager.CreateAsync(admin);
if (result.Succeeded)
{
await userManager.AddPasswordAsync(admin, "Pass123!");
await userManager.AddToRoleAsync(admin, "Admin");
}
}
if (await userManager.FindByNameAsync("james.lawn@gradconnect.network") == null)
{
var mod = new User()
{
Forename = "James",
Surname = "Lawn",
Email = "james.lawn@gradconnect.network",
EmailConfirmed = true,
UserName = "james.lawn@gradconnect.network",
StudentEmial = "",
StudentEmailConfirmed = false,
DateOfBirth = DateTime.Parse("11/07/1990"),
About = "Staff at GradConect",
InstitutionName = "Glasgow Caledonian University",
CourseName = "Computing"
};
var result = await userManager.CreateAsync(mod);
if (result.Succeeded)
{
await userManager.AddPasswordAsync(mod, "Pass123!");
await userManager.AddToRoleAsync(mod, "Moderator");
}
}
if (await userManager.FindByNameAsync("lukasz.bonkowski@gradconnect.network") == null)
{
var staff = new User()
{
Forename = "Lukasz",
Surname = "Bonkowski",
Email = "lukasz.bonkowski@gradconnect.network",
EmailConfirmed = true,
UserName = "lukasz.bonkowski@gradconnect.network",
StudentEmial = "",
StudentEmailConfirmed = false,
DateOfBirth = DateTime.Parse("01/01/1990"),
About = "3rd Year Computing student @ GCU",
InstitutionName = "Glasgow Caledonian University",
CourseName = "Computing"
};
var result = await userManager.CreateAsync(staff);
if (result.Succeeded)
{
await userManager.AddPasswordAsync(staff, "Pass123!");
await userManager.AddToRoleAsync(staff, "Staff");
}
}
if (await userManager.FindByNameAsync("ibm@gradconnect.network") == null)
{
var employer = new User()
{
Forename = "IBM",
Surname = "",
Email = "jobs@ibm.com",
EmailConfirmed = true,
UserName = "jobs@ibm.com",
StudentEmial = "",
StudentEmailConfirmed = false,
DateOfBirth = DateTime.Parse("01/01/1980"),
About = "Job oppertunities at IBM",
InstitutionName = "",
CourseName = ""
};
var result = await userManager.CreateAsync(employer);
if (result.Succeeded)
{
await userManager.AddPasswordAsync(employer, "Pass123!");
await userManager.AddToRoleAsync(employer, "Employer");
}
}
if (await userManager.FindByNameAsync("arooney200@caledonian.ac.uk") == null)
{
var user = new User()
{
Forename = "Aidan",
Surname = "Rooney",
Email = "arooney200@caledonian.ac.uk",
EmailConfirmed = true,
UserName = "arooney200@caledonian.ac.uk",
StudentEmial = "arooney200@caledonian.ac.uk",
StudentEmailConfirmed = true,
DateOfBirth = DateTime.Parse("10/11/1999"),
About = "3rd Year Computing student @ GCU",
InstitutionName = "Glasgow Caledonian University",
CourseName = "Computing"
};
var result = await userManager.CreateAsync(user);
if (result.Succeeded)
{
await userManager.AddPasswordAsync(user, "Pass123!");
await userManager.AddToRoleAsync(user, "User");
}
}
//seeding new skills if none exist in the database
if (!context.Skills.Any()) {
Skill Leadership = new Skill()
{
Name = "Leadership"
};
Skill ActiveListening = new Skill()
{
Name = "Active Listening"
};
Skill Teamwork = new Skill()
{
Name = "Teamwork"
};
Skill Communication = new Skill()
{
Name = "Communication"
};
context.Skills.Add(Leadership);
context.Skills.Add(ActiveListening);
context.Skills.Add(Teamwork);
context.Skills.Add(Communication);
}
if (!context.Jobs.Any())
{
Job RockstarGames = new Job()
{
Title = "Games Designer",
Description = "Games Designer at World Famous developer, Rockstar Games.",
Salary = 40000.00,
Location = "Dundee",
ContractType = "Permanent",
ContractedHours = "Full Time",
DatePosted = DateTime.Now
};
context.Jobs.Add(RockstarGames);
}
if (!context.Posts.Any())
{
Post post = new Post()
{
Title = "Sample Post",
Description = "This is a sample seeded post.",
DatePosted = DateTime.Now,
Thumbnail = 0
};
context.Posts.Add(post);
}
context.SaveChanges();
}
}
}
|
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using Upgrader.Infrastructure;
namespace Upgrader.Schema
{
/// <inheritdoc />
/// <summary>
/// Collection of all columns in the specified table.
/// </summary>
public class ColumnCollection : IEnumerable<ColumnInfo>
{
private readonly Database database;
private readonly string tableName;
internal ColumnCollection(Database database, string tableName)
{
this.database = database;
this.tableName = tableName;
}
/// <summary>
/// Gets column information for the specified column. Returns null if the specified column name does not exist.
/// </summary>
/// <param name="columnName">Column name.</param>
/// <returns>Column information.</returns>
public ColumnInfo this[string columnName]
{
get
{
Validate.IsNotNullAndNotEmpty(columnName, nameof(columnName));
Validate.MaxLength(columnName, nameof(columnName), database.MaxIdentifierLength);
return new ColumnInfo(database, tableName, columnName);
}
}
public IEnumerator<ColumnInfo> GetEnumerator()
{
return database
.GetColumnNames(tableName)
.Select(columnName => new ColumnInfo(database, tableName, columnName))
.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
/// <summary>
/// Checks if a column exists in the table.
/// </summary>
/// <param name="columnName">Column name.</param>
/// <returns>True, if the column exists or False if it does not exist.</returns>
public bool Exists(string columnName)
{
return database.GetColumnDataType(tableName, columnName) != null;
}
/// <summary>
/// Adds a column to the table.
/// </summary>
/// <param name="columnName">Column name.</param>
/// <param name="dataType">SQL data type.</param>
/// <param name="nullable">True to allow null values.</param>
/// <param name="initialValue">Initial value to set to all existing rows.</param>
public void Add(string columnName, string dataType, bool nullable, object initialValue)
{
Validate.IsNotNullAndNotEmpty(columnName, nameof(columnName));
Validate.MaxLength(columnName, nameof(columnName), database.MaxIdentifierLength);
Validate.IsNotNullAndNotEmpty(dataType, nameof(dataType));
// Add column.
if (nullable == false && initialValue != null)
{
database.AddColumn(tableName, columnName, dataType, true);
}
else
{
database.AddColumn(tableName, columnName, dataType, nullable);
}
// Set value.
if (initialValue != null)
{
database.SetColumnValue(tableName, columnName, initialValue);
}
// Change nullable.
if (nullable == false && initialValue != null)
{
database.ChangeColumn(tableName, columnName, dataType, false);
}
}
/// <summary>
/// Adds a column to the table.
/// </summary>
/// <param name="columnName">Column name.</param>
/// <param name="dataType">SQL data type.</param>
/// <param name="nullable">True to allow null values.</param>
public void Add(string columnName, string dataType, bool nullable)
{
Add(columnName, dataType, nullable, null);
}
/// <summary>
/// Adds a column to the table.
/// </summary>
/// <param name="columnName">Column name.</param>
/// <param name="dataType">SQL data type.</param>
public void Add(string columnName, string dataType)
{
Add(columnName, dataType, false, null);
}
/// <summary>
/// Adds a column to the table.
/// </summary>
/// <param name="columnName">Column name.</param>
/// <typeparam name="TType">CLR data typed to resolve SQL data type from.</typeparam>
public void Add<TType>(string columnName)
{
Validate.IsNotNullAndNotEmpty(columnName, nameof(columnName));
var dataType = database.TypeMappings.GetDataType(typeof(TType));
if (dataType == null)
{
var type = Nullable.GetUnderlyingType(typeof(TType)) ?? typeof(TType);
throw new ArgumentException($"No type mapping could be found for type \"{type.FullName}\".", nameof(TType));
}
var nullable = Nullable.GetUnderlyingType(typeof(TType)) != null;
var initialValue = typeof(TType) == typeof(string) ? "" : (object)default(TType);
Add(columnName, dataType, nullable, initialValue);
}
/// <summary>
/// Adds a column to the table.
/// </summary>
/// <param name="columnName">Column name.</param>
/// <param name="initialValue">Initial value to set to all existing rows.</param>
/// <typeparam name="TType">CLR data typed to resolve SQL data type from.</typeparam>
public void Add<TType>(string columnName, TType initialValue)
{
Validate.IsNotNullAndNotEmpty(columnName, nameof(columnName));
var dataType = database.TypeMappings.GetDataType(typeof(TType));
if (dataType == null)
{
var type = Nullable.GetUnderlyingType(typeof(TType)) ?? typeof(TType);
throw new ArgumentException($"No type mapping could be found for type \"{type.FullName}\".", nameof(TType));
}
var nullable = Nullable.GetUnderlyingType(typeof(TType)) != null;
Add(columnName, dataType, nullable, initialValue);
}
/// <summary>
/// Adds a column to the table.
/// </summary>
/// <param name="columnName">Column name.</param>
/// <param name="length">Length of string data type.</param>
/// <param name="nullable">True to allow null values.</param>
/// <typeparam name="TType">CLR data typed to resolve SQL data type from.</typeparam>
public void Add<TType>(string columnName, int length, bool nullable)
{
Validate.IsNotNullable(typeof(TType), nameof(TType));
Validate.IsNotNullAndNotEmpty(columnName, nameof(columnName));
Validate.IsEqualOrGreaterThan(length, 1, nameof(length));
var dataType = database.TypeMappings.GetDataType(typeof(TType), length);
if (dataType == null)
{
var type = Nullable.GetUnderlyingType(typeof(TType)) ?? typeof(TType);
throw new ArgumentException($"No type mapping could be found for type \"{type.FullName}\".", nameof(TType));
}
object initialValue;
if (typeof(TType) == typeof(string) && nullable)
{
initialValue = null;
}
else if (typeof(TType) == typeof(string) && nullable == false)
{
initialValue = "";
}
else
{
initialValue = default(TType);
}
Add(columnName, dataType, nullable, initialValue);
}
/// <summary>
/// Adds a column to the table.
/// </summary>
/// <param name="columnName">Column name.</param>
/// <param name="length">Length of string data type.</param>
/// <param name="nullable">True to allow null values.</param>
/// <param name="initialValue">Initial value to set to all existing rows.</param>
/// <typeparam name="TType">CLR data typed to resolve SQL data type from.</typeparam>
public void Add<TType>(string columnName, int length, bool nullable, TType initialValue)
{
Validate.IsNotNullable(typeof(TType), nameof(TType));
Validate.IsNotNullAndNotEmpty(columnName, nameof(columnName));
Validate.IsEqualOrGreaterThan(length, 1, nameof(length));
var dataType = database.TypeMappings.GetDataType(typeof(TType), length);
if (dataType == null)
{
var type = Nullable.GetUnderlyingType(typeof(TType)) ?? typeof(TType);
throw new ArgumentException($"No type mapping could be found for type \"{type.FullName}\".", nameof(TType));
}
Add(columnName, dataType, nullable, initialValue);
}
/// <summary>
/// Adds a column to the table.
/// </summary>
/// <param name="columnName">Column name.</param>
/// <param name="scale">Scale of numeric data type.</param>
/// <param name="precision">Precision of numeric data type.</param>
/// <typeparam name="TType">CLR data typed to resolve SQL data type from.</typeparam>
public void Add<TType>(string columnName, int scale, int precision)
{
Validate.IsNotNullAndNotEmpty(columnName, nameof(columnName));
Validate.IsEqualOrGreaterThan(scale, 1, nameof(scale));
Validate.IsEqualOrGreaterThan(precision, 0, nameof(precision));
var dataType = database.TypeMappings.GetDataType(typeof(TType), scale, precision);
if (dataType == null)
{
var type = Nullable.GetUnderlyingType(typeof(TType)) ?? typeof(TType);
throw new ArgumentException($"No type mapping could be found for type \"{type.FullName}\".", nameof(TType));
}
var nullable = Nullable.GetUnderlyingType(typeof(TType)) != null;
var initialValue = typeof(TType) == typeof(string) ? "" : (object)default(TType);
Add(columnName, dataType, nullable, initialValue);
}
/// <summary>
/// Adds a column to the table.
/// </summary>
/// <param name="columnName">Column name.</param>
/// <param name="scale">Scale of numeric data type.</param>
/// <param name="precision">Precision of numeric data type.</param>
/// <param name="initialValue">Initial value to set to all existing rows.</param>
/// <typeparam name="TType">CLR data typed to resolve SQL data type from.</typeparam>
public void Add<TType>(string columnName, int scale, int precision, TType initialValue)
{
Validate.IsNotNullAndNotEmpty(columnName, nameof(columnName));
Validate.IsEqualOrGreaterThan(scale, 1, nameof(scale));
Validate.IsEqualOrGreaterThan(precision, 0, nameof(precision));
var dataType = database.TypeMappings.GetDataType(typeof(TType), scale, precision);
if (dataType == null)
{
var type = Nullable.GetUnderlyingType(typeof(TType)) ?? typeof(TType);
throw new ArgumentException($"No type mapping could be found for type \"{type.FullName}\".", nameof(TType));
}
var nullable = Nullable.GetUnderlyingType(typeof(TType)) != null;
Add(columnName, dataType, nullable, initialValue);
}
/// <summary>
/// Adds a computed column to the table.
/// </summary>
/// <param name="columnName">Column name.</param>
/// <param name="dataType">SQL data type.</param>
/// <param name="nullable">True to allow null values.</param>
/// <param name="expression">SQL expression used to compute computed value.</param>
/// <param name="persisted">True to store the computed value in the table.</param>
public void AddComputed(string columnName, string dataType, bool nullable, string expression, bool persisted = false)
{
Validate.IsNotNullAndNotEmpty(columnName, nameof(columnName));
Validate.MaxLength(columnName, nameof(columnName), database.MaxIdentifierLength);
Validate.IsNotNullAndNotEmpty(dataType, nameof(dataType));
Validate.IsNotNullAndNotEmpty(expression, nameof(expression));
database.AddComputedColumn(tableName, columnName, dataType, nullable, expression, persisted);
}
/// <summary>
/// Adds a computed column to the table.
/// </summary>
/// <param name="columnName">Column name.</param>
/// <param name="expression">SQL expression used to compute computed value.</param>
/// <param name="persisted">True to store the computed value in the table.</param>
public void AddComputed(string columnName, string expression, bool persisted = false)
{
Validate.IsNotNullAndNotEmpty(columnName, nameof(columnName));
Validate.MaxLength(columnName, nameof(columnName), database.MaxIdentifierLength);
Validate.IsNotNullAndNotEmpty(expression, nameof(expression));
database.AddComputedColumn(tableName, columnName, null, false, expression, persisted);
}
/// <summary>
/// Adds a computed column to the table.
/// </summary>
/// <param name="columnName">Column name.</param>
/// <param name="expression">SQL expression used to compute computed value.</param>
/// <param name="persisted">True to store the computed value in the table.</param>
/// <typeparam name="TType">CLR data typed to resolve SQL data type from.</typeparam>
public void AddComputed<TType>(string columnName, string expression, bool persisted = false)
{
Validate.IsNotNullAndNotEmpty(columnName, nameof(columnName));
Validate.IsNotNullAndNotEmpty(expression, nameof(expression));
var dataType = database.TypeMappings.GetDataType(typeof(TType));
if (dataType == null)
{
var type = Nullable.GetUnderlyingType(typeof(TType)) ?? typeof(TType);
throw new ArgumentException($"No type mapping could be found for type \"{type.FullName}\".", nameof(TType));
}
var nullable = Nullable.GetUnderlyingType(typeof(TType)) != null;
AddComputed(columnName, dataType, nullable, expression, persisted);
}
/// <summary>
/// Adds a computed column to the table.
/// </summary>
/// <param name="columnName">Column name.</param>
/// <param name="length">Length of string data type.</param>
/// <param name="nullable">True to allow null values.</param>
/// <param name="expression">SQL expression used to compute computed value.</param>
/// <param name="persisted">True to store the computed value in the table.</param>
/// <typeparam name="TType">CLR data typed to resolve SQL data type from.</typeparam>
public void AddComputed<TType>(string columnName, int length, bool nullable, string expression, bool persisted = false)
{
Validate.IsNotNullable(typeof(TType), nameof(TType));
Validate.IsNotNullAndNotEmpty(columnName, nameof(columnName));
Validate.IsEqualOrGreaterThan(length, 1, nameof(length));
Validate.IsNotNullAndNotEmpty(expression, nameof(expression));
var dataType = database.TypeMappings.GetDataType(typeof(TType), length);
if (dataType == null)
{
var type = Nullable.GetUnderlyingType(typeof(TType)) ?? typeof(TType);
throw new ArgumentException($"No type mapping could be found for type \"{type.FullName}\".", nameof(TType));
}
AddComputed(columnName, dataType, nullable, expression, persisted);
}
/// <summary>
/// Adds a computed column to the table.
/// </summary>
/// <param name="columnName">Column name.</param>
/// <param name="scale">Scale of numeric data type.</param>
/// <param name="precision">Precision of numeric data type.</param>
/// <param name="expression">SQL expression used to compute computed value.</param>
/// <param name="persisted">True to store the computed value in the table.</param>
/// <typeparam name="TType">CLR data typed to resolve SQL data type from.</typeparam>
public void AddComputed<TType>(string columnName, int scale, int precision, string expression, bool persisted = false)
{
Validate.IsNotNullAndNotEmpty(columnName, nameof(columnName));
Validate.IsEqualOrGreaterThan(scale, 1, nameof(scale));
Validate.IsEqualOrGreaterThan(precision, 0, nameof(precision));
Validate.IsNotNullAndNotEmpty(expression, nameof(expression));
var dataType = database.TypeMappings.GetDataType(typeof(TType), scale, precision);
if (dataType == null)
{
var type = Nullable.GetUnderlyingType(typeof(TType)) ?? typeof(TType);
throw new ArgumentException($"No type mapping could be found for type \"{type.FullName}\".", nameof(TType));
}
var nullable = Nullable.GetUnderlyingType(typeof(TType)) != null;
AddComputed(columnName, dataType, nullable, expression, persisted);
}
/// <summary>
/// Rename a column in the table.
/// </summary>
/// <param name="currentColumnName">Current name of column.</param>
/// <param name="newColumnName">New name of column.</param>
public void Rename(string currentColumnName, string newColumnName)
{
Validate.IsNotNullAndNotEmpty(currentColumnName, nameof(currentColumnName));
Validate.MaxLength(currentColumnName, nameof(currentColumnName), database.MaxIdentifierLength);
Validate.IsNotNullAndNotEmpty(newColumnName, nameof(newColumnName));
Validate.MaxLength(newColumnName, nameof(newColumnName), database.MaxIdentifierLength);
database.RenameColumn(tableName, currentColumnName, newColumnName);
}
/// <summary>
/// Removes a column from the table.
/// </summary>
/// <param name="columnName">Column name.</param>
public void Remove(string columnName)
{
Validate.IsNotNullAndNotEmpty(columnName, nameof(columnName));
Validate.MaxLength(columnName, nameof(columnName), database.MaxIdentifierLength);
database.RemoveColumn(tableName, columnName);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.EntityFrameworkCore;
using AtendimentoProntoSocorro.Data;
using AtendimentoProntoSocorro.Models;
using AtendimentoProntoSocorro.Repositories;
namespace AtendimentoProntoSocorro.Controllers
{
public class PacienteController : Controller
{
private readonly ApplicationDbContext _context;
private readonly IPacienteRepository pacienteRepository;
public PacienteController(ApplicationDbContext context, IPacienteRepository pacienteRepository)
{
_context = context;
this.pacienteRepository = pacienteRepository;
}
public async Task<IActionResult> Busca(string searchString)
{
var isAjax = Request.Headers["X-Requested-With"] == "XMLHttpRequest";
if (isAjax)
{
var pacientes = await pacienteRepository.ListaPaciente(searchString);
//if (pacientes != null)
//{
if (pacientes.Count() == 0)
{
TempData["AlertMessage"] = "Nenhum registro encontrado!";
}
return PartialView("_Busca", pacientes.ToList());
//}
}
return View();
}
public IActionResult Index()
{
return View();
}
public async Task<IActionResult> Lista(long cpf)
{
if (!ModelState.IsValid)
{
return RedirectToAction(nameof(Index));
}
/// uma das formas de fazer consulta
var paciente = await pacienteRepository.GetPaciente(cpf); //_context.Paciente.Where(m => m.CPF == cpf).FirstOrDefault();
if (paciente == null)
{
return RedirectToAction(nameof(Create));
}
return View(paciente);
}
// GET: Pacientes/Details/5
public async Task<IActionResult> Details(long cpf)
{
if (!ModelState.IsValid)
{
return RedirectToAction(nameof(Index));
}
/// uma das formas de fazer consulta
var paciente = await pacienteRepository.GetPaciente(cpf); //_context.Paciente.Where(m => m.CPF == cpf).FirstOrDefault();
if (paciente == null)
{
return RedirectToAction(nameof(Create));
}
return View(paciente);
}
// GET: Pacientes/Create
public IActionResult Create()
{
return View();
}
// POST: Pacientes/Create
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create([Bind("CPF,RG,CartaoSUS,Nome,DataNascimento,Sexo,RacaId,Logradouro,NumeroLogradouro,Complemento,Bairro,Municipio,UF,CEP,NomeMae,NomePai,Responsavel,Telefone1,Telefone2,Email,NumeroProntuario,RegistroFuncional,InformacaoComplementar,GeneroPaciente,EtiniaPaciente,OrigemFuncionario")] Paciente paciente)
{
if (ModelState.IsValid)
{
_context.Add(paciente);
await _context.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
return View(paciente);
}
// GET: Pacientes/Edit/5
public async Task<IActionResult> Edit(long? id)
{
if (id == null)
{
return NotFound();
}
var paciente = await _context.Pacientes.FindAsync(id);
if (paciente == null)
{
return NotFound();
}
return View(paciente);
}
// POST: Pacientes/Edit/5
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Edit(long id, [Bind("CPF,RG,CartaoSUS,Nome,DataNascimento,Sexo,RacaId,Logradouro,NumeroLogradouro,Complemento,Bairro,Municipio,UF,CEP,NomeMae,NomePai,Responsavel,Telefone1,Telefone2,Email,NumeroProntuario,RegistroFuncional,InformacaoComplementar")] Paciente paciente)
{
if (id != paciente.CPF)
{
return NotFound();
}
if (ModelState.IsValid)
{
try
{
_context.Update(paciente);
await _context.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException)
{
if (!PacienteExists(paciente.CPF))
{
return NotFound();
}
else
{
throw;
}
}
return RedirectToAction(nameof(Index));
}
return View(paciente);
}
// GET: Pacientes/Delete/5
public async Task<IActionResult> Delete(long? cpf)
{
if (cpf == null)
{
return NotFound();
}
var paciente = await _context.Pacientes
.FirstOrDefaultAsync(m => m.CPF == cpf);
if (paciente == null)
{
return NotFound();
}
return View(paciente);
}
// POST: Pacientes/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public async Task<IActionResult> DeleteConfirmed(long id)
{
var paciente = await _context.Pacientes.FindAsync(id);
_context.Pacientes.Remove(paciente);
await _context.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
private bool PacienteExists(long id)
{
return _context.Pacientes.Any(e => e.CPF == id);
}
}
}
|
/* Xiufeng Xie did the function implementation of 3D mouse */
/* Yuye Wamg did the layout and integration */
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Text;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Windows.Threading;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using Microsoft.Devices;
using Microsoft.Devices.Sensors;
using Microsoft.Xna.Framework;
//using System.Windows.DependencyObject;
namespace sdkAppBarCS
{
public partial class Page3Dmouse : PhoneApplicationPage
{
Motion motion;
Double[] attitude = new double[3];
Vector3 acceleration;
bool canStart = false;
String default_IP = "192.168.16.2";
//String default_IP = "72.33.244.171";
int default_Port = 13001;
int controlClick = 0;
public Page3Dmouse()
{
InitializeComponent();
motion = new Motion();
// Specify the desired time between updates. The sensor accepts
// intervals in multiples of 1s.
motion.TimeBetweenUpdates = TimeSpan.FromMilliseconds(30);
motion.CurrentValueChanged += new
EventHandler<SensorReadingEventArgs<MotionReading>>(motion_CurrentValueChanged);
motion.Start();
#region initialize server name and port number
(Application.Current as App).HostName = sdkAppBarCS.PanoramaPage.connectIP;
(Application.Current as App).PortNumber = sdkAppBarCS.PanoramaPage.connectPort;
#endregion
}
#region Update sensor data
void motion_CurrentValueChanged(object sender,
SensorReadingEventArgs<MotionReading> e)
{
if (motion.IsDataValid)
{
attitude[0] = MathHelper.ToDegrees(e.SensorReading.Attitude.Yaw);
attitude[1] = MathHelper.ToDegrees(e.SensorReading.Attitude.Pitch);
attitude[2] = MathHelper.ToDegrees(e.SensorReading.Attitude.Roll);
acceleration = e.SensorReading.DeviceAcceleration;
}
}
#endregion
#region send data receive feedback
void receive_Data(object sender, ResponseReceivedEventArgs e)
{
//receive data from the server, display it
//textBlock_Test.Text = e.response;
if (motion.IsDataValid & canStart)
{
AsynchronousClient client = new AsynchronousClient((Application.Current as App).HostName, 13001);
client.ResponseReceived += new ResponseReceivedEventHandler(receive_Data);
String stringToSend = ("3" + "|"
+ attitude[1].ToString("0.00") + "|" + attitude[2].ToString("0.00")
+ "|" + controlClick.ToString("0"));
client.SendData(stringToSend);
//reset after button command is sent
controlClick = 0;
}
if (e.response == "1")
{
VibrateController vibrate = VibrateController.Default;
vibrate.Start(TimeSpan.FromMilliseconds(30));
}
}
#endregion
private void button3Dleft_Tap(object sender, GestureEventArgs e)
{
controlClick = 1;
}
private void button3Dleft_DoubleTap(object sender, GestureEventArgs e)
{
controlClick = 2;
}
private void button3Dright_Tap(object sender, GestureEventArgs e)
{
controlClick = 3;
}
private void button3Dright_DoubleTap(object sender, GestureEventArgs e)
{
controlClick = 4;
}
//**********************************************************
// Below is page navigation
private void Button1_Click(object sender, EventArgs e)
{
NavigationService.Navigate(new Uri("/PanoramaPage.xaml?goto=2", UriKind.Relative));
}
private void Button2_Click(object sender, EventArgs e)
{
//let the connection start
if (canStart == false)
{
canStart = true;
}
else
{
canStart = false;
MessageBox.Show("Pause! ");
}
#region transmit data for the first time
AsynchronousClient client = new AsynchronousClient((Application.Current as App).HostName, 13001);
client.ResponseReceived += new ResponseReceivedEventHandler(receive_Data);
String stringToSend = ("3" + "|"
+ attitude[1].ToString("0.00") + "|" + attitude[2].ToString("0.00")
+ "|" + controlClick.ToString("0"));
client.SendData(stringToSend);
//reset after button command is sent
controlClick = 0;
#endregion
}
private void Button3_Click(object sender, EventArgs e)
{
NavigationService.Navigate(new Uri("/PanoramaPage.xaml?goto=1", UriKind.Relative));
}
private void Button4_Click(object sender, EventArgs e)
{
NavigationService.Navigate(new Uri("/HelpPage.xaml", UriKind.Relative));
}
}
} |
using Microsoft.Extensions.Logging;
using RabbitMQ.Client.Core.DependencyInjection.MessageHandlers;
using RabbitMQ.Client.Events;
using VetClinicPublic.Web.Interfaces;
namespace VetClinicPublic.Web.Services
{
public class CustomMessageHandler : IMessageHandler
{
readonly ILogger<CustomMessageHandler> _logger;
private readonly ISendConfirmationEmails _emailSender;
public CustomMessageHandler(ILogger<CustomMessageHandler> logger,
ISendConfirmationEmails emailSender)
{
_logger = logger;
_emailSender = emailSender;
}
public void Handle(BasicDeliverEventArgs eventArgs, string matchingRoute)
{
// Do whatever you want with the message.
_logger.LogInformation("Message Received - Sending Email!");
System.Threading.Thread.Sleep(500);
// send email
}
}
}
|
using ExitGames.Client.Photon;
using Photon.Pun;
using Photon.Realtime;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class EndGameLeaderboard : MonoBehaviour
{
private void OnEnable()
{
GameObject localPlayer = (GameObject)PhotonNetwork.LocalPlayer.TagObject;
if (localPlayer != null)
{
if (localPlayer.GetPhotonView().ViewID == World.currentWorld.playerList[0].playerID)
{
GameObject winnerObj = World.currentWorld.playerList[0].playerGameObject;
Car winnerCar = winnerObj.GetComponent<Car>();
winnerCar.RemoveBomb();
CameraController cameraRig = GameObject.FindGameObjectWithTag("CameraRig").GetComponent<CameraController>();
cameraRig.SetGameOverPosition();
Car_Control winnerControl = winnerObj.GetComponent<Car_Control>();
winnerControl.enabled = false;
winnerControl.MotorForce = 0;
winnerControl.SteerForce = 0;
byte evCode = 4; // Custom Event 4: Used as "DisplayLeaderboard" event
object[] content = new object[] { }; // Name of random car to recieve the bomb after past bomb holder blows up
RaiseEventOptions raiseEventOptions = new RaiseEventOptions { Receivers = ReceiverGroup.All };
SendOptions sendOptions = new SendOptions { Reliability = true };
PhotonNetwork.RaiseEvent(evCode, content, raiseEventOptions, sendOptions);
}
}
}
}
|
namespace Project
{
interface IManager
{
void DisableComponent();
void EnableComponent();
}
}
|
using System.Collections.Generic;
using InRule.Authoring.Commanding;
using InRule.Authoring.Services;
using InRule.Repository;
using InRuleLabs.AuthoringExtensions.GenerateSDKCode.Features.GenerateSDKCode;
namespace InRuleLabs.AuthoringExtensions.GenerateSDKCode.Extension
{
public class GenerateSDKCodeCommandProvider : ICommandProvider
{
private readonly ServiceManager _serviceManager;
private readonly RuleApplicationService _ruleApplicationService;
public GenerateSDKCodeCommandProvider(ServiceManager serviceManager)
{
_serviceManager = serviceManager;
_ruleApplicationService = serviceManager.GetService<RuleApplicationService>();
}
public IEnumerable<IVisualCommand> GetCommands(object o)
{
var def = o as RuleRepositoryDefBase;
var commands = new List<IVisualCommand>();
var controller = _ruleApplicationService.Controller;
if (def != null)
{
commands.Add(_serviceManager.Compose<ShowSDKCodeCommand>(def));
commands.Add(_serviceManager.Compose<ShowSDKCodeCommand>(def.GetRuleApp()));
}
return commands;
}
}
}
|
using System;
using System.Globalization;
using System.Net.Http;
using System.Threading.Tasks;
using Microsoft.AspNetCore.SignalR.Client;
namespace SocketTraining.Client
{
internal static class ChatHandlers
{
private static string _userName;
public static async Task Chat()
{
var connection = new HubConnectionBuilder()
.WithUrl("http://localhost:5005/chathub")
.Build();
var msg = "";
Console.Write("Name>");
_userName = Console.ReadLine();
try
{
await Connect(connection);
}
catch (HttpRequestException)
{
Console.WriteLine("Server not availible,press any key to exit");
Console.ReadKey();
msg = "exit";
}
while (msg != "exit")
{
msg = Console.ReadLine();
switch (msg)
{
case "getChat":
await connection.InvokeAsync("GetHistory", _userName);
break;
default:
await connection.InvokeAsync("AddMessage", msg, _userName);
break;
}
}
await connection.StopAsync();
}
private static async Task Connect(HubConnection connection)
{
connection.On<string, string>("getNewMessage",
(message, user) =>
{
if (user != _userName)
Console.WriteLine($"[{DateTime.Now.ToString(CultureInfo.CurrentCulture)}] {user}: {message}");
});
connection.On<string>("recieveChatHistory",
result =>
{
Console.WriteLine($"Chat history:\n{result}");
});
await connection.StartAsync();
}
}
} |
using Assets.Code.Actors;
using Assets.Code.Items;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class KeyItem : MonoBehaviour {
void OnTriggerEnter(Collider collider)
{
if (collider.gameObject.name == "Player")
{
UIPopupTextController.CreatePopupText("Key picked up", transform);
var inventory = Player.Inventory;
inventory.AddKey();
Destroy(gameObject);
}
}
}
|
namespace ProgFrog.Interface.TaskRunning.Runners
{
public class ExecRunResults
{
public bool IsError { get; set; }
public string Results { get; set; }
}
}
|
using EPiServer.Shell.ObjectEditing;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace EpiserverSiteFromScratch.Business
{
public class LanguageSelectionFactory: ISelectionFactory
{
public IEnumerable<ISelectItem> GetSelections(ExtendedMetadata metadata)
{
return new ISelectItem[] { new SelectItem() { Text = "English", Value = "EN" }, new SelectItem() { Text = "Guinean", Value = "GN" } };
}
}
} |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Input;
using ApartmentApps.Client;
using ApartmentApps.Client.Models;
using MvvmCross.Core.ViewModels;
using MvvmCross.Plugins.Messenger;
using ResidentAppCross.Commands;
using ResidentAppCross.Extensions;
using ResidentAppCross.Resources;
namespace ResidentAppCross.ViewModels.Screens
{
public class NotificationIndexFormViewModel : ViewModelBase
{
private NotificationStatusFilter _currentNotificationStatusFilter;
private ObservableCollection<NotificationStatusFilter> _notificationStatusFilters;
private ObservableCollection<AlertBindingModel> _filteredNotifications;
private AlertBindingModel _selectedNotification;
private ObservableCollection<AlertBindingModel> _notifications;
private IApartmentAppsAPIService _service;
public NotificationIndexFormViewModel(IApartmentAppsAPIService service)
{
_service = service;
}
public AlertBindingModel SelectedNotification
{
get { return _selectedNotification; }
set { SetProperty(ref _selectedNotification,value); }
}
public ObservableCollection<AlertBindingModel> FilteredNotifications
{
get { return _filteredNotifications ?? (FilteredNotifications = new ObservableCollection<AlertBindingModel>()); }
set { SetProperty(ref _filteredNotifications, value); }
}
public ObservableCollection<AlertBindingModel> Notifications
{
get { return _notifications ?? (Notifications = new ObservableCollection<AlertBindingModel>()); }
set { SetProperty(ref _notifications, value); }
}
public ObservableCollection<NotificationStatusFilter> NotificationStatusFilters
{
get { return _notificationStatusFilters ?? (NotificationStatusFilters = new ObservableCollection<NotificationStatusFilter>()); }
set { SetProperty(ref _notificationStatusFilters,value); }
}
public NotificationStatusFilter CurrentNotificationStatusFilter
{
get { return _currentNotificationStatusFilter; }
set
{
SetProperty(ref _currentNotificationStatusFilter,value);
UpdateFilters();
}
}
public ICommand UpdateNotificationsCommand
{
get
{
return this.TaskCommand(async context =>
{
var task = await _service.Alerts.GetWithOperationResponseAsync();
Notifications.Clear();
Notifications.AddRange(task.Body);
UpdateFilters();
}).OnStart("Fetching Notifications...");
}
}
public ICommand OpenSelectedNotificationDetailsCommand => new MvxCommand(() =>
{
if (SelectedNotification?.RelatedId == null) return;
SelectedNotification.HasRead = true;
var alertId = SelectedNotification?.Id;
if (alertId.HasValue)
Task.Run(()=> _service.Alerts.PostWithOperationResponseAsync(alertId.Value));
if (SelectedNotification.Type == "Maintenance")
{
ShowViewModel<MaintenanceRequestStatusViewModel>(vm =>
{
vm.MaintenanceRequestId = SelectedNotification.RelatedId.Value;
});
}
else if (SelectedNotification.Type == "Courtesy")
{
ShowViewModel<IncidentReportStatusViewModel>(vm =>
{
vm.IncidentReportId = SelectedNotification.RelatedId.Value;
});
}
else
{
ShowViewModel<MessageDetailsViewModel>(vm =>
{
vm.Data = SelectedNotification;
});
}
//ShowViewModel<NotificationDetailsFormViewModel>();
});
public override void Start()
{
base.Start();
NotificationStatusFilters.Clear();
var defaultStatusFilter = new NotificationStatusFilter()
{
MarkerTitle = "Filtered: Unread",
Title = "Unread",
FilterExpression = item => !item.HasRead.HasValue || !item.HasRead.Value
};
NotificationStatusFilters.Add(defaultStatusFilter);
NotificationStatusFilters.Add(new NotificationStatusFilter()
{
MarkerTitle = null,
Title = "All",
FilterExpression = item => true
});
CurrentNotificationStatusFilter = defaultStatusFilter;
UpdateNotificationsCommand.Execute(null);
}
private void UpdateFilters()
{
FilteredNotifications.Clear();
FilteredNotifications.AddRange(Notifications.Where(item => (CurrentNotificationStatusFilter?.FilterExpression(item) ?? true)));
this.Publish(new NotificationFiltersUpdatedEvent(this));
}
}
public class NotificationFiltersUpdatedEvent : MvxMessage
{
public NotificationFiltersUpdatedEvent(object sender) : base(sender)
{
}
}
public class NotificationStatusFilter
{
public string Title { get; set; }
public Func<AlertBindingModel, bool> FilterExpression { get; set; }
public string MarkerTitle { get; set; }
}
}
|
using System;
using iSukces.Code.Interfaces;
using iSukces.Code.Serenity;
using Xunit;
namespace iSukces.Code.Tests.Serenity
{
public class SerenityEntityBuilderTests
{
[Fact]
public void T01()
{
var a = new SerenityEntityBuilder("Sample", "Cloud", "Common");
a.WithConnectionKey("Piotr")
.WithTableName("dbo.Table");
a.AddProperty<int>("Id")
.WithDisplayName("identifier")
.WithColumn("idx")
.WithIdRow()
.WithPrimaryKey();
a.AddStringProperty("Name", 32)
.WithNameRow();
a.AddProperty<Guid>("Uid")
.WithQuickFilter()
.WithNotNull()
.WithQuickSearch();
a.AddProperty<bool>("SomeFlag")
.WithQuickFilter()
.WithNotNull();
a.AddProperty<DateTime>("CreationDate")
.WithQuickFilter()
.WithNotNull();
a.AddProperty<SomeEnum32>("Kind32")
.WithQuickFilter()
.WithNotNull();
a.AddProperty<SomeEnum16>("Kind16")
.WithQuickFilter()
.WithNotNull()
.WithFileUpload(aa =>
{
aa.FilenameFormat = "Documents/~";
aa.CopyToHistory = true;
aa.OriginalNameProperty = "Name";
aa.AllowNonImage = true;
aa.DisableDefaultBehavior = true;
});
a.AddProperty<short>("MyInt16");
a.AddProperty<long>("MyInt64");
var file = new CsFile();
file.AddImportNamespace(typeof(SomeEnum32));
a.Build(file);
ICsCodeWriter w = new CsCodeWriter();
file.MakeCode(w);
var newExpected = Encode(w.Code);
var expected= @"// ReSharper disable All
using iSukces.Code.Tests.Serenity;
namespace Cloud.Common
{
using Serenity.Data;
using Serenity.Data.Mapping;
using System;
using System.ComponentModel;
[ConnectionKey(""Piotr"")]
[TableName(""dbo.Table"")]
public class SampleRow : Row, IIdRow, INameRow
{
public SampleRow()
: (Fields)
{
}
[Column(""idx"")]
[DisplayName(""identifier"")]
[PrimaryKey]
public int? Id
{
get { return Fields.Id[this]; }
set { Fields.Id[this] = value; }
}
[Column(""Name"")]
[DisplayName(""Name"")]
[Size(32)]
public string Name
{
get { return Fields.Name[this]; }
set { Fields.Name[this] = value; }
}
[Column(""Uid"")]
[DisplayName(""Uid"")]
[NotNull]
[Serenity.ComponentModel.QuickFilter]
[QuickSearch]
public Guid? Uid
{
get { return Fields.Uid[this]; }
set { Fields.Uid[this] = value; }
}
[Column(""SomeFlag"")]
[DisplayName(""SomeFlag"")]
[NotNull]
[Serenity.ComponentModel.QuickFilter]
public bool? SomeFlag
{
get { return Fields.SomeFlag[this]; }
set { Fields.SomeFlag[this] = value; }
}
[Column(""CreationDate"")]
[DisplayName(""CreationDate"")]
[NotNull]
[Serenity.ComponentModel.QuickFilter]
public DateTime? CreationDate
{
get { return Fields.CreationDate[this]; }
set { Fields.CreationDate[this] = value; }
}
[Column(""Kind32"")]
[DisplayName(""Kind32"")]
[NotNull]
[Serenity.ComponentModel.QuickFilter]
public SomeEnum32? Kind32
{
get { return (SomeEnum32?)Fields.Kind32[this]; }
set { Fields.Kind32[this] = (int?)value; }
}
[Column(""Kind16"")]
[DisplayName(""Kind16"")]
[Serenity.ComponentModel.FileUploadEditor(AllowNonImage = true,OriginalNameProperty = ""Name"",CopyToHistory = true,FilenameFormat = ""Documents/~"",DisableDefaultBehavior = true)]
[NotNull]
[Serenity.ComponentModel.QuickFilter]
public SomeEnum16? Kind16
{
get { return (SomeEnum16?)Fields.Kind16[this]; }
set { Fields.Kind16[this] = (short?)value; }
}
[Column(""MyInt16"")]
[DisplayName(""MyInt16"")]
public short? MyInt16
{
get { return Fields.MyInt16[this]; }
set { Fields.MyInt16[this] = value; }
}
[Column(""MyInt64"")]
[DisplayName(""MyInt64"")]
public long? MyInt64
{
get { return Fields.MyInt64[this]; }
set { Fields.MyInt64[this] = value; }
}
IIdField IIdRow.IdField
{
get { return Fields.Id }
}
StringField INameRow.IdField
{
get { return Fields.Name }
}
public readonly RowFields Fields = new RowFields().Init();
public class RowFields : RowFieldsBase
{
public Int32Field Id;
public StringField Name;
public GuidField Uid;
public BooleanField SomeFlag;
public DateTimeField CreationDate;
public Int32Field Kind32;
public Int16Field Kind16;
public Int16Field MyInt16;
public Int64Field MyInt64;
}
}
}
";
Assert.Equal(expected, w.Code);
}
private static string Encode(string c)
{
c = c.Replace("\"", "\"\"");
c = "@\"" + c + "\"";
return c;
}
}
public enum SomeEnum32:int {One, Two, Three}
public enum SomeEnum16:short {One, Two, Three}
} |
using OpenQA.Selenium;
using OpenQA.Selenium.Firefox;
using OpenQA.Selenium.Support.PageObjects;
using OpenQA.Selenium.Support.UI;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace HotlineAutoTest.pages
{
public class GooglePage:PageObject
{
IWebDriver driver = new FirefoxDriver();
[FindsBy(How = How.CssSelector, Using = "#lst-ib")]
private IWebElement searchField;
public GooglePage(IWebDriver driver):base(driver)
{
Url = "https://www.google.com.ua/";
}
public override void ToUrl(string _url)
{
driver.Navigate().GoToUrl(Url);
}
public void SendRequest(string _text)
{
searchField.SendKeys(_text);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Reflection;
namespace iSukces.Code;
public static class CodeReflectionUtils
{
public static IReadOnlyList<PropertyInfo> GetInstanceProperties(this Type type)
{
const BindingFlags allInstanceProperties =
BindingFlags.Instance
| BindingFlags.Public
| BindingFlags.NonPublic;
return type
#if COREFX
.GetTypeInfo()
#endif
.GetProperties(allInstanceProperties);
}
} |
using System;
using System.Collections.Generic;
using System.Reflection.Metadata.Ecma335;
using System.Runtime.CompilerServices;
namespace EmployeeWages
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Welcome to Employee Wage Computation Program");
Console.WriteLine("=============================================");
EmpWageBuilder allCompanyWages = new EmpWageBuilder();
bool cont = true;
int option;
while (cont)
{
Console.WriteLine("Enter\n" +
"1 : Enter Company Details\n" +
"2 : Retrieve all Monthly Wage Details\n" +
"3 : Retrieve Monthly Wage of one company\n" +
"4 : Print daily Wages of a company\n" +
"0 : Exit");
option = Int32.Parse(Console.ReadLine());
switch(option)
{
case 0:
cont = false;
break;
case 1:
Console.Write("Number of Company details you want to enter : ");
int numDetail = Int32.Parse(Console.ReadLine());
List<Company> companyList = new List<Company>();
Company company = new Company();
for(int i=0; i<numDetail; i++)
{
company.CompanyWageProfile();
companyList.Add(company);
}
allCompanyWages.AddCompanies(companyList);
break;
case 2:
allCompanyWages.PrintAllCompanyWages();
Console.WriteLine();
break;
case 3:
Console.Write("Enter Company Name :");
int wageOfCompany = allCompanyWages.RetrieveWageByCompany(Console.ReadLine());
Console.WriteLine(wageOfCompany);
break;
case 4:
Console.Write("Enter Company Name :");
allCompanyWages.PrintDailyWage(Console.ReadLine());
break;
default:
Console.WriteLine("Wrong Option choosed");
break;
}
}
Console.WriteLine("Thanks for use Employee Wage Computation Program");
return;
}
}
}
|
using Game.Entity.NativeWeb;
using Game.Facade;
using Game.Utils;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace Game.Web
{
public partial class QrDownload : System.Web.UI.Page
{
protected string downloadURL = string.Empty;
protected string gameIcoURL = string.Empty;
protected string gameName = string.Empty;
protected string gameSize = string.Empty;
protected string gameDate = string.Empty;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
int KindID = GameRequest.GetQueryInt("KindID", -1);
downloadURL = string.Format("http://" + Request.Url.Authority.ToString() + "/DownLoadMB.aspx?KindID={0}", KindID);
//获取游戏信息
GameRulesInfo Info = FacadeManage.aideNativeWebFacade.GetGameHelp(KindID);
if (Info != null)
{
gameIcoURL = Info.ThumbnailUrl;
gameName = Info.KindName + " 手机版" + Info.MobileVersion;
gameSize = Info.MobileSize;
gameDate = Info.MobileDate;
}
}
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ValidationExtensions.Exception
{
public class CommunicationException : System.Exception
{
private System.Exception exc;
public CommunicationException(System.Exception exc)
{
this.exc = exc;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using KartObjects;
namespace KartSystem
{
[Serializable]
public class ParameterDocumentPrintForm : Entity
{
public override string FriendlyName
{
get { return "Настроки просмотра документов"; }
}
public string File1 { get; set; }
public string File2 { get; set; }
public string File3 { get; set; }
public string File4 { get; set; }
public string File5 { get; set; }
}
}
|
namespace Sind.Model
{
public enum TipoCalculoEnum
{
Manual = 1,
Banco,
Formula
}
} |
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity.ModelConfiguration;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Welic.Dominio.Models.City.Map;
namespace Infra.Mapeamentos
{
public class MappingCity : EntityTypeConfiguration<CityMap>
{
public MappingCity()
{
// Primary Key
this.HasKey(t => t.IdCity);
// Properties
this.Property(t => t.Nome)
.IsRequired()
.HasMaxLength(256);
this.Property(x => x.IdCity)
.IsRequired()
.HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
this.Property(x => x.Estado)
.IsRequired();
this.Property(x => x.Cep)
.IsRequired();
// Table & Column Mappings
this.ToTable("City");
this.Property(t => t.IdCity).HasColumnName("IdCity");
this.Property(t => t.Nome).HasColumnName("Nome");
this.Property(x => x.Estado).HasColumnName("Estado");
this.Property(x => x.Cep).HasColumnName("Cep");
}
}
}
|
using System;
using System.Drawing;
using Newtonsoft;
using Microsoft.AspNet.Identity;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.EntityFramework;
using System.Web.Http.Cors;
using System.Threading.Tasks;
using webApi2;
using System.Net;
using System.Web.Http;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using System.Web;
using System.IO;
namespace WebApi2.Controllers
{
// [EnableCors(origins: "http://localhost:81", headers: "*", methods: "*")]
//[EnableCors(origins: "http://localhost:81", headers: "*",methods: "*", SupportsCredentials = true)]
[RoutePrefix("api/Values")]
public class ValuesController : ApiController
{
private Workinstruction_testEntities entity = new Workinstruction_testEntities();
public HttpResponseMessage Options() {
return new HttpResponseMessage { StatusCode = HttpStatusCode.OK };
}
// KPI_Datamart_1Entities1 db = new KPI_Datamart_1Entities1();
// GET api/values
[Authorize(Users = "ensco\\011311")]
[Route("")]
public IEnumerable< aaWi> Get() {
//return db.a0.Select(s => new { s.name });
string s = User.Identity.Name;
//UserManager = new UserManager<ApplicationUser, string>(new UserStore<ApplicationUser, CustomRole, string, CustomUserLogin, CustomUserRole, CustomUserClaim>(new myDbContext()));
//UserManager<IdentityUser> userManager=new UserManager<IdentityUser>();
// RoleManager<IdentityRole> rolesManager;
//userManager.AddToRole("011311", "admin");
return this.entity.aaWis;
}
[Route("equipment/{id:int=0}")]
public IHttpActionResult GetEquipment(int? id ) {
string sql = "select id, name from equipmentType where lang='e' ";
if (id != 0)
sql = "select id, name from equipmentMake where lang='e' and equipmentTypeId= " + id.ToString();
sql = "select 0 as id, '' as name union " +sql ;
var data = this.entity.Database.SqlQuery<MyList>(sql);
return Ok(data);
}
//GET api/values/5
[Route("{id:int}")]
public IHttpActionResult Get(int id) {
var wi = this.entity.aaWis.Where(t => t.id == id).FirstOrDefault();
var js = this.entity.aaJobSteps.Where(t => t.wiid == id);
// var obj = new { "result":"fail"};
return Ok( new {
header = wi,
jobSteps = js
}) ;
}
// ClaimsIdentityFactory
// POST api/values
public string wPost() {
var httpRequest = HttpContext.Current.Request;
return this.UpdateFiles(httpRequest.Files);
}
[HttpPost]
[Route("")]
public int Post( MyModel m ) {
using (var tran = this.entity.Database.BeginTransaction()) {
try {
//this.entity.Entry(m.header).State = System.Data.Entity.EntityState.Modified ;
this.entity.SaveChanges();
if (m.header.id == 0) {
aaWi header= this.entity.aaWis.Add(m.header);
this.entity.SaveChanges();
m.header.id = header.id;
} else {
this.entity.Entry(m.header).State = System.Data.Entity.EntityState.Modified;
}
int wiid = m.header.id;
foreach (aaJobStep js in m.jobSteps)
js.wiid = wiid;
List<int> list = m.jobSteps.Select(j => j.id).ToList();
var deleted = this.entity.aaJobSteps.Where(j => j.wiid == wiid && !list.Contains(j.id));
this.entity.aaJobSteps.RemoveRange(deleted);
var added = m.jobSteps.Where(t => t.id == 0);
this.entity.aaJobSteps.AddRange(added);
var updated= this.entity.aaJobSteps.Where(j => j.wiid == wiid && list.Contains(j.id));
foreach(aaJobStep js in m.jobSteps) {
if (!list.Contains(js.id) || js.id==0)
continue;
this.entity.Entry(js).State = System.Data.Entity.EntityState.Modified;
}
//this.entity.Entry()
this.entity.SaveChanges();
tran.Commit();
return wiid;
} catch (Exception e) {
tran.Rollback();
throw;
}
}
return 0;
}
[HttpPost]
[Route("file")]
public string Post() {
var httpRequest = HttpContext.Current.Request;
return this.UpdateFiles(httpRequest.Files);
}
string UpdateFiles(HttpFileCollection files) {
string imgFolder = @"c:\dev\emoc\images\";
try {
foreach (string name in files) {
HttpPostedFile file = files[name];
string guid = Guid.NewGuid().ToString() + Path.GetExtension(file.FileName);
file.SaveAs(imgFolder +guid);
return guid;
}
} catch (Exception ex) {
return ex.Message;
}
return "OK";
}
void UpdatePhoto( aaJobStep jobStep ) {
string photo = jobStep.photo;
string name = jobStep.note;
if (name == "")
return;
string imgFolder = @"c:\dev\emoc\images\";
string guid = Guid.NewGuid().ToString() + Path.GetExtension(name);
var myString = photo.Split(new char[] { ',' });
byte[] bytes = Convert.FromBase64String(myString[1]);
using (MemoryStream ms = new MemoryStream(bytes)) {
Image image = Image.FromStream(ms);
image.Save( imgFolder+ guid ) ;
}
jobStep.photo = guid;
jobStep.note = "";
}
// PUT api/values/5
[Authorize(Users = "ensco\\011311")]
public string Put(MyModel m) {
return "put ";
}
// DELETE api/values/5
public void Delete(int id) {
}
[HttpGet]
[Route("Search/{text}")]
public IHttpActionResult Search(string text ) {
string sql = " exec usp_WiTools '" + text + "'";
var data = this.entity.Database.SqlQuery<MyList>(sql);
return Ok(data);
}
}
public class MyModel
{
public aaWi header;
public aaJobStep [] jobSteps;
}
public class Header
{
public string jobTitle { get; set; }
public string facility { get; set; }
public string generalPrecaution { get; set; }
public string localPrecaution { get; set; }
public string wiNo { get; set; }
public string status { get; set; }
}
public class JobStep
{
public string description { get; set; }
public string warning { get; set; }
public string caution { get; set; }
public string note { get; set; }
public string photo { get; set; }
public bool barrier { get; set; }
}
public class MyList
{
public int id { get; set; }
public string name { get; set; }
}
public class EquipmentMake
{
public int id { get; set; }
public int parentId { get; set; }
public string name { get; set; }
}
public class ApplicationRole
{
public string Role { get; set; } // example, not necessary
}
}
|
using NUnit.Framework;
using OpenQA.Selenium;
using Selenio.Core.SUT;
using Selenio.HtmlReporter;
using Selenio.NUnit.PageObjects;
using Selenio.NUnit.Reporting;
namespace Selenio.NUnit
{
public class Driver : SUTDriver
{
public static void Initialize<T>(DriverOptions options = null) where T : IWebDriver
{
string assemblyLocation = TestContext.CurrentContext.TestDirectory;
string methodName = TestContext.CurrentContext.Test.MethodName;
string className = TestContext.CurrentContext.Test.ClassName;
var reporter = new Reporter(new ReportSettingsProvider(), assemblyLocation, className, methodName);
if (options == null) InitDriver<T>(reporter); else InitDriver<T>(reporter, options);
Driver.Manage().Window.Maximize();
}
public static LandingPage HomePage => GetPage<LandingPage>();
public static SearchResults SearchResults => GetPage<SearchResults>();
public static SeleniumHomePage SeleniumHomePage => GetPage<SeleniumHomePage>();
public static SeleniumDownlaods SeleniumDownlaods => GetPage<SeleniumDownlaods>();
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.EntityFrameworkCore;
using SbdProjekto.Models;
namespace SbdProjekto.Controllers
{
public class ZamowienieController : Controller
{
private readonly ApplicationDbContext _context;
public ZamowienieController(ApplicationDbContext context)
{
_context = context;
}
// GET: Zamowienie
public async Task<IActionResult> Index()
{
var applicationDbContext = _context.Zamowienia.Include(k => k.Kurier).Include(o => o.Odbiorca).Include(n => n.Nadawca);
return View(await applicationDbContext.ToListAsync());
}
// GET: Zamowienie/Details/5
public async Task<IActionResult> Details(int? id)
{
if (id == null)
{
return NotFound();
}
var zamowienie = await _context.Zamowienia
.Include(z => z.Kurier)
.Include(z => z.Nadawca)
.Include(z => z.Odbiorca)
.FirstOrDefaultAsync(m => m.ZamowienieId == id);
if (zamowienie == null)
{
return NotFound();
}
return View(zamowienie);
}
// GET: Zamowienie/Create
public IActionResult Create()
{
IEnumerable<SelectListItem> kurierzy = _context.Kurierzy.Select(x => new SelectListItem { Value = x.KurierId.ToString(), Text = x.Imie + " " + x.Nazwisko });
IEnumerable<SelectListItem> nadawcy = _context.Nadawcy.Select(x => new SelectListItem { Value = x.NadawcaId.ToString(), Text = x.Imie + " " + x.Nazwisko});
IEnumerable<SelectListItem> odbiorcy = _context.Odbiorcy.Select(x => new SelectListItem { Value = x.OdbiorcaId.ToString(), Text = x.Imie + " " + x.Nazwisko });
ViewData["KurierId"] = new SelectList(kurierzy, "Value", "Text");
ViewData["NadawcaId"] = new SelectList(nadawcy, "Value", "Text");
ViewData["OdbiorcaId"] = new SelectList(odbiorcy, "Value", "Text");
return View();
}
// POST: Zamowienie/Create
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create([Bind("ZamowienieId,KurierId,NadawcaId,OdbiorcaId,DataNadania,DataOdbioru")] Zamowienie zamowienie)
{
if (ModelState.IsValid)
{
_context.Add(zamowienie);
await _context.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
IEnumerable<SelectListItem> kurierzy = _context.Kurierzy.Select(x => new SelectListItem { Value = x.KurierId.ToString(), Text = x.Imie + " " + x.Nazwisko });
IEnumerable<SelectListItem> nadawcy = _context.Nadawcy.Select(x => new SelectListItem { Value = x.NadawcaId.ToString(), Text = x.Imie + " " + x.Nazwisko });
IEnumerable<SelectListItem> odbiorcy = _context.Odbiorcy.Select(x => new SelectListItem { Value = x.OdbiorcaId.ToString(), Text = x.Imie + " " + x.Nazwisko });
ViewData["KurierId"] = new SelectList(kurierzy, "Value", "Text");
ViewData["NadawcaId"] = new SelectList(nadawcy, "Value", "Text");
ViewData["OdbiorcaId"] = new SelectList(odbiorcy, "Value", "Text");
return View(zamowienie);
}
// GET: Zamowienie/Edit/5
public async Task<IActionResult> Edit(int? id)
{
if (id == null)
{
return NotFound();
}
var zamowienie = await _context.Zamowienia.FindAsync(id);
if (zamowienie == null)
{
return NotFound();
}
IEnumerable<SelectListItem> kurierzy = _context.Kurierzy.Select(x => new SelectListItem { Value = x.KurierId.ToString(), Text = x.Imie + " " + x.Nazwisko });
IEnumerable<SelectListItem> nadawcy = _context.Nadawcy.Select(x => new SelectListItem { Value = x.NadawcaId.ToString(), Text = x.Imie + " " + x.Nazwisko });
IEnumerable<SelectListItem> odbiorcy = _context.Odbiorcy.Select(x => new SelectListItem { Value = x.OdbiorcaId.ToString(), Text = x.Imie + " " + x.Nazwisko });
ViewData["KurierId"] = new SelectList(kurierzy, "Value", "Text");
ViewData["NadawcaId"] = new SelectList(nadawcy, "Value", "Text");
ViewData["OdbiorcaId"] = new SelectList(odbiorcy, "Value", "Text");
return View(zamowienie);
}
// POST: Zamowienie/Edit/5
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Edit(int id, [Bind("ZamowienieId,KurierId,NadawcaId,OdbiorcaId,DataNadania,DataOdbioru")] Zamowienie zamowienie)
{
if (id != zamowienie.ZamowienieId)
{
return NotFound();
}
if (ModelState.IsValid)
{
try
{
_context.Update(zamowienie);
await _context.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException)
{
if (!ZamowienieExists(zamowienie.ZamowienieId))
{
return NotFound();
}
else
{
throw;
}
}
return RedirectToAction(nameof(Index));
}
IEnumerable<SelectListItem> kurierzy = _context.Kurierzy.Select(x => new SelectListItem { Value = x.KurierId.ToString(), Text = x.Imie + " " + x.Nazwisko });
IEnumerable<SelectListItem> nadawcy = _context.Nadawcy.Select(x => new SelectListItem { Value = x.NadawcaId.ToString(), Text = x.Imie + " " + x.Nazwisko });
IEnumerable<SelectListItem> odbiorcy = _context.Odbiorcy.Select(x => new SelectListItem { Value = x.OdbiorcaId.ToString(), Text = x.Imie + " " + x.Nazwisko });
ViewData["KurierId"] = new SelectList(kurierzy, "Value", "Text");
ViewData["NadawcaId"] = new SelectList(nadawcy, "Value", "Text");
ViewData["OdbiorcaId"] = new SelectList(odbiorcy, "Value", "Text");
return View(zamowienie);
}
// GET: Zamowienie/Delete/5
public async Task<IActionResult> Delete(int? id)
{
if (id == null)
{
return NotFound();
}
var zamowienie = await _context.Zamowienia
.Include(z => z.Kurier)
.Include(z => z.Nadawca)
.Include(z => z.Odbiorca)
.FirstOrDefaultAsync(m => m.ZamowienieId == id);
if (zamowienie == null)
{
return NotFound();
}
return View(zamowienie);
}
// POST: Zamowienie/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public async Task<IActionResult> DeleteConfirmed(int id)
{
var zamowienie = await _context.Zamowienia.FindAsync(id);
_context.Zamowienia.Remove(zamowienie);
await _context.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
private bool ZamowienieExists(int id)
{
return _context.Zamowienia.Any(e => e.ZamowienieId == id);
}
}
}
|
namespace BSMU_Schedule.Interfaces.DataAccess.StorageAdapters
{
public interface IHasConnectionConfiguration
{
string ConnectionConfiguration { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Machine.Specifications;
namespace Foundry.Security.AuthorizationInformationSpecs
{
public abstract class InContextOfTestingAuthorizationInformation : BaseSpecification<AuthorizationInformation>
{
protected static Guid _userId = Guid.NewGuid();
protected static List<UserAuthorization> _userPermissions;
Establish context = () =>
{
_userPermissions = new List<UserAuthorization>
{
new UserAuthorization { SubjectId = Guid.NewGuid(), SubjectType = "Test", Allow = false, Level = 99, Operation="Allow" },
new UserAuthorization { SubjectId = Guid.Empty, SubjectType = "Test", Allow = true, Level = 50, Operation="Allow" },
new UserAuthorization { SubjectId = Guid.NewGuid(), SubjectType = "Test", Allow = false, Level = 1, Operation="Allow" },
new UserAuthorization { SubjectId = Guid.NewGuid(), SubjectType = "Test", Allow = true, Level = 99, Operation="Deny" },
new UserAuthorization { SubjectId = Guid.Empty, SubjectType = "Test", Allow = false, Level = 50, Operation="Deny" },
new UserAuthorization { SubjectId = Guid.NewGuid(), SubjectType = "Test", Allow = true, Level = 1, Operation="Deny" },
};
_subjectUnderTest = new AuthorizationInformation(_userId, _userPermissions);
};
protected class AuthorizableA
{
public Guid Id { get; set; }
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Newtonsoft.Json;
using POSServices.Models;
using POSServices.WebAPIModel;
namespace POSServices.WebAPIBackendController
{
[Route("api/PriceList")]
[ApiController]
public class PriceListController : Controller
{
private readonly DB_BIENSI_POSContext _context;
public PriceListController(DB_BIENSI_POSContext context)
{
_context = context;
}
[HttpGet]
public async Task<IActionResult> getPriceList()
{
try
{
var priceList = (from pl in _context.PriceList
select new
{
ItemId = pl.ItemId,
SalesPrice = pl.SalesPrice,
Currency = pl.Currency
}).ToList();
return Json(new[] { priceList });
}
catch (Exception ex)
{
return StatusCode(500, new
{
status = "500",
message = ex.ToString()
});
}
}
[HttpPost("Create")]
public async Task<IActionResult> create(ListPrice listPrice)
{
try
{
List<PriceList> list = listPrice.prices;
for (int i = 0; i < list.Count; i++)
{
PriceList price = new PriceList();
price.ItemId = list[i].ItemId;
price.SalesPrice = list[i].SalesPrice;
price.Currency = list[i].Currency;
_context.Add(price);
bool discExist = false;
discExist = _context.PriceList.Any(c => c.ItemId == price.ItemId);
if (discExist == false)
{
_context.SaveChanges();
}
else
{
return StatusCode(404, new
{
status = "404",
create = false,
message = "Cannot create a record, item number already exist."
});
}
}
return StatusCode(200, new
{
status = "200",
create = true,
message = "Created successfully!"
});
}
catch (Exception ex)
{
return StatusCode(500, new
{
status = "500",
create = false,
message = ex.ToString()
});
}
}
[HttpPost("Update")]
public async Task<IActionResult> update(ListPrice listPrice)
{
try
{
List<PriceList> list = listPrice.prices;
for (int i = 0; i < list.Count; i++)
{
bool discExist = false;
discExist = _context.PriceList.Any(c => c.ItemId == list[i].ItemId);
if (discExist == true)
{
var price = _context.PriceList.Where(x => x.ItemId == list[i].ItemId).First();
price.SalesPrice = list[i].SalesPrice;
price.Currency = list[i].Currency;
_context.PriceList.Update(price);
_context.SaveChanges();
}
else
{
return StatusCode(404, new
{
status = "404",
update = false,
message = "Item number not found."
});
}
}
return StatusCode(200, new
{
status = "200",
update = true,
message = "updated successfully!"
});
}
catch (Exception ex)
{
return StatusCode(500, new
{
status = "500",
update = false,
message = ex.ToString()
});
}
}
[HttpPost("Delete")]
public async Task<IActionResult> delete(ListPrice listPrice)
{
try
{
List<PriceList> list = listPrice.prices;
for (int i = 0; i < list.Count; i++)
{
var price = _context.PriceList.Where(x => x.ItemId == list[i].ItemId).First();
_context.PriceList.Remove(price);
_context.SaveChanges();
}
return StatusCode(200, new
{
status = "200",
delete = true,
message = "Deleted successfully!"
});
}
catch (Exception ex)
{
return StatusCode(500, new
{
status = "500",
delete = false,
message = ex.ToString()
});
}
}
}
} |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DrugMgmtSys.codes
{
class Order
{
private List<Drug> order = new List<Drug>();
private ArrayList num = new ArrayList();
internal List<Drug> Orders
{
get
{
return order;
}
set
{
order = value;
}
}
/// <summary>
/// 添加药品
/// </summary>
/// <param name="drug"></param>
public void add(Drug drug)
{
Orders.Add(drug);
}
public void setNum(double num)
{
this.num.Add(num);
}
public string[] getMessage()
{
string[] result ={"","" };
string result_head = "药品清单:\n\n";
double money = 0;
for (int i = 0; i < Orders.Count; i++)
{
Drug drug = Orders[i];
//string item= string.Format("{0}、 {1} \t数量 {2} \t\t单价 {3} 元\n\n", i + 1, drug.Name, (double)num[i], drug.R_price);
string item = string.Format("{0}{1}{2}{3}\n\n", padRightEx(i + 1 +"、",5 ), padRightEx(drug.Name,30), padRightEx("数量 X"+num[i].ToString(),10), padRightEx("单价 "+drug.R_price.ToString(),10));
result_head += item;
money += drug.R_price*(double)num[i];
//统计
insertOrder(drug, (double)num[i]);
}
result[0] = result_head;
result[1] = money.ToString();
return result;
}
/// <summary>
/// 订单信息写入数据库
/// </summary>
private void insertOrder(Drug drug,double n)
{
string date = DateTime.Now.ToLongDateString().ToString();
string name = drug.Name;
double number = n;
double r_price = drug.R_price;
double money = (drug.R_price-drug.W_price)*n;
string sql=string.Format("INSERT INTO tb_order (o_time,o_name,o_num,o_r_price,o_money) VALUES ('{0}','{1}',{2},{3},{4})", date, name, number, r_price, money);
int result = MySqlTools.ExecuteNonQuery(sql);
}
//对齐
private static string padRightEx(string str, int totalByteCount)
{
Encoding coding = Encoding.GetEncoding("gb2312");
int dcount = 0;
foreach (char ch in str.ToCharArray())
{
if (coding.GetByteCount(ch.ToString()) == 2)
dcount++;
}
string w = str.PadRight(totalByteCount - dcount);
return w;
}
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace lr_detect.Models
{
public class Validation
{
[Key]
public int validation_id { get; set; }
public string detection_object { get; set; } = String.Empty;
public DateTime created_at { get; set; } = DateTime.Now;
public int user_id { get; set; }
public User user { get; set; }
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Reporting.WinForms;
using System.IO;
namespace UseFul.Uteis
{
public class ReportViewerMensagens : IReportViewerMessages
{
#region IReportViewerMessages Members
public string BackButtonToolTip
{
get { return ("Tradução"); }
}
public string BackMenuItemText
{
get { return ("Tradução"); }
}
public string ChangeCredentialsText
{
get { return ("Tradução"); }
}
public string CurrentPageTextBoxToolTip
{
get { return ("Tradução"); }
}
public string DocumentMapButtonToolTip
{
get { return ("Tradução"); }
}
public string DocumentMapMenuItemText
{
get { return ("Tradução"); }
}
public string ExportButtonToolTip
{
get { return ("Tradução"); }
}
public string ExportMenuItemText
{
get { return ("Tradução"); }
}
public string FalseValueText
{
get { return ("Tradução"); }
}
public string FindButtonText
{
get { return ("Tradução"); }
}
public string FindButtonToolTip
{
get { return ("Tradução"); }
}
public string FindNextButtonText
{
get { return ("Tradução"); }
}
public string FindNextButtonToolTip
{
get { return ("Tradução"); }
}
public string FirstPageButtonToolTip
{
get { return ("Tradução"); }
}
public string LastPageButtonToolTip
{
get { return ("Tradução"); }
}
public string NextPageButtonToolTip
{
get { return ("Tradução"); }
}
public string NoMoreMatches
{
get { return ("Tradução"); }
}
public string NullCheckBoxText
{
get { return ("Tradução"); }
}
public string NullCheckBoxToolTip
{
get { return ("Tradução"); }
}
public string NullValueText
{
get { return ("Tradução"); }
}
public string PageOf
{
get { return ("Tradução"); }
}
public string PageSetupButtonToolTip
{
get { return ("Tradução"); }
}
public string PageSetupMenuItemText
{
get { return ("Tradução"); }
}
public string ParameterAreaButtonToolTip
{
get { return ("Tradução"); }
}
public string PasswordPrompt
{
get { return ("Tradução"); }
}
public string PreviousPageButtonToolTip
{
get { return ("Tradução"); }
}
public string PrintButtonToolTip
{
get { return ("Tradução"); }
}
public string PrintLayoutButtonToolTip
{
get { return ("Tradução"); }
}
public string PrintLayoutMenuItemText
{
get { return ("Tradução"); }
}
public string PrintMenuItemText
{
get { return ("Tradução"); }
}
public string ProgressText
{
get { return ("Gerando Relatório … "); }
}
public string RefreshButtonToolTip
{
get { return ("Tradução"); }
}
public string RefreshMenuItemText
{
get { return ("Tradução"); }
}
public string SearchTextBoxToolTip
{
get { return ("Tradução"); }
}
public string SelectAValue
{
get { return ("Tradução"); }
}
public string SelectAll
{
get { return ("Tradução"); }
}
public string StopButtonToolTip
{
get { return ("Tradução"); }
}
public string StopMenuItemText
{
get { return ("Tradução"); }
}
public string TextNotFound
{
get { return ("Tradução"); }
}
public string TotalPagesToolTip
{
get { return ("Tradução"); }
}
public string TrueValueText
{
get { return ("Tradução"); }
}
public string UserNamePrompt
{
get { return ("Tradução"); }
}
public string ViewReportButtonText
{
get { return ("Tradução"); }
}
public string ViewReportButtonToolTip
{
get { return ("Tradução"); }
}
public string ZoomControlToolTip
{
get { return ("Tradução"); }
}
public string ZoomMenuItemText
{
get { return ("Tradução"); }
}
public string ZoomToPageWidth
{
get { return ("Tradução"); }
}
public string ZoomToWholePage
{
get { return ("Tradução"); }
}
#endregion
}
public class ReportUteis
{
public enum rptFormat
{
Excel,
PDF,
Image,
}
private rptFormat _tipoExportacao;
public rptFormat TipoExportacao
{
get { return _tipoExportacao; }
set { _tipoExportacao = value; }
}
public void ExportarReport(LocalReport report, rptFormat rptFormat, string filePath)
{
Warning[] warnings = null;
string[] streamids = null;
string mimeType = null;
string encoding = null;
string extension = null;
byte[] bytes = report.Render(rptFormat.ToString(), null, out mimeType, out encoding, out extension, out streamids, out warnings);
switch (rptFormat)
{
case rptFormat.Excel:
filePath = Path.ChangeExtension(filePath, "xls");
break;
case rptFormat.Image:
filePath = Path.ChangeExtension(filePath, "jpg");
break;
case rptFormat.PDF:
filePath = Path.ChangeExtension(filePath, "pdf");
break;
}
using (FileStream fs = new FileStream(filePath, FileMode.Create))
{
fs.Write(bytes, 0, bytes.Length);
fs.Close();
}
bytes = null;
}
}
}
|
using UnityEngine;
using UnityEngine.UI;
using UnityGPPhysics;
using System.Collections;
/// <summary>Script to apply to a slider to give slow motion</summary>
/// <author>Robert McDonnell</author>
public class TimeHandler : MonoBehaviour
{
private float slider;
private bool buttonState;
private float initFixedDeltaTime;
private float initTimeScale;
void Awake()
{
// allow changing fixed timestep in editor
initFixedDeltaTime = Time.fixedDeltaTime;
initTimeScale = Time.timeScale;
Time.timeScale = 0;
}
//Constantly change time based on slider
public void UpdateTime()
{
buttonState = GameObject.Find("ObjectForButton").GetComponent<PausePlay>().active;
slider = GameObject.Find("Slider").GetComponent<Slider>().value;
if (buttonState == true)
{
Time.timeScale = slider;
float factor = initTimeScale / slider;
Time.fixedDeltaTime = initFixedDeltaTime / factor;
}
else //paused
{
Time.timeScale = 0;
}
}
}
|
using System.Collections.Generic;
using System.Threading.Tasks;
using SpaceHosting.Index.Sparnn.Distances;
namespace SpaceHosting.Index.Sparnn.Clusters
{
internal interface IClusterIndex<TRecord>
where TRecord : notnull
{
bool IsOverflowed { get; }
Task<IEnumerable<NearestSearchResult<TRecord>[]>> SearchAsync(IList<MathNet.Numerics.LinearAlgebra.Double.SparseVector> featureVectors, int resultsNumber, int clustersToSearchNumber);
Task InsertAsync(IList<MathNet.Numerics.LinearAlgebra.Double.SparseVector> featureVectors, TRecord[] records);
(IList<MathNet.Numerics.LinearAlgebra.Double.SparseVector> featureVectors, IList<TRecord> records) GetChildData();
Task DeleteAsync(IList<TRecord> recordsToBeDeleted);
}
}
|
using System;
class PrintDateTime
{
static void Main(string[] args)
{
Console.WriteLine("Current date and time at the moment: ");
Console.WriteLine(DateTime.Now);
}
}
|
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ManageFiles
{
class Program
{
static void Main(string[] args)
{
string fileName = @"C:\myTemp\myFile.txt";
string path = @"C:\myTemp";
string rootPath = @"C:\";
string directoryName;
Console.WriteLine();
Console.WriteLine($"*************************************");
Console.WriteLine();
Console.WriteLine($"*** Using file, path, creating text files");
//using Path of System.IO
//Path.GetDirectoryName;
directoryName = Path.GetDirectoryName(fileName);
Console.WriteLine($"GetDirectoryName of ({fileName}) returns {directoryName}");
directoryName = Path.GetDirectoryName(path);
Console.WriteLine($"GetDirectoryName of ({path}) returns {directoryName}");
directoryName = Path.GetDirectoryName(rootPath);
Console.WriteLine($"GetDirectoryName of ({rootPath}) returns *{directoryName}*");
Console.WriteLine();
Console.WriteLine();
//
//Console.WriteLine(File.Exists(fileName) ? $"File {fileName} exists." : $"File {fileName} does not exist.");
//Console.ReadLine();
//File.Exist; Directory.Exist; Directory.CreateDirectory; File.Create;
if (!File.Exists(fileName))
{
Console.WriteLine($"the file {fileName} does not Exist");
Console.WriteLine();
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
Console.WriteLine($"the directory {path} has been created ");
}
else
{
Console.WriteLine($"the directory {path} Exist");
}
File.Create(fileName);
Console.WriteLine($"the file {fileName} has been created into {path} ");
}
else
{
Console.WriteLine($"the file {fileName} Exist into {path}");
}
Console.ReadLine();
}
}
}
|
using System;
using System.Windows.Forms;
using System.Drawing;
using com.Sconit.SmartDevice.SmartDeviceRef;
using System.Web.Services.Protocols;
namespace com.Sconit.SmartDevice
{
public partial class UCHuAging : UserControl
{
public event MainForm.ModuleSelectHandler ModuleSelectionEvent;
private SD_SmartDeviceService smartDeviceService;
private User user;
private int qty;
private static UCHuAging ucHuAging;
private static object obj = new object();
private bool isMark;
private int keyCodeDiff;
private bool isStart;
public UCHuAging(User user, bool isStart)
{
InitializeComponent();
this.smartDeviceService = new SD_SmartDeviceService();
this.smartDeviceService.Url = Utility.WEBSERVICE_URL;
this.user = user;
this.isStart = isStart;
this.Reset();
}
public static UCHuAging GetUCHuAging(User user, bool isStart)
{
if (ucHuAging == null)
{
lock (obj)
{
if (ucHuAging == null)
{
ucHuAging = new UCHuAging(user, isStart);
}
}
}
ucHuAging.user = user;
ucHuAging.isStart = isStart;
ucHuAging.lblMessage.ForeColor = Color.Black;
if (isStart)
{
ucHuAging.lblMessage.Text = "老化开始,请扫描条码";
}
else
{
ucHuAging.lblMessage.Text = "老化结束,请扫描条码";
}
ucHuAging.Reset();
return ucHuAging;
}
private void tbBarCode_KeyUp(object sender, KeyEventArgs e)
{
if (this.isMark)
{
this.isMark = false;
this.tbBarCode.Focus();
return;
}
try
{
string barCode = this.tbBarCode.Text.Trim();
if (sender is Button)
{
this.ScanBarCode();
}
else
{
if ((e.KeyData & Keys.KeyCode) == Keys.Enter)
{
this.ScanBarCode();
}
else if (((e.KeyData & Keys.KeyCode) == Keys.Escape))
{
if (!string.IsNullOrEmpty(barCode))
{
this.tbBarCode.Text = string.Empty;
}
else
{
this.Reset();
}
}
//else if ((e.KeyData & Keys.KeyCode) == Keys.F4)
else if (e.KeyValue == 115 + this.keyCodeDiff)
{
this.ModuleSelectionEvent(CodeMaster.TerminalPermission.M_Switch);
}
else if (e.KeyValue == 112 + this.keyCodeDiff)
//else if ((e.KeyData & Keys.KeyCode) == Keys.F1)
{
//todo Help
}
}
}
catch (SoapException ex)
{
this.isMark = true;
this.tbBarCode.Text = string.Empty;
this.tbBarCode.Focus();
Utility.ShowMessageBox(ex.Message);
}
catch (BusinessException ex)
{
this.isMark = true;
this.tbBarCode.Text = string.Empty;
this.tbBarCode.Focus();
Utility.ShowMessageBox(ex);
}
catch (Exception ex)
{
if ((ex is System.Net.WebException) || (ex is SoapException))
{
Utility.ShowMessageBox(ex);
}
else if (ex is BusinessException)
{
Utility.ShowMessageBox(ex.Message);
}
else
{
this.Reset();
Utility.ShowMessageBox(ex.Message);
}
this.isMark = true;
this.tbBarCode.Text = string.Empty;
this.tbBarCode.Focus();
}
}
private void ScanBarCode()
{
string barCode = this.tbBarCode.Text.Trim();
this.tbBarCode.Focus();
this.tbBarCode.Text = string.Empty;
if (barCode.Length < 3)
{
throw new BusinessException("条码格式不合法");
}
try
{
Hu hu = new Hu();
if (this.isStart)
{
hu = smartDeviceService.StartAging(barCode, this.user.Code);
//if (hu.Status != HuStatus.Location)
//{
// throw new BusinessException("此条码不在库存中,不能进行老化操作");
//}
if (hu.IsFreeze)
{
throw new BusinessException("此条码已经冻结,不能进行老化操作");
}
if (!Utility.HasPermission(user.Permissions, null, true, false, hu.Region, null))
{
throw new BusinessException("没有此条码的权限");
}
this.lblMessage.Text = string.Format("老化开始成功,时间:{0}", DateTime.Now.ToString("yyyy-MM-dd HH:mm"));
if (hu.HuOption == HuOption.NoNeed)
{
this.lblMessage.Text = string.Format("老化开始成功.注:此条码无需老化");
}
else
{
this.lblMessage.Text = string.Format("老化开始成功,时间:{0}", DateTime.Now.ToString("yyyy-MM-dd HH:mm"));
}
}
else
{
hu = smartDeviceService.DoAging(barCode, this.user.Code);
this.lblMessage.Text = string.Format("老化成功,新条码:{0}", hu.HuId);
}
this.lbl01.Text = hu.Item;
this.lbl02.Text = hu.ReferenceItemCode;
this.lbl03.Text = hu.Direction;
this.lbl04.Text = hu.Qty.ToString("0.###") + " " + hu.Uom;
this.lbl06.Text = hu.Location;
this.lbl07.Text = hu.Bin;
this.lbl08.Text = hu.HuOption == HuOption.Aged ? "已老化" : "未老化";
this.lbl09.Text = hu.ManufactureDate.ToString("yyyy-MM-dd");
this.lbl10.Text = hu.ManufactureParty;
this.lblBarCodeInfo.Text = hu.HuId;
this.lblItemDescInfo.Text = hu.ItemDescription;
}
catch (Exception ex)
{
if ((ex is System.Net.WebException) || (ex is SoapException))
{
Utility.ShowMessageBox(ex);
}
else if (ex is BusinessException)
{
Utility.ShowMessageBox(ex.Message);
}
else
{
this.Reset();
Utility.ShowMessageBox(ex.Message);
}
this.isMark = true;
this.tbBarCode.Text = string.Empty;
this.tbBarCode.Focus();
}
}
private void Reset()
{
this.tbBarCode.Text = string.Empty;
this.tbBarCode.Focus();
this.label01.Text = "物料号:";
this.label02.Text = "参考号:";
this.label03.Text = "方向:";
this.label04.Text = "数量:";
//this.label05.Text = "单位:";
this.label06.Text = "库位:";
this.label07.Text = "库格:";
this.label08.Text = "条码选项:";
this.label09.Text = "制造时间:";
this.label10.Text = "制造厂商:";
this.lbl01.Text = string.Empty;
this.lbl02.Text = string.Empty;
this.lbl03.Text = string.Empty;
this.lbl04.Text = string.Empty;
//this.lbl05.Text = string.Empty;
this.lbl06.Text = string.Empty;
this.lbl07.Text = string.Empty;
this.lbl08.Text = string.Empty;
this.lbl09.Text = string.Empty;
this.lbl10.Text = string.Empty;
this.lblBarCodeInfo.Text = string.Empty;
this.lblItemDescInfo.Text = string.Empty;
this.keyCodeDiff = Utility.GetKeyCodeDiff();
//this.lblMessage.Text = "老化开始,请扫描条码";
if (this.isStart)
{
this.lblMessage.Text = "老化开始,请扫描条码";
}
else
{
this.lblMessage.Text = "老化结束,请扫描条码";
}
this.tbBarCode.Focus();
}
private void btnBack_Click(object sender, EventArgs e)
{
this.ModuleSelectionEvent(CodeMaster.TerminalPermission.M_Switch);
}
private void btnOrder_Click(object sender, EventArgs e)
{
this.tbBarCode_KeyUp(sender, null);
}
private void btnOrder_KeyUp(object sender, KeyEventArgs e)
{
this.tbBarCode_KeyUp(sender, e);
}
}
}
|
using System.Threading.Tasks;
using Elrond.Dotnet.Sdk.Domain;
using Elrond.Dotnet.Sdk.Domain.Values;
using Elrond.Dotnet.Sdk.Provider;
using Elrond.Dotnet.Sdk.Provider.Dtos;
using Moq;
using NUnit.Framework;
namespace Elrond_sdk.dotnet.tests.Domain
{
public class GasLimitTests
{
private IElrondProvider _elrondProvider;
[SetUp]
public void Setup()
{
var mock = new Mock<IElrondProvider>();
mock.Setup(s => s.GetConstants()).ReturnsAsync(new ConfigDataDto
{
Config = new ConfigDto
{
erd_min_gas_limit = 50000,
erd_gas_per_data_byte = 1500,
erd_min_gas_price = 1000000000
}
});
_elrondProvider = mock.Object;
}
[Test]
public async Task GasLimit_Should_Compute_Gas_ForTransfer()
{
// Arrange
var constants = await Constants.GetFromNetwork(_elrondProvider);
var address = AddressValue.FromBech32("erd1qqqqqqqqqqqqqpgq3wltgm6g8n6telq3wz2apgjqcydladdtu4cq3ch0l0");
var transactionRequest = TransactionRequest.CreateTransaction(new Account(address), constants);
transactionRequest.SetData("KLJHGFhjbnklmjghfdhfkjl");
// Act
var gasLimit = GasLimit.ForTransfer(constants, transactionRequest);
// Assert
Assert.AreEqual(84500, gasLimit.Value);
}
}
} |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Автошкола
{
public partial class CategoriesForm : Form
{
public CategoriesForm()
{
InitializeComponent();
}
public BusinessLogic BusinessLogic = new BusinessLogic();
AutoschoolDataSet dataSet;
string LastSearchingText = "";
int LastFoundRow = -1;
int LastSelectionIndex;
bool FirstLoad = true;
void ReloadCategories()
{
dataSet = BusinessLogic.ReadCategories();
Categories_dataGridView.DataSource = dataSet;
Categories_dataGridView.DataMember = "Categories";
Categories_dataGridView.Columns["ID"].Visible = false;
Categories_dataGridView.Columns["Name"].Visible = false;
IDColumn.DataPropertyName = "ID";
NameColumn.DataPropertyName = "Name";
if (LastSelectionIndex != -1)
Categories_dataGridView.CurrentCell = Categories_dataGridView[1, LastSelectionIndex];
}
private void CategoriesForm_Load(object sender, EventArgs e)
{
LastSelectionIndex = -1;
ReloadCategories();
Edit_button.Enabled = false;
Delete_button.Enabled = false;
Categories_dataGridView_SelectionChanged(sender, e);
}
private void Categories_dataGridView_SelectionChanged(object sender, EventArgs e)
{
if (Categories_dataGridView.SelectedRows.Count == 1)
{
Edit_button.Enabled = true;
Delete_button.Enabled = true;
}
else
{
Edit_button.Enabled = false;
Delete_button.Enabled = false;
}
}
private void Search_button_Click(object sender, EventArgs e)
{
SearchingInDataGridViewClass.Search(SearchCategory_textBox, ref Categories_dataGridView, Direction_checkBox,
ref LastSearchingText, ref LastFoundRow, "NameColumn");
}
private void SearchCategory_textBox_KeyPress(object sender, KeyPressEventArgs e)
{
if ((char)e.KeyChar == (Char)Keys.Enter)
{
Search_button_Click(sender, e);
}
if ((char)e.KeyChar == (Char)Keys.Back)
{
LastSearchingText = "";
}
}
private void CategoriesForm_FormClosing(object sender, FormClosingEventArgs e)
{
MainForm.Perem(MainForm.FormsNames[7], false);
}
private void Add_button_Click(object sender, EventArgs e)
{
dataSet = BusinessLogic.ReadCategories();
AddEditCategoryForm AddCategory = new AddEditCategoryForm(dataSet.Categories, null);
AddCategory.Text = "Добавление категории";
this.Enabled = false;
AddCategory.ShowDialog();
if (AddCategory.DialogResult == DialogResult.OK)
{
dataSet = BusinessLogic.WriteCategories(dataSet);
ReloadCategories();
}
this.Enabled = true;
}
private void Edit_button_Click(object sender, EventArgs e)
{
dataSet = BusinessLogic.ReadCategories();
LastSelectionIndex = Categories_dataGridView.SelectedRows[0].Index;
AddEditCategoryForm EditCategory = new AddEditCategoryForm(dataSet.Categories, dataSet.Categories.Rows.Find(Categories_dataGridView.SelectedRows[0].Cells["ID"].Value));
EditCategory.Text = "Редактирование категории";
this.Enabled = false;
EditCategory.ShowDialog();
if (EditCategory.DialogResult == DialogResult.OK)
{
dataSet = BusinessLogic.WriteCategories(dataSet);
ReloadCategories();
}
this.Enabled = true;
}
private void Delete_button_Click(object sender, EventArgs e)
{
LastSelectionIndex = -1;
if (Categories_dataGridView.SelectedRows.Count != 1)
{
MessageBox.Show("Не выбрана строка для удаления", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
DialogResult result = MessageBox.Show("Вы действительно хотите удалить выбранную запись?", "Подтверждение удаления", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
if (result == DialogResult.Yes)
{
try
{
dataSet.Categories.Rows.Find(Categories_dataGridView.SelectedRows[0].Cells["ID"].Value).Delete();
dataSet = BusinessLogic.WriteCategories(dataSet);
ReloadCategories();
}
catch
{
MessageBox.Show("Не удалось удалить выбранную строку.\nСкорее всего, на данную строку имеются ссылки из других таблиц", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
ReloadCategories();
}
}
}
private void Reload_button_Click(object sender, EventArgs e)
{
LastSelectionIndex = -1;
ReloadCategories();
}
private void Close_button_Click(object sender, EventArgs e)
{
Close();
}
private void CategoriesForm_VisibleChanged(object sender, EventArgs e)
{
if (Visible)
{
if (!FirstLoad)
Reload_button_Click(sender, e);
else
FirstLoad = false;
}
}
}
}
|
using System;
using MusicLibrary;
namespace BassPlayer.CS
{
class MusicFile
{
public string filePath { get; protected set; }
public string fileName { get; protected set; }
public string song { get; protected set; }
public string artist { get; protected set; }
public string album { get; protected set; }
public string genre { get; protected set; }
public MusicFile(string file)
{
this.filePath = file;
this.fileName = Vars.GetFileName(file);
try
{
string[] streamTags = BassMethods.GetStreamTags(file);
this.song = streamTags[0];
this.artist = streamTags[1];
this.album = streamTags[2];
this.genre = GetGenre(Convert.ToInt32(streamTags[5]));
}
catch
{ }
}
public string GetGenre(int genreID)
{
switch (genreID)
{
case 0: return "Blues";
case 1: return "Classic Rock";
case 2: return "Country";
case 3: return "Dance";
case 4: return "Disco";
case 5: return "Funk";
case 6: return "Grunge";
case 7: return "Hip - Hop";
case 8: return "Jazz";
case 9: return "Metal";
case 10: return "New Age";
case 11: return "Oldies";
case 12: return "Other";
case 13: return "Pop";
case 14: return "R & B";
case 15: return "Rap";
case 16: return "Reggae";
case 17: return "Rock";
case 18: return "Techno";
case 19: return "Industrial";
case 20: return "Alternative";
case 21: return "Ska";
case 22: return "Death Metal";
case 23: return "Pranks";
case 24: return "Soundtrack";
case 25: return "Euro - Techno";
case 26: return "Ambient";
case 27: return "Trip - Hop";
case 28: return "Vocal";
case 29: return "Jazz + Funk";
case 30: return "Fusion";
case 31: return "Trance";
case 32: return "Classical";
case 33: return "Instrumental";
case 34: return "Acid";
case 35: return "House";
case 36: return "Game";
case 37: return "Sound Clip";
case 38: return "Gospel";
case 39: return "Noise";
case 40: return "AlternRock";
case 41: return "Bass";
case 42: return "Soul";
case 43: return "Punk";
case 44: return "Space";
case 45: return "Meditative";
case 46: return "Instrumental Pop";
case 47: return "Instrumental Rock";
case 48: return "Ethnic";
case 49: return "Gothic";
case 50: return "Darkwave";
case 51: return "Techno - Industrial";
case 52: return "Electronic";
case 53: return "Pop - Folk";
case 54: return "Eurodance";
case 55: return "Dream";
case 56: return "Southern Rock";
case 57: return "Comedy";
case 58: return "Cult";
case 59: return "Gangsta";
case 60: return "Top 40";
case 61: return "Christian Rap";
case 62: return "Pop / Funk";
case 63: return "Jungle";
case 64: return "Native American";
case 65: return "Cabaret";
case 66: return "New Wave";
case 67: return "Psychadelic";
case 68: return "Rave";
case 69: return "Showtunes";
case 70: return "Trailer";
case 71: return "Lo - Fi";
case 72: return "Tribal";
case 73: return "Acid Punk";
case 74: return "Acid Jazz";
case 75: return "Polka";
case 76: return "Retro";
case 77: return "Musical";
case 78: return "Rock & Roll";
case 79: return "Hard Rock";
case 80: return "Folk";
case 81: return "Folk - Rock";
case 82: return "National Folk";
case 83: return "Swing";
case 84: return "Fast Fusion";
case 85: return "Bebob";
case 86: return "Latin";
case 87: return "Revival";
case 88: return "Celtic";
case 89: return "Bluegrass";
case 90: return "Avantgarde";
case 91: return "Gothic Rock";
case 92: return "Progressive Rock";
case 93: return "Psychedelic Rock";
case 94: return "Symphonic Rock";
case 95: return "Slow Rock";
case 96: return "Big Band";
case 97: return "Chorus";
case 98: return "Easy Listening";
case 99: return "Acoustic";
case 100: return "Humour";
case 101: return "Speech";
case 102: return "Chanson";
case 103: return "Opera";
case 104: return "Chamber Music";
case 105: return "Sonata";
case 106: return "Symphony";
case 107: return "Booty Bass";
case 108: return "Primus";
case 109: return "Porn Groove";
case 110: return "Satire";
case 111: return "Slow Jam";
case 112: return "Club";
case 113: return "Tango";
case 114: return "Samba";
case 115: return "Folklore";
case 116: return "Ballad";
case 117: return "Power Ballad";
case 118: return "Rhythmic Soul";
case 119: return "Freestyle";
case 120: return "Duet";
case 121: return "Punk Rock";
case 122: return "Drum Solo";
case 123: return "A capella";
case 124: return "Euro - House";
case 125: return "Dance Hall";
}
return null;
}
}
}
|
using BHLD.Data.Infrastructure;
using BHLD.Model.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BHLD.Data.Repositories
{
public interface Ihu_org_titleRepository : IRepository<hu_org_title>
{
IEnumerable<hu_org_title> GetAllByOrgTitle(int tag, int page, int pageSize, out int totalRow);
}
public class hu_org_titleRepository : RepositoryBase<hu_org_title>, Ihu_org_titleRepository
{
public hu_org_titleRepository(IDbFactory dbFactory) : base(dbFactory)
{
}
public IEnumerable<hu_org_title> GetAllByOrgTitle(int tag, int page, int pageSize, out int totalRow)
{
throw new NotImplementedException();
}
}
}
|
namespace com.Sconit.Service.SI.Impl
{
using System.Collections.Generic;
using AutoMapper;
using Castle.Services.Transaction;
using System;
public class SD_MasterDataMgrImpl : BaseMgr, com.Sconit.Service.SI.ISD_MasterDataMgr
{
[Transaction(TransactionMode.Requires)]
public Entity.SI.SD_MD.Bin GetBin(string binCode)
{
var locationBin = this.genericMgr.FindById<Entity.MD.LocationBin>(binCode);
var bin = Mapper.Map<Entity.MD.LocationBin, Entity.SI.SD_MD.Bin>(locationBin);
var location = this.genericMgr.FindById<Entity.MD.Location>(bin.Location);
bin.Region = location.Region;
return bin;
}
[Transaction(TransactionMode.Requires)]
public Entity.SI.SD_MD.Location GetLocation(string locationCode)
{
var locationBase = this.genericMgr.FindById<Entity.MD.Location>(locationCode);
return Mapper.Map<Entity.MD.Location, Entity.SI.SD_MD.Location>(locationBase);
}
[Transaction(TransactionMode.Requires)]
public Entity.SI.SD_MD.Pallet GetPallet(string palletCode)
{
var palletBase = this.genericMgr.FindById<Entity.MD.Pallet>(palletCode);
return Mapper.Map<Entity.MD.Pallet, Entity.SI.SD_MD.Pallet>(palletBase);
}
[Transaction(TransactionMode.Requires)]
public string GetEntityPreference(Entity.SYS.EntityPreference.CodeEnum entityEnum)
{
return this.systemMgr.GetEntityPreferenceValue(entityEnum);
}
[Transaction(TransactionMode.Requires)]
public Entity.SI.SD_MD.Item GetItem(string itemCode)
{
var itemBase = this.genericMgr.FindById<Entity.MD.Item>(itemCode);
return Mapper.Map<Entity.MD.Item, Entity.SI.SD_MD.Item>(itemBase);
}
public DateTime GetEffDate(string date)
{
DateTime effDate = DateTime.Now;
if (date.Length == 6)
{
string newStr = effDate.Year.ToString() + "-";//年
newStr += date.Substring(0, 2) + "-";//月
newStr += date.Substring(2, 2) + " ";//日
newStr += date.Substring(4, 2) + ":00:00";//时:分:秒
effDate = DateTime.Parse(newStr);
if (effDate > DateTime.Now)
{
if (effDate.Month == 1)
{
effDate.AddYears(-1);
}
else
{
throw new Entity.Exception.BusinessException("输入的时间不能大于当前时间");
}
}
}
else
{
throw new Entity.Exception.BusinessException("输入正确的格式,2月3日14时输入..020314");
}
Entity.MD.FinanceCalendar financeCalendar = financeCalendarMgr.GetNowEffectiveFinanceCalendar();
if (financeCalendar.StartDate.Value > effDate || financeCalendar.EndDate.Value <= effDate)
{
throw new Entity.Exception.BusinessException("不在开放的会计期间里面");
}
return effDate;
}
}
}
|
using Newtonsoft.Json.Serialization;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http.Formatting;
using System.Web.Http;
using Newtonsoft.Json;
using JsonSerializer = Microsoft.ApplicationInsights.Extensibility.Implementation.JsonSerializer;
namespace WebApi
{
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Web API configuration and services
MediaTypeFormatterCollection formatters = config.Formatters;
//Habilitar xml
formatters.Remove(formatters.XmlFormatter);
JsonSerializerSettings jsonSettings = formatters.JsonFormatter.SerializerSettings;
jsonSettings.Formatting = Formatting.Indented;
jsonSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
formatters.JsonFormatter.SerializerSettings.PreserveReferencesHandling = PreserveReferencesHandling.None;
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{action}/{id}",
defaults: new { id = RouteParameter.Optional }
);
config.Routes.MapHttpRoute(
name: "DefaultCategory",
routeTemplate: "api/{controller}/{category}/{id}",
defaults: new { category = "all", id = RouteParameter.Optional }
);
// Convention-based routing.
config.Routes.MapHttpRoute(
name: "ConventionalDefault",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}
}
|
using AlgorithmProblems.matrix_problems;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AlgorithmProblems.Recursion
{
class Sudoku
{
private int[,] grid;
public int[,] Grid
{
get
{
return grid;
}
set
{
grid = value;
}
}
public Sudoku(int[,] grid)
{
this.grid = grid;
}
public bool SolveSudoku()
{
int row =0, col = 0;
if (!FindUnassignedSpace(ref row, ref col))
{
return true; // base condition
}
else
{
for (int i = 1; i <= grid.GetLength(0); i++) // Using i <= grid.GetLength(0) assumin this is a square matrix
{
if (!IsConflict(row, col, i))
{
grid[row, col] = i;
if (!SolveSudoku())
{
grid[row, col] = 0;
}
else
{
return true;
}
}
}
return false; // trigger back tracking
}
}
private bool IsConflict(int row, int col, int val)
{
// Make sure that the row does not contain the same value
for (int r = 0; r < grid.GetLength(0); r++)
{
if(grid[r,col] == val)
{
return true;
}
}
// Make sure that the column does not contain the same value
for (int c = 0; c < grid.GetLength(1); c++)
{
if(grid[row,c] == val)
{
return true;
}
}
// Make sure that the box does not contain the same value
int boxRow = (row / 3)*3; // Get the row value of the top left of the square box
int boxCol = (col / 3)*3; // Get the col value of the top left of the square box
// Here change 3 to square root of GetLength(0) for more genaralized solution
for(int r= boxRow; r<boxRow + grid.GetLength(0)/3; r++)
{
for(int c = boxCol; c<boxCol + grid.GetLength(1)/3; c++)
{
if(grid[r,c] == val)
{
return true;
}
}
}
return false;
}
private bool FindUnassignedSpace(ref int row, ref int col)
{
for (int r = 0; r < grid.GetLength(0); r++)
{
for (int c = 0; c < grid.GetLength(1); c++)
{
if (grid[r, c] == 0)
{
row = r;
col = c;
return true;
}
}
}
return false;
}
public static void TestSudokuSolver()
{
int[,] grid = new int[,]
{
{0,0,0,0,0,0,0,0,0},
{0,0,0,0,7,9,6,0,0},
{2,9,3,0,5,6,0,0,0},
{4,0,0,5,0,2,0,0,0},
{3,8,1,4,0,0,5,0,0},
{0,5,2,0,1,0,0,9,0},
{9,0,0,0,3,0,0,0,0},
{0,0,5,0,0,0,0,0,0},
{0,6,0,0,0,8,0,0,7}
};
Sudoku sk = new Sudoku(grid);
Console.WriteLine("Sudoku problem");
MatrixProblemHelper.PrintMatrix(sk.Grid);
bool IsSudokuSolved = sk.SolveSudoku();
if (IsSudokuSolved)
{
Console.WriteLine("Sudoku solution");
MatrixProblemHelper.PrintMatrix(sk.Grid);
}
else
{
Console.WriteLine("Sudoku cannot be solved");
}
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class temaInfo : MonoBehaviour{
public int idTema;
public GameObject estrela1;
public GameObject estrela2;
public GameObject estrela3;
private int notaFinal;
// Start is called before the first frame update
void Start()
{
estrela1.SetActive(false);
estrela2.SetActive(false);
estrela3.SetActive(false);
int notaFinal = PlayerPrefs.GetInt("notaFinal"+idTema.ToString());
if(notaFinal == 10)
{
estrela1.SetActive(true);
estrela2.SetActive(true);
estrela3.SetActive(true);
}
else if(notaFinal >= 6)
{
estrela1.SetActive(true);
estrela2.SetActive(true);
estrela3.SetActive(false);
}
else if(notaFinal >= 2)
{
estrela1.SetActive(true);
estrela2.SetActive(false);
estrela3.SetActive(false);
}
}
} |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
namespace Abhs.Common
{
public static class EnumHelper
{
public static string GetDescription(this Enum value)
{
FieldInfo field = value.GetType().GetField(value.ToString());
DescriptionAttribute attribute = Attribute.GetCustomAttribute(field, typeof(DescriptionAttribute)) as DescriptionAttribute;
return attribute == null ? value.ToString() : attribute.Description;
}
public static string GetEnumDesc(this Type e, int? value)
{
FieldInfo[] fields = e.GetFields();
for (int i = 1, count = fields.Length; i < count; i++)
{
if ((int)System.Enum.Parse(e, fields[i].Name) == value)
{
DescriptionAttribute[] EnumAttributes = (DescriptionAttribute[])fields[i].
GetCustomAttributes(typeof(DescriptionAttribute), false);
if (EnumAttributes.Length > 0)
{
return EnumAttributes[0].Description;
}
}
}
return "";
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
// representation of a unit in battle
public class BattleUnit {
public static readonly float MaxStagger = 100.0f;
public Unit unit { get; private set; }
public Battle battle { get; private set; }
public Alignment align { get { return unit.align; } }
public List<StatusInstance> statuses { get; private set; }
public bool hasActedThisTurn { get; private set; }
public Doll doll {
get {
return battle.controller.GetDollForUnit(this);
}
}
public string name {
get {
return unit.unitName;
}
}
// === INITIALIZATION ==========================================================================
// we create battle units from three sources
// - unit, this is a keyed by what comes in from tiled and used to look up hero/enemy in db
// - battle, the parent battle creating this unit for
public BattleUnit(Unit unit, Battle battle) {
this.unit = unit;
this.battle = battle;
statuses = new List<StatusInstance>();
unit.stats.Set(StatTag.STAGGER, MaxStagger);
if (align == Alignment.Hero) {
battle.controller.playerHP.Populate(Get(StatTag.MHP), Get(StatTag.HP));
}
}
// === STATE MACHINE ===========================================================================
// called at the end of this unit's action
public void MarkActionTaken() {
hasActedThisTurn = true;
}
// called at the beginning of this unit's faction's turn
public IEnumerator TurnStartRoutine() {
hasActedThisTurn = false;
if (align == Alignment.Hero) {
battle.controller.StartCoroutine(battle.controller.playerStagger.AnimateWithSpeedRoutine(1.0f));
}
unit.stats.Set(StatTag.AP, Get(StatTag.MAP));
unit.stats.Set(StatTag.STAGGER, MaxStagger);
foreach (StatusInstance status in statuses) {
yield return status.TurnStartRoutine();
}
}
public IEnumerator TurnEndRoutine() {
foreach (StatusInstance status in statuses) {
yield return status.TurnEndRoutine();
}
}
public IEnumerator ActionStartRoutine() {
foreach (StatusInstance status in statuses) {
yield return status.ActionStartRoutine();
}
if (align == Alignment.Enemy) {
yield return battle.controller.enemyHUD.enableRoutine(this);
}
}
public IEnumerator ActionEndRoutine() {
foreach (StatusInstance status in statuses) {
yield return status.ActionEndRoutine();
}
}
public IEnumerator TakeDamageRoutine(int damage, bool includeMessage = true) {
battle.Log(this + " took " + damage + " damages");
if (align == Alignment.Hero) {
unit.stats.Sub(StatTag.HP, damage);
yield return CoUtils.RunParallel(new IEnumerator[] {
doll.damagePopup.DamageRoutine(damage),
battle.controller.playerHP.AnimateWithSpeedRoutine(Get(StatTag.MHP), Get(StatTag.HP)),
CoUtils.Wait(0.4f),
}, battle.controller);
yield return CoUtils.Wait(0.3f);
} else {
yield return battle.controller.enemyHUD.enableRoutine(this);
unit.stats.Sub(StatTag.HP, damage);
yield return CoUtils.RunParallel(new IEnumerator[] {
doll.damagePopup.DamageRoutine(damage),
battle.controller.enemyHUD.hpBar.AnimateWithSpeedRoutine(Get(StatTag.HP) / Get(StatTag.MHP)),
CoUtils.Wait(0.4f),
}, battle.controller);
yield return CoUtils.Wait(0.3f);
yield return battle.controller.enemyHUD.disableRoutine();
}
yield return doll.damagePopup.DeactivateRoutine();
if (IsDead()) {
yield return DeathRoutine();
}
}
public IEnumerator TakeStaggerRoutine(float stagger) {
if (IsStaggered()) {
yield return CoUtils.Wait(0.3f);
yield break;
}
battle.Log(this + " staggered by " + stagger + "%.");
if (align == Alignment.Hero) {
unit.stats.Sub(StatTag.STAGGER, stagger);
yield return CoUtils.RunParallel(new IEnumerator[] {
doll.damagePopup.StaggerDamageRoutine((int)stagger),
battle.controller.playerStagger.AnimateWithSpeedRoutine(Get(StatTag.STAGGER) / MaxStagger),
CoUtils.Wait(0.4f),
}, battle.controller);
yield return CoUtils.Wait(0.3f);
} else {
yield return battle.controller.enemyHUD.enableRoutine(this);
unit.stats.Sub(StatTag.STAGGER, stagger);
yield return CoUtils.RunParallel(new IEnumerator[] {
doll.damagePopup.StaggerDamageRoutine((int)stagger),
battle.controller.enemyHUD.stagger.AnimateWithSpeedRoutine(Get(StatTag.STAGGER) / MaxStagger),
CoUtils.Wait(0.4f),
}, battle.controller);
yield return CoUtils.Wait(0.3f);
yield return battle.controller.enemyHUD.disableRoutine();
}
yield return doll.damagePopup.DeactivateRoutine();
if (IsStaggered()) {
yield return InflictStatusRoutine(GetStaggerEffect());
}
}
public IEnumerator HealRoutine(int heal) {
int effectiveHeal = (int) Mathf.Min(heal, Get(StatTag.MHP) - Get(StatTag.HP));
battle.Log(this + " healed for " + heal);
unit.stats.Add(StatTag.HP, effectiveHeal);
yield return null;
}
public IEnumerator DeathRoutine() {
battle.Log(this + " died");
yield return PlayAnimationRoutine(doll.deathAnimation);
doll.appearance.sprite = null;
yield return null;
}
// inflict power is a prerolled chance 0.0-1.0, we'll check against it
public IEnumerator TryInflictStatusRoutine(StatusEffect effect, float baseInflictPower) {
float resistance = 0.0f;
if (effect.resistanceStat != StatTag.None) {
resistance += Get(effect.resistanceStat);
}
if (baseInflictPower > resistance || Has(effect)) {
yield return InflictStatusRoutine(effect);
} else {
battle.Log(name + " resisted.");
yield return CoUtils.Wait(0.7f);
}
}
public IEnumerator InflictStatusRoutine(StatusEffect effect) {
battle.Log(effect.inflictMessage, new Dictionary<string, string>() { ["$target"] = name });
yield return PlayAnimationRoutine(effect.inflictAnimation);
statuses.Add(new StatusInstance(effect, this));
}
public IEnumerator RemoveStatusRoutine(StatusEffect effect) {
battle.Log(effect.cureMessage, new Dictionary<string, string>() { ["$target"] = name });
if (effect.cureAnimation != null) {
yield return PlayAnimationRoutine(effect.cureAnimation);
} else {
yield return CoUtils.Wait(0.7f);
}
statuses = statuses.Where(status => status.effect != effect).ToList();
}
// === RPG =====================================================================================
public float Get(StatTag tag) {
return unit.stats.Get(tag);
}
public bool Is(StatTag tag) {
return unit.stats.Is(tag);
}
public bool IsStaggered() {
return unit.stats.Get(StatTag.STAGGER) <= 0;
}
public bool Has(StatusEffect effect) {
foreach (StatusInstance status in statuses) {
if (status.effect == effect) {
return true;
}
}
return false;
}
// checks for deadness and dead-like conditions like petrification
public bool IsDead() {
return unit.stats.Get(StatTag.HP) <= 0;
}
// === MISC ====================================================================================
public IEnumerator PlayAnimationRoutine(LuaAnimation animation) {
yield return doll.PlayAnimationRoutine(animation);
}
public override string ToString() {
return unit.ToString();
}
private StatusEffect GetStaggerEffect() {
return Resources.Load<StatusEffect>("Database/StatusEffects/stagger");
}
}
|
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using RazorPagesMvc.Data;
namespace RazorPagesMvc
{
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<GuestbookContext>(o =>
o.UseInMemoryDatabase("GuestbookDatabase"));
services.AddMvc();
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
app.UseMvc();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using OpenQA.Selenium;
using WebAutomationFramework.Pages;
namespace WebAutomationFramework
{
class SearchPodPage: BasePage
{
private IWebDriver Driver { get; set; }
private static By PageLocator = By.ClassName("checkbox");
public SearchPodPage(IWebDriver driver) : base(driver, PageLocator)
{
Driver = driver;
Console.WriteLine("Search Pod Page has loaded");
}
public void CheckBoxClick()
{
var checkBox = Driver.FindElement(By.ClassName("checkbox"));
checkBox.Click();
}
public bool IsCheckBoxChecked()
{
var checkBox = Driver.FindElement(By.ClassName("checkbox"));
return checkBox.Enabled;
}
public void OriginFieldClick()
{
Wait.WaitForElement(Driver, By.CssSelector("input[id^= origin-]"));
var originTextField = Driver.FindElement(By.CssSelector("input[id^= origin-]"));
originTextField.Click();
}
public void OriginFieldSendKeys(String originAirport)
{
Wait.WaitForElement(Driver, By.CssSelector("input[id^= origin-]"));
var originTextField = Driver.FindElement(By.CssSelector("input[id^= origin-]"));
originTextField.SendKeys(originAirport + Keys.Enter);
}
public void DestinationFieldClick()
{
Wait.WaitForElement(Driver, By.CssSelector("input[id^= origin-]"));
var destinationTestField = Driver.FindElement(By.CssSelector("input[id^=destination-]"));
destinationTestField.Click();
}
public void DestinationFieldSendKeys(String destinationAirport)
{
var destinationTextField = Driver.FindElement(By.CssSelector("input[id^= destination-]"));
destinationTextField.SendKeys(destinationAirport + Keys.Enter);
}
public void DepartingCalendarClick()
{
var departingCalendar = Driver.FindElement(By.ClassName("calendar"));
departingCalendar.Click();
}
public void OriginCalendarDateSelect()
{
var originDateInsert = DateTime.UtcNow.AddDays(7).ToString("yyyy-MM-dd");
var originDate = Driver.FindElement(By.CssSelector($"div[data-date='{originDateInsert}'] a"));
originDate.Click();
}
public void ShowFlightsButtonClick()
{
Wait.WaitForElement(Driver, By.CssSelector("button[class*= search-submit]"));
var showFlights = Driver.FindElement(By.CssSelector("button[class*= search-submit]"));
showFlights.Click();
}
public void HotelsTabClick()
{
Wait.WaitForElement(Driver, By.CssSelector("class[title*=Hotels]"));
var hotelsTabClick = Driver.FindElement(By.CssSelector("class[title*=Hotels]"));
hotelsTabClick.Click();
}
}
}
|
using PatientWebApp.DTOs;
namespace PatientWebAppTests.CreateObjectsForTests
{
public class CreateSurveyDTO
{
public SurveyDTO CreateInvalidTestObject()
{
return new SurveyDTO();
}
public SurveyDTO CreateValidTestObject()
{
return new SurveyDTO();
}
}
}
|
using Assets.Gamelogic.Utils;
using Improbable.Unity.Visualizer;
using Improbable;
using Improbable.Core;
using UnityEngine;
namespace Assets.Gamelogic.Core
{
public class TransformSender : MonoBehaviour
{
[Require]
private Position.Writer PositionWriter;
[Require]
private Rotation.Writer RotationWriter;
private void Update()
{
var positionUpdate = new Position.Update();
var rotationUpdate = new Rotation.Update();
var newPosition = transform.position.ToCoordinates();
var newRotation = transform.rotation;
if (PositionNeedsUpdate(newPosition))
{
positionUpdate.SetCoords(newPosition);
PositionWriter.Send(positionUpdate);
}
if (RotationNeedsUpdate(newRotation))
{
rotationUpdate.SetRotation(MathUtils.ToNativeQuaternion(transform.rotation));
RotationWriter.Send(rotationUpdate);
}
}
private bool PositionNeedsUpdate(Coordinates newPosition)
{
return !MathUtils.ApproximatelyEqual(newPosition.ToUnityVector(), PositionWriter.Data.coords.ToUnityVector());
}
private bool RotationNeedsUpdate(UnityEngine.Quaternion newRotation)
{
return !MathUtils.ApproximatelyEqual(newRotation, MathUtils.ToUnityQuaternion(RotationWriter.Data.rotation));
}
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
/// <summary>
/// Script encargado de darle la capacidad a un objeto de dashear a la direccion en la que se mueve.
/// </summary>
public class PlayerDash : MonoBehaviour
{
[SerializeField]
[Tooltip("Distancia recorrida al hacer un dash")]
private float dashDistance;
[SerializeField]
[Tooltip("Tiempo de recarga del Dash")]
private float dashCouldown;
// Para controlar el couldown del dash
private float couldownCounter;
private bool canDash;
private void Start()
{
canDash = false;
couldownCounter = dashCouldown;
}
private void Update()
{
if (canDash)
{
if (Input.GetKeyDown(KeyCode.Space))
{
canDash = false;
couldownCounter = 0;
Dash();
}
}
else
{
couldownCounter += Time.deltaTime;
if (couldownCounter >= dashCouldown)
canDash = true;
}
}
private void Dash()
{
float vAxis = Input.GetAxis("Vertical");
float hAxis = Input.GetAxis("Horizontal");
Vector3 dashDirection = new Vector3(hAxis, vAxis);
dashDirection = dashDirection.normalized * dashDistance;
transform.Translate(dashDirection);
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
namespace SimbaTvaerfagligt
{
public class Field
{
public List<Animal> animals;
public bool grass { get; set; }
public Field()
{
animals = new List<Animal>(); // Denne skal ændres da vi skal trække fra databasen
}
public void AddAnimal(Animal animal)
{
this.animals.Add(animal);
}
public List<Animal> Breed(string animalName)
{
bool maleFound = false;
List<Animal> newAnimals = new List<Animal>();
for (int i = 0; i < animals.Count; i++)
{
foreach (Animal item in animals)
{
if (item.IsFemale == false && item.Name == animalName)
{
maleFound = true;
}
}
if (maleFound)
{
foreach (Animal item in animals)
{
if (item.IsFemale == true && item.Name == animalName && IsReadyToBreed())
{
for (int j = 0; j < item.OffSpring; j++)
{
Animal w = null;
if (animalName == "Wildebeest") w = new Wildebeest();
if (animalName == "Lion") w = new Lion();
w.IsOffspring = true;
w.SetGender();
w.AddWeight();
newAnimals.Add(w);
}
//tilføjet efter aflevering -->
item.HasJustBreeded = true;
//<--
}
}
}
}
return newAnimals;
}
//Tilføjet efter aflevering af opgaven -->
private bool IsReadyToBreed()
{
foreach (Animal item in animals)
{
if (item.HasJustBreeded == true && item.breakFromBreeding >= 0 && item.IsFemale)
{
if (item.breakFromBreeding == 0)
{
item.HasJustBreeded = false;
item.breakFromBreeding = 3;
return true;
}
item.breakFromBreeding--;
return false;
}
}
return true;
}
//<--
public void EatAnimal()
{
Animal lion = null;
Animal prey = null;
for (int i = 0; i < animals.Count; i++)
{
foreach (Animal item in animals)
{
if (item.Name == "Lion")
{
lion = item;
}
}
if (lion != null && IsReadytoEatPrey())
{
foreach (Animal item in animals)
{
if (item.Name == "Wildebeest")
{
prey = item;
lion.AddWeight(prey.Weight);
lion.HasEatenAnimal = true;
}
}
animals.Remove(prey);
}
}
}
//Tilføjet efter aflevering af opgaven -->
private bool IsReadytoEatPrey()
{
foreach (Animal item in animals)
{
if (item.HasEatenAnimal && item.breakFromEating >= 0 && item.Name == "Lion")
{
if (item.breakFromEating == 0)
{
item.HasEatenAnimal = false;
item.breakFromEating = 3;
return true;
}
item.breakFromEating--;
return false;
}
}
return true;
}
public void EatGrass()
{
Animal hungryWildbeest = null;
for (int i = 0; i < animals.Count(); i++)
{
foreach (Animal item in animals)
{
if (item.Name == "Wildebeest")
{
hungryWildbeest = item;
}
}
if (hungryWildbeest != null)
{
if (this.grass == true)
{
hungryWildbeest.AddWeight(hungryWildbeest.Weight, grass);
//Fjerner græsset - det er spist og der dukker nyt græs op et andet sted.
this.grass = false;
}
}
}
}
public void StarveAnimals()
{
Animal starvingWildebeest = null;
Animal starvingLion = null;
for (int i = 0; i < animals.Count(); i++)
{
foreach (Animal item in animals)
{
if (item.Name == "Wildebeest" && this.grass == false)
{
starvingWildebeest = item;
starvingWildebeest.RemoveWeight(starvingWildebeest.Weight);
}
}
if (starvingWildebeest == null)
{
foreach (Animal item in animals)
{
if (item.Name == "Lion")
{
starvingLion = item;
starvingLion.RemoveWeight(starvingLion.Weight);
}
}
}
}
}
}
}
|
using System;
namespace Core.EventBus.Abstraction
{
public interface IEventHandlerFactory
{
IIntegrationEventHandler GetHandler(Type handlerType);
}
}
|
using System.Windows;
namespace CourseWork_CSaN
{
/// <summary>
/// Логика взаимодействия для DialogWithTextBox.xaml
/// </summary>
public partial class DialogWithTextBox : Window
{
public string NewName { get => tbNewName.Text.Trim(); }
public DialogWithTextBox()
{
InitializeComponent();
}
private void ButtonAcceptClick(object sender, RoutedEventArgs e)
{
DialogResult = true;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Autodesk.AutoCAD.DatabaseServices;
namespace fi.upm.es.dwgDecoder.dwgElementos
{
/**
* @brief Clase que contiene los atributos de una entidad Arco de AutoCAD.
*
**/
public class dwgArco : dwgEntidadBase
{
/**
* @brief Variabe de tipo lista que contiene la lista de los identificadores de las lineas en las que se descompone el arco.
*
**/
public List<ObjectId> lineas = new List<ObjectId>();
/**
* @brief Variabe de tipo Double que contiene el radio del arco.
*
**/
public Double radio;
/**
* @brief Variabe de tipo Double que contiene el ángulo inicial del arco.
*
**/
public Double angulo_inicio;
/**
* @brief Variabe de tipo Double que contiene el ángulo final del arco.
*
**/
public Double angulo_final;
/**
* @brief Variabe de tipo ObjectId que identifica el punto situado en el centro del arco.
*
**/
public ObjectId punto_centro;
/**
* @brief Variabe que serializa el contenido de la entidad Arco.
* @deprecated No esta actualizado con los últimos atributos de la entidad.
**/
public override String ToString()
{
StringBuilder sb = new StringBuilder();
sb.AppendLine("ARCO " + this.objId );
sb.AppendLine("\tCapaId " + this.capaId);
sb.AppendLine("\tParentId " + this.parentId);
foreach (ObjectId obj in this.lineas)
{
sb.AppendLine("\t\tLinea " + obj.ToString());
}
return sb.ToString();
}
}
}
|
using System.Linq;
using System.Threading.Tasks;
using DFC.ServiceTaxonomy.JobProfiles.Module.EFDataModels;
using DFC.ServiceTaxonomy.JobProfiles.Module.Interfaces;
namespace DFC.ServiceTaxonomy.JobProfiles.Module.Repositories
{
public class SocMappingRepository : ISocMappingRepository
{
private readonly DfcDevOnetSkillsFrameworkContext _dbContext;
public SocMappingRepository(DfcDevOnetSkillsFrameworkContext dbContext)
{
_dbContext = dbContext;
}
public async Task<bool> UpdateMappingAsync(string socCode, string onetId)
{
var onetData = _dbContext.OccupationData.AsQueryable().FirstOrDefault(o => o.OnetsocCode == onetId);
if (onetData == null)
{
// If we don't find a valid ONet data id then we can't map skills
return false;
}
var socMapping = _dbContext.DfcSocMappings.AsQueryable().FirstOrDefault(s => s.SocCode == socCode);
if(socMapping == null)
{
// Add a new soc code - onet id mapping
await _dbContext.DfcSocMappings.AddAsync(new DfcSocMapping { SocCode = socCode, OnetCode = onetData.OnetsocCode, JobProfile = onetData.Title, QualityRating = 0, UpdateStatus = "UpdateCompleted" });
}
else if(socMapping.OnetCode != onetId)
{
// Update and existing soc code with a new onet id mapping
socMapping.OnetCode = onetData.OnetsocCode;
socMapping.JobProfile = onetData.Title;
_dbContext.DfcSocMappings.Update(socMapping);
}
else
{
// Soc code - onet id mapping already existis
return true;
}
var resultCount = await _dbContext.SaveChangesAsync();
return resultCount == 1;
}
}
}
|
using System;
namespace Phenix.Test.使用指南._12._6._2._7
{
/// <summary>
/// FinancialStatisticPeriod
/// </summary>
[Serializable]
[Phenix.Core.Mapping.ReadOnly]
public class FinancialStatisticPeriodReadOnly : FinancialStatisticPeriod<FinancialStatisticPeriodReadOnly>
{
private FinancialStatisticPeriodReadOnly()
{
//禁止添加代码
}
}
/// <summary>
/// FinancialStatisticPeriod清单
/// </summary>
[Serializable]
public class FinancialStatisticPeriodReadOnlyList : Phenix.Business.BusinessListBase<FinancialStatisticPeriodReadOnlyList, FinancialStatisticPeriodReadOnly>
{
private FinancialStatisticPeriodReadOnlyList()
{
//禁止添加代码
}
}
/// <summary>
/// FinancialStatisticPeriod
/// </summary>
[Serializable]
public class FinancialStatisticPeriod : FinancialStatisticPeriod<FinancialStatisticPeriod>
{
private FinancialStatisticPeriod()
{
//禁止添加代码
}
}
/// <summary>
/// FinancialStatisticPeriod清单
/// </summary>
[Serializable]
public class FinancialStatisticPeriodList : Phenix.Business.BusinessListBase<FinancialStatisticPeriodList, FinancialStatisticPeriod>
{
private FinancialStatisticPeriodList()
{
//禁止添加代码
}
}
/// <summary>
/// 财务统计时段
/// </summary>
//* CascadingDelete = false
[Phenix.Core.Mapping.ClassDetailAttribute("CFC_FINANCIAL_CLASS_RELATION", "FCR_FSP_ID", "FK_FCR_FSP_ID", FriendlyName = "财务类关系", CascadingDelete = false), Phenix.Core.Mapping.ClassAttribute("CFC_FINANCIAL_STATISTIC_PERIOD", FriendlyName = "财务统计时段"), System.ComponentModel.DisplayNameAttribute("财务统计时段"), System.SerializableAttribute()]
public abstract class FinancialStatisticPeriod<T> : Phenix.Business.BusinessBase<T> where T : FinancialStatisticPeriod<T>
{
/// <summary>
/// ID
/// </summary>
public static readonly Phenix.Business.PropertyInfo<long?> FSP_IDProperty = RegisterProperty<long?>(c => c.FSP_ID);
[Phenix.Core.Mapping.Field(FriendlyName = "ID", TableName = "CFC_FINANCIAL_STATISTIC_PERIOD", ColumnName = "FSP_ID", IsPrimaryKey = true, NeedUpdate = true)]
private long? _FSP_ID;
/// <summary>
/// ID
/// </summary>
[System.ComponentModel.DisplayName("ID")]
public long? FSP_ID
{
get { return GetProperty(FSP_IDProperty, _FSP_ID); }
internal set
{
SetProperty(FSP_IDProperty, ref _FSP_ID, value);
}
}
[System.ComponentModel.Browsable(false)]
[System.ComponentModel.DataAnnotations.Display(AutoGenerateField = false)]
public override string PrimaryKey
{
get { return FSP_ID.ToString(); }
}
}
}
|
using Microsoft.AspNetCore.SignalR;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
public class PlayerHub: Hub
{
public Player CreatePlayerBackend(string name)
{
Player player = new Player(name, Clients.Caller, Context.ConnectionId);
if (Room.activeRoom == null)
{
Room.activeRoom = new Room();
}
Room.activeRoom.AddPlayer(player);
Console.WriteLine("createplayer"+name);
return player;
}
public async void StartGameBackend()
{
if (Room.activeRoom.CanStartGame())
{
Console.WriteLine("can start game");
// await here?
BackToFront.clients = Clients;
BackToFront.NotifyOthersBackend();
// no need to wait here?
Room.activeRoom.StartGame();
Console.WriteLine("finish start game");
}
else
{
await Clients.Caller.SendAsync("showErrorMessage", "Cannot start the game!");
}
}
public List<object> GetAllPlayers()
{
return Room.activeRoom.PlayerList.Select((o)=>new {
connectionId = o.ConnectionId,
name = o.Name
}).ToList<object>();
}
public void ReturnUserHandBackend(List<string> cards)
{
var formattedCards = cards.Select(cardString => new Card(cardString)).ToList();
PlayerHubTempData.userHand = formattedCards;
PlayerHubTempData.finishPlay = true;
}
public void ReturnTributeBackend(List<string> cards)
{
var formattedCards = cards.Select(cardString => new Card(cardString)).ToList();
PlayerHubTempData.returnCards = formattedCards;
PlayerHubTempData.finishTribute = true;
}
public void ReturnPlayOneMoreRoundBackend(bool returnvalue)
{
PlayerHubTempData.playOneMoreRound &= returnvalue;
}
public void ReturnAceGoPublicBackend(bool returnvalue)
{
if(returnvalue)
PlayerHubTempData.aceGoPublic = returnvalue;
}
public string getMyConnectionId()
{
return Context.ConnectionId;
}
public void showAceIdPlayerListBackend()
{
BackToFront.showAceIdPlayerListBackend(Context.ConnectionId);
}
public override async Task OnDisconnectedAsync(System.Exception exception)
{
Console.WriteLine("disconnected");
Console.WriteLine();
Room.activeRoom = new Room();
await Clients.All.SendAsync("showErrorMessage", "Someone disconnected from the game. The game will be restarted in 5 seconds");
await Task.Delay(5000);
await Clients.All.SendAsync("BreakGameFrontend");
// we should reinit some static variable and static class. Because they are not reset into default
// value when the connection is stopped.
PlayerHubTempData.reinitTempData();
}
}
// a => b => client
// client => b => a
// a => b => client
// test =>?b => ?a
// A (server) => A (client) => Return (server)
// Return (server) => A (client) => A (server) |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class EngineSoundManager : MonoBehaviour
{
public bool playProblem = false;
public bool playSmoke = false;
public bool stop = true;
private AudioSource engineSound;
public AudioClip engineProblem, engineExplose, engineSmoke;
private float myPitch = 0;
void Start()
{
engineSound = this.GetComponent<AudioSource>();
myPitch = 0;
}
void Update()
{
if (playProblem == true)
{
if (engineSound.clip != engineProblem)
{
engineSound.clip = engineProblem;
engineSound.Play();
engineSound.volume = 1.5f;
}
engineSound.pitch = Mathf.Lerp(myPitch,2,0.01f);
myPitch = engineSound.pitch;
}
if (playSmoke == true)
{
if (engineSound.clip != engineSmoke)
{
engineSound.clip = engineSmoke;
engineSound.Play();
engineSound.volume = 1.5f;
engineSound.pitch = 1;
myPitch = 0;
}
}
if (stop == true)
{
engineSound.Stop();
}
}
}
|
using System;
using System.Windows.Forms;
using System.Collections.Generic;
namespace TechnicalSupport
{
public partial class TarifForm : Form
{
SettingsJSON ConectionSettings;
public TarifForm()
{
InitializeComponent();
}
private void TarifForm_Load(object sender, EventArgs e)
{
ConectionSettings = (SettingsJSON)new WorkWithFileJson().GetJSONDataWithFile(@"JSONFile/DataBase.json", typeof(SettingsJSON));
for (int i = 0; i < ConectionSettings.DataBase.Tarif.nameTarif.Count; i++)
{
TarifBox.Items.Add(ConectionSettings.DataBase.Tarif.nameTarif[i]);
}
}
private void TarifBox_SelectedIndexChanged(object sender, EventArgs e)
{
int index = TarifBox.SelectedIndex;
TarifText.Text = "";
List<string> textTarif = ConectionSettings.DataBase.Tarif.ListTextTarif[index];
for (int i = 0; i < textTarif.Count; i++)
{
TarifText.Text += textTarif[i] + "\r\n\r\n";
}
}
private void button1_Click(object sender, EventArgs e)
{
Close();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NSTOX.DAL.Model;
using NSTOX.DAL.Helper;
namespace NSTOX.DAL.DAL
{
public class JobAuditDAL : BaseDAL
{
public static void InsertJobAudit(JobAudit job)
{
try
{
ExecuteNonQuery("usp_Insert_JobAudit", job, true);
}
catch (Exception ex)
{
Logger.LogException(ex);
}
}
public static List<JobAudit> GetNewJobAudits(int retailerId)
{
try
{
return GetFromDBAndMapToObjectsList<JobAudit>("usp_Get_NewJobAudits", new { RetailerId = retailerId });
}
catch (Exception ex)
{
Logger.LogException(ex);
return null;
}
}
public static JobAudit GetJobAuditByFilePath(int retailerId, string filePath)
{
try
{
return GetFromDBAndMapToObjectsList<JobAudit>("usp_Get_JobAuditByFilePath",
new
{
RetailerId = retailerId,
FilePath = filePath
}).FirstOrDefault();
}
catch (Exception ex)
{
Logger.LogException(ex);
return null;
}
}
public static void UpdateJobAudit(JobAudit job)
{
try
{
ExecuteNonQuery("usp_Update_JobAudit", job, false, true);
}
catch (Exception ex)
{
Logger.LogException(ex);
}
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CameraSizeBomb : MonoBehaviour
{
public float bombTime;
public bool tf;
private float timer;
void Update()
{
if (timer > 0)
timer -= Time.deltaTime;
else
{
timer = bombTime;
tf = !tf;
}
if (tf)
Zoom(true, 15);
else
Zoom(false, 15);
}
void Zoom(bool TF, int speed, int maxSize = 10)
{
if (TF && Camera.main.orthographicSize < maxSize)
{
Camera.main.orthographicSize += speed * Time.deltaTime;
if (Camera.main.orthographicSize > maxSize)
Camera.main.orthographicSize = maxSize;
}
else if (!TF && Camera.main.orthographicSize > 7)
{
Camera.main.orthographicSize -= speed * Time.deltaTime;
if (Camera.main.orthographicSize < 7)
Camera.main.orthographicSize = 7;
}
}
}
|
using Microsoft.Extensions.Options;
using Sentry.Internal.Http;
using MauiConstants = Sentry.Maui.Internal.Constants;
namespace Sentry.Maui.Tests;
public partial class SentryMauiAppBuilderExtensionsTests
{
private class Fixture
{
public MauiAppBuilder Builder { get; }
public Fixture()
{
var builder = MauiApp.CreateBuilder();
builder.Services.AddSingleton(Substitute.For<IApplication>());
builder.Services.Configure<SentryMauiOptions>(options =>
{
options.Transport = Substitute.For<ITransport>();
options.Dsn = ValidDsn;
options.AutoSessionTracking = false;
options.InitNativeSdks = false;
});
Builder = builder;
}
}
private readonly Fixture _fixture = new();
[Fact]
public void CanUseSentry_WithConfigurationOnly()
{
// Arrange
var builder = _fixture.Builder;
builder.Services.Configure<SentryMauiOptions>(options =>
{
options.Dsn = ValidDsn;
});
// Act
var chainedBuilder = builder.UseSentry();
using var app = builder.Build();
var options = app.Services.GetRequiredService<IOptions<SentryMauiOptions>>().Value;
var hub = app.Services.GetRequiredService<IHub>();
// Assert
Assert.Same(builder, chainedBuilder);
Assert.True(hub.IsEnabled);
Assert.Equal(ValidDsn, options.Dsn);
Assert.False(options.Debug);
}
[Fact]
public void CanUseSentry_WithDsnStringOnly()
{
// Arrange
var builder = _fixture.Builder;
// Act
var chainedBuilder = builder.UseSentry(ValidDsn);
using var app = builder.Build();
var options = app.Services.GetRequiredService<IOptions<SentryMauiOptions>>().Value;
var hub = app.Services.GetRequiredService<IHub>();
// Assert
Assert.Same(builder, chainedBuilder);
Assert.True(hub.IsEnabled);
Assert.Equal(ValidDsn, options.Dsn);
Assert.False(options.Debug);
}
[Fact]
public void CanUseSentry_WithOptionsOnly()
{
// Arrange
var builder = _fixture.Builder;
// Act
var chainedBuilder = builder.UseSentry(options =>
{
options.Dsn = ValidDsn;
});
using var app = builder.Build();
var options = app.Services.GetRequiredService<IOptions<SentryMauiOptions>>().Value;
var hub = app.Services.GetRequiredService<IHub>();
// Assert
Assert.Same(builder, chainedBuilder);
Assert.True(hub.IsEnabled);
Assert.Equal(ValidDsn, options.Dsn);
Assert.False(options.Debug);
}
[Fact]
public void CanUseSentry_WithConfigurationAndOptions()
{
// Arrange
var builder = _fixture.Builder;
builder.Services.Configure<SentryMauiOptions>(options =>
{
options.Dsn = ValidDsn;
});
// Act
var chainedBuilder = builder.UseSentry(options =>
{
options.Release = "test";
});
using var app = builder.Build();
var options = app.Services.GetRequiredService<IOptions<SentryMauiOptions>>().Value;
var hub = app.Services.GetRequiredService<IHub>();
// Assert
Assert.Same(builder, chainedBuilder);
Assert.True(hub.IsEnabled);
Assert.Equal(ValidDsn, options.Dsn);
Assert.Equal("test", options.Release);
}
[Fact]
public void UseSentry_EnablesGlobalMode()
{
// Arrange
var builder = _fixture.Builder;
// Act
_ = builder.UseSentry(ValidDsn);
using var app = builder.Build();
var options = app.Services.GetRequiredService<IOptions<SentryMauiOptions>>().Value;
// Assert
Assert.True(options.IsGlobalModeEnabled);
}
[Fact]
public void UseSentry_SetsMauiSdkNameAndVersion()
{
// Arrange
SentryEvent @event = null;
var builder = _fixture.Builder
.UseSentry(options =>
{
options.Dsn = ValidDsn;
options.SetBeforeSend((e, _) =>
{
// capture the event
@event = e;
// but don't actually send it
return null;
}
);
});
// Act
using var app = builder.Build();
var client = app.Services.GetRequiredService<ISentryClient>();
client.CaptureMessage("test");
// Assert
Assert.NotNull(@event);
Assert.Equal(MauiConstants.SdkName, @event.Sdk.Name);
Assert.Equal(MauiConstants.SdkVersion, @event.Sdk.Version);
}
[Fact]
public void UseSentry_EnablesHub()
{
// Arrange
var builder = _fixture.Builder.UseSentry(ValidDsn);
// Act
using var app = builder.Build();
var hub = app.Services.GetRequiredService<IHub>();
// Assert
Assert.True(hub.IsEnabled);
}
[Fact]
public void UseSentry_AppDispose_DisposesHub()
{
// Note: It's crucial to dispose the hub when the app disposes, so that we flush events from the
// queue in the BackgroundWorker. The app container will dispose any services registered
// that implement IDisposable.
// Arrange
var builder = _fixture.Builder.UseSentry(ValidDsn);
// Act
IHub hub;
using (var app = builder.Build())
{
hub = app.Services.GetRequiredService<IHub>();
}
// Assert
// Note, the hub is disabled when disposed. We ensure it's first enabled in the previous test.
Assert.False(hub.IsEnabled);
}
[Fact]
public void UseSentry_WithCaching_Default()
{
// Arrange
var builder = _fixture.Builder;
// Act
builder.UseSentry();
using var app = builder.Build();
var options = app.Services.GetRequiredService<IOptions<SentryMauiOptions>>().Value;
// Assert
#if PLATFORM_NEUTRAL
Assert.Null(options.CacheDirectoryPath);
Assert.IsNotType<CachingTransport>(options.Transport);
#else
var expectedPath = Microsoft.Maui.Storage.FileSystem.CacheDirectory;
Assert.Equal(expectedPath, options.CacheDirectoryPath);
Assert.IsType<CachingTransport>(options.Transport);
#endif
}
[Fact]
public void UseSentry_WithCaching_CanChangeCacheDirectoryPath()
{
// Arrange
var builder = _fixture.Builder;
var fileSystem = new FakeFileSystem();
using var cacheDirectory = new TempDirectory(fileSystem);
var cachePath = cacheDirectory.Path;
// Act
builder.UseSentry(options =>
{
options.FileSystem = fileSystem;
options.CacheDirectoryPath = cachePath;
});
using var app = builder.Build();
var options = app.Services.GetRequiredService<IOptions<SentryMauiOptions>>().Value;
// Assert
Assert.Equal(cachePath, options.CacheDirectoryPath);
}
}
|
using System.Collections.Generic;
using System.Linq;
using NUnit.Framework;
using SpaceHosting.Index.Sparnn.Distances;
namespace SpaceHosting.Index.Tests.Sparnn.Distances
{
public class JaccardBinarySingleFeatureOrientedSpaceTests
{
[Test]
public void SanityCheck()
{
var baseVectors = new[,]
{
{1.0, 0.0, 0.0, 1.0, 1.0},
{1.0, 1.0, 0.0, 0.0, 0.0},
{0.0, 0.0, 1.0, 0.0, 0.0},
{0.0, 1.0, 1.0, 0.0, 0.0}
};
var searchVectors = new[,]
{
{0.0, 1.0, 1.0, 0.0, 0.0},
{0.0, 0.0, 1.0, 1.0, 1.0},
{1.0, 1.0, 1.0, 0.0, 1.0}
};
var expectedResults = new[,]
{
{5.0 / 5.0, 2.0 / 3.0, 1.0 / 2.0, 0.0 / 2.0},
{2.0 / 4.0, 5.0 / 5.0, 2.0 / 3.0, 3.0 / 4.0},
{3.0 / 5.0, 2.0 / 4.0, 3.0 / 4.0, 2.0 / 4.0}
};
var jaccardDistanceSpace = CreateJaccardBinaryDistanceSpace(baseVectors);
var actualResults = jaccardDistanceSpace.SearchNearestAsync(CreateSparseVectors(searchVectors), baseVectors.Length).GetAwaiter().GetResult().ToArray();
Assert.AreEqual(actualResults.Length, expectedResults.GetLength(0));
for (var i = 0; i < actualResults.Length; i++)
{
Assert.AreEqual(actualResults[i].Length, expectedResults.GetLength(1));
foreach (var nearestSearchResult in actualResults[i])
{
Assert.AreEqual(expectedResults[i, nearestSearchResult.Element], nearestSearchResult.Distance, 1e-6);
}
}
}
[Test]
public void OnlyZeroDistance_ShouldNotThrow()
{
var baseVectors = new[,]
{
{1.0, 0.0, 0.0, 0.0, 0.0},
{1.0, 0.0, 0.0, 0.0, 0.0},
{1.0, 0.0, 0.0, 0.0, 0.0},
};
var searchVectors = new[,]
{
{1.0, 0.0, 0.0, 0.0, 0.0}
};
var expectedResults = new[,]
{
{0.0 / 1.0, 0.0 / 1.0, 0.0 / 1.0}
};
var jaccardDistanceSpace = CreateJaccardBinaryDistanceSpace(baseVectors);
var actualResults = jaccardDistanceSpace.SearchNearestAsync(CreateSparseVectors(searchVectors), baseVectors.Length).GetAwaiter().GetResult().ToArray();
Assert.AreEqual(actualResults.Length, expectedResults.GetLength(0));
for (var i = 0; i < actualResults.Length; i++)
{
Assert.AreEqual(actualResults[i].Length, expectedResults.GetLength(1));
foreach (var nearestSearchResult in actualResults[i])
{
Assert.AreEqual(expectedResults[i, nearestSearchResult.Element], nearestSearchResult.Distance, 1e-6);
}
}
}
private static JaccardBinarySingleFeatureOrientedSpace<int> CreateJaccardBinaryDistanceSpace(double[,] matrix)
{
var vectorsCount = matrix.GetLength(0);
var baseVectors = CreateSparseVectors(matrix);
var indexes = Enumerable
.Range(0, vectorsCount)
.ToArray();
return new JaccardBinarySingleFeatureOrientedSpace<int>(baseVectors, indexes);
}
private static IList<MathNet.Numerics.LinearAlgebra.Double.SparseVector> CreateSparseVectors(double[,] matrix)
{
var vectorsCount = matrix.GetLength(0);
var vectorsLength = matrix.GetLength(1);
return Enumerable
.Range(0, vectorsCount)
.Select(row => MathNet.Numerics.LinearAlgebra.Double.SparseVector.Create(vectorsLength, col => matrix[row, col]))
.ToList();
}
}
}
|
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace server.Model
{
public class NewsList
{
[JsonProperty(PropertyName = "articles")]
public List<News> ListOfNews { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Breeze;
using Breeze.Screens;
using Breeze.AssetTypes;
using Breeze.Helpers;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
namespace Breeze.Helpers
{
public static class SpriteBatchHelpers
{
public static void DrawBorder(this SmartSpriteBatch spriteBatch, FloatRectangle rect, Color color, int brushSize, FloatRectangle? clip)
{
for (int x = 0; x < brushSize; x++)
{
for (int y = 0; y < brushSize; y++)
{
FloatRectangle r = new FloatRectangle(rect.X + x, rect.Y + y, rect.Width - x - x, rect.Height - y - y);
spriteBatch.DrawRectangle(r, color, clip: clip);
}
}
}
public static void DrawTexturedRectangle(this SmartSpriteBatch spriteBatch, FloatRectangle rect, Color color, string fillTexture, FloatRectangle? clip = null)
{
DrawTexturedRectangle(spriteBatch, rect, color, Solids.Instance.AssetLibrary.GetTexture(fillTexture), clip: clip);
}
public static void DrawTexturedRectangle(this SmartSpriteBatch spriteBatch, FloatRectangle trect, Color color, Texture2D fillTexture2D, TileMode tileMode = TileMode.JustStretch, FloatRectangle? clip = null)
{
// using (new SmartSpriteBatchManager(Solids.Instance.SpriteBatch))
{
FloatRectangle rect = trect.Clip(clip);
switch (tileMode)
{
case (TileMode.Tile):
{
for (int y = 0; y < rect.Height; y = y + fillTexture2D.Height)
{
for (int x = 0; x < rect.Width; x = x + fillTexture2D.Width)
{
float twidth = fillTexture2D.Width;
float theight = fillTexture2D.Height;
float rX = x + rect.X;
float rY = y + rect.Y;
if (x + twidth > rect.Width)
{
twidth = fillTexture2D.Width - ((x + twidth) - rect.Width);
}
if (y + theight > rect.Height)
{
theight = fillTexture2D.Height - ((y + theight) - rect.Height);
}
Rectangle sourceRectangle = new Rectangle(0, 0, (int) twidth, (int) theight);
Rectangle destRectangle = new Rectangle((int) rX, (int) rY, (int) twidth, (int) theight);
spriteBatch.Draw(fillTexture2D, destRectangle, sourceRectangle, color);
}
}
break;
}
case (TileMode.JustStretch):
{
spriteBatch.Draw(fillTexture2D, rect.ToRectangle, color);
break;
}
case (TileMode.StretchToFill):
{
float rectAspectRatio = (float) rect.Width / (float) rect.Height;
float aspectRatio = (float) fillTexture2D.Width / (float) fillTexture2D.Height;
float sw = 0;
float sh = 0;
int xo = 0;
int yo = 0;
sw = fillTexture2D.Width;
sh = sw / rectAspectRatio;
yo = (int) ((fillTexture2D.Height - sh) / 2f);
if (sh > fillTexture2D.Height)
{
sh = fillTexture2D.Height;
sw = sh * rectAspectRatio;
yo = 0;
xo = (int) ((fillTexture2D.Width - sw) / 2f);
}
Rectangle sourceRect = new Rectangle((int) xo, (int) yo, (int) sw, (int) sh);
spriteBatch.Draw(fillTexture2D, rect.ToRectangle, sourceRect, color);
break;
}
}
}
}
}
}
|
using System;
using ResilienceClasses;
using System.Collections.Generic;
using AppKit;
using Foundation;
using Xceed.Words.NET;
namespace ManageSales
{
public partial class ViewController : NSViewController
{
private clsLoan loan;
private clsEntity borrower;
private clsEntity lender;
private clsEntity title;
private bool bRecordSaleContract = false;
private clsLoan.State statusFilter = clsLoan.State.Unknown;
private int lenderID = -1;
private Dictionary<string, clsLoan> loansByAddress = new Dictionary<string, clsLoan>();
public ViewController(IntPtr handle) : base(handle)
{
}
public override void ViewDidLoad()
{
base.ViewDidLoad();
// load Loans By Address
clsCSVTable tbl = new clsCSVTable(clsLoan.strLoanPath);
for (int i = 0; i < tbl.Length(); i++)
{
clsLoan l = new clsLoan(i);
loansByAddress.Add(l.Property().Address(), l);
}
// Do any additional setup after loading the view.
this.UpdateAddressList();
this.SaleDatePicker.DateValue = (NSDate)System.DateTime.Today.Date;
this.ChooseActionPopUp.RemoveAllItems();
this.RecordDatePicker.DateValue = (NSDate)System.DateTime.Today.Date;
this.LenderComboBox.RemoveAll();
clsCSVTable tblEntities = new clsCSVTable(clsEntity.strEntityPath);
for (int i = 0; i < tblEntities.Length(); i++)
{
if (tbl.Matches(clsLoan.LenderColumn,i.ToString()).Count > 0)
this.LenderComboBox.Add((NSString)(new clsEntity(i)).Name());
}
this.StatusComboBox.RemoveAll();
foreach (clsLoan.State c in Enum.GetValues(typeof(clsLoan.State)))
this.StatusComboBox.Add((NSString)c.ToString());
}
public override NSObject RepresentedObject
{
get
{
return base.RepresentedObject;
}
set
{
base.RepresentedObject = value;
// Update the view, if already loaded.
}
}
#region Event Handlers
partial void AddressChosen(NSComboBox sender)
{
this.UpdateChosenAddress();
}
partial void GoButtonPressed(NSButton sender)
{
if (this.ChooseActionPopUp.SelectedItem == null)
{
this.StatusMessageTextField.StringValue = "No Action Chosen / Available. Nothing was updated.";
}
else
{
if (this.ChooseActionPopUp.TitleOfSelectedItem == "Schedule")
{
this.ScheduleNewSale();
}
else if (this.ChooseActionPopUp.TitleOfSelectedItem == "Update")
{
if (StatusTextField.StringValue == clsLoan.State.PendingSale.ToString())
this.UpdateScheduledSale();
else
this.UpdateProjectedDisposition();
}
else if (this.ChooseActionPopUp.TitleOfSelectedItem == "Cancel")
{
this.CancelScheduledSale();
}
else if (this.ChooseActionPopUp.TitleOfSelectedItem == "Mark Loan Repaid")
{
this.MarkRepaid();
}
else if (this.ChooseActionPopUp.TitleOfSelectedItem == "Mark Addl Int Actual")
{
this.MarkAdditionalInterestActual();
}
else if (this.ChooseActionPopUp.TitleOfSelectedItem == "Update/Add")
{
this.UpdateScheduledAdditionalInterest();
}
else if (this.ChooseActionPopUp.TitleOfSelectedItem == "Add Addl Int and Mark Actual")
{
this.UpdateScheduledAdditionalInterest();
this.MarkAdditionalInterestActual();
}
else if (this.ChooseActionPopUp.TitleOfSelectedItem == "Payoff Letter")
{
this.GeneratePayoffLetter();
}
else if (this.ChooseActionPopUp.TitleOfSelectedItem == "Discharge Letter")
{
this.GenerateDischargeLetter();
}
}
this.UpdateChosenAddress(false);
}
partial void ContractReceivedToggled(NSButton sender)
{
this.bRecordSaleContract = !this.bRecordSaleContract;
}
#endregion
private void UpdateChosenAddress(bool clearMessageText = true)
{
this.ChooseActionPopUp.RemoveAllItems();
if (clsLoan.LoanID(this.AddressComboBox.StringValue) >= 0)
{
this.loan = new clsLoan(clsLoan.LoanID(this.AddressComboBox.StringValue));
this.borrower = new clsEntity(this.loan.BorrowerID);
this.lender = new clsEntity(this.loan.LenderID);
this.title = new clsEntity(this.loan.TitleCompanyID());
if (clearMessageText)
this.StatusMessageTextField.StringValue = "";
this.StatusTextField.StringValue = this.loan.Status().ToString();
this.RepaymentAmountTextField.DoubleValue = 0D;
this.SetDefaultLabels();
switch (this.loan.Status())
{
case clsLoan.State.PendingSale:
this.ChooseActionPopUp.AddItem("Cancel");
this.ChooseActionPopUp.AddItem("Update");
this.ChooseActionPopUp.AddItem("Payoff Letter");
this.ChooseActionPopUp.AddItem("Discharge Letter");
if (this.loan.SaleDate() <= System.DateTime.Today) this.ChooseActionPopUp.AddItem("Mark Loan Repaid");
this.SaleDatePicker.DateValue = (NSDate)this.loan.SaleDate().Date.ToUniversalTime();
this.ExpectedSalePriceTextField.DoubleValue = 0D;
this.ExpectedAdditionalInterestTextField.DoubleValue = this.loan.ScheduledAdditionalInterest(System.DateTime.Today.Date);
DateTime scheduledSale = this.loan.SaleDate().Date;
double dPrincipalRepay = this.loan.LoanAsOf(scheduledSale.AddDays(1),true).PrincipalPaid(scheduledSale.AddDays(1));
double dHardInterest = this.loan.LoanAsOf(scheduledSale).AccruedInterest(scheduledSale);
double perdiem = dHardInterest - this.loan.LoanAsOf(scheduledSale.AddDays(-1)).AccruedInterest(scheduledSale.AddDays(-1));
double dAdditionalInterest = this.ExpectedAdditionalInterestTextField.DoubleValue;
this.ShowLoanPayoffLetterInfo(dPrincipalRepay, dHardInterest, perdiem);
break;
case clsLoan.State.Listed:
case clsLoan.State.Rehab:
this.ChooseActionPopUp.AddItem("Schedule");
this.ChooseActionPopUp.AddItem("Update");
this.SaleDatePicker.DateValue = (NSDate)this.loan.SaleDate().Date.ToUniversalTime();
this.ExpectedSalePriceTextField.DoubleValue = 0D;
this.ExpectedAdditionalInterestTextField.DoubleValue = this.loan.ProjectedAdditionalInterest(System.DateTime.Today.Date);
break;
case clsLoan.State.PendingAcquisition:
this.ChooseActionPopUp.AddItem("Update");
this.SaleDatePicker.DateValue = (NSDate)this.loan.SaleDate().Date.ToUniversalTime();
this.ExpectedSalePriceTextField.DoubleValue = 0D;
this.ExpectedAdditionalInterestTextField.DoubleValue = this.loan.ProjectedAdditionalInterest(System.DateTime.Today.Date);
break;
case clsLoan.State.Unknown:
case clsLoan.State.Cancelled:
break;
case clsLoan.State.Sold:
default:
this.SetSoldLabels();
this.ChooseActionPopUp.AddItem("Update/Add");
this.ChooseActionPopUp.AddItem("Add Addl Int and Mark Actual");
this.ChooseActionPopUp.AddItem("Mark Addl Int Actual");
this.ChooseActionPopUp.AddItem("Discharge Letter");
this.ExpectedSalePriceTextField.DoubleValue = 0D;
this.ExpectedAdditionalInterestTextField.DoubleValue = this.loan.ScheduledAdditionalInterest()
+ this.loan.PastDueAdditionalInterest();
this.SaleDatePicker.DateValue =
(NSDate)this.loan.FindDate(clsCashflow.Type.InterestAdditional,false,true).ToUniversalTime();
// check for LoanRecording and populate book/page or instrument/parcel if applicable
this.PopulateRecordingInfo();
break;
}
}
}
#region Generate Docs
private void GeneratePayoffLetter()
{
// identify template
string destinationPath = "/Volumes/GoogleDrive/Shared Drives/Resilience/Documents/Payoff Letter (" + this.AddressComboBox.StringValue + ") (" + this.loan.SaleDate().ToString("yyMMdd") + ").docx";
string templatePath = "/Volumes/GoogleDrive/Shared Drives/Resilience/Document Templates/Payoff Letter " +
this.lender.PathAbbreviation() + " " + this.borrower.PathAbbreviation() + ".docx";
// copy template to correct folder
System.IO.File.Copy(templatePath, destinationPath, true);
// find and replace using doc library
// get/compute replacement values
DateTime letterDate = DateTime.Today.Date;
DateTime scheduledSale = this.loan.SaleDate().Date;
double dPrincipalRepay = this.loan.LoanAsOf(scheduledSale.AddDays(1),true).PrincipalPaid(scheduledSale.AddDays(1)) -
this.loan.PrincipalPaid();
double dHardInterest = this.loan.LoanAsOf(scheduledSale).AccruedInterest(scheduledSale);
double perdiem = dHardInterest - this.loan.LoanAsOf(scheduledSale.AddDays(-1)).AccruedInterest(scheduledSale.AddDays(-1));
// find and replace
DocX newLetter = DocX.Load(destinationPath);
newLetter.ReplaceText("[LETTERDATE]",letterDate.ToString("MMMM d, yyyy"));
newLetter.ReplaceText("[SALEDATE]",scheduledSale.ToString("MMMM d, yyyy"));
newLetter.ReplaceText("[ADDRESS]",this.AddressComboBox.StringValue);
newLetter.ReplaceText("[INTEREST]",dHardInterest.ToString("#,##0.00"));
newLetter.ReplaceText("[PRINCIPAL]",dPrincipalRepay.ToString("#,##0.00"));
newLetter.ReplaceText("[PAYOFF]",(dHardInterest + dPrincipalRepay).ToString("#,##0.00"));
newLetter.ReplaceText("[PERDIEM]",perdiem.ToString("#0.00"));
// save new file
newLetter.Save();
// notify
this.StatusMessageTextField.StringValue = "Payoff Letter Created at " + destinationPath;
}
private void GenerateDischargeLetter()
{
// identify template
string destinationPath = "/Volumes/GoogleDrive/Shared Drives/Resilience/Documents/";
string templatePath = "/Volumes/GoogleDrive/Shared Drives/Resilience/Document Templates/";
switch (this.loan.Property().State())
{
case "MD":
templatePath += "Certificate of Satisfaction MD";
destinationPath += "Certificate of Satisfaction";
break;
case "NJ":
templatePath += "Discharge of Mortgage NJ";
destinationPath += "Discharge of Mortgage";
break;
case "PA":
templatePath += "Satisfaction of Mortgage PA";
destinationPath += "Discharge of Mortgage";
break;
case "GA":
templatePath += "Cancellation of Security Deed GA";
destinationPath += "Discharge of Mortgage";
break;
default:
templatePath += "Discharge of Mortgage GN";
destinationPath += "Discharge of Mortgage";
break;
}
templatePath += " " + this.lender.PathAbbreviation() + " " + this.borrower.PathAbbreviation() + ".docx";
destinationPath += " (" + this.AddressComboBox.StringValue + ").docx";
System.IO.File.Copy(templatePath, destinationPath, true);
// find and replace using doc library
// get/compute replacement values
DateTime todayDate = DateTime.Today.Date;
DateTime datedDate = this.loan.OriginationDate().Date;
string county = this.loan.Property().County();
string address = this.loan.Property().Address();
string city = this.loan.Property().Town();
DateTime recordDate = (DateTime)this.RecordDatePicker.DateValue;
// find and replace
DocX newLetter = DocX.Load(destinationPath);
if ((this.loan.Property().State() == "NJ") || (this.loan.Property().State() == "MD"))
{
string book = ExpectedSalePriceTextField.IntValue.ToString("#");
if (book == "0") { book = "____________"; }
string pages = RepaymentAmountTextField.IntValue.ToString("#");
if (pages == "0") { pages = "____________"; }
newLetter.ReplaceText("[TODAYDAY]", todayDate.Day.ToString());
newLetter.ReplaceText("[TODAYMONTH]", todayDate.ToString("MMMM"));
newLetter.ReplaceText("[TODAYYEAR]", todayDate.ToString("yyyy"));
newLetter.ReplaceText("[DATEDDATE]", datedDate.ToString("MMMM d, yyyy"));
newLetter.ReplaceText("[RECORDDATE]", recordDate.ToString("MMMM d, yyyy"));
newLetter.ReplaceText("[ADDRESS]", address);
newLetter.ReplaceText("[BOOK]", book);
newLetter.ReplaceText("[PAGES]", pages);
newLetter.ReplaceText("[COUNTY]", county);
newLetter.ReplaceText("[CITY]", city);
clsLoanRecording lr = new clsLoanRecording(address);
if (lr.ID() < 0)
{
lr = new clsLoanRecording(this.loan.ID(), Int32.Parse(book), Int32.Parse(pages), 0, 0, recordDate);
lr.Save();
}
}
else if (this.loan.Property().State() == "PA")
{
string instrument = ExpectedSalePriceTextField.IntValue.ToString("#");
if (instrument == "0") { instrument = "____________"; }
string parcel = RepaymentAmountTextField.IntValue.ToString("#");
if (parcel == "0") { parcel = "____________"; }
newLetter.ReplaceText("[DATEDDATE]", datedDate.ToString("MMMM d, yyyy"));
newLetter.ReplaceText("[RECORDDATE]", recordDate.ToString("MMMM d, yyyy"));
newLetter.ReplaceText("[ADDRESS]", address);
newLetter.ReplaceText("[CITY]", city);
newLetter.ReplaceText("[COUNTY]", county);
newLetter.ReplaceText("[TODAYDATE]", todayDate.ToString("MMMM d, yyyy"));
newLetter.ReplaceText("[PARCEL]", parcel);
newLetter.ReplaceText("[INSTRUMENT]", instrument);
clsLoanRecording lr = new clsLoanRecording(address);
if (lr.ID() < 0)
{
int a = Int32.Parse(instrument);
int b = Int32.Parse(parcel);
lr = new clsLoanRecording(this.loan.ID(), 0, 0, a, b, recordDate);
lr.Save();
}
}
else if (this.loan.Property().State() == "GA")
{
// COMPLETE GA DISCHARGE FIND/REPLACES
}
// save new file
newLetter.Save();
string destinationPath2 = "/Volumes/GoogleDrive/Shared Drives/";
destinationPath2 += this.lender.Name();
destinationPath2 += "/Loans/" + this.loan.Property().State() + "/" + address + ", " + city;
destinationPath2 += "/Sale/Satisfaction of Mortgage (" + address + ").docx";
try
{
newLetter.SaveAs(destinationPath2);
}
catch
{
destinationPath2 = " FAILED";
}
// notify
this.StatusMessageTextField.StringValue = "Release Letter Created at:/n" + destinationPath;
this.StatusMessageTextField.StringValue += "/n/nRelease Letter Copied to:/n" + destinationPath2;
}
#endregion
#region Update / Schedule / Cancel / Complete Loan
private void UpdateScheduledSale()
{
// cancel principal, move to new date
// cancel interest, calculate new accrued to new date
// cancel additional, move to new date, reduce by 1/2 (new accrued - old accrued)
DateTime scheduledSale = (DateTime)this.SaleDatePicker.DateValue;
if (scheduledSale <= System.DateTime.MinValue)// Today.Date)
{
this.StatusMessageTextField.StringValue = "Can't reschedule to a date in the past.";
}
else
{
// check to make sure scheduled date is after all rehabs
if (scheduledSale < this.loan.FindDate(clsCashflow.Type.RehabDraw, false, true))
{
scheduledSale = this.loan.FindDate(clsCashflow.Type.RehabDraw, false, true).AddDays(1);
this.StatusMessageTextField.StringValue =
"Proposed Sale Date is before last Rehab Date. \nChanging Sale Date to " + scheduledSale.ToString("MM/dd/yyyy");
}
// expire Scheduled Principal, Interest Payments; Accumulate AdditionalInterest
double dAdditionalInterest = 0D;
double dHardInterest = 0D;
double dAccrued = this.loan.LoanAsOf(scheduledSale).AccruedInterest(scheduledSale);
foreach (clsCashflow cf in this.loan.Cashflows())
{
if (cf.DeleteDate() > System.DateTime.Today.AddYears(50))
{
if (cf.TypeID() == clsCashflow.Type.Principal)
{
if (cf.Delete(System.DateTime.Today))
this.StatusMessageTextField.StringValue += "\nScheduled Principal Repayment Deleted as of Today.";
}
else if (cf.TypeID() == clsCashflow.Type.InterestHard)
{
dHardInterest += cf.Amount();
if (cf.Delete(System.DateTime.Today))
this.StatusMessageTextField.StringValue += "\nScheduled Hard Interest Deleted as of Today.";
}
else if (cf.TypeID() == clsCashflow.Type.InterestAdditional)
{
dAdditionalInterest += cf.Amount();
if (cf.Delete(System.DateTime.Today))
this.StatusMessageTextField.StringValue += "\nScheduled Additional Interest Deleted as of Today.";
}
}
}
// schedule principal repay
double dPrincipalRepay = this.loan.LoanAsOf(scheduledSale).Balance(scheduledSale);
this.loan.AddCashflow(new clsCashflow(scheduledSale, System.DateTime.Today, System.DateTime.MaxValue,
this.loan.ID(), dPrincipalRepay, false, clsCashflow.Type.Principal));
this.StatusMessageTextField.StringValue += "\nPrincipal Added: " + dPrincipalRepay.ToString("000,000.00");
this.StatusMessageTextField.StringValue += "," + scheduledSale.ToString("MM/dd/yyyy");
// schedule hard interest
dHardInterest = this.loan.LoanAsOf(scheduledSale).AccruedInterest(scheduledSale);
double perdiem = dHardInterest - this.loan.LoanAsOf(scheduledSale.AddDays(-1)).AccruedInterest(scheduledSale.AddDays(-1));
this.loan.AddCashflow(new clsCashflow(scheduledSale, System.DateTime.Today, System.DateTime.MaxValue,
this.loan.ID(), dHardInterest, false, clsCashflow.Type.InterestHard));
this.StatusMessageTextField.StringValue += "\nInterest Added: " + dHardInterest.ToString("000,000.00");
this.StatusMessageTextField.StringValue += "," + scheduledSale.ToString("MM/dd/yyyy");
// schedule additional interest
double dPrevAdditional = dAdditionalInterest;
dAdditionalInterest += this.ExpectedAdditionalInterestTextField.DoubleValue;
this.loan.AddCashflow(new clsCashflow(scheduledSale.AddDays(7), System.DateTime.Today, System.DateTime.MaxValue,
this.loan.ID(), dAdditionalInterest, false, clsCashflow.Type.InterestAdditional));
this.StatusMessageTextField.StringValue += "\nAddlInt Added: " + dAdditionalInterest.ToString("000,000.00");
this.StatusMessageTextField.StringValue += "," + scheduledSale.AddDays(7).ToString("MM/dd/yyyy");
this.StatusMessageTextField.StringValue += "\nPrev AddlInt: " + dPrevAdditional.ToString("000,000.00");
this.StatusMessageTextField.StringValue += "\nSave = " + this.loan.Save().ToString();
this.ShowLoanPayoffLetterInfo(dPrincipalRepay, dHardInterest, perdiem);
}
}
private void UpdateProjectedDisposition()
{
DateTime scheduledSale = (DateTime)this.SaleDatePicker.DateValue;
if (scheduledSale <= System.DateTime.Today.Date)
{
this.StatusMessageTextField.StringValue = "Can't Reschedule to a date in the past.";
}
else
{
double dHardInterest = this.loan.ProjectedHardInterest();
// check to make sure scheduled date is after all rehabs
if (scheduledSale < this.loan.FindDate(clsCashflow.Type.RehabDraw, false, true))
{
scheduledSale = this.loan.FindDate(clsCashflow.Type.RehabDraw, false, true).AddDays(1);
this.StatusMessageTextField.StringValue =
"Proposed Sale Date is before last Rehab Date. \nChanging Sale Date to " + scheduledSale.ToString("MM/dd/yyyy");
}
double dImpliedAdditional = this.loan.ImpliedAdditionalInterest();
// expire Projected Disposition
foreach (clsCashflow cf in this.loan.Cashflows())
{
if ((cf.TypeID() == clsCashflow.Type.NetDispositionProj) && (cf.DeleteDate() > System.DateTime.Today.AddYears(50)))
{
this.StatusMessageTextField.StringValue += "\nProjected Disposition Deleted as of Today.\n";
this.StatusMessageTextField.StringValue += cf.Amount().ToString("000,000.00") + " : " + cf.PayDate().ToString("MM/dd/yyyy");
cf.Delete(System.DateTime.Today);
}
}
double dAccrued = this.loan.LoanAsOf(scheduledSale).AccruedInterest(scheduledSale);
double dDispAmount = this.loan.LoanAsOf(scheduledSale).Balance(scheduledSale);
dDispAmount += dAccrued + dImpliedAdditional + this.ExpectedAdditionalInterestTextField.DoubleValue;
dDispAmount += 0.5 * (dHardInterest - dAccrued); // adjustment to additional interest for change in hard interest
this.loan.AddCashflow(new clsCashflow(scheduledSale, System.DateTime.Today, System.DateTime.MaxValue,
this.loan.ID(), dDispAmount, false, clsCashflow.Type.NetDispositionProj));
this.StatusMessageTextField.StringValue += "\nNew Projected: " + dDispAmount.ToString("000,000.00");
this.StatusMessageTextField.StringValue += " : " + scheduledSale.ToString("MM/dd/yyyy");
this.StatusMessageTextField.StringValue += "\nSave = " + this.loan.Save().ToString();
}
}
private void ScheduleNewSale()
{
DateTime scheduledSale = (DateTime)this.SaleDatePicker.DateValue;
if (scheduledSale <= System.DateTime.Today.Date)
{
this.StatusMessageTextField.StringValue = "Can't schedule a new sale in the past.";
}
else
{
// check to make sure scheduled date is after all rehabs
if (scheduledSale < this.loan.FindDate(clsCashflow.Type.RehabDraw, false, true))
{
scheduledSale = this.loan.FindDate(clsCashflow.Type.RehabDraw, false, true).AddDays(1);
this.StatusMessageTextField.StringValue =
"Proposed Sale Date is before last Rehab Date. \nChanging Sale Date to " + scheduledSale.ToString("MM/dd/yyyy");
}
double dImpliedAdditional = this.loan.ImpliedAdditionalInterest();
// expire Projected Disposition
foreach (clsCashflow cf in this.loan.Cashflows())
{
if ((cf.TypeID() == clsCashflow.Type.NetDispositionProj) && (cf.DeleteDate() > System.DateTime.Today.AddYears(50)))
{
this.StatusMessageTextField.StringValue += "\nProjected Disposition Deleted as of Today.";
cf.Delete(System.DateTime.Today);
}
}
// schedule principal repay
double dPrincipalRepay = this.loan.LoanAsOf(scheduledSale).Balance(scheduledSale);
this.loan.AddCashflow(new clsCashflow(scheduledSale, System.DateTime.Today, System.DateTime.MaxValue,
this.loan.ID(), dPrincipalRepay, false, clsCashflow.Type.Principal));
this.StatusMessageTextField.StringValue += "\nPrincipal Added: " + dPrincipalRepay.ToString("000,000.00");
this.StatusMessageTextField.StringValue += "," + scheduledSale.ToString("MM/dd/yyyy");
// schedule hard interest
double dHardInterest = this.loan.LoanAsOf(scheduledSale).AccruedInterest(scheduledSale);
double perdiem = dHardInterest - this.loan.LoanAsOf(scheduledSale.AddDays(-1)).AccruedInterest(scheduledSale.AddDays(-1));
this.loan.AddCashflow(new clsCashflow(scheduledSale, System.DateTime.Today, System.DateTime.MaxValue,
this.loan.ID(), dHardInterest, false, clsCashflow.Type.InterestHard));
this.StatusMessageTextField.StringValue += "\nInterest Added: " + dHardInterest.ToString("000,000.00");
this.StatusMessageTextField.StringValue += "," + scheduledSale.ToString("MM/dd/yyyy");
// schedule additional interest
double dAdditionalInterest = this.ExpectedAdditionalInterestTextField.DoubleValue;
this.loan.AddCashflow(new clsCashflow(scheduledSale.AddDays(7), System.DateTime.Today, System.DateTime.MaxValue,
this.loan.ID(), dAdditionalInterest, false, clsCashflow.Type.InterestAdditional));
this.StatusMessageTextField.StringValue += "\nAddlInt Added: " + dAdditionalInterest.ToString("000,000.00");
this.StatusMessageTextField.StringValue += "," + scheduledSale.AddDays(7).ToString("MM/dd/yyyy");
this.StatusMessageTextField.StringValue += "\nPrev AddlInt: " + dImpliedAdditional.ToString("000,000.00");
this.StatusMessageTextField.StringValue += "\nSave = " + this.loan.Save().ToString();
this.ShowLoanPayoffLetterInfo(dPrincipalRepay, dHardInterest, perdiem);
// Record Sale Contract
if (this.bRecordSaleContract)
{
clsDocument saleContract = new clsDocument(clsDocument.DocumentID(this.loan.PropertyID(), clsDocument.Type.SaleContract));
clsDocumentRecord saleContractRecord = new clsDocumentRecord(saleContract.ID(),
System.DateTime.Now,
(DateTime)this.RecordDatePicker.DateValue,
this.loan.CoBorrowerID(),
this.loan.LenderID,
clsDocumentRecord.Status.Preliminary,
clsDocumentRecord.Transmission.Electronic);
if (saleContractRecord.Save())
this.StatusMessageTextField.StringValue += "\nSale Contract Recorded";
else
this.StatusMessageTextField.StringValue += "\nSale Contract FAILED TO RECORD";
}
else
this.StatusMessageTextField.StringValue += "\nSale Contract NOT RECORDED";
}
}
private void CancelScheduledSale()
{
// delete scheduled Principal, HardInterest, AdditionalInterest
// add new ProjDisposition in amount = Principal, Accrued As Of (new proj date),
// Prior Additional Interest - Change in Hard Interest
DateTime scheduledSale = (DateTime)this.SaleDatePicker.DateValue;
if (scheduledSale <= System.DateTime.Today.Date)
{
this.StatusMessageTextField.StringValue = "Can't reschedule to a date in the past.";
}
else
{
// check to make sure scheduled date is after all rehabs
if (scheduledSale < this.loan.FindDate(clsCashflow.Type.RehabDraw, false, true))
{
scheduledSale = this.loan.FindDate(clsCashflow.Type.RehabDraw, false, true).AddDays(1);
this.StatusMessageTextField.StringValue =
"Proposed Sale Date is before last Rehab Date. \nChanging Sale Date to " + scheduledSale.ToString("MM/dd/yyyy");
}
// expire Scheduled Principal, Interest Payments; Accumulate AdditionalInterest
double dAdditionalInterest = 0D;
double dHardInterest = 0D;
double dAccrued = this.loan.LoanAsOf(scheduledSale).AccruedInterest(scheduledSale);
foreach (clsCashflow cf in this.loan.Cashflows())
{
if (cf.DeleteDate() > System.DateTime.Today.AddYears(50))
{
if (cf.TypeID() == clsCashflow.Type.Principal)
{
if (cf.Delete(System.DateTime.Today))
this.StatusMessageTextField.StringValue += "\nScheduled Principal Repayment Deleted as of Today.";
}
else if (cf.TypeID() == clsCashflow.Type.InterestHard)
{
dHardInterest += cf.Amount();
if (cf.Delete(System.DateTime.Today))
this.StatusMessageTextField.StringValue += "\nScheduled Hard Interest Deleted as of Today.";
}
else if (cf.TypeID() == clsCashflow.Type.InterestAdditional)
{
dAdditionalInterest += cf.Amount();
if (cf.Delete(System.DateTime.Today))
this.StatusMessageTextField.StringValue += "\nScheduled Additional Interest Deleted as of Today.";
}
}
}
// new Disposition Projection = Principal + new Accrued As Of Projected Sale Date + current Projected Addl adjusted for
// change in HardInterest
double dDispAmount = this.loan.LoanAsOf(scheduledSale).Balance() + dAccrued + dAdditionalInterest;
dDispAmount += 0.5 * (dHardInterest - dAccrued); // adjustment to additional interest for change in hard interest
this.loan.AddCashflow(new clsCashflow(scheduledSale, System.DateTime.Today, System.DateTime.MaxValue,
this.loan.ID(), dDispAmount, false, clsCashflow.Type.NetDispositionProj));
this.StatusMessageTextField.StringValue += "\nProjected Disposition Added: " + dDispAmount.ToString("000,000.00");
this.StatusMessageTextField.StringValue += "," + scheduledSale.ToString("MM/dd/yyyy");
this.StatusMessageTextField.StringValue += "\nSave = " + this.loan.Save().ToString();
}
}
private void MarkRepaid()
{
double dAdditionalInterestPaidAtClosing = this.RepaymentAmountTextField.DoubleValue;
double dHardInterest = 0D;
double dAdditionalInterest = 0D;
// first check that amount is sufficient
foreach (clsCashflow cf in this.loan.Cashflows())
{
if (cf.DeleteDate() > System.DateTime.Today.AddYears(50))
{
if (cf.TypeID() == clsCashflow.Type.Principal)
dAdditionalInterestPaidAtClosing -= cf.Amount();
else if (cf.TypeID() == clsCashflow.Type.InterestHard)
{
dHardInterest += cf.Amount();
dAdditionalInterestPaidAtClosing -= cf.Amount();
}
else if (cf.TypeID() == clsCashflow.Type.InterestAdditional)
dAdditionalInterest += cf.Amount();
}
}
if (dAdditionalInterestPaidAtClosing < 0)
{
this.StatusMessageTextField.StringValue += "\nRepayment Amount is too low. No updates made.";
}
else
{
foreach (clsCashflow cf in this.loan.Cashflows())
{
if (cf.DeleteDate() > System.DateTime.Today.AddYears(50))
{
if (cf.TypeID() == clsCashflow.Type.Principal)
{
this.StatusMessageTextField.StringValue += "\nScheduled Principal Payment : ";
this.StatusMessageTextField.StringValue += cf.Amount().ToString("#,##0.00");
if (cf.MarkActual(System.DateTime.Today))
this.StatusMessageTextField.StringValue += " marked paid.";
else
this.StatusMessageTextField.StringValue += " FAILED to mark paid.";
}
else if (cf.TypeID() == clsCashflow.Type.InterestHard)
{
dHardInterest += cf.Amount();
this.StatusMessageTextField.StringValue += "\nScheduled Hard Interest : ";
this.StatusMessageTextField.StringValue += cf.Amount().ToString("#,##0.00");
if (cf.MarkActual(System.DateTime.Today))
this.StatusMessageTextField.StringValue += " marked paid.";
else
this.StatusMessageTextField.StringValue += " FAILED to mark paid.";
}
}
}
// if an extra days of interest were paid, add this cashflow as Additional Interest paid on the closing date
// don't adjust scheduled additional interest, this will be updated soon after closing
if (dAdditionalInterestPaidAtClosing > 0)
{
this.loan.AddCashflow(new clsCashflow(this.loan.SaleDate(), System.DateTime.Today, System.DateTime.MaxValue,
this.loan.ID(), dAdditionalInterestPaidAtClosing, true, clsCashflow.Type.InterestAdditional));
this.StatusMessageTextField.StringValue += "\nAddl Interest Paid at Closing added: ";
this.StatusMessageTextField.StringValue += dAdditionalInterestPaidAtClosing.ToString("#,##0.00");
}
else
this.StatusMessageTextField.StringValue += "\nNO Additional Interest Paid at Closing.";
}
this.StatusMessageTextField.StringValue += "\nLoan Save to File : " + this.loan.Save().ToString().ToUpper();
}
#endregion
private void ShowLoanPayoffLetterInfo(double principal, double interest, double perDiem)
{
this.StatusMessageTextField.StringValue += "\nPrincipal: " + principal.ToString("#,##0.00");
this.StatusMessageTextField.StringValue += "\nInterest : " + interest.ToString("#,##0.00");
this.StatusMessageTextField.StringValue += "\nTotal : " + (principal + interest).ToString("#,##0.00");
this.StatusMessageTextField.StringValue += "\nPer Diem : " + perDiem.ToString("#,##0.00");
}
#region Additional Interest
private void MarkAdditionalInterestActual()
{
double dAddlInterestReceived = 0D;
this.StatusMessageTextField.StringValue = "";
foreach (clsCashflow cf in this.loan.Cashflows())
{
if ((cf.TypeID() == clsCashflow.Type.InterestAdditional)
&& (cf.PayDate() <= System.DateTime.Today)
&& (!cf.Actual())
&& (cf.DeleteDate() > System.DateTime.Today))
{
if (cf.MarkActual(System.DateTime.Today))
{
this.StatusMessageTextField.StringValue += cf.Amount().ToString("#,##0.00") + "(" + cf.TransactionID().ToString() + ") Marked ACTUAL\n";
dAddlInterestReceived += cf.Amount();
}
else
this.StatusMessageTextField.StringValue += "!" + cf.TransactionID().ToString() + "! FAILED\n";
}
}
this.StatusMessageTextField.StringValue += "Total Marked Actual: " + dAddlInterestReceived.ToString("#,##0.00");
this.loan.Save();
}
private void UpdateScheduledAdditionalInterest()
{
double dAddlInterestExpired = 0D;
this.StatusMessageTextField.StringValue = "";
foreach (clsCashflow cf in this.loan.Cashflows())
{
if ((cf.TypeID() == clsCashflow.Type.InterestAdditional) && (!cf.Actual()) && (cf.DeleteDate() > System.DateTime.Today))
{
if (cf.Delete(System.DateTime.Today))
{
this.StatusMessageTextField.StringValue += cf.Amount().ToString("#,##0.00") + "(" + cf.TransactionID().ToString() + ") EXPIRED\n";
dAddlInterestExpired += cf.Amount();
}
else
this.StatusMessageTextField.StringValue += "!" + cf.TransactionID().ToString() + "! FAILED\n";
}
}
loan.AddCashflow(new clsCashflow((DateTime)this.SaleDatePicker.DateValue,
(DateTime)this.RecordDatePicker.DateValue,
System.DateTime.MaxValue,
this.loan.ID(),
this.ExpectedAdditionalInterestTextField.DoubleValue,
false,
clsCashflow.Type.InterestAdditional));
this.StatusMessageTextField.StringValue += "\nTotal Expired: " + dAddlInterestExpired.ToString("#,##0.00");
this.loan.Save();
}
#endregion
#region Update Labels and Dropdowns
private void SetDefaultLabels()
{
this.SalePriceLabel.StringValue = "Expected Sale Price (Net)";
this.CashflowDateLabel.StringValue = "Expected Sale Date";
this.RepaymentAmountLabel.StringValue = "Repayment Amount Received";
this.AdditionalInterestLabel.StringValue = "Expected Additional Interest";
}
private void SetSoldLabels()
{
if (this.loan.Property().State() == "PA")
{
this.SalePriceLabel.StringValue = "Instrument";
this.RepaymentAmountLabel.StringValue = "Parcel";
}
else
{
this.SalePriceLabel.StringValue = "Book";
this.RepaymentAmountLabel.StringValue = "Pages";
}
this.CashflowDateLabel.StringValue = "Addl Interest Pay Date";
this.AdditionalInterestLabel.StringValue = "Addl Interest Amount";
}
private void PopulateRecordingInfo()
{
clsLoanRecording rec = new clsLoanRecording(this.loan.Property().Address());
if (rec.ID() >= 0)
{
if (this.loan.Property().State() == "PA")
{
this.ExpectedSalePriceTextField.IntValue = rec.Instrument();
this.RepaymentAmountTextField.IntValue = rec.Parcel();
}
else
{
this.ExpectedSalePriceTextField.IntValue = rec.Book();
this.RepaymentAmountTextField.IntValue = rec.Page();
}
}
else
{
this.ExpectedSalePriceTextField.IntValue = 0;
this.RepaymentAmountTextField.IntValue = 0;
}
}
private void UpdateAddressList()
{
this.AddressComboBox.RemoveAll();
foreach (string address in clsProperty.AddressList())
{
if (((this.lenderID < 0) || (this.lenderID == loansByAddress[address].LenderID)) &&
((this.statusFilter == clsLoan.State.Unknown) || (this.statusFilter == loansByAddress[address].Status())))
{
this.AddressComboBox.Add((NSString)address);
}
}
}
#endregion
#region Event Handlers
partial void LenderChosen(NSComboBox sender)
{
this.lenderID = (int)this.LenderComboBox.SelectedIndex;
this.UpdateAddressList();
}
partial void StatusChosen(NSComboBox sender)
{
this.statusFilter = (clsLoan.State)((int)this.StatusComboBox.SelectedIndex);
this.UpdateAddressList();
}
#endregion
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.