text
stringlengths
13
6.01M
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Shapes; namespace db_project { public partial class UpdateWindow : Window { Database db; string table; string fields; string idField; string id; string fFieldName = ""; string[] fkeys; string[] fvalues; System.Data.DataView data = null; //entity data public UpdateWindow() { InitializeComponent(); } public UpdateWindow(Database db, string table, string idField, string id) { InitializeComponent(); this.db = db; this.table = table; this.idField = idField; this.id = id; labelTable.Content = table; LoadEntity(); } void LoadEntity() { switch (table) { case "artist": fields = "first_name, last_name"; fFieldComboBox.Visibility = Visibility.Hidden; break; case "painting": fields = "title, technique, year"; break; case "exhibition": fields = "exhibition_name"; break; case "auction": fields = "auction_name"; break; case "internet_site": fields = "site"; break; } data = db.LoadTable(fields, table, idField + " = " + id) ; dataGrid.ItemsSource = data; System.Data.DataView foreignData; string fId; switch (table) { case "painting": labelFField.Content = "Author"; fFieldName = "artist_id"; //get fkey for updating entity foreignData = db.ExecuteQuery(String.Format("SELECT artist_id FROM painting WHERE {0} = {1}", idField, id)); fId = foreignData.Table.Rows[0].ItemArray[0].ToString(); //load combobox values and corresponding fkeys foreignData = db.ExecuteQuery("SELECT artist_id, first_name, last_name FROM artist"); fvalues = new string[foreignData.Table.Rows.Count]; fkeys = new string[fvalues.Length]; for (int i = 0; i < fvalues.Length; i++) { fkeys[i] = foreignData.Table.Rows[i].ItemArray[0].ToString(); fvalues[i] = foreignData.Table.Rows[i].ItemArray[1].ToString() + " " + foreignData.Table.Rows[i].ItemArray[2].ToString(); if (fkeys[i] == fId) fFieldComboBox.SelectedItem = fvalues[i]; //set foreign value of updating entity } fFieldComboBox.ItemsSource = fvalues; break; case "auction": case "exhibition": labelFField.Content = "Address"; fFieldName = "address_id"; //get fkey for updating entity foreignData = db.ExecuteQuery(String.Format("SELECT address_id FROM {0} WHERE {1} = {2}", table, idField, id)); fId = foreignData.Table.Rows[0].ItemArray[0].ToString(); //load combobox values and corresponding fkeys foreignData = db.ExecuteQuery("SELECT address.address_id, address, city, country FROM address, city, country WHERE address.city_id = city.city_id AND city.country_id = country.country_id"); fvalues = new string[foreignData.Table.Rows.Count]; fkeys = new string[fvalues.Length]; for (int i = 0; i < fvalues.Length; i++) { fkeys[i] = foreignData.Table.Rows[i].ItemArray[0].ToString(); fvalues[i] = foreignData.Table.Rows[i].ItemArray[1].ToString() + ", " + foreignData.Table.Rows[i].ItemArray[2].ToString() + ", " + foreignData.Table.Rows[i].ItemArray[3].ToString(); if (fkeys[i] == fId) fFieldComboBox.SelectedItem = fvalues[i]; //set foreign value of updating entity } fFieldComboBox.ItemsSource = fvalues; break; } } bool CommitUpdates() { var items = data.Table.Rows[0].ItemArray; string fieldsValues = "'" + items[0].ToString() + "'"; for (int i = 1; i < items.Count(); i++) fieldsValues += ", '" + items[i].ToString() + "'"; //если у таблицы есть fkey, записывается его значение if (fFieldName != "") { fields += ", " + fFieldName; fieldsValues += ", " + fkeys[fFieldComboBox.SelectedIndex]; } if (data.Table.GetChanges() == null) { MessageBox.Show("Error occured or no changes were made!", "Error", MessageBoxButton.OK, MessageBoxImage.Error); return false; } if (!db.UpdateEntity(table, fields, fieldsValues, idField, id)) { MessageBox.Show("Error occured!", "Error", MessageBoxButton.OK, MessageBoxImage.Error); return false; } return true; } private void buttonOK_Click(object sender, RoutedEventArgs e) { if (CommitUpdates()) Close(); } private void buttonCancel_Click(object sender, RoutedEventArgs e) { Close(); } } }
using SciVacancies.Domain.Enums; using SciVacancies.Domain.Events; using SciVacancies.ReadModel.Core; using System; using MediatR; using NPoco; using AutoMapper; namespace SciVacancies.ReadModel.EventHandlers { public class OrganizationEventsHandler : INotificationHandler<OrganizationCreated>, INotificationHandler<OrganizationUpdated>, INotificationHandler<OrganizationRemoved> { private readonly IDatabase _db; public OrganizationEventsHandler(IDatabase db) { _db = db; } public void Handle(OrganizationCreated msg) { Organization organization = Mapper.Map<Organization>(msg); using (var transaction = _db.GetTransaction()) { _db.Insert(organization); if (organization.researchdirections != null) { foreach (ResearchDirection rd in organization.researchdirections) { _db.Execute(new Sql($"INSERT INTO org_researchdirections (guid, researchdirection_id, organization_guid) VALUES (@0, @1, @2)", Guid.NewGuid(), rd.id, msg.OrganizationGuid)); } } transaction.Complete(); } } public void Handle(OrganizationUpdated msg) { Organization organization = _db.SingleById<Organization>(msg.OrganizationGuid); Organization updatedOrganization = Mapper.Map<Organization>(msg); updatedOrganization.creation_date = organization.creation_date; using (var transaction = _db.GetTransaction()) { _db.Update(updatedOrganization); //TODO - без удаления надо _db.Execute(new Sql($"DELETE FROM org_researchdirections WHERE organization_guid = @0", msg.OrganizationGuid)); if (updatedOrganization.researchdirections != null) { foreach (ResearchDirection rd in updatedOrganization.researchdirections) { _db.Execute(new Sql($"INSERT INTO org_researchdirections (guid, researchdirection_id, organization_guid) VALUES (@0, @1, @2)", Guid.NewGuid(), rd.id, msg.OrganizationGuid)); } } transaction.Complete(); } } public void Handle(OrganizationRemoved msg) { using (var transaction = _db.GetTransaction()) { _db.Update(new Sql($"UPDATE org_organizations SET status = @0, update_date = @1 WHERE guid = @2", OrganizationStatus.Removed, msg.TimeStamp, msg.OrganizationGuid)); transaction.Complete(); } } } }
using Models.Interfaces; using System; using System.Collections.Generic; using System.Text; namespace Models.Repositories { public class TasksRepository : ITasksRepository { } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Microsoft.Win32; namespace Domain { public class ProjectService { private readonly ProjectRepository _repository; public ProjectService(ProjectRepository repository) { if (repository == null) { throw new ArgumentException(); } _repository = repository; } public IEnumerable<Project> GetFeaturedProjects() { var items = _repository.GetFeaturedProject(); //apply some actions like discount } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Xml.Linq; using System.Xml.XPath; using System.Diagnostics; using System.Xml; namespace RandomGenerator { /// <summary> /// Provides features and styles that should be included for a given run. /// </summary> public class RunConfig{ /// TODO: Limit to single instance of document (caching) XmlNode root; Defaults defaults; public RunConfig(String fileName, Defaults defaults) { XmlDocument doc = new XmlDocument(); doc.Load(fileName); root = doc.DocumentElement; this.defaults = defaults; } /// <summary> /// Returns list of features to be used for a run /// </summary> /// <returns>List of strings representing feature names</returns> public IEnumerable<String> GetFeatureList(){ XmlNodeList features = root.SelectNodes("/config/features/*"); foreach (var feature in features) { XmlElement tmp = (XmlElement)feature; yield return tmp.Name; } } /// <summary> /// Returns /// </summary> /// <param name="feature"></param> /// <returns></returns> public int GetMaxNestedDepth(String feature) { XmlNode featureNode = root.SelectSingleNode("/config/features/" + feature); String nestingAttrib = ((XmlElement)featureNode).GetAttribute("nesting"); int result; bool success = Int32.TryParse(nestingAttrib, out result); if (success) return result; else { return defaults.GetDefaultNestingLevel(feature); } } public IEnumerable<StyleInfo> GetStyleList(){ XmlNodeList styles = root.SelectNodes("/config/styles/*"); foreach (var style in styles) { XmlElement tmp = (XmlElement)style; yield return CreateStyleInfo(tmp); } } private StyleInfo CreateStyleInfo(XmlElement styleElement) { StyleInfo tmpStyle = new StyleInfo(); tmpStyle.Name = styleElement.Name; tmpStyle.Value = styleElement.GetAttribute("value"); tmpStyle.MinValue = styleElement.GetAttribute("minValue"); tmpStyle.MaxValue = styleElement.GetAttribute("maxValue"); return tmpStyle; } public Range GetElementCount(String parent, String Child) { XmlElement element = (XmlElement) root.SelectSingleNode("/config/constraints/"+parent+"/"+Child); if (element == null) return null; Range tmp = new Range(); tmp.minValue = int.Parse( element.GetAttribute("minCount")); tmp.maxValue = int.Parse(element.GetAttribute("maxCount")); return tmp; } /// <summary> /// Returns all contraints for given path and all sub paths /// </summary> /// <param name="featurePath"></param> /// <returns></returns> public IEnumerable<StyleInfo> GetStyles(String featurePath) { XmlNodeList styles = root.SelectNodes("/config/specific" + featurePath +"/styles/*"); foreach (var style in styles) { XmlElement tmp = (XmlElement)style; yield return CreateStyleInfo(tmp); } } public IEnumerable<StyleInfo> GetStylesPartial(String featurePath) { String[] features = featurePath.Split('/'); List<StyleInfo> styleList = new List<StyleInfo>(); StringBuilder pathBuilder = new StringBuilder(); for (int i = features.Length-1 ; i >= 0; i--) { pathBuilder.Insert(0, features[i]); pathBuilder.Insert(0, '/'); styleList.AddRange(GetStyles(pathBuilder.ToString())); } return styleList.AsEnumerable(); } } public class Range { public int minValue; public int maxValue; } }
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 Sistema_de_Vendas { public partial class Frm_CadProdutos : Form { public Frm_CadProdutos() { InitializeComponent(); } private void Frm_CadProdutos_Load(object sender, EventArgs e) { string query = String.Format(@" SELECT N_IDFORNECEDOR, T_NOMEFORNECEDOR FROM tb_fornecedores "); cb_fornecedor.DataSource = Banco.dql(query); cb_fornecedor.DisplayMember = "T_NOMEFORNECEDOR"; cb_fornecedor.ValueMember = "N_IDFORNECEDOR"; } private void btn_fechar_Click(object sender, EventArgs e) { this.Close(); } private void btn_Novo_Click(object sender, EventArgs e) { txt_nome.Enabled = true; txt_precoCompra.Enabled = true; txt_precoVenda.Enabled = true; nud_qtde.Enabled = true; cb_fornecedor.Enabled = true; btn_salvar.Enabled = true; btn_Novo.Enabled = false; txt_nome.Clear(); txt_precoCompra.Clear(); txt_precoVenda.Clear(); nud_qtde.Value = 0; } private void btn_salvar_Click(object sender, EventArgs e) { if (txt_nome.Text == "" || txt_precoCompra.Text == "" || txt_precoVenda.Text == "" ) { MessageBox.Show("O preenchimento de todos os campos é obrigatório"); return; } string querySalvar = String.Format(@" INSERT INTO tb_produtos ( T_NOMEPRODUTO, N_QTDE, N_PRECO_COMPRA, N_PRECO_VENDA, N_IDFORNECEDOR ) VALUES ( '{0}', {1}, {2}, {3}, {4} ) ",txt_nome.Text,nud_qtde.Value,float.Parse(txt_precoCompra.Text),float.Parse(txt_precoVenda.Text),cb_fornecedor.SelectedValue); Banco.dml(querySalvar); MessageBox.Show("Produto Cadastrado!"); txt_nome.Enabled = false; txt_precoCompra.Enabled = false; txt_precoVenda.Enabled = false; nud_qtde.Enabled = false; cb_fornecedor.Enabled = false; btn_salvar.Enabled = false; btn_Novo.Enabled = true; } private void button3_Click(object sender, EventArgs e) { Frm_GerirProdutos frm_GerirProdutos = new Frm_GerirProdutos(); frm_GerirProdutos.Show(); this.Close(); } } }
using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace SpreedlyWebApp.Spreedly.SpreedlyModels { [JsonObject("transaction")] public class SpreedlyTransactionRequest { [JsonProperty("payment_method_token")] public string PaymentMethodToken { get; set; } [JsonProperty("amount")] public long Amount { get; set; } [JsonProperty("currency_code")] public string CurrencyCode { get; set; } [JsonProperty("retain_on_success")] public bool RetainOnSuccess { get; set; } public override string ToString() { return JsonConvert.SerializeObject(this); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace SQMS.Services.Domain.QualityControl { public class TimeItem { private string timeItemId; public string TimeItemId { get { return timeItemId; } set { timeItemId = value; } } private string timeSchemaId; public string TimeSchemaId { get { return timeSchemaId; } set { timeSchemaId = value; } } private string timeItemType; public string TimeItemType { get { return timeItemType; } set { timeItemType = value; } } private string timeSpot; public string TimeSpot { get { return timeSpot; } set { timeSpot = value; } } private TimeSpan timeSpan; public TimeSpan TimeSpan { get { return timeSpan; } set { timeSpan = value; } } private TimeSpan floatTime; public TimeSpan FloatTime { get { return floatTime; } set { floatTime = value; } } private decimal times; public decimal Times { get { return times; } set { times = value; } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Reflection; using System.Xml; using System.Windows.Forms; using System.Data; using DevExpress.XtraEditors; using IRAP.Global; using IRAP.WCF.Client.Method; namespace IRAP.Client.GUI.MESPDC.Actions { public class MultiPrint : CustomAction, IUDFAction { private string className = MethodBase.GetCurrentMethod().DeclaringType.FullName; private CustomPrint print = null; private string sqlCmd = ""; public MultiPrint(XmlNode actionParams, ExtendEventHandler extendAction, ref object tag) : base(actionParams, extendAction, ref tag) { print = CustomPrintFactory.CreateInstance(actionParams); if (actionParams.Attributes["DataCommand"] != null) sqlCmd = actionParams.Attributes["DataCommand"].Value.ToString(); } public void DoAction() { string strProcedureName = string.Format( "{0}.{1}", className, MethodBase.GetCurrentMethod().Name); if (print == null) { XtraMessageBox.Show( "不支持当前的打印方式", "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } if (sqlCmd == "") { XtraMessageBox.Show( "没有设置打印数据源,无法打印!", "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } WriteLog.Instance.WriteBeginSplitter(strProcedureName); try { int errCode = 0; string errText = ""; DataTable dt = new DataTable(); IRAPUTSClient.Instance.GetDataTableWithSQL( sqlCmd, ref dt, out errCode, out errText); WriteLog.Instance.Write( string.Format("[{0}]{1}", errCode, errText), strProcedureName); if (errCode == 0) foreach (DataRow dr in dt.Rows) { print.DoPrint(dr[0].ToString()); } else { XtraMessageBox.Show(errText, strProcedureName); } } finally { WriteLog.Instance.WriteEndSplitter(strProcedureName); } } } public class MultiPrintFactory : CustomActionFactory, IUDFActionFactory { public IUDFAction CreateAction(XmlNode actionParams, ExtendEventHandler extendAction, ref object tag) { return new MultiPrint(actionParams, extendAction, ref tag); } } }
using UnityEngine; using UnityEngine.UI; using UnityEditor; using UnityEditorInternal; using System; [CustomEditor(typeof(BookPro))] public class BookProEditor : Editor { ReorderableList list; Texture tex; private void OnEnable() { tex = AssetDatabase.LoadAssetAtPath("Assets\\Book-Page Curl\\Editor\\replace.png", typeof(Texture)) as Texture; if (tex == null) { tex = Texture2D.blackTexture; } list = new ReorderableList(serializedObject, serializedObject.FindProperty("papers"), true, true, true, true); list.elementHeight = 75; list.drawElementCallback = DrawElement; list.drawHeaderCallback = drawHeader; list.onAddCallback = addElement; list.onCanRemoveCallback = canremove; list.onRemoveCallback = (ReorderableList l) => { if (EditorUtility.DisplayDialog("Warning!", "Are you sure you want to delete this Paper?\r\nThe paper pages (front and back) will be deleted from the scene", "Yes", "No")) { BookPro book = target as BookPro; if (book.EndFlippingPaper == book.papers.Length - 1) book.EndFlippingPaper--; OnInspectorGUI(); Paper paper = book.papers[l.index]; book.LeftPageShadow.gameObject.SetActive(false); book.LeftPageShadow.transform.SetParent(book.transform); book.RightPageShadow.gameObject.SetActive(false); book.RightPageShadow.transform.SetParent(book.transform); Undo.DestroyObjectImmediate(paper.Back); Undo.DestroyObjectImmediate(paper.Front); ReorderableList.defaultBehaviours.DoRemoveButton(l); EditorUtility.SetDirty(book); } }; } private bool canremove(ReorderableList list) { if (list.count == 1) return false; return true; } private void addElement(ReorderableList list) { BookPro book = target as BookPro; if (book.EndFlippingPaper == book.papers.Length - 1) { book.EndFlippingPaper = book.papers.Length; OnInspectorGUI(); } list.serializedProperty.arraySize++; var lastElement = list.serializedProperty.GetArrayElementAtIndex(list.count - 1); GameObject rightPage = Instantiate(book.RightPageTransform.gameObject) as GameObject; rightPage.transform.SetParent(book.transform, true); rightPage.GetComponent<RectTransform>().sizeDelta = book.RightPageTransform.GetComponent<RectTransform>().sizeDelta; rightPage.GetComponent<RectTransform>().pivot = book.RightPageTransform.GetComponent<RectTransform>().pivot; rightPage.GetComponent<RectTransform>().anchoredPosition = book.RightPageTransform.GetComponent<RectTransform>().anchoredPosition; rightPage.GetComponent<RectTransform>().localScale = book.RightPageTransform.GetComponent<RectTransform>().localScale; rightPage.name = "Page" + ((list.serializedProperty.arraySize - 1) * 2); rightPage.AddComponent<Image>(); //rightPage.AddComponent<Mask>().showMaskGraphic = true; rightPage.AddComponent<CanvasGroup>(); lastElement.FindPropertyRelative("Front").objectReferenceInstanceIDValue = rightPage.GetInstanceID(); GameObject leftPage = Instantiate(book.LeftPageTransform.gameObject) as GameObject; leftPage.transform.SetParent(book.transform, true); leftPage.GetComponent<RectTransform>().sizeDelta = book.LeftPageTransform.GetComponent<RectTransform>().sizeDelta; leftPage.GetComponent<RectTransform>().pivot = book.LeftPageTransform.GetComponent<RectTransform>().pivot; leftPage.GetComponent<RectTransform>().anchoredPosition = book.LeftPageTransform.GetComponent<RectTransform>().anchoredPosition; leftPage.GetComponent<RectTransform>().localScale = book.LeftPageTransform.GetComponent<RectTransform>().localScale; leftPage.name = "Page" + ((list.serializedProperty.arraySize - 1) * 2 + 1); leftPage.AddComponent<Image>(); //leftPage.AddComponent<Mask>().showMaskGraphic = true; leftPage.AddComponent<CanvasGroup>(); lastElement.FindPropertyRelative("Back").objectReferenceInstanceIDValue = leftPage.GetInstanceID(); list.index = list.count - 1; Undo.RegisterCreatedObjectUndo(leftPage, ""); Undo.RegisterCreatedObjectUndo(rightPage, ""); } private void drawHeader(Rect rect) { EditorGUI.LabelField(rect, "Papers"); } private void DrawElement(Rect rect, int index, bool isActive, bool isFocused) { BookPro book = target as BookPro; var serialzedpaper = list.serializedProperty.GetArrayElementAtIndex(index); rect.y += 2; GUIStyle style = new GUIStyle(); EditorGUI.DrawRect(new Rect(rect.x, rect.y, rect.width, rect.height - 6), new Color(0.8f, 0.8f, 0.8f)); EditorGUI.LabelField(new Rect(rect.x, rect.y, 100, EditorGUIUtility.singleLineHeight), "Paper#" + index); if (index == book.CurrentPaper) EditorGUI.DrawRect(new Rect(rect.x, rect.y + EditorGUIUtility.singleLineHeight, 140, EditorGUIUtility.singleLineHeight), new Color(1, 0.3f, 0.3f)); EditorGUI.LabelField(new Rect(rect.x, rect.y + EditorGUIUtility.singleLineHeight, 40, EditorGUIUtility.singleLineHeight), "Front:"); EditorGUI.PropertyField( new Rect(rect.x + 40, rect.y + EditorGUIUtility.singleLineHeight, 100, EditorGUIUtility.singleLineHeight), serialzedpaper.FindPropertyRelative("Front"), GUIContent.none); if (index == book.CurrentPaper - 1) EditorGUI.DrawRect(new Rect(rect.x, rect.y + 3 * EditorGUIUtility.singleLineHeight, 140, EditorGUIUtility.singleLineHeight), new Color(1, 0.3f, 0.3f)); EditorGUI.LabelField(new Rect(rect.x, rect.y + 3 * EditorGUIUtility.singleLineHeight, 35, EditorGUIUtility.singleLineHeight), "Back:"); EditorGUI.PropertyField( new Rect(rect.x + 40, rect.y + 3 * EditorGUIUtility.singleLineHeight, 100, EditorGUIUtility.singleLineHeight), serialzedpaper.FindPropertyRelative("Back"), GUIContent.none); style.padding = new RectOffset(2, 2, 2, 2); if (GUI.Button(new Rect(rect.x + 70, rect.y + 2 * EditorGUIUtility.singleLineHeight, 20, EditorGUIUtility.singleLineHeight), tex, GUIStyle.none)) { Debug.Log("Clicked at index:" + index); Paper paper = book.papers[index]; GameObject temp = paper.Back; paper.Back = paper.Front; paper.Front = temp; } if (GUI.Button(new Rect(rect.x + 150, rect.y + EditorGUIUtility.singleLineHeight, 80, (int)(1.5 * EditorGUIUtility.singleLineHeight)), "Show")) { Paper paper = book.papers[index]; BookUtility.ShowPage(paper.Back); paper.Back.transform.SetAsLastSibling(); BookUtility.ShowPage(paper.Front); paper.Front.transform.SetAsLastSibling(); book.LeftPageShadow.gameObject.SetActive(false); book.LeftPageShadow.transform.SetParent(book.transform); book.RightPageShadow.gameObject.SetActive(false); book.RightPageShadow.transform.SetParent(book.transform); } if (GUI.Button(new Rect(rect.x + 150, rect.y + (int)(2.5 * EditorGUIUtility.singleLineHeight), 80, (int)(1.5 * EditorGUIUtility.singleLineHeight)), "Set Current")) { book.CurrentPaper = index; } } public override void OnInspectorGUI() { base.OnInspectorGUI(); serializedObject.Update(); list.DoLayoutList(); serializedObject.ApplyModifiedProperties(); DrawNavigationPanel(); DrawFlippingPapersRange(); if (GUILayout.Button("Update Pages Order")) { (target as BookPro).UpdatePages(); } if (GUILayout.Button("Update Pages Names")) { if (EditorUtility.DisplayDialog("Warning!", "All Pages will be renamed according to its order", "Ok", "Cancel")) { BookPro book = target as BookPro; for (int i = 0; i < book.papers.Length; i++) { book.papers[i].Front.name = "Page" + (i * 2); book.papers[i].Back.name = "Page" + (i * 2 + 1); } } } } private void DrawFlippingPapersRange() { BookPro book = target as BookPro; #if UNITY_5_3_OR_NEWER EditorGUILayout.BeginVertical(EditorStyles.helpBox); #else EditorGUILayout.BeginVertical(EditorStyles.textArea); #endif EditorGUILayout.LabelField("Flipping Range", EditorStyles.boldLabel); EditorGUILayout.LabelField("First Flippable Paper: " + "Paper#" + book.StartFlippingPaper); EditorGUILayout.LabelField("Last Flippable Paper: " + "Paper#" + book.EndFlippingPaper); float start = book.StartFlippingPaper; float end = book.EndFlippingPaper; EditorGUILayout.MinMaxSlider(ref start, ref end, 0, book.papers.Length - 1); book.StartFlippingPaper = Mathf.RoundToInt(start); book.EndFlippingPaper = Mathf.RoundToInt(end); EditorGUILayout.EndVertical(); } private void DrawNavigationPanel() { BookPro book = target as BookPro; #if UNITY_5_3_OR_NEWER EditorGUILayout.BeginHorizontal(EditorStyles.helpBox); #else EditorGUILayout.BeginHorizontal(EditorStyles.textArea); #endif GUILayout.Label(new GUIContent("Current Paper", "represent current paper on the right side of the book. if you want to show the back page of the last paper you may set this value with the index of last paper + 1")); if (GUILayout.Button("|<")) { book.CurrentPaper = 0; } if (GUILayout.Button("<")) { book.CurrentPaper--; } book.CurrentPaper = EditorGUILayout.IntField(book.CurrentPaper, GUILayout.Width(30)); EditorUtility.SetDirty(book); Undo.RecordObject(book, "CurrentPageChange"); if (GUILayout.Button(">")) { book.CurrentPaper++; } if (GUILayout.Button(">|")) { book.CurrentPaper = book.papers.Length; } EditorGUILayout.EndHorizontal(); } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; //********************************************************************** // // 文件名称(File Name):AuthUtil.CS // 功能描述(Description): // 作者(Author):Aministrator // 日期(Create Date): 2017-05-15 13:48:46 // // 修改记录(Revision History): // R1: // 修改作者: // 修改日期:2017-05-15 13:48:46 // 修改理由: //********************************************************************** namespace ND.FluentTaskScheduling.Web.App_Start { public class AuthUtil { private static string GetToken() { string token = HttpContext.Current.Request.QueryString["Token"]; if (!String.IsNullOrEmpty(token)) return token; var cookie = HttpContext.Current.Request.Cookies["Token"]; return cookie == null ? String.Empty : cookie.Value; } } }
using EasyBuy.Models; using EasyBuyCR.Models; using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace EasyBuy.Controllers { public class ClienteController : Controller { OracleConection con = OracleConection.obtenerInstancia(); // GET: Cliente public ActionResult Index() { if (Session["Correo"] != null) return View(); else return RedirectToAction("Login","Account"); } public ActionResult Hombre(String categoria = "abrigos") { if (Session["Correo"] != null) { List<Producto> listaProductos = con.ObtenerProductosHombre(categoria); if (listaProductos != null && listaProductos.Count != 0) { ViewBag.categoria = listaProductos.ElementAt(0).categoria; if (listaProductos.ElementAt(0).list_detalle_producto != null && listaProductos.ElementAt(0).list_detalle_producto.Count != 0) { ViewBag.genero = listaProductos.ElementAt(0).list_detalle_producto.ElementAt(0).genero; ViewBag.precios = con.ObtenerPreciosProductosHombre(categoria); ViewBag.colores = con.ObtenerColoresProductosHombre(categoria); ViewBag.tallas = con.ObtenerTallaProductosHombre(categoria); String[] prov = { "Alajuela", "Cartago", "Guanacaste", "Puntarenas", "Limon", "San Jose", "Heredia" }; ViewBag.provincias = prov; } } return View(listaProductos); } else return RedirectToAction("Login", "Account"); } public ActionResult Mujer(String categoria = "abrigos") { if (Session["Correo"] != null) { List<Producto> listaProductos = con.ObtenerProductosMujer(categoria); if (listaProductos != null && listaProductos.Count != 0) { ViewBag.categoria = listaProductos.ElementAt(0).categoria; if (listaProductos.ElementAt(0).list_detalle_producto != null && listaProductos.ElementAt(0).list_detalle_producto.Count != 0) { ViewBag.genero = listaProductos.ElementAt(0).list_detalle_producto.ElementAt(0).genero; ViewBag.precios = con.ObtenerPreciosProductosMujer(categoria); ViewBag.colores = con.ObtenerColoresProductosMujer(categoria); ViewBag.tallas = con.ObtenerTallaProductosHombre(categoria); String[] prov = { "Alajuela", "Cartago", "Guanacaste", "Puntarenas", "Limon", "San Jose", "Heredia"}; ViewBag.provincias = prov; } } return View(listaProductos); } else return RedirectToAction("Login", "Account"); } [HttpPost] //[AllowAnonymous] //[ValidateAntiForgeryToken] public ActionResult Filtrar(Filtrar model) { List<Producto> listaProductos = con.ObtenerProductosHombreFiltros(model); ViewBag.categoria = model.categoria; ViewBag.genero = model.genero; ViewBag.precios = con.ObtenerPreciosProductosHombre(model.categoria); ViewBag.colores = con.ObtenerColoresProductosHombre(model.categoria); ViewBag.tallas = con.ObtenerTallaProductosHombre(model.categoria); String[] prov = { "Alajuela", "Cartago", "Guanacaste", "Puntarenas", "Limon", "San Jose", "Heredia" }; ViewBag.provincias = prov; return View("Hombre",listaProductos); } public ActionResult FiltrarMujer(Filtrar model) { List<Producto> listaProductos = con.ObtenerProductosHombreFiltros(model); ViewBag.categoria = model.categoria; ViewBag.genero = model.genero; ViewBag.precios = con.ObtenerPreciosProductosMujer(model.categoria); ViewBag.colores = con.ObtenerColoresProductosMujer(model.categoria); ViewBag.tallas = con.ObtenerTallaProductosHombre(model.categoria); String[] prov = { "Alajuela", "Cartago", "Guanacaste", "Puntarenas", "Limon", "San Jose", "Heredia" }; ViewBag.provincias = prov; return View("Mujer", listaProductos); } } }
using System.Linq; using Newtonsoft.Json; namespace Newbe.Claptrap.DataSerializer.Json { public class JsonEventDataStringSerializer : IEventDataStringSerializer { private readonly IClaptrapDesignStore _claptrapDesignStore; public JsonEventDataStringSerializer( IClaptrapDesignStore claptrapDesignStore) { _claptrapDesignStore = claptrapDesignStore; } public string Serialize(string claptrapTypeCode, string eventTypeCode, IEventData eventData) { var re = JsonConvert.SerializeObject(eventData); return re; } public IEventData Deserialize(string claptrapTypeCode, string eventTypeCode, string source) { var design = _claptrapDesignStore.FindDesign(new ClaptrapIdentity(default!, claptrapTypeCode)); var (_, value) = design.EventHandlerDesigns.Single(x => x.Key == eventTypeCode); var re = (IEventData) JsonConvert.DeserializeObject(source, value.EventDataType)!; return re; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace MintaZH1 { class Film { string film_cím; int ár; List<int> értékelés = new List<int>(); public string Film_cím { get => film_cím; } public int Ár { get => ár; } public Film(string film_cím, int ár) { this.film_cím = film_cím; this.ár = ár; } public virtual void Értékel(int érték) { if (értékelés.Count() < 10) { if (érték > 0 && érték < 6) { értékelés.Add(érték); } } else { } } } }
using System.Windows.Controls; namespace InRuleLabs.AuthoringExtensions.RuleAppMetrics.Controls { public class IrSeparator : Separator { public IrSeparator() { DefaultStyleKey = ToolBar.SeparatorStyleKey; } } }
using MediatR; using Microsoft.AspNetCore.Mvc; using Payment.Api.RequestDto; using Payment.Application.PaymentProcess.Commands; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Payment.Api.Controllers.v1 { public class PaymentController : V1ControllerBase { public PaymentController(IMediator mediator) : base(mediator) { } [Route("ProcessPayment"), HttpPost] public async Task<IActionResult> ProcessPaymentAsync(PaymentProcessRequest request) { return Ok(await _mediator.Send(new ProcessPaymentCommand() { Amount = request.Amount, CardHolderName = request.CardHolderName, CardNumber = request.CardNumber, ExpirationDate = request.ExpirationDate, SecurityCode = request.SecurityCode })); } } }
namespace Mashup.Data.Model { public class Weather { public int ID { get; set; } public int ID_user { get; set; } public string City { get; set; } public int Quantity { get; set; } } }
namespace DChild.Gameplay.Player { public interface IAmbrosia { void AddValue(int value); void ReduceValue(int value); } }
using UnityEngine; using System.Collections.Generic; using DChild.Gameplay.Player.Inventories; using System.Data; using DChild.Databases.Content; using Sirenix.OdinInspector; using DChild.Gameplay.Combat; namespace DChild.Databases { [System.Serializable] public struct WeaponData : IInventoryData { [SerializeField] private ItemData m_itemData; [SerializeField] [ReadOnly] private WeaponType m_type; [SerializeField] [ReadOnly] private int m_strengthRequired; [SerializeField] [ReadOnly] private AttackDamage[] m_attacks; [SerializeField] [ReadOnly] private Effect[] m_onHitEffects; public WeaponData(IDataReader itemReader, IDataReader weaponReader, IDataReader weaponDamageReader,IDataReader effectReader) { m_itemData = new ItemData(itemReader); if (weaponReader.Read()) { m_strengthRequired = (int)weaponReader[WeaponTable.STRENGTH]; m_type = (WeaponType)(int)weaponReader[WeaponTable.TYPE]; } else { m_strengthRequired = 0; m_type = WeaponType._COUNT; } if (weaponDamageReader.Read()) { m_attacks = CreateAttackArray(weaponDamageReader); } else { m_attacks = null; } if (effectReader.Read()) { m_onHitEffects = CreateEffectArray(effectReader); } else { m_onHitEffects = null; } } public WeaponData(ItemData m_itemData, WeaponType m_type,int m_strengthRequired, AttackDamage[] m_attacks, Effect[] m_onHitEffects = null) { this.m_itemData = m_itemData; this.m_strengthRequired = m_strengthRequired; this.m_type = m_type; this.m_attacks = m_attacks; this.m_onHitEffects = m_onHitEffects; } public ItemData itemData => m_itemData; public int id => m_itemData.id; public string name => m_itemData.name; public ItemType itemType => m_itemData.itemType; public Sprite icon => m_itemData.icon; public Rarity rarity => m_itemData.rarity; public int maxStack => m_itemData.maxStack; public int barterValue => m_itemData.barterValue; public WeaponType type => m_type; public int strengthRequired => m_strengthRequired; public AttackDamage[] attacks => m_attacks; public Effect[] onHitEffects => m_onHitEffects; /// <summary> /// /// </summary> /// <param name="weaponReader">Reader must be Read Before Giving it to this Function</param> /// <returns></returns> private static AttackDamage[] CreateAttackArray(IDataReader weaponDamageReader) { List<AttackDamage> attackList = new List<AttackDamage>(); AttackDamage attack = CreateAttack(weaponDamageReader); attackList.Add(attack); while (weaponDamageReader.Read()) { attack = CreateAttack(weaponDamageReader); attackList.Add(attack); } return attackList.ToArray(); } /// <summary> /// /// </summary> /// <param name="weaponReader">Reader must be Read Before Giving it to this Function</param> /// <returns></returns> private static AttackDamage CreateAttack(IDataReader weaponDamageReader) => new AttackDamage((AttackType)(int)weaponDamageReader[WeaponDamageTable.ATTACK_TYPE], (int)weaponDamageReader[WeaponDamageTable.ATTACK_DAMAGE]); /// <summary> /// /// </summary> /// <param name="effectReader">Reader must be Read Before Giving it to this Function</param> /// <returns></returns> private static Effect[] CreateEffectArray(IDataReader effectReader) { List<Effect> effectList = new List<Effect>(); Effect effect = CreateEffect(effectReader); effectList.Add(effect); while (effectReader.Read()) { effect = CreateEffect(effectReader); effectList.Add(effect); } return effectList.ToArray(); } /// <summary> /// /// </summary> /// <param name="effectReader">must be Read Before Giving it to this Function</param> /// <returns></returns> private static Effect CreateEffect(IDataReader effectReader) => new Effect(SQLDatabase.GetEquipmentEffect((int)effectReader[ItemWithEffectsTable.EFFECT]), (int)effectReader[ItemWithEffectsTable.VALUE]); } }
using System.Collections; using System.Collections.Generic; using System.Linq; using UnityEngine; public class GetLightmap : MonoBehaviour { public GameObject GO; public RenderTexture RT; public Texture2D Lightmap; public Shader GetSingleLightmap; // Use this for initialization void Start () { RT = new RenderTexture(1024,1024,24, RenderTextureFormat.ARGB32); RT.enableRandomWrite = true; RT.Create(); } public Bounds CalcAABB(List<MeshRenderer> meshes) { var boxColliders = meshes.Select(x => x.bounds).ToList(); var aabb = boxColliders[0]; foreach (var obj in boxColliders) { aabb.Encapsulate(obj); } return aabb; } // Update is called once per frame void Update() { if (GO == null) return; var allRenderer = GameObject.FindObjectsOfType<MeshRenderer>(); foreach (var meshRenderer in allRenderer) { meshRenderer.gameObject.SetActive(false); } GO.SetActive(true); var go = GameObject.Find("GBufferCamera"); Camera gBufferCamera = null; if (go == null) gBufferCamera = new GameObject("GBufferCamera").AddComponent<Camera>(); else gBufferCamera = go.GetComponent<Camera>(); var aabb = CalcAABB(new List<MeshRenderer>() {GO.GetComponent<MeshRenderer>()}); var maxExtend = Mathf.Max(aabb.extents.x, aabb.extents.y, aabb.extents.z); ; gBufferCamera.orthographic = true; gBufferCamera.aspect = 1; gBufferCamera.orthographicSize = maxExtend * 2; gBufferCamera.allowMSAA = false; gBufferCamera.allowHDR = false; gBufferCamera.enabled = false; gBufferCamera.clearFlags = CameraClearFlags.SolidColor; gBufferCamera.backgroundColor = Color.clear; gBufferCamera.farClipPlane = maxExtend * 2; var cameraTransform = gBufferCamera.transform; cameraTransform.position = aabb.center; cameraTransform.forward = aabb.extents.x <= aabb.extents.y ? (aabb.extents.x <= aabb.extents.z ? new Vector3(1, 0, 0) : new Vector3(0, 0, 1)) : (aabb.extents.y <= aabb.extents.z ? new Vector3(0, 1, 0) : new Vector3(0, 0, 1)); cameraTransform.position = aabb.center - cameraTransform.forward * maxExtend; gBufferCamera.targetTexture = RT; Shader.SetGlobalTexture("_Lightmap", Lightmap); Shader.SetGlobalVector("_LightmspST", GO.GetComponent<MeshRenderer>().lightmapScaleOffset); gBufferCamera.RenderWithShader(GetSingleLightmap, ""); } }
using System; using System.Collections.Generic; using System.Text; namespace CarritoCompras.Modelo { public class Categoria { public string idcategoria { get; set; } public string imagen { get; set; } public string nombre { get; set; } public Dictionary<string, Producto> productos { get; set; } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class Astar : MonoBehaviour { List<Vector3> PointsList; int pointIndex; public int jumpIndex; Vector3 vec; RaycastHit hit; public List<Vector3> Search(GameObject start, GameObject target, float distance) { int loop = 0; // 経路ポイントの初期化 pointIndex = 0; PointsList = new List<Vector3>(); PointsList.Add(start.transform.position); // 目的地にたどり着くまでポイントを追加する while (true) { // 経路ポイントが見つからなさそうだったらループから抜ける loop++; if(loop >= 1000) { Debug.Log("経路が見つかりませんでした。"); break; } // 経路ポイントと目標ポイントのベクトル vec = target.transform.position - PointsList[pointIndex]; // 自身の大きさ分のBOXを目標位置まで飛ばす if (Physics.BoxCast(PointsList[pointIndex], start.transform.localScale * 0.5f , vec, out hit, Quaternion.LookRotation(vec), distance)) { // 目的地に着いたらwhile文から抜ける if (hit.collider.gameObject == target.gameObject) { PointsList.Add(hit.collider.gameObject.transform.position); break; } // 目標地点以外のオブジェクトに当たったらオブジェクトを避ける else { var bb = hit.collider.gameObject.transform; if (bb.transform.localScale.y < (start.transform.localScale.y / 4)) { float length = Vector3.Distance(PointsList[pointIndex], hit.point); length -= 0.5f; Vector3 jumpStart = PointsList[pointIndex] + ((hit.point - PointsList[pointIndex]).normalized * length); jumpStart = new Vector3(jumpStart.x, start.transform.position.y, jumpStart.z); PointsList.Add(jumpStart); ++pointIndex; length = Vector3.Distance(PointsList[pointIndex], hit.point); length += bb.localScale.x * 2; Vector3 jumpEnd = PointsList[pointIndex] + ((hit.point - PointsList[pointIndex]).normalized * length); jumpEnd = new Vector3(jumpEnd.x, start.transform.position.y, jumpEnd.z); PointsList.Add(jumpEnd); ++pointIndex; jumpIndex = pointIndex; break; } else { // 4隅の座標を取得 Vector3[] corners = new Vector3[] { new Vector3(bb.position.x + (bb.localScale.x / 2), start.transform.position.y, bb.position.z + (bb.localScale.z / 2)), new Vector3(bb.position.x + (bb.localScale.x / 2), start.transform.position.y, bb.position.z - (bb.localScale.z / 2)), new Vector3(bb.position.x - (bb.localScale.x / 2) , start.transform.position.y, bb.position.z + (bb.localScale.z / 2)), new Vector3(bb.position.x - (bb.localScale.x / 2) , start.transform.position.y, bb.position.z - (bb.localScale.z / 2)) }; int cornerIndex = 0; float length = 1000; for (int i = 0; i < 4; i++) { Vector3 dirCorner = (corners[i] - PointsList[pointIndex]).normalized; // 4隅のうち自身から見える位置を取得 if (Physics.Linecast(PointsList[pointIndex], corners[i], out hit) && (corners[i] - PointsList[pointIndex]).magnitude <= 0.1f) { // 見えた位置の中でターゲットに1番近い位置を取得 float targetDistance = (corners[i] - target.transform.position).magnitude; if (targetDistance <= length && targetDistance >= 0.5f) { length = targetDistance; cornerIndex = i; } } } // オブジェクトにめり込まないように位置を調整 corners = new Vector3[] { new Vector3(bb.position.x + (bb.localScale.x), start.transform.position.y, bb.position.z + (bb.localScale.z)), new Vector3(bb.position.x + (bb.localScale.x), start.transform.position.y, bb.position.z - (bb.localScale.z)), new Vector3(bb.position.x - (bb.localScale.x) , start.transform.position.y, bb.position.z + (bb.localScale.z)), new Vector3(bb.position.x - (bb.localScale.x) , start.transform.position.y, bb.position.z - (bb.localScale.z)) }; // 四隅のうち目標地点に近い位置を経路ポイントとして格納する PointsList.Add(corners[cornerIndex]); ++pointIndex; } } } // Rayに何も当たらなけらばRayの先をポイントとして格納する else { // 2点のベクトルをノーマライズ化 var length = vec.magnitude; var direction = vec / length; Vector3 point = PointsList[pointIndex] + (direction * distance); point = new Vector3(point.x, start.transform.position.y, point.z); // スタート地点からdistance分進んだ位置を格納 PointsList.Add(point); ++pointIndex; } } // 格納したポイントを返す return PointsList; } bool IsJump(GameObject self) { Rigidbody rb = self.GetComponent<Rigidbody>(); Vector3 vec; return false; } public int GetJumpIndex() { return jumpIndex; } }
using UnityEngine; using System.Collections; public class BallBoundary : MonoBehaviour { public GameObject ballSpawnLocation; public GameObject ballPrefab; // Use this for initialization void Start () { } // Update is called once per frame void Update () { } void OnTriggerEnter( Collider other) { if( other.tag == "ball") { Destroy(other.gameObject); // destroy this ball Instantiate( ballPrefab, ballSpawnLocation.transform.position, ballSpawnLocation.transform.rotation); } } }
using NRaas.CommonSpace.Booters; using NRaas.CommonSpace.Helpers; using Sims3.Gameplay; using Sims3.Gameplay.Abstracts; using Sims3.Gameplay.Actors; using Sims3.Gameplay.Autonomy; using Sims3.Gameplay.Core; using Sims3.Gameplay.Interactions; using Sims3.Gameplay.Interfaces; using Sims3.Gameplay.Objects; using Sims3.Gameplay.Skills; using Sims3.Gameplay.Utilities; using Sims3.SimIFace; using Sims3.UI; using System; using System.Collections.Generic; using System.Reflection; using System.Text; namespace NRaas { public class AddressBook : Common, Common.IWorldLoadFinished, Common.IWorldQuit { [Tunable, TunableComment("Scripting Mod Instantiator, value does not matter, only its existence")] protected static bool kInstantiator = false; static AddressBook() { Bootstrap(); } [PersistableStatic] public static Dictionary<ulong, string> mAddresses; public static void AddAddress (ulong id, string address) { if (address == null) return; if (mAddresses == null) mAddresses = new Dictionary<ulong, string> (); if (mAddresses.ContainsKey (id)) mAddresses [id] = address; else mAddresses.Add (id, address); } public void OnWorldLoadFinished() { if (mAddresses != null) { List<ulong> invalidIds = new List<ulong> (); foreach (ulong lotId in mAddresses.Keys) { Lot lot; if (LotManager.sLots.TryGetValue (lotId, out lot)) { lot.mAddressLocalizationKey = mAddresses [lotId]; } else { invalidIds.Add (lotId); } } foreach (ulong id in invalidIds) { mAddresses.Remove (id); BooterLogger.AddTrace("Removed: " + id); } } } public void OnWorldQuit() { mAddresses = null; } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class MainMenu : MonoBehaviour { public Texture backgroundTexture; void OnGUI(){ //Display our Background Texture GUI.DrawTexture(new Rect(0, 0, Screen.width, Screen.height),backgroundTexture); Time.timeScale = 0; //buttons if (GUI.Button (new Rect(Screen.width*0.10f, Screen.height * .30f, Screen.width * .15f, Screen.height * .1f), "Play game")) { Application.LoadLevel ("Scene"); Time.timeScale = 1; }; if (GUI.Button (new Rect(Screen.width*.74f, Screen.height * .30f, Screen.width * .15f, Screen.height * .1f), "Quit")) { Application.Quit(); }; } }
using System.Collections; using System.Collections.Generic; using UnityEngine; [System.Serializable] [CreateAssetMenu(fileName = "QTE_Template_xxx_n", menuName = "Qte Template")] public class Qte_Template : ScriptableObject { public string qteDescription = "Descripcion del QTE"; public int speed = 5; public float arrowsHeight = 10f; public Vector3 QTEPosition = new Vector3(-30f, 8f, -9f); public Quaternion QTERotation = new Quaternion(-90f, 180, 0, 0); public DatosNotas[] noteData; } [System.Serializable] public class DatosNotas { public float notePosition; public float noteDelay; }
namespace Olive.Desktop.WPF.Behavior { using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Windows; public class ValidationBehavior { //public static int GetMyProperty(DependencyObject obj) //{ // return (int)obj.GetValue(MyPropertyProperty); //} //public static void SetMyProperty(DependencyObject obj, int value) //{ // obj.SetValue(MyPropertyProperty, value); //} //// Using a DependencyProperty as the backing store for MyProperty. This enables animation, styling, binding, etc... //public static readonly DependencyProperty MyPropertyProperty = // DependencyProperty.RegisterAttached("MyProperty", typeof(int), typeof(ownerclass), new UIPropertyMetadata(0)); } }
 using System.Configuration; namespace Pe.Stracon.Politicas.Infraestructura.Core.Context { /// <summary> /// Clase de datos constantes de la Base datos /// </summary> /// <remarks> /// Creación: GMD 20140310 <br /> /// Modificación: <br /> /// </remarks> public sealed class DatosConstantes { /// <summary> /// Constantes de parametros generales /// </summary> public sealed class ParametrosGenerales { /// <summary> /// Código de parametro general tipo nivel /// </summary> public const string CodigoNivel = "00001"; public const string TipoUnidadOperativa = "00002"; public const string TipoDocumentoIdentidad = "00003"; public const string TipoArchivoPermitido = "00004"; public const string FormaGeneracion = "00005"; public const string SistemaIntegracion = "00006"; public const string OperacionIntegracion = "00007"; public const string TipoEvidencia = "00008"; public const string TipoActividad = ""; public const string EstadoCalendarizacion = "00009"; public const string EstadoActividad = "00010"; public const string EstadoCumplimiento = "00011"; public const string EstadoEvidencia = "00012"; public const string TipoServicio = "00013"; public const string TipoContrato = "00014"; public const string FormaContrato = "00015"; public const string RepositorioSharePoint = "00016"; public const string TipoNotificacionSCC = "00017"; public const string CuentaNotificacionSCC = "00018"; public const string DominioEmpresa = "00019"; public const string ConfiguracionSharePoint = "00020"; public const string CredencialAcceso = "00021"; public const string TipoDocumentoContrato = "00022"; public const string EstadoVigencia = "00023"; public const string TipoRespuestaObservacion = "00025"; public const string MontoMinimoControl = "00026"; public const string EstadoContrato = "00027"; public const string EstadoEdicion = "00028"; public const string Moneda = "00029"; public const string RepositorioSharePointSGC = "00030"; public const string AlertaVencimientoContrato = "00031"; public const string TipoOrden = "00032"; public const string MontoAcumuladoParaContrato = "00033"; public const string CuentaNotificacionSGC = "00034"; public const string URLSistemas = "00035"; public const string TipoTarifaBien = "00036"; public const string PeriodoAlquilerBien = "00037"; public const string TipoDeBien = "00038"; public const string ConfiguracionGeneracionContratos = "00039"; public const string TipoNotificacion = "00040"; public const string Valor = "00041"; public const string TipoConsulta = "00042"; public const string Area = "00043"; public const string EstadoConsulta = "00044"; } /// <summary> /// Constantes de Empresa /// </summary> public sealed class Empresa { /// <summary> /// Codigo de la Stracon /// </summary> public const string CodigoStracon = "190E8EF5-11E2-45C7-BC4F-8A673B4640B5"; } /// <summary> /// Constantes de Sistema /// </summary> public sealed class Sistema { /// <summary> /// Codigo del Sistema SCC /// </summary> public const string CodigoSCC = "9DE41BC7-3A1C-481B-821B-FFE44AD9F0D5"; /// <summary> /// Codigo del Sistema SGC /// </summary> public const string CodigoSGC = "A4C353EF-A593-4E59-8366-CA1BEC446115"; /// <summary> /// Codigo del Sistema Trasciende /// </summary> public const string CodigoTRA = "390480EE-2D28-456D-98FE-05BC82316B8C"; } /// <summary> /// Constantes de Estado de Registro /// </summary> public sealed class EstadoRegistro { /// <summary> /// Estado de Activo /// </summary> public const string Activo = "1"; /// <summary> /// Estado de Inactivo /// </summary> public const string Inactivo = "0"; } /// <summary> /// Constantes Formato /// </summary> public sealed class Formato { /// <summary> /// Formato de Fecha /// </summary> public const string FormatoFecha = "dd/MM/yyyy"; /// <summary> /// Formato de Fecha de Selector /// </summary> public const string FormatoFechaSelector = "dd/mm/yy"; /// <summary> /// Formato de Fecha de Mascara /// </summary> public const string FormatoFechaMascara = "00/00/0000"; } /// <summary> /// Constantes de Tipo de Parámetro /// </summary> public sealed class TipoParametro { /// <summary> /// Tipo de Parámetro Común /// </summary> public const string Comun = "C"; /// <summary> /// Tipo de Parámetro Sistema /// </summary> public const string Sistema = "S"; /// <summary> /// Tipo de Parámetro Funcional /// </summary> public const string Funcional = "F"; } /// <summary> /// Constantes de Tipo de Dato /// </summary> public sealed class TipoDato { /// <summary> /// Tipo Decimal /// </summary> public const string Decimal = "DEC"; /// <summary> /// Tipo Encriptado /// </summary> public const string Encriptado = "ENC"; /// <summary> /// Tipo Entero /// </summary> public const string Entero = "ENT"; /// <summary> /// Tipo Fecha /// </summary> public const string Fecha = "FEC"; /// <summary> /// Tipo Texto /// </summary> public const string Texto = "TEX"; } /// <summary> /// Tipo de Visualización de Unidad Operativa /// </summary> public sealed class TipoVisualizacionUnidadOperativa { /// <summary> /// Responsable /// </summary> public const string Responsable = "RES"; /// <summary> /// Representantes y Dirección /// </summary> public const string RepresentanteDireccion = "REPDIR"; } /// <summary> /// Tipo de Documento de Identidad /// </summary> public sealed class TipoDocumentoIdentidad { /// <summary> /// Tipo Dni /// </summary> public const string Dni = "01"; /// <summary> /// Tipo RUC /// </summary> public const string Ruc = "02"; } /// <summary> /// Constantes de Niveles /// </summary> public sealed class Nivel { /// <summary> /// Nivel de Empresa Matriz /// </summary> public static readonly string EmpresaMatriz = "01"; /// <summary> /// Nivel de Empresa /// </summary> public static readonly string Empresa = "02"; /// <summary> /// Nivel de Proyecto /// </summary> public static readonly string Proyecto = "03"; } /// <summary> /// Configuración de la capa de presentación /// </summary> public sealed class ConfiguracionPresentacion { /// <summary> /// Titulo de la aplicación /// </summary> public static readonly string TituloAplicacion = ConfigurationManager.AppSettings["TitloSistema"]; } /// <summary> /// Configuración de file server /// </summary> public sealed class ConfiguracionFileServer { /// <summary> /// Ubicacion de fotos del colaborador /// </summary> public static readonly string UbicacionFotoColaborador = ConfigurationManager.AppSettings["FileServerUbicacionFotoColaborador"]; } /// <summary> /// Configuración de la Nombre DataBase Politicas /// </summary> public sealed class ConfiguracionNombreDataBasePoliticas { /// <summary> /// Nombre Base Datos /// </summary> public static readonly string NombreBaseDatosPoliticas = ConfigurationManager.AppSettings["NombreBaseDatosPoliticas"]; } } }
using UnityEngine; using System.Collections; public class Lamp : MonoBehaviour { public GameObject lamp; public GameObject knew; void start() { knew.SetActive (false); } void OnTriggerEnter ( Collider other ) { if (other.gameObject.CompareTag ("Man")) { Destroy(lamp); knew.SetActive (true); } } }
using UnityEngine; namespace Submarines.Utilities.Extension { /** * Extension methods for the GameObject class. */ public static class GameObjectExtensions { public static T GetOrAddComponent<T>(this GameObject gameObject) where T : Component { T component = gameObject.GetComponent<T>(); if (component == null) { component = gameObject.AddComponent<T>(); } return component; } } }
using MassTransit; using Ntech.Saga.Contracts; using System; using System.Collections.Generic; using System.Text; using System.Threading.Tasks; namespace Ntech.Saga.Service.Handling.Consumers { public class BookingFailedConsumer : IConsumer<IBookingFailedEvent> { public async Task Consume(ConsumeContext<IBookingFailedEvent> context) { var bookingId = context.Message.BookingId; await Console.Out.WriteLineAsync($"Booking operation is failed! " + $"Booking Id: {bookingId}. " + $"Fault Message: {context.Message.FaultMessage}. " + $"Correlation Id: {context.Message.CorrelationId}"); //Send mail, push notification, etc... } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class Weapon : MonoBehaviour { [Range(0, 3)] public float fireRate = 0.1f; [Range(0, 100)] public float angle = 10.0f; public int ammoMax = 100; public GameObject projectile; public Transform emitTransform; protected float fireTimer = 0; protected int ammo = 100; void Update() { fireTimer += Time.deltaTime; } public bool Fire(Vector3 position, Vector3 direction) { if(fireTimer >= fireRate) { fireTimer = 0; GameObject gameObject = Instantiate(this.projectile, position, Quaternion.identity); gameObject.GetComponent<Projectile>().Fire(direction); return true; } return false; } public bool Fire(Vector3 direction) { if (fireTimer >= fireRate) { fireTimer = 0; GameObject gameObject = Instantiate(this.projectile, emitTransform.position, emitTransform.rotation); gameObject.GetComponent<Projectile>().Fire(direction); return true; } return false; } }
using System; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Metadata; using School.Domain.Models; namespace School.Domain { public partial class SchoolContext : DbContext { public SchoolContext() { } // public SchoolContext(DbContextOptions <SchoolContext> options) // : base(options) // { // } public virtual DbSet<Course> Courses { get; set; } public virtual DbSet<Standard> Standards { get; set; } public virtual DbSet<Student> Students { get; set; } public virtual DbSet<StudentAddress> StudentAddresses { get; set; } public virtual DbSet<StudentCourse> StudentCourse { get; set; } public virtual DbSet<Teacher> Teachers { get; set; } protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { if (!optionsBuilder.IsConfigured) { //warning To protect potentially sensitive information in your connection string, you should move it out of source code. See http://go.microsoft.com/fwlink/?LinkId=723263 for guidance on storing connection strings. optionsBuilder.UseSqlServer(@"Server=(local);Database=SchoolDB;Trusted_Connection=True;"); } } protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.Entity<Course>(entity => { entity.Property(e => e.CourseName) .HasMaxLength(50) .IsUnicode(false); entity.HasOne(d => d.Teacher) .WithMany(p => p.Courses) .HasForeignKey(d => d.TeacherId) .OnDelete(DeleteBehavior.Cascade) .HasConstraintName("FK_Course_Teacher"); }); modelBuilder.Entity<Standard>(entity => { entity.Property(e => e.Description) .HasMaxLength(50) .IsUnicode(false); entity.Property(e => e.StandardName) .HasMaxLength(50) .IsUnicode(false); }); modelBuilder.Entity<Student>(entity => { entity.Property(e => e.StudentID).HasColumnName("StudentID"); entity.Property(e => e.StudentName) .HasMaxLength(50) .IsUnicode(false); // entity.Property(e => e.LastName) // .HasMaxLength(50) // .IsUnicode(false); entity.HasOne(d => d.Standard) .WithMany(p => p.Students) .HasForeignKey(d => d.StandardId) .OnDelete(DeleteBehavior.Cascade) .HasConstraintName("FK_Student_Standard"); }); modelBuilder.Entity<StudentAddress>(entity => { entity.HasKey(e => e.StudentID); entity.Property(e => e.StudentID) .HasColumnName("StudentID") .ValueGeneratedNever(); entity.Property(e => e.Address1) .IsRequired() .HasMaxLength(50) .IsUnicode(false); entity.Property(e => e.Address2) .HasMaxLength(50) .IsUnicode(false); entity.Property(e => e.City) .IsRequired() .HasMaxLength(50) .IsUnicode(false); entity.Property(e => e.State) .IsRequired() .HasMaxLength(50) .IsUnicode(false); entity.HasOne(d => d.Student) .WithOne(p => p.StudentAddress) .HasForeignKey<StudentAddress>(d => d.StudentID) .HasConstraintName("FK_StudentAddress_Student"); }); modelBuilder.Entity<StudentCourse>(entity => { entity.HasKey(e => new { e.StudentID, e.CourseId }); entity.HasOne(d => d.Course) .WithMany(p => p.StudentCourse) .HasForeignKey(d => d.CourseId) .OnDelete(DeleteBehavior.ClientSetNull) .HasConstraintName("FK_StudentCourse_Course"); entity.HasOne(d => d.Student) .WithMany(p => p.StudentCourse) .HasForeignKey(d => d.StudentID) .HasConstraintName("FK_StudentCourse_Student"); }); modelBuilder.Entity<Teacher>(entity => { entity.Property(e => e.StandardId).HasDefaultValueSql("((0))"); entity.Property(e => e.TeacherName) .HasMaxLength(50) .IsUnicode(false); entity.HasOne(d => d.Standard) .WithMany(p => p.Teachers) .HasForeignKey(d => d.StandardId) .OnDelete(DeleteBehavior.Cascade) .HasConstraintName("FK_Teacher_Standard"); }); } } }
using EFTeste.Entidades.Entidades; using System.Data.Entity.ModelConfiguration; namespace EFTeste.DataModel.Map { public class ProfessorEspecialMap : EntityTypeConfiguration<ProfessorEspecial> { public ProfessorEspecialMap() { ToTable("ProfessorEspecial"); HasKey(p => p.Id); Property(p => p.Nome).HasMaxLength(80).IsRequired(); HasMany(p => p.Turmas); HasRequired(p => p.Coordenador); } } }
/* Program Name: Movies Library System * * Author: Kazembe Rodrick * * Author Description: Freelancer software/web developer & Technical writter. Has over 7 years experience developing software * in Languages such as VB 6.0, C#.Net,Java, PHP and JavaScript & HTML. Services offered include custom * development, writting technical articles,tutorials and books. * Website: http://www.kazemberodrick.com * * Project URL: http://www.kazemberodrick.com/movies-library-system.html * * Email Address: kr@kazemberodrick. * * Purpose: Fairly complex Movies Library System For Educational purposes. Demonstrates how to develop complete database powered * Applications that Create and Update data in the database. The system also demonstrates how to create reports from * the database. * * Limitations: The system is currently a standalone. It does not support multiple users. This will be implemented in future * versions. * The system does not have a payments module. This can be developed upon request. Just sent an email to kr@kazemberodrick.com * The system does not have keep track of the number of movies to check for availability. This can be developed upon request. * * Movies Library System Road Map: This system is for educational purposes. I will be writting step-by-step tutorials on my * website http://www.kazemberodrick.com that explain; * -System Specifications for Movies Library System * -System Design Considerations * -System Database ERD * -System Class Diagram * -Explainations of the codes in each window * -Multiple-database support. The Base class BaseDBUtilities will be extended to create * classes that will support client-server database engines such as MySQL, MS SQL Server etc. * * Support Movies Library System: The System is completely free. Please support it by visiting http://www.kazemberodrick.com/c-sharp.html and recommending the site to * your friends. Share the tutorials on social media such as twitter and facebook. * * Github account: https://github.com/KazembeRodrick I regulary post and update sources on my Github account.Make sure to follow me * and never miss an update. * Facebook page: http://www.facebook.com/pages/Kazembe-Rodrick/487855197902730 Please like my page and get updates on latest articles * and source codes. You can get to ask questions too about the system and I will answer them. * * Twitter account: https://twitter.com/KazembeRodrick Spread the news. Tweet the articles and source code links on twitter. */ using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; namespace Movies_Library_System { public partial class frmCustomers : Form { #region Static Variables public static bool ADD_NEW = false; public static string key = string.Empty; #endregion #region Private Variables string sql_stmt = string.Empty; #endregion #region Private Methods private void display_record() { sql_stmt = "SELECT * FROM customers WHERE CustomerId = '" + key + "';"; DataTable dtCustomer = clsPublicMethods.DBUtilies.get_data_table(sql_stmt); if (dtCustomer.Rows.Count > 0) { foreach (DataRow dr in dtCustomer.Rows) { txtCustomerId.Text = dr["CustomerId"].ToString(); txtCustomerName.Text = dr["CustomerName"].ToString(); txtTelephone.Text = dr["Telephone"].ToString(); txtPhysicalAddress.Text = dr["PhysicalAddress"].ToString(); } } } #endregion #region Form Init Method and Control Events public frmCustomers() { InitializeComponent(); } private void frmCustomers_Load(object sender, EventArgs e) { if (ADD_NEW == false) { txtCustomerId.Enabled = false; display_record(); txtCustomerName.Focus(); } } private void txtCustomerId_Leave(object sender, EventArgs e) { if (txtCustomerId.Text != string.Empty) { sql_stmt = "SELECT * FROM customers WHERE customerid = '" + txtCustomerId.Text + "';"; if (clsPublicMethods.record_exists(sql_stmt) == true) { clsPublicMethods.duplicate_msg("Customer Id"); } } } private void btnSave_Click(object sender, EventArgs e) { if (txtCustomerId.Text == string.Empty) { clsPublicMethods.required_field_msg("Customer Id"); txtCustomerId.Focus(); return; } if (txtCustomerName.Text == string.Empty) { clsPublicMethods.required_field_msg("Customer Name"); txtCustomerName.Focus(); return; } if (clsPublicMethods.confirm_save_update() == DialogResult.Yes) { if (ADD_NEW == true) { sql_stmt = "INSERT INTO customers (CustomerID, CustomerName, Occupation, PhysicalAddress, Telephone) "; sql_stmt += "VALUES ('" + txtCustomerId.Text + "','" + txtCustomerName.Text + "','" + cboOccupation.Text + "','" + txtPhysicalAddress.Text + "','" + txtTelephone.Text + "');"; } else { sql_stmt = "UPDATE customers SET CustomerName = '" + txtCustomerName.Text + "',Occupation = '" + cboOccupation.Text + "', PhysicalAddress = '" + txtPhysicalAddress.Text + "', Telephone = '" + txtTelephone.Text + "' WHERE CustomerId = '" + txtCustomerId.Text + "';"; } clsPublicMethods.DBUtilies.execute_sql_statement(sql_stmt); ADD_NEW = false; txtCustomerId.Enabled = false; clsPublicMethods.saved_updated_msg(); } } private void btnClose_Click(object sender, EventArgs e) { Close(); } #endregion } }
using System; using System.IO; using System.ServiceProcess; using System.Text; namespace ServiceHost { static class Program { /// <summary> /// Handles exceptions not caught by the rest of the application. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e) { string logPath = @"c:\log\"; if (!Directory.Exists(logPath)) Directory.CreateDirectory(logPath); if (!logPath.EndsWith("\\")) logPath += "\\"; string logFile = logPath + "movieslog.log"; if (!File.Exists(logPath + logFile)) { using (TextWriter tw = new StreamWriter(logPath + logFile)) { tw.WriteLine("Exception in ServiceHost:"); tw.WriteLine(GetExceptions((Exception)e.ExceptionObject)); tw.Flush(); tw.Close(); } } else { using (TextWriter tw = new StreamWriter(logPath + logFile, true)) { tw.WriteLine("Exception in ServiceHost:"); tw.WriteLine(GetExceptions((Exception)e.ExceptionObject)); tw.Flush(); tw.Close(); } } } /// <summary> /// Gets all exceptions contained in the current exception. /// </summary> /// <param name="e">The exception containing the data.</param> /// <returns>A string representation of the exception.</returns> private static string GetExceptions(Exception e) { StringBuilder sb = new StringBuilder(); sb.AppendLine(e.Message); sb.AppendLine(e.StackTrace); if (e.InnerException != null) sb.AppendLine(GetExceptions(e.InnerException)); return sb.ToString(); } /// <summary> /// The main entry point for the application. /// </summary> static void Main(string[] args) { AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException; if (args.Length > 0 && args[0].Trim().ToUpperInvariant() == "-D") { ServiceHostContainer container = new ServiceHostContainer(); try { container.StartServices(); Console.WriteLine("Hosting the following services:"); string[] names = container.GetHostedServiceNames(); foreach (string s in names) Console.WriteLine("Service: " + s); Console.WriteLine("Press <Enter> to close."); Console.ReadLine(); container.StopServices(); } catch (Exception e) { Console.WriteLine(e.ToString()); } } else { ServiceBase[] ServicesToRun; ServicesToRun = new ServiceBase[] { new ServiceHost() }; ServiceBase.Run(ServicesToRun); } } } }
using System; namespace _01._Disneyland_Journey { class Program { static void Main(string[] args) { double journeyPrice = double.Parse(Console.ReadLine()); int months = int.Parse(Console.ReadLine()); double sumSaved = 0; for (int i = 1; i <= months; i++) { if (i == 1) { sumSaved += 0.25 * journeyPrice; } else { if (i % 2 == 1) { sumSaved -= 0.16 * sumSaved; } if (i % 4 == 0) { sumSaved += 0.25 * sumSaved; } sumSaved += 0.25 * journeyPrice; } } if (sumSaved >= journeyPrice) { Console.WriteLine($"Bravo! You can go to Disneyland and you will have {(sumSaved - journeyPrice):f2}lv. for souvenirs."); } else { Console.WriteLine($"Sorry. You need {(journeyPrice - sumSaved):f2}lv. more."); } } } }
using ScheduleService.DTO; using ScheduleService.Model; using System.Collections.Generic; namespace ScheduleService.Services { public interface IExaminationService { Examination Get(int id); IEnumerable<Examination> GetFinishedByPatient(string jmbg); IEnumerable<Examination> GetCanceledByPatient(string jmbg); IEnumerable<Examination> GetCreatedByPatient(string jmbg); void Schedule(ScheduleExaminationDTO examinationDTO); void Cancel(int id); } }
using System; using System.Collections.Generic; using System.IO; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Newtonsoft.Json.Linq; using Microsoft.AspNetCore.Authorization; using service.Models; namespace service.Controllers { [Produces("application/json")] [Route("api/[controller]")] public class HawkController : ControllerBase { public Logmodel log = new Logmodel(); private Dictionary<object, object> Hawknetcore_default_condition; public HawkController() { } //[Authorize] [HttpGet] public IEnumerable<string> Get() { return new string[] { "value1", "value2" }; } [Authorize] [HttpPost] public async Task<IActionResult> Post() { var body = ""; using (var mem = new MemoryStream()) using (var reader = new StreamReader(mem)) { Request.Body.CopyTo(mem); body = reader.ReadToEnd(); mem.Seek(0, SeekOrigin.Begin); body = reader.ReadToEnd(); } //log.info("log Post Wealth : " + body.ToString()); var Hawknetcore_status = ""; var request_data = JObject.Parse(body); //log.info("log Parser Wealth : " + request_data.ToString()); switch (request_data["apiname"].ToString()) { case "Exitsing": Hawknetcore_default_condition = new Dictionary<object, object>(); Hawknetcore_default_condition.Add("webapi_access_token", request_data["webapi_access_token"].ToString()); Hawknetcore_default_condition.Add("apiname", request_data["apiname"].ToString()); Hawknetcore_default_condition.Add("version", request_data["version"].ToString()); Hawknetcore_default_condition.Add("response time", DateTime.Now.ToString("dd-MM-yyy HH':'mm':'ss")); // Hawknetcore_default_condition.Add("response",await Hawknet_Model.Hawknet_Exitscustomer(request_data["version"].ToString(), request_data["data"].ToString())); Hawknetcore_status = "true"; break; case "Openaccount": Hawknetcore_default_condition = new Dictionary<object, object>(); Hawknetcore_default_condition.Add("webapi_access_token", request_data["webapi_access_token"].ToString()); Hawknetcore_default_condition.Add("apiname", request_data["apiname"].ToString()); Hawknetcore_default_condition.Add("version", request_data["version"].ToString()); Hawknetcore_default_condition.Add("response time", DateTime.Now.ToString("dd-MM-yyy HH':'mm':'ss")); switch (request_data["data"]["func"].ToString()) { //case "trn_cust": // Hawknetcore_default_condition.Add("response", await Hawknet_Model.central_customer(request_data["data"]["func"].ToString(), request_data["data"].ToString())); // Hawknetcore_status = "true"; // break; //case "trn_cust_ext": // Hawknetcore_default_condition.Add("response", await Hawknet_Model.central_customer(request_data["data"]["func"].ToString(), request_data["data"].ToString())); // Hawknetcore_status = "true"; // break; //case "trn_cust_sys": // Hawknetcore_default_condition.Add("response", await Hawknet_Model.central_customer(request_data["data"]["func"].ToString(), request_data["data"].ToString())); // Hawknetcore_status = "true"; // break; //case "trn_acc": // Hawknetcore_default_condition.Add("response", await Hawknet_Model.central_customer(request_data["data"]["func"].ToString(), request_data["data"].ToString())); // Hawknetcore_status = "true"; // break; //case "trn_acc_ext": // Hawknetcore_default_condition.Add("response", await Hawknet_Model.central_customer(request_data["data"]["func"].ToString(), request_data["data"].ToString())); // Hawknetcore_status = "true"; // break; //case "trn_acc_subaccount": // Hawknetcore_default_condition.Add("response", await Hawknet_Model.central_customer(request_data["data"]["func"].ToString(), request_data["data"].ToString())); // Hawknetcore_status = "true"; // break; //case "trn_group_exposure": // Hawknetcore_default_condition.Add("response", await Hawknet_Model.central_customer(request_data["data"]["func"].ToString(), request_data["data"].ToString())); // Hawknetcore_status = "true"; // break; //case "trn_group_exposure_member": // Hawknetcore_default_condition.Add("response", await Hawknet_Model.central_customer(request_data["data"]["func"].ToString(), request_data["data"].ToString())); // Hawknetcore_status = "true"; // break; //case "trn_cust_sys_add": // Hawknetcore_default_condition.Add("response", await Hawknet_Model.central_customer(request_data["data"]["func"].ToString(), request_data["data"].ToString())); // Hawknetcore_status = "true"; // break; //case "trn_cust_sys_bank": // Hawknetcore_default_condition.Add("response", await Hawknet_Model.central_customer(request_data["data"]["func"].ToString(), request_data["data"].ToString())); // Hawknetcore_status = "true"; // break; //case "trn_cust_sys_person": // Hawknetcore_default_condition.Add("response", await Hawknet_Model.central_customer(request_data["data"]["func"].ToString(), request_data["data"].ToString())); // Hawknetcore_status = "true"; // break; //case "trn_person": // Hawknetcore_default_condition.Add("response", await Hawknet_Model.central_customer(request_data["data"]["func"].ToString(), request_data["data"].ToString())); // Hawknetcore_status = "true"; // break; //case "trn_cust_sys_questionnaire": // Hawknetcore_default_condition.Add("response", await Hawknet_Model.central_customer(request_data["data"]["func"].ToString(), request_data["data"].ToString())); // Hawknetcore_status = "true"; // break; //case "trn_cust_sys_questionnaire_answer": // Hawknetcore_default_condition.Add("response", await Hawknet_Model.central_customer(request_data["data"]["func"].ToString(), request_data["data"].ToString())); // Hawknetcore_status = "true"; // break; //default: // Hawknetcore_default_condition.Add("response","Fail No api match"); // Hawknetcore_status = "fail"; // break; } // Hawknetcore_default_condition.Add("response",await Hawknet_Model.Hawknet_centralizedcustomer(request_data["version"].ToString(), request_data["data"].ToString())); break; case "Kyc": Hawknetcore_default_condition = new Dictionary<object, object>(); Hawknetcore_default_condition.Add("webapi_access_token", request_data["webapi_access_token"].ToString()); Hawknetcore_default_condition.Add("apiname", request_data["apiname"].ToString()); Hawknetcore_default_condition.Add("version", request_data["version"].ToString()); Hawknetcore_default_condition.Add("response time", DateTime.Now.ToString("dd-MM-yyy HH':'mm':'ss")); // Hawknetcore_default_condition.Add("response",await Hawknet_Model.Hawknet_KYC(request_data["version"].ToString(), request_data["data"].ToString())); Hawknetcore_status = "true"; break; case "BatchKyc": Hawknetcore_default_condition = new Dictionary<object, object>(); Hawknetcore_default_condition.Add("webapi_access_token", request_data["webapi_access_token"].ToString()); Hawknetcore_default_condition.Add("apiname", request_data["apiname"].ToString()); Hawknetcore_default_condition.Add("version", request_data["version"].ToString()); Hawknetcore_default_condition.Add("response time", DateTime.Now.ToString("dd-MM-yyy HH':'mm':'ss")); // Hawknetcore_default_condition.Add("response",await Hawknet_Model.Hawknet_BatchKyc(request_data["version"].ToString(), request_data["data"].ToString())); Hawknetcore_status = "true"; break; case "UpdateProfile": Hawknetcore_default_condition = new Dictionary<object, object>(); Hawknetcore_default_condition.Add("webapi_access_token", request_data["webapi_access_token"].ToString()); Hawknetcore_default_condition.Add("apiname", request_data["apiname"].ToString()); Hawknetcore_default_condition.Add("version", request_data["version"].ToString()); Hawknetcore_default_condition.Add("response time", DateTime.Now.ToString("dd-MM-yyy HH':'mm':'ss")); // Hawknetcore_default_condition.Add("response",await Hawknet_Model.Hawknet_UpdateProfile(request_data["version"].ToString(), request_data["data"].ToString())); Hawknetcore_status = "true"; break; case "Importdata": Hawknetcore_default_condition = new Dictionary<object, object>(); Hawknetcore_default_condition.Add("webapi_access_token", request_data["webapi_access_token"].ToString()); Hawknetcore_default_condition.Add("apiname", request_data["apiname"].ToString()); Hawknetcore_default_condition.Add("version", request_data["version"].ToString()); Hawknetcore_default_condition.Add("response time", DateTime.Now.ToString("dd-MM-yyy HH':'mm':'ss")); //Hawknetcore_default_condition.Add("response",await Hawknet_Model.Hawknet_Importdata(request_data["version"].ToString(), request_data["data"].ToString())); Hawknetcore_status = "true"; break; case "Management_datakyc": Hawknetcore_default_condition = new Dictionary<object, object>(); Hawknetcore_default_condition.Add("webapi_access_token", request_data["webapi_access_token"].ToString()); Hawknetcore_default_condition.Add("apiname", request_data["apiname"].ToString()); Hawknetcore_default_condition.Add("version", request_data["version"].ToString()); Hawknetcore_default_condition.Add("response time", DateTime.Now.ToString("dd-MM-yyy HH':'mm':'ss")); //Hawknetcore_default_condition.Add("response",await Hawknet_Model.Hawknet_Management_datakyc(request_data["version"].ToString(), request_data["data"].ToString())); Hawknetcore_status = "true"; break; default: Hawknetcore_default_condition = new Dictionary<object, object>(); Hawknetcore_default_condition.Add("info", "Web Api Access Not allow"); Hawknetcore_default_condition.Add("response time", DateTime.Now.ToString("dd-MM-yyy HH':'mm':'ss")); Hawknetcore_status = "fail"; break; } if (Hawknetcore_status == "fail") { return StatusCode(400, Hawknetcore_default_condition); } else { return StatusCode(200, Hawknetcore_default_condition); } } // PUT: api/App1/5 [Authorize] [HttpPut("{id}")] public IActionResult Put(int id, [FromBody] string value) { return StatusCode(200, "method Not allow"); } // DELETE: api/ApiWithActions/5 [Authorize] [HttpDelete("{id}")] public IActionResult Delete(int id) { return StatusCode(200, "method Not allow"); } } }
using System.Threading; using System.Threading.Tasks; using Microsoft.Extensions.Hosting; namespace CronScheduler.Extensions.StartupInitializer; /// <summary> /// Allows to run async jobs on Program.cs. /// </summary> public interface IStartupJob { /// <summary> /// Starts async job for <see cref="IHost"/>. /// </summary> /// <param name="cancellationToken"></param> /// <returns></returns> Task ExecuteAsync(CancellationToken cancellationToken = default); }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Data.SqlClient; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace PersonnelRecord { public partial class Position : Form { public Position() { InitializeComponent(); } private void save_Click(object sender, EventArgs e) { if (string.IsNullOrEmpty(textBox.Text)) { label2.Text = "Введите название должности!"; return; } positionBindingSource.EndEdit(); DialogResult = DialogResult.OK; } private void cancel_Click(object sender, EventArgs e) { positionBindingSource.CancelEdit(); DialogResult = DialogResult.Abort; } } }
using System.Net.Http; using System.Threading.Tasks; using System.Xml.Linq; namespace ServerApi.Services.Base { public abstract class SkautIsService { internal SkautIsHttpClient Client { get; } protected SkautIsService() { Client = new SkautIsHttpClient(); } protected async Task<XDocument> GetResponseXmlAsync(HttpResponseMessage response) { XDocument responseXml; using (var responseStream = await response.Content.ReadAsStreamAsync()) { responseXml = XDocument.Load(responseStream); } return responseXml; } } }
using System; using System.Collections.Generic; using System.Text; namespace PatronAbstract_Factory { public class FabricaAlcohol : IFabricante { public IBebida crearBebida() { Alcohol Bebida = new Alcohol(); return Bebida; } } }
using System; using System.Data.SqlClient; using System.IO; using Microsoft.SqlServer.Management.Common; using Microsoft.SqlServer.Management.Smo; using SqlServerRunnerNet.ViewModel; namespace SqlServerRunnerNet.Business { public static class SqlScriptRunner { public static bool RunSqlScriptOnConnection(string connectionString, ScriptViewModel script) { try { var filePath = script.Path; var scriptContents = File.ReadAllText(filePath); var sqlConnection = new SqlConnection(connectionString); var server = new Server(new ServerConnection(sqlConnection)); server.ConnectionContext.ExecuteNonQuery(scriptContents); script.ErrorMessage = string.Empty; return true; } catch (ExecutionFailureException ex) { var sqlException = ex.InnerException as SqlException; if (sqlException != null) { script.ErrorMessage = string.Format("At line {0}:\n{1}", sqlException.LineNumber, sqlException.Message); } else if (ex.InnerException != null) { script.ErrorMessage = ex.InnerException.Message; } else script.ErrorMessage = ex.Message; } catch (Exception ex) { script.ErrorMessage = ex.Message; } return false; } } }
using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc.TagHelpers.Internal; using Microsoft.Extensions.Caching.Memory; using Microsoft.Extensions.DependencyInjection; namespace Pobs.Web.Helpers { public static class HttpContextExtensions { public static string AddFileVersionToPath(this HttpContext context, string path) { var hostingEnvironment = context.RequestServices.GetRequiredService<IHostingEnvironment>(); var cache = context.RequestServices.GetRequiredService<IMemoryCache>(); var versionProvider = new FileVersionProvider(hostingEnvironment.WebRootFileProvider, cache, context.Request.Path); return versionProvider.AddFileVersionToPath(path); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using YouOpine2.DataAccess; namespace YouOpine2 { public partial class IronManOp : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { //Establecer la conexion con la base de datos using (yodbModel dbCtx = new yodbModel()) { //SELECT * FROM var query = (from x in dbCtx.IronManOp select new { Comentarios = x.Comentario }).ToList(); //Asiganmos la lista al GridView gvComent.DataSource = query; //Refrescar el gvComent.DataBind(); } } protected void Button1_Click(object sender, EventArgs e) { //using (yodbModel dbCtx = new yodbModel()) //{ // var Comentario = TxtComentario.DataSource // Comentario nuevocom = new Comentario // { // Comentario = TxtComentario // } // youbdModel.Comentario.InsertOnSubmit(nuevocom); // youbdModel.SubmitChanges(); //} } } }
using NLog; using SQLServerBackupTool.Web.Models; using System.Diagnostics; using System.Linq; using System.Net; using System.Web.Mvc; using System.Web.Routing; namespace SQLServerBackupTool.Web.Lib.Mvc { [Authorize] public abstract partial class ApplicationController : Controller, IFlashMessageProvider { protected Logger Logger { get; set; } protected SSBTDbContext DbContext { get; set; } public void AddFlashMessage(string message, FlashMessageType t) { FlashMessagesHelper.AddFlashMessage(this, message, t); } public void FlashInfo(string message) { AddFlashMessage(message, FlashMessageType.Info); } public void FlashSuccess(string message) { AddFlashMessage(message, FlashMessageType.Success); } public void FlashWarning(string message) { AddFlashMessage(message, FlashMessageType.Warning); } public void FlashError(string message) { AddFlashMessage(message, FlashMessageType.Error); } protected override void Initialize(RequestContext r) { var controllerName = r.RouteData.GetRequiredString("controller"); var actionName = r.RouteData.GetRequiredString("action"); ViewBag.ControllerName = controllerName; Logger = LogManager.GetLogger(string.Format("{0}_{1}", controllerName, actionName)); DbContext = new SSBTDbContext(); base.Initialize(r); } [Conditional("DEBUG")] protected void DebugModelStateErrors() { var errs = ModelState.Where(_ => _.Value.Errors.Any()); foreach (var e in errs) { Debug.WriteLine( "[ModelStateError] : '{0}' -> {1}", e.Key, string.Join(", ", e.Value.Errors.Select(_ => string.Format("'{0}'", _.ErrorMessage))) ); } } protected static ActionResult HttpNotAcceptable(string message = null) { return new HttpStatusCodeResult(406); // Not acceptable } protected static ActionResult HttpNotAuthorized() { return new HttpStatusCodeResult(HttpStatusCode.Unauthorized); } protected static string GetBackupsConnectionString() { return BackupsManager.GetBackupsConnectionString(); } protected override void Dispose(bool disposing) { DbContext.Dispose(); base.Dispose(disposing); } } }
using System.Data.Entity.ModelConfiguration; using AppStore.Domain.Orders; namespace AppStore.Infra.Data.Persistence.EF.Configurations { public class CreditCardTransationConfiguration : EntityTypeConfiguration<CreditCardTransation> { public CreditCardTransationConfiguration() { base.HasKey(u => u.CreditCardTransationId); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace J4F.Models { public class LoginViewModal { public bool Success { get; set; } public string ReturnUrl { get; set; } public string ErrorMessage { get; set; } } public class LoginInModal { public string UserName { get; set; } public string PassWord { get; set; } public string ReturnUrl { get; set; } } }
using BlazorWA.Shared.Entidades; using Microsoft.AspNetCore.Components; using Microsoft.JSInterop; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using static BlazorWA.Client.Shared.MainLayout; namespace BlazorWA.Client.Pages { public class CounterBase:ComponentBase { [Inject] protected ServiciosSingleton Singleton { get; set; } [Inject] protected ServiciosTransient Transient { get; set; } [Inject] protected IJSRuntime JS { get; set; } //[CascadingParameter (Name = "Color")] protected string Color { get; set; } //este parametro se pasa desde el main layout [CascadingParameter] protected AppState appState { get; set; } //este parametro se pasa desde el main layout protected int currentCount = 0; static int currentCountStatic = 0; [JSInvokable] public async Task IncrementCount() { currentCount++; Singleton.Valor = currentCount; Transient.Valor = currentCount; currentCountStatic++; await JS.InvokeVoidAsync("pruebaPuntoNetStatic"); } //Funcion que puede ser llamada desde JS [JSInvokable] public static Task<int> ObtenerCurrentCount() { return Task.FromResult(currentCountStatic); } protected async Task IncrementCountJS() { //Pelicula pelicula = new Pelicula(); //el segundo parametro es una instancia de la clase donde se encuentra el metodo que vamos a llamar, pelicula tambien serviria como segundo parametro //con this hace referencia a la clase actual await JS.InvokeVoidAsync("pruebaPuntoNetInstancia", DotNetObjectReference.Create(this)); } } }
using Owin; using RRExpress.Common.Extends; using RRExpress.Moq.Auth; using System.Web.Http; namespace RRExpress.Service { public class Startup { public void Configuration(IAppBuilder app) { var config = new HttpConfiguration(); //支持直接路由 config.MapHttpAttributeRoutes(); // 路由表配置 config.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{id}", defaults: new { id = RouteParameter.Optional } ); config.IncludeErrorDetailPolicy = IncludeErrorDetailPolicy.LocalOnly; //配置 Json.Net , 使其支持抽象类的序列化及反序列化 config.Formatters.JsonFormatter.SerializerSettings = new Newtonsoft.Json.JsonSerializerSettings() { TypeNameHandling = Newtonsoft.Json.TypeNameHandling.Auto }; // 使用 Protobuf config.UseProtobuf(); config.EnableSystemDiagnosticsTracing(); //TODO 这里使用的是模拟认证,请更换 app.UseMoqAuth(); app.UseWebApi(config); config.EnsureInitialized(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; using Microsoft.Expression.Encoder.Devices; using WebcamControl; using System.IO; using System.Drawing.Imaging; namespace ManyFoodZ { /// <summary> /// Camera.xaml 的交互逻辑 /// </summary> public partial class Camera : Window { public Camera() { InitializeComponent(); // Prepare Camera cameraGrid.DataContext = WebCamCtrl; WebCamCtrl.VidFormat = VideoFormat.mp4; WebCamCtrl.PictureFormat = ImageFormat.Png; WebCamCtrl.FrameRate = 30; WebCamCtrl.FrameSize = new System.Drawing.Size(780, 480); var vidDevices = EncoderDevices.FindDevices(EncoderDeviceType.Video); var audDevices = EncoderDevices.FindDevices(EncoderDeviceType.Audio); foreach (EncoderDevice dvc in vidDevices) camVideoComboBox.Items.Add(dvc.Name); foreach (EncoderDevice dvc in audDevices) camAudioComboBox.Items.Add(dvc.Name); } private void camStartButton_Click(object sender, RoutedEventArgs e) { try { WebCamCtrl.StartCapture(); } catch (Microsoft.Expression.Encoder.SystemErrorException) { MessageBox.Show("Device is in use by another application"); } } private void camStopButton_Click(object sender, RoutedEventArgs e) { WebCamCtrl.StopCapture(); } private void SnapshotButton_Click(object sender, RoutedEventArgs e) { if (Directory.Exists(MainWindow.MWInstance.imageDir)) { WebCamCtrl.ImageDirectory = MainWindow.MWInstance.imageDir; WebCamCtrl.TakeSnapshot(); } } private void RecordButton_Click(object sender, RoutedEventArgs e) { if (Directory.Exists(MainWindow.MWInstance.videoDir)) { WebCamCtrl.VideoDirectory = MainWindow.MWInstance.videoDir; WebCamCtrl.StartRecording(); } } private void StopRecordButton_Click(object sender, RoutedEventArgs e) { WebCamCtrl.StopRecording(); } private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e) { WebCamCtrl.StopCapture(); MainWindow.MWInstance.camButton.IsEnabled = true; } } }
using AutoTests.Framework.Web.Attributes; using AutoTests.Framework.Web.Common.Handlers; namespace AutoTests.Framework.Tests.Web.Elements { public class Input : DemoElement { [FromLocator] public string Locator { get; private set; } public Input(Application application) : base(application) { } [SetValue] public void SetValue(string value) { Context.SetValue(Locator, value); } [GetValue] public string GetValue() { return Locator; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.ComponentModel.DataAnnotations; namespace SSISTeam9.Models { public class Inventory: IComparable<Inventory> { public long ItemId { get; set; } [Display(Name = "Item Code")] [Required] public string ItemCode { get; set; } [Display(Name = "Bin No.")] [Required] public string BinNo { get; set; } public int StockLevel { get; set; } public int ReorderLevel { get; set; } public int ReorderQty { get; set; } public int ActualStock { get; set; } [Display(Name = "Category")] [Required] public string Category { get; set; } [Display(Name = "Description")] [Required] public string Description { get; set; } [Display(Name = "Unit Of Measure")] [Required] public string UnitOfMeasure { get; set; } public string ImageUrl { get; set; } public bool IsChecked { get; set; } public PriceList ItemSuppliersDetails { get; set; } public int PendingOrderQuantity; public List<bool> CheckedItems { get; set; } public List<Inventory> Items { get; set; } public int Flag { get; set; } public int CompareTo(Inventory other) { return (this.StockLevel - this.ReorderLevel).CompareTo(other.StockLevel - other.ReorderLevel); } } }
using Client.Bussness; using Client.Helpers; using Client.Helpers.Manager; using GalaSoft.MvvmLight; using GalaSoft.MvvmLight.Command; using Page.Note.Comment.Message; using Sardf.Helpers; using System; using System.ComponentModel; using System.IO; using WPF.NewClientl.UI; using WPF.NewClientl.UI.OfficeNote; namespace WPF.NewClientl.ViewModel.PageOfficeNote { public class PageOfficeNoteViewModel: ViewModelBase { private BackgroundWorker backgroundWorker = new BackgroundWorker(); private MeetingNoteBase _context; private IofficeManager _manager = null; private PageNoteMainTest mainFrame = null; private PageOfficeNoteWindow officeDialog = null; public PageOfficeNoteViewModel(MeetingNoteBase meetingNoteBase, PageNoteMainTest pageNoteMainTest, PageOfficeNoteWindow pageOfficeNoteWindow) { _context = meetingNoteBase; mainFrame = pageNoteMainTest; officeDialog = pageOfficeNoteWindow; if (_context != null) { switch (_context.OfficeType) { case officeType.ppt: _manager = new PptManager(); break; case officeType.word: _manager = new WordManager(); break; case officeType.excel: _manager = new ExcelManager(); break; default: break; } } } protected void ExecuteAsync(object argument, Action<DoWorkEventArgs> doAction, Action<RunWorkerCompletedEventArgs> completeAction) { backgroundWorker.DoWork += (o, e) => { doAction?.Invoke(e); }; backgroundWorker.RunWorkerCompleted += (o, e) => { completeAction?.Invoke(e); }; backgroundWorker.RunWorkerAsync(argument); } #region DoOfficeNoteCommand private RelayCommand<string> _doOfficeNoteCommand; public RelayCommand<string> DoOfficeNoteCommand { get { if (_doOfficeNoteCommand == null) _doOfficeNoteCommand = new RelayCommand<string>(flag => { switch (flag) { case "Pen1": _manager.DoBallPoint(); break; case "Pen2": _manager.DoHighlighter(); break; case "Eraser": _manager.DoEraser(); break; case "Clear": _manager.DoClear(); break; case "Save": Save(); break; default: _manager.DoInkToolsClose(); _manager.DoSave(); _manager.DoClose(); officeDialog.Close(); mainFrame.Show(); break; } }); return _doOfficeNoteCommand; } } private void Save() { _manager.DoSave(); var fileName = _manager.DoGetFileName(); if (!fileName.IsNullOrEmpty() && !fileName.Contains(string.Format(@"{0}\Note", AppClientContext.Context.ClientId))) { var index = fileName.IndexOf(AppClientContext.Context.ClientId); if (index >= 0) { var dataPath = fileName.Substring(index + AppClientContext.Context.ClientId.Length + 1); var noteFileName = string.Format(@"{0}\{1}\Note\{2}", AppDomain.CurrentDomain.BaseDirectory, AppClientContext.Context.ClientId, dataPath); FileHelper.EnsureFile(noteFileName); try { if (File.Exists(noteFileName)) { File.Delete(noteFileName); File.Copy(fileName, noteFileName); } else { File.Copy(fileName, noteFileName); } PageNoteMessage.ShowPageNoteMessage("保存成功!", PageNoteMessageType.success); } catch (Exception se) { GC.Collect(); PageNoteMessage.ShowPageNoteMessage("保存失败!", PageNoteMessageType.error); return; } } } } #endregion } }
using System; using System.Collections.Generic; using System.Linq; /* * tags: counting sort, radix sort * Time(n), Space(n) */ namespace alg.tree { public class BinarySearchTree { public IList<int> InorderTraversal(TreeNode root) { var ret = new List<int>(); InorderTraversalRc(root, ret); return ret; } void InorderTraversalRc(TreeNode root, IList<int> res) { if (root == null) return; InorderTraversalRc(root.Left, res); res.Add(root.Value); InorderTraversalRc(root.Right, res); } public IList<int> InorderTraversalStack(TreeNode root) { var ret = new List<int>(); var stack = new Stack<TreeNode>(); var curr = root; while (curr != null || stack.Count > 0) { while (curr != null) { stack.Push(curr); curr = curr.Left; } var node = stack.Pop(); ret.Add(node.Value); // visit curr = node.Right; // move to its right } return ret; } /* * Space(1), will modify the tree * if curr has no left then visit it, otherwise make curr as its predecessor's right * after done, all nodes have only right child with missing some nodes. */ public IList<int> InorderTraversalMorris(TreeNode root) { var ret = new List<int>(); var stack = new Stack<TreeNode>(); var curr = root; while (curr != null) { if (curr.Left == null) { ret.Add(curr.Value); // visit curr = curr.Right; } else { var pre = curr.Left; while (pre.Right != null) pre = pre.Right; // find rightmost pre.Right = curr; var tmp = curr.Left; curr.Left = null; // modify the tree curr = tmp; } } return ret; } public IList<int> PreorderTraversaStack(TreeNode root) { var ret = new List<int>(); var stack = new Stack<TreeNode>(); if (root != null) stack.Push(root); while (stack.Count > 0) { var node = stack.Pop(); ret.Add(node.Value); // visit if (node.Right != null) stack.Push(node.Right); if (node.Left != null) stack.Push(node.Left); } return ret; } /* * tag: dp * Time(n^2), Space(n) * dp[n] = sum(dp[i]*dp[n-i-1]), i=[1..n] * select i as root * Given n, return the amount of unique BST's (binary search trees) that store values 1 ... n. */ int UniqueTrees(int n) { var dp = new int[n + 1]; dp[0] = dp[1] = 1; for (int len = 2; len <= n; len++) { for (int i = 0; i < len; i++) dp[len] += dp[i] * dp[len - i - 1]; } return dp[n]; } public IList<int> LevelorderTraversal(TreeNode root) { var ret = new List<int>(); var queue = new Queue<TreeNode>(); if (root != null) queue.Enqueue(root); while (queue.Count > 0) { for (int i = queue.Count; i > 0; i--) { var node = queue.Dequeue(); ret.Add(node.Value); // visit if (node.Left != null) queue.Enqueue(node.Left); if (node.Right != null) queue.Enqueue(node.Right); } } return ret; } public class TreeNode { public int Value; public TreeNode Left, Right; public TreeNode(int v) { Value = v; } public TreeNode(TreeNode root) { Value = root.Value; if (root.Left != null) Left = new TreeNode(root.Left); if (root.Right != null) Right = new TreeNode(root.Right); } } public void Test() { var root = new TreeNode(1) { Left = new TreeNode(2), Right = new TreeNode(3) { Right = new TreeNode(4) } }; var exp = new List<int> { 2, 1, 3, 4 }; Console.WriteLine(exp.SequenceEqual(InorderTraversal(root))); Console.WriteLine(exp.SequenceEqual(InorderTraversalStack(root))); Console.WriteLine(exp.SequenceEqual(InorderTraversalMorris(new TreeNode(root)))); exp = new List<int> { 1, 2, 3, 4 }; Console.WriteLine(exp.SequenceEqual(PreorderTraversaStack(root))); exp = new List<int> { 1, 2, 3, 4 }; Console.WriteLine(exp.SequenceEqual(LevelorderTraversal(root))); } } }
using System; using System.Collections.Generic; using System.Linq; namespace _10._Predicate_Party_ { class Program { static void Main(string[] args) { var people = Console.ReadLine().Split(' ',StringSplitOptions.RemoveEmptyEntries).ToList(); var command = Console.ReadLine(); Func<string, string, bool> startsWith = (s, c) => { if (s.StartsWith(c)) { return true; } return false; }; Func<string, string, bool> endsWith = (s, c) => { if (s.EndsWith(c)) { return true; } return false; }; Func<string, int, bool> hasLength = (s, l) => { if (s.Length == l) { return true; } return false; }; Action<List<string>, Func<string, string, bool>,string> clone = (l, func, c) => { for (int i = 0; i < l.Count; i++) { if (func(l[i],c)) { l.Insert(i,l[i]); i++; } } }; Action<List<string>, Func<string, int, bool>, int> cloneLength = (l, func, c) => { for (int i = 0; i < l.Count; i++) { if (func(l[i], c)) { l.Insert(i, l[i]); i++; } } }; Action<List<string>, Func<string, string, bool>, string> remove = (l, func, c) => { for (int i = 0; i < l.Count; i++) { if (func(l[i], c)) { l.RemoveAt(i); i--; } } }; Action<List<string>, Func<string, int, bool>, int> removeLength = (l, func, c) => { for (int i = 0; i < l.Count; i++) { if (func(l[i], c)) { l.RemoveAt(i); i--; } } }; while (command != "Party!") { var tokens = command.Split(); var action = tokens[0]; var predicate = tokens[1]; if (action == "Double") { if (predicate == "StartsWith") { var symbol = tokens[2]; clone(people,startsWith,symbol); } else if (predicate == "EndsWith") { var symbol = tokens[2]; clone(people, endsWith, symbol); } else { var length = int.Parse(tokens[2]); cloneLength(people, hasLength, length); } } else if (action == "Remove") { if (predicate == "StartsWith") { var symbol = tokens[2]; remove(people, startsWith, symbol); } else if (predicate == "EndsWith") { var symbol = tokens[2]; remove(people, endsWith, symbol); } else { var length = int.Parse(tokens[2]); removeLength(people, hasLength, length); } } command = Console.ReadLine(); } if (people.Count > 0) { Console.WriteLine(string.Join(", ",people) + " are going to the party!"); } else { Console.WriteLine("Nobody is going to the party!"); } } } }
using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Drawing; using System.Drawing.Imaging; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ZM.TiledScreenDesigner { public class ImageJsonConverter : JsonConverter { public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { var strValue = (string)reader.Value; if (strValue != null) return Image.FromStream(new MemoryStream(Convert.FromBase64String(strValue))); else return null; } public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { var img = (Image)value; var ms = new MemoryStream(); img.Save(ms, img.RawFormat); byte[] b = ms.ToArray(); writer.WriteValue(b); } public override bool CanConvert(Type objectType) { return (objectType == typeof(Image)); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Web.Http; using WebApplication1.Models; namespace WebApplication1.Controllers { public class ItemsController : ApiController { public const string select = @"Select RecordId, ItemID, Description, OurRetail as Price, Misc1, Misc2, Misc3, Misc4, Misc5, Available as Qty, TransCode, AvgCost as Cost from Items "; // GET: api/Items //public IEnumerable<Item> Get(string search) //{ // var searchQuery = select + string.Format("where itemid = '{0}'" , search); // return SharedDb.PosimDb.GetMany<Item>(searchQuery); //} // GET: api/Items/5 public Item Get(string id) { var searchQuery = select + string.Format("where itemid = '{0}'", id); return SharedDb.PosimDb.Get<Item>(searchQuery); } // POST: api/Items public void Post([FromBody]string value) { } // PUT: api/Items/5 public void Put(int id, [FromBody]string value) { } // DELETE: api/Items/5 public void Delete(int id) { } } }
namespace SubC.Attachments { using UnityEngine; using System.Collections.Generic; using ClingyPhysics; [CreateAssetMenu(fileName = "New Physics One-to-One Strategy", menuName = "Clingy/Attach Strategies/Physics One-to-One Strategy")] public class PhysicsOneToOneStrategy : OneToOneAttachStrategy { public new enum Categories { JointedObject = OneToOneAttachStrategy.Categories.Object1, ConnectedObject = OneToOneAttachStrategy.Categories.Object2 } [System.Serializable] public class OneToOneJointDescription : AttachStrategyJointDescription { [ParamSelector(new int[] { (int) Providers.Object1, (int) Providers.Object2 })] public ParamSelector anchorParam; [ParamSelector(new int[] { (int) Providers.Object1, (int) Providers.Object2 })] public ParamSelector connectedAnchorParam; [ParamSelector(new int[] { (int) Providers.Object1, (int) Providers.Object2 })] public ParamSelector axisParam; [ParamSelector(new int[] { (int) Providers.Object1, (int) Providers.Object2 })] public ParamSelector swingAxisParam; [ParamSelector(new int[] { (int) Providers.Object1, (int) Providers.Object2 })] public ParamSelector secondaryAxisParam; // [ParamSelector(new int[] { (int) Providers.Object1, (int) Providers.Object2 })] // public ParamSelector limitsParam; public override ParamSelector GetAnchorParamSelector() { return anchorParam; } public override ParamSelector GetConnectedAnchorParamSelector() { return connectedAnchorParam; } public override ParamSelector GetAxisParamSelector() { return axisParam; } public override ParamSelector GetSecondaryAxisParamSelector() { return secondaryAxisParam; } public override ParamSelector GetSwingAxisParamSelector() { return swingAxisParam; } public override void Reset() { base.Reset(); anchorParam = ParamSelector.Position(provider: (int) Providers.Object1); connectedAnchorParam = ParamSelector.Position(provider: (int) Providers.Object2); axisParam = new ParamSelector(new Param(ParamType.Vector3, "axis"), (int) Providers.Object1); secondaryAxisParam = new ParamSelector(new Param(Vector3.right, "secondaryAxis"), (int) Providers.Object1); swingAxisParam = new ParamSelector(new Param(Vector3.right, "swingAxis"), (int) Providers.Object1); // limitsParam = new ParamSelector(Param.defaultNameForType[ParamType.AngleLimits], // new Param(ParamType.AngleLimits), (int) Providers.Object1); } } public OneToOneJointDescription[] jointDescriptions; public bool hideJointsInInspector = true; // public bool detachOnJointBreak = true; public override string GetLabelForObject1() { return "Jointed Object"; } public override string GetLabelForObject2() { return "Connected Object"; } public AttachObject GetJointedObject(Attachment attachment) { return GetObject1(attachment); } public AttachObject GetConnectedObject(Attachment attachment) { return GetObject2(attachment); } protected override void Reset() { base.Reset(); jointDescriptions = new OneToOneJointDescription[1]; jointDescriptions[0] = new OneToOneJointDescription(); jointDescriptions[0].Reset(); } protected override void ConnectBoth(AttachObject jointed, AttachObject connected) { PhysicsAttachStrategyHelper.CreateOrApplyAllJoints(jointed, connected, jointDescriptions, null, hideJointsInInspector); } protected override void DisconnectBoth(AttachObject jointed, AttachObject connected) { PhysicsAttachStrategyHelper.DestroyJoints(jointed); } void UpdateFromParamsAndApply(Attachment attachment) { if (!IsConnected(attachment)) return; AttachObject jointed = GetJointedObject(attachment); AttachObject connected = GetConnectedObject(attachment); // fixme - need to only update anchors if they have actually changed (same as 2D)? PhysicsAttachStrategyHelper.CreateOrApplyAllJoints(jointed, connected, jointDescriptions, null, hideJointsInInspector); } public override void OnParamsUpdated(Attachment attachment) { UpdateFromParamsAndApply(attachment); } public override void UpdateForEditorChanges(Attachment attachment) { UpdateFromParamsAndApply(attachment); } } }
using WitsmlExplorer.Api.Jobs.Common; using System.Collections.Generic; namespace WitsmlExplorer.Api.Jobs { public class DeleteLogObjectsJob { public IEnumerable<LogReference> LogReferences { get; set; } } }
using System; using System.Collections.Generic; using Microsoft.Xna.Framework; using Terraria; using Terraria.DataStructures; using Terraria.ID; using Terraria.ModLoader; using Caserraria.Items; namespace Caserraria.Items.Healing { public class StalwartPotion : ModItem { public override void SetStaticDefaults() { DisplayName.SetDefault("Stalwart Healing Potion"); } public override void SetDefaults() { item.useStyle = 2; item.useTime = 17; item.useAnimation = 17; item.UseSound = SoundID.Item3; item.value = 100000; item.rare = 9; item.healLife = 300; item.maxStack = 30; item.consumable = true; item.potion = true; } public override void AddRecipes() { ModRecipe recipe = new ModRecipe(mod); recipe.AddIngredient(ItemID.SuperHealingPotion, 6); recipe.AddIngredient(ItemID.LifeFruit, 1); recipe.AddIngredient(ItemID.LunarOre, 5); if(Caserraria.instance.thoriumLoaded) { recipe.AddIngredient(ModLoader.GetMod("ThoriumMod").ItemType("BioMatter"), 4); } if(Caserraria.instance.calamityLoaded) { recipe.AddIngredient(ModLoader.GetMod("CalamityMod").ItemType("LivingShard"), 2); } if(Caserraria.instance.cosmeticvarietyLoaded) { recipe.AddIngredient(ModLoader.GetMod("CosmeticVariety").ItemType("StarlightOre"), 2); recipe.AddIngredient(ModLoader.GetMod("CosmeticVariety").ItemType("Veridanite"), 2); recipe.AddIngredient(ModLoader.GetMod("CosmeticVariety").ItemType("Chalchum"), 2); } recipe.AddTile(TileID.Bottles); recipe.SetResult(this, 3); recipe.AddRecipe(); } } }
using Alabo.Cloud.Cms.Votes.Domain.Entities; using Alabo.Domains.Repositories; using MongoDB.Bson; namespace Alabo.Cloud.Cms.Votes.Domain.Repositories { public interface IVoteRepository : IRepository<Vote, ObjectId> { } }
using Masuit.LuceneEFCore.SearchEngine.Interfaces; using System.Collections.Generic; namespace Masuit.LuceneEFCore.SearchEngine { /// <summary> /// 搜索结果集 /// </summary> /// <typeparam name="T"></typeparam> public class SearchResultCollection<T> : ISearchResultCollection<T> { /// <summary> /// 实体集 /// </summary> public IList<T> Results { get; set; } /// <summary> /// 耗时 /// </summary> public long Elapsed { get; set; } /// <summary> /// 总条数 /// </summary> public int TotalHits { get; set; } public SearchResultCollection() { Results = new List<T>(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace EmirateHMBot.Models { public class CompanyStatut { public string CompanyName { get; set; } public string CompanyCode { get; set; } public string CompanyStatus { get; set; } } }
using System; namespace com.Sconit.Entity.SYS { [Serializable] public partial class Menu : EntityBase { #region O/R Mapping Properties public string Code { get; set; } public string Name { get; set; } public string ParentMenuCode { get; set; } public Int32 Sequence { get; set; } public string Description { get; set; } public string PageUrl { get; set; } public string ImageUrl { get; set; } public Boolean IsActive { get; set; } #endregion public override int GetHashCode() { if (Code != null) { return Code.GetHashCode(); } else { return base.GetHashCode(); } } public override bool Equals(object obj) { Menu another = obj as Menu; if (another == null) { return false; } else { return (this.Code == another.Code); } } } }
/* The MIT License (MIT) * * Copyright (c) 2018 Marc Clifton * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ /* Code Project Open License (CPOL) 1.02 * https://www.codeproject.com/info/cpol10.aspx */ using System; using System.Collections.Generic; using System.Linq; using Clifton.Core.Assertions; namespace Clifton.Meaning { public class FieldContextPath { public Field Field { get; protected set; } public IReadOnlyList<ContextPath> Path { get { return contextPath; } } protected List<ContextPath> contextPath; public FieldContextPath(Field field, Stack<ContextPath> cp) { Field = field; contextPath = cp.Reverse().ToList(); } } public class Parser { public const string CRLF = "\r\n"; public Action<string> Log { get; set; } public IReadOnlyList<Group> Groups { get { return groups.AsReadOnly(); } } public IReadOnlyList<FieldContextPath> FieldContextPaths { get { return fieldContextPaths; } } public IReadOnlyList<Type> MissingDeclarations { get { return missingDeclarations.AsReadOnly(); } } protected List<Type> missingDeclarations = new List<Type>(); protected List<Group> groups = new List<Group>(); protected Stack<ContextPath> contextPath = new Stack<ContextPath>(); protected bool parsed = false; protected List<Type> allEntities = new List<Type>(); protected List<FieldContextPath> fieldContextPaths = new List<FieldContextPath>(); // relationships and abstractions. // We don't really need the list of right-side types, but we may at some point want this. protected Dictionary<Type, List<Type>> allRelationships = new Dictionary<Type, List<Type>>(); // Track visited abstractions for a particular context. protected Dictionary<Type, List<AbstractionDeclaration>> visitedContextAbstractions = new Dictionary<Type, List<AbstractionDeclaration>>(); // Track type ID's within the parser's context so we use consistent context ID's when creating context values. protected Dictionary<Type, Guid> typeDictionary = new Dictionary<Type, Guid>(); /// <summary> /// Track contexts that have lookups that define rendering. /// </summary> protected Dictionary<Type, Lookup> contextLookupMap = new Dictionary<Type, Lookup>(); /// <summary> /// Returns true if the declarations are valid, meaning that there should not be any abstractions without a declared sub-entity /// and relationships without a left-side declared entity. This requires that the context already be parsed, otherwise an exception /// is thrown. /// </summary> public bool AreDeclarationsValid { get { missingDeclarations.Clear(); bool ret = true; if (!parsed) { throw new ContextException("Context has not yet been parsed."); } // Keys must exist in allEntities. foreach (var key in allRelationships.Keys) { if (!allEntities.Contains(key)) { ret = false; missingDeclarations.Add(key); } } return ret; } } public void Parse(IContext context) { allEntities.Clear(); allRelationships.Clear(); visitedContextAbstractions.Clear(); // contextPath.Push(new ContextPath(ContextPath.ContextPathType.Root, context.GetType())); Group group = CreateGroup(context, RelationshipDeclaration.NullRelationship, contextPath); groups.Add(group); GenerateMasterGroups(contextPath, groups, group, context, RelationshipDeclaration.NullRelationship); parsed = true; } public bool HasLookup(Type contextType) { return contextLookupMap.ContainsKey(contextType); } public Lookup GetLookup(Type contextType) { return contextLookupMap[contextType]; } public ContextValue CreateValue<T1>(string val, int recordNumber = 0) { return CreateContextValue(val, recordNumber, typeof(T1)); } public ContextValue CreateValue<T1, T2>(string val, int recordNumber = 0) { return CreateContextValue(val, recordNumber, typeof(T1), typeof(T2)); } public ContextValue CreateValue<T1, T2, T3>(string val, int recordNumber = 0) { return CreateContextValue(val, recordNumber, typeof(T1), typeof(T2), typeof(T3)); } public ContextValue CreateValue<T1, T2, T3, T4>(string val, int recordNumber = 0) { return CreateContextValue(val, recordNumber, typeof(T1), typeof(T2), typeof(T3), typeof(T4)); } public ContextValue CreateValue<T1, T2, T3, T4, T5>(string val, int recordNumber = 0) { return CreateContextValue(val, recordNumber, typeof(T1), typeof(T2), typeof(T3), typeof(T4), typeof(T5)); } public ContextValue CreateValue<T1, T2, T3, T4, T5, T6>(string val, int recordNumber = 0) { return CreateContextValue(val, recordNumber, typeof(T1), typeof(T2), typeof(T3), typeof(T4), typeof(T5), typeof(T6)); } public ContextValue CreateContextValue(string val, int recordNumber, params Type[] types) { Assert.That(types.Last().HasInterface<IValueEntity>(), "The last type in the context path must implement the IValueEntity interface."); // Clone the working list. List<FieldContextPath> matchingFieldPaths = new List<FieldContextPath>(fieldContextPaths); int n = 0; foreach (Type type in types) { // Reduce the working list down to only the matches. matchingFieldPaths = new List<FieldContextPath>(matchingFieldPaths.Where(fcp => fcp.Path[n].Type == type)); ++n; } Assert.That(matchingFieldPaths.Count == 1, "Expected a single matching field to remain."); List<Guid> instancePath = CreateInstancePath(types); ContextValue cv = matchingFieldPaths[0].Field.CreateValue(val, instancePath); cv.RecordNumber = recordNumber; return cv; } public List<Guid> CreateInstancePath(IEnumerable<Type> types) { return CreateInstancePath(types.ToArray()); } public List<Guid> CreateInstancePath(Type[] types) { List<Guid> instanceIdList = new List<Guid>(); for (int pathIdx = 0; pathIdx < types.Length - 1; pathIdx++) { Guid pathId; Type t = types[pathIdx]; if (!typeDictionary.TryGetValue(t, out pathId)) { pathId = Guid.NewGuid(); typeDictionary[t] = pathId; } instanceIdList.Add(pathId); } // Finally, always add a unique ID for the last path entry which is the context value! instanceIdList.Add(Guid.NewGuid()); return instanceIdList; } protected void LogEntityType(Type t) { if (!allEntities.Contains(t)) { allEntities.Add(t); } if (!allRelationships.ContainsKey(t)) { allRelationships[t] = new List<Type>(); } } protected void LogRelationship(Type left, Type right) { if (!allRelationships.ContainsKey(left)) { allRelationships[left] = new List<Type>(); } allRelationships[left].Add(right); } protected void LogVisitedAbstraction(IContext context, AbstractionDeclaration abstraction) { Type tcontext = context.GetType(); if (!visitedContextAbstractions.ContainsKey(tcontext)) { visitedContextAbstractions[tcontext] = new List<AbstractionDeclaration>(); } visitedContextAbstractions[tcontext].Add(abstraction); } protected Group GenerateMasterGroups(Stack<ContextPath> contextPath, List<Group> groups, Group group, IContext context, RelationshipDeclaration relationship) { if (contextPath.Any(c => c.Type == context.GetType())) { throw new ContextException("Context " + context.GetType().Name + " is recursive."); } Log?.Invoke("Top level root entity: " + context.GetType().Name); LogEntityType(context.GetType()); //Group group = CreateGroup(context, relationship, contextPath); //groups.Add(group); if (relationship.RelationshipType == typeof(NullRelationship)) { contextPath.Push(new ContextPath(ContextPath.ContextPathType.Root, context.GetType())); } else { contextPath.Push(new ContextPath(ContextPath.ContextPathType.Relationship, context.GetType())); } var rootEntities = context.RootEntities; CreateFields(contextPath, context, group); foreach (var root in rootEntities) { DrillIntoAbstraction(contextPath, context, group, root); } GenerateRelationalGroups(contextPath, groups, group, context); // Get all abstractions defined by self-context. // This handles abstractions declared on this context by this context. // We skip abstractions we've already drilled into. // TODO: This seems kludgy but if we omit this, the unit tests on self-declared abstractions fails. // However, we can't qualify abstractions by this context type because then disassociated context don't // get parsed, which causes the DisassociatedAbtractionTest to fail. var abstractions = context.GetAbstractions(); Type tcontext = context.GetType(); foreach (var abstraction in abstractions) { // We only drill into abstractions that we haven't visited for this context. // See unit tests: // ContextWithAbstractionAndRelationTest // SubcontextWithSelfAbstractionTest // ContextWithAbstractionAndRelationshipTest if (!visitedContextAbstractions.ContainsKey(tcontext) || !visitedContextAbstractions[tcontext].Contains(abstraction)) { DrillIntoAbstraction(contextPath, context, group, abstraction); } } contextPath.Pop(); return group; } protected void GenerateRelationalGroups(Stack<ContextPath> contextPath, List<Group> groups, Group group, IContext context) { var relationships = context.Relationships; foreach (var relationship in relationships) { foreach (var sourceType in relationship.AllSourceTypes) { LogRelationship(relationship.TargetType, sourceType); LogEntityType(sourceType); if (sourceType.HasBaseClass<Context>()) { Log?.Invoke("Context Relationship: " + relationship.RelationshipType.Name + " => Drilling into " + sourceType.Name); // Create the context so we can explore its declarations of entities, relationships, abstractions, and ValueEntity types. IContext relatedContext = (IContext)Activator.CreateInstance(sourceType); MapPotentialLookup(relatedContext, sourceType); // Push the relationship. // contextPath.Push(new ContextPath(ContextPath.ContextPathType.Relationship, relationship.RelationshipType)); // Push the type related to. // contextPath.Push(new ContextPath(ContextPath.ContextPathType.Implements, sourceType)); Group newGroup = group; if (!relationship.ShouldCoalesceRelationship) { newGroup = CreateGroup(relatedContext, relationship, contextPath); groups.Add(newGroup); } GenerateMasterGroups(contextPath, groups, newGroup, relatedContext, relationship); // contextPath.Pop(); // contextPath.Pop(); } else if (sourceType.HasInterface<IEntity>()) { // An IEntity doesn't have a context, it can't implement relationships or fields, so // the only thing we can do is explore the abstractions. // Note that Context implements IEntity, but IEntity is not a context! Log?.Invoke(CRLF + "Entity Relationship: " + relationship.RelationshipType.Name + " => Drilling into " + sourceType.Name); // Get abstractions for the source type: var abstractions = context.GetAbstractions(sourceType); Group egroup = CreateGroup(sourceType, relationship, contextPath, relationship.Label); // contextPath.Push(new ContextPath(ContextPath.ContextPathType.Relationship, relationship.RelationshipType)); DrillIntoAbstractions(contextPath, context, egroup, abstractions); // Only add the group if there are fields associated with the abstractions. // Otherwise, we get groups for abstractions that have no fields. if (egroup.Fields.Count > 0) { groups.Add(egroup); } // contextPath.Pop(); } } } } protected Group CreateGroup(EntityDeclaration decl, RelationshipDeclaration relationship, Stack<ContextPath> contextPath) { Log?.Invoke(CRLF + "Creating group: " + decl.EntityType.Name + " relationship: " + relationship.RelationshipType.Name); Group group = new Group(decl.Label ?? relationship.Label, decl.EntityType, contextPath, relationship); return group; } protected Group CreateGroup(IContext context, RelationshipDeclaration relationship, Stack<ContextPath> contextPath) { Type t = context.GetType(); Log?.Invoke(CRLF + "Creating group: " + t.Name + " relationship: " + relationship.RelationshipType.Name); Group group = new Group(relationship.Label ?? context.Label ?? t.Name, t, contextPath, relationship); return group; } protected Group CreateGroup(Type t, RelationshipDeclaration relationship, Stack<ContextPath> contextPath, string label) { Log?.Invoke(CRLF + "Creating group: " + t.Name + " relationship: " + relationship.RelationshipType.Name); Group group = new Group(label ?? relationship.Label ?? t.Name, t, contextPath, relationship); return group; } protected void PopulateGroupFields(Stack<ContextPath> contextPath, IContext context, Group group, EntityDeclaration decl) { // CreateFields(contextPath, context, group); DrillIntoAbstraction(contextPath, context, group, decl); } protected void MapPotentialLookup(IContext context, Type contextType) { if (context.HasLookup) { contextLookupMap[contextType] = context.Lookup; } } protected void CreateFields(Stack<ContextPath> contextPath, IContext context, Group group) { foreach (var root in context.RootEntities) { LogEntityType(root.EntityType); // Drill into root entity declarations that are contexts. if (root.EntityType.HasBaseClass<Context>()) { Log?.Invoke("CreateFields: Drilling into " + root.EntityType.Name); IContext rootContext = (IContext)Activator.CreateInstance(root.EntityType); MapPotentialLookup(rootContext, root.EntityType); var rootEntities = rootContext.RootEntities; contextPath.Push(new ContextPath(ContextPath.ContextPathType.HasA, root.EntityType)); foreach (var rce in rootEntities) { LogEntityType(rce.EntityType); // contextPath.Push(new ContextPath(ContextPath.ContextPathType.Root, root.EntityType)); // contextPath.Push(new ContextPath(ContextPath.ContextPathType.Root, rce.EntityType)); if (rce.EntityType.HasInterface<IValueEntity>()) { Log?.Invoke("Adding field " + rce.EntityType.Name); contextPath.Push(new ContextPath(ContextPath.ContextPathType.Field, rce.EntityType)); var field = group.AddField(root.Label ?? rce.EntityType.Name, contextPath); fieldContextPaths.Add(new FieldContextPath(field, contextPath)); contextPath.Pop(); } else if (rce.EntityType.HasBaseClass<Context>()) { // Child entities (not abstractions or relationships) stay in the same group. // See TwoSubcontextDeclarationsTest for a test that executes this code path. Log?.Invoke("CreateFields: Drilling into child context " + rce.EntityType.Name); contextPath.Push(new ContextPath(ContextPath.ContextPathType.Child, rce.EntityType)); // Create the context so we can explore its declarations of entities, relationships, abstractions, and IValueEntity types IContext childContext = (IContext)Activator.CreateInstance(rce.EntityType); MapPotentialLookup(childContext, rce.EntityType); CreateFields(contextPath, childContext, group); contextPath.Pop(); } else { throw new ContextException(rce.EntityType.Name + " is not a Context or an IValueEntity."); } } DrillIntoAbstraction(contextPath, rootContext, group, root); contextPath.Pop(); } else if (root.EntityType.HasInterface<IValueEntity>()) { Log?.Invoke("Adding field " + root.EntityType.Name); contextPath.Push(new ContextPath(ContextPath.ContextPathType.Field, root.EntityType)); var field = group.AddField(root.Label ?? root.EntityType.Name, contextPath); fieldContextPaths.Add(new FieldContextPath(field, contextPath)); contextPath.Pop(); } else { throw new ContextException(root.EntityType.Name + " is not a Context or an IValueEntity."); } } } protected void DrillIntoAbstraction(Stack<ContextPath> contextPath, IContext context, Group group, EntityDeclaration decl) { var abstractions = context.GetAbstractions(decl); DrillIntoAbstractions(contextPath, context, group, abstractions); } protected void DrillIntoAbstractions(Stack<ContextPath> contextPath, IContext context, Group group, IEnumerable<AbstractionDeclaration> abstractions) { foreach (var abstraction in abstractions) { DrillIntoAbstraction(contextPath, context, group, abstraction); } } protected void DrillIntoAbstraction(Stack<ContextPath> contextPath, IContext context, Group group, AbstractionDeclaration abstraction) { LogEntityType(abstraction.SuperType); LogRelationship(abstraction.SubType, abstraction.SuperType); LogVisitedAbstraction(context, abstraction); if (abstraction.SuperType.HasBaseClass<Context>()) { Log?.Invoke("Abstraction: Drilling into " + abstraction.SuperType.Name); // Create the context so we can explore its declarations of entities, relationships, abstractions, and IValueEntity types. IContext superContext = (IContext)Activator.CreateInstance(abstraction.SuperType); MapPotentialLookup(superContext, abstraction.SuperType); var rootEntities = superContext.RootEntities; if (rootEntities.Count() > 0) { Group group2 = group; if (!abstraction.ShouldCoalesceAbstraction) { group2 = CreateGroup(abstraction.SuperType, RelationshipDeclaration.NullRelationship, contextPath, abstraction.Label); groups.Add(group2); } foreach (var root in rootEntities) { contextPath.Push(new ContextPath(ContextPath.ContextPathType.Abstraction, abstraction.SuperType)); CreateFields(contextPath, superContext, group2); PopulateGroupFields(contextPath, superContext, group2, root); contextPath.Pop(); } } } // TODO: What if the abstraction is a plain-old entity? // Entities never have content? Anything that has content would be in a context! } } }
using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Security.Principal; using System.Text; using System.Web; using System.Web.Http.Filters; using Integer.Domain.Acesso; using Integer.Domain.Paroquia; using Integer.Infrastructure.Criptografia; using Integer.Infrastructure.IoC; namespace Integer.Api.Security { public class BasicAuthenticationAttribute : ActionFilterAttribute { private readonly Grupos grupos; private readonly Usuarios usuarios; public BasicAuthenticationAttribute() { this.grupos = IoCWorker.Resolve<Grupos>(); this.usuarios = IoCWorker.Resolve<Usuarios>(); } public override void OnActionExecuting(System.Web.Http.Controllers.HttpActionContext actionContext) { if (actionContext.Request.Headers.Authorization == null) { actionContext.Response = new System.Net.Http.HttpResponseMessage(System.Net.HttpStatusCode.Unauthorized); } else { string authToken = actionContext.Request.Headers.Authorization.Parameter; string decodedToken = Encoding.UTF8.GetString(Convert.FromBase64String(authToken)); string email = decodedToken.Substring(0, decodedToken.IndexOf(":")); string senha = decodedToken.Substring(decodedToken.IndexOf(":") + 1); Usuario usuario = this.ObterUsuario(email, senha); if (usuario != null) { HttpContext.Current.User = new GenericPrincipal(new ApiIdentity(usuario), new string[] { }); // TODO: user roles base.OnActionExecuting(actionContext); } else { actionContext.Response = new System.Net.Http.HttpResponseMessage(System.Net.HttpStatusCode.Unauthorized); } } } public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext) { var usuarioPrecisaTrocarSenha = ((ApiIdentity)HttpContext.Current.User.Identity).Usuario.PrecisaTrocarSenha; if (usuarioPrecisaTrocarSenha) { actionExecutedContext.Response.StatusCode = HttpStatusCode.RedirectMethod; HttpContext.Current.Response.Headers.Set("Location", actionExecutedContext.Request.RequestUri.Host + "/Usuario/Criar"); } base.OnActionExecuted(actionExecutedContext); } private Usuario ObterUsuario(string email, string senha) { Usuario usuario = null; Grupo grupo = grupos.Com(g => g.Email == email); if (grupo != null && grupo.PrecisaCriarUsuario) { if (grupo.ValidarSenha(senha)) { usuario = new Usuario(email, senha, grupo.Id); usuarios.Salvar(usuario); } } else { usuario = usuarios.Com(u => u.Email == email && u.Senha == Encryptor.Encrypt(senha)); } return usuario; } } }
using System.Collections; using UnityEngine; public class Road : MonoBehaviour { public bool isMoveByAnim = false; public int numberOfMove = 0; public float deltaMoveTime = 0.4f; public float timeAdded = 10; public float speed = 10; private float timeToMove = 0; public GameObject body; public float waitAndSetAnimator = 3; public bool movingToCenter = false; private bool isMovingDown = false; public bool isGizmasStart = false; // Use this for initialization void Start () { timeToMove = deltaMoveTime * numberOfMove + timeAdded; body.GetComponent<Animator>().enabled = false; //body.transform.localPosition = Vector3.zero; } // Update is called once per frame void Update () { if (timeToMove + waitAndSetAnimator <= Player.player.time) { body.GetComponent<Animator>().enabled = true; Destroy(this); } else if (movingToCenter && timeToMove <= Player.player.time) { RoadMove(body.transform); } } void RoadMove(Transform body) { // Move our position a step closer to the target. body.transform.position = Vector3.MoveTowards(body.position, body.parent.position, speed * Time.deltaTime); if (Vector3.Distance(body.position, body.parent.position) == 0) movingToCenter = false; } public void voidStartMovingDown() { if (!isMovingDown) { StartCoroutine(waitAndMoveDown()); isMovingDown = false; } } IEnumerator waitAndMoveDown() { yield return new WaitForSeconds(1f); GetComponent<Move>().enabled = true; } /* void OnDrawGizmos() { if (isGizmasStart) { GameObject go = new GameObject("Body"); go.transform.parent = transform.parent; isGizmasStart = false; } } */ }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Net.Http; using Newtonsoft.Json.Linq; using CEMAPI.DAL; using CEMAPI.Models; namespace CEMAPI.BAL { public class TECustomisationOrderBAL { RecordExceptions excepton = new RecordExceptions(); HttpResponseMessage APIResult = new HttpResponseMessage(); CustomizationEmailDAL CEmailDAL = new CustomizationEmailDAL(); SuccessInfo Info = new SuccessInfo { errorcode = 1, errormessage = "Failed", listcount = 0 }; #region Initiate Customisation Order public HttpResponseMessage InitiateOrder(JObject TEData, int authuser) { try { if (authuser == 0) { Info.errormessage = "Login User is Mandatory"; Info.errorcode = 1; APIResult.Content = new JsonContent(new { result = string.Empty, info = Info }); return APIResult; } //Validate the Request Object Starts Info = InitiateOrderValidation(TEData); if (Info.errorcode == 1) { APIResult.Content = new JsonContent(new { result = string.Empty, info = Info }); return APIResult; } //Validate the Request Object Ends InitiateOrder InitiateOrder = new InitiateOrder(); InitiateOrder.OrderID = TEData["OrderID"].ToObject<int>(); InitiateOrder.SAPCustomerID = TEData["SAPCustomerID"].ToObject<string>(); InitiateOrder.SaleOrderID = TEData["SaleOrderID"].ToObject<string>(); InitiateOrder.CurrentCustomisationOption = TEData["CurrentCusOption"].ToObject<string>(); InitiateOrder.NewCustomisationOption = TEData["ChooseCusOption"].ToObject<string>(); InitiateOrder.CustDesignFee = TEData["CustDesignFee"].ToObject<decimal>(); InitiateOrder.CustomisationPlatform = TEData["CustomisationPlatform"].ToObject<int>(); TECustomisationOrderDAL DAL = new TECustomisationOrderDAL(); #region Create Customisation Order int OrderID =DAL.InitiateOrder(authuser, InitiateOrder); if (OrderID <= 0) { Info.errormessage = "Initiate Order Failed!"; Info.errorcode = 1; APIResult.Content = new JsonContent(new { result = string.Empty, info = Info }); return APIResult; } #endregion #region Updating Iscustomisation Status in Offer DAL.UpdateMainOrderStatus(InitiateOrder.SAPCustomerID, InitiateOrder.SaleOrderID,1); #endregion #region Milestone and Invoice Generation if (InitiateOrder.CustDesignFee > 0) DAL.MileStoneInvoiceCreationForOrder(authuser, OrderID, InitiateOrder.OrderID); #endregion DAL.MainOrderEvents(InitiateOrder.SAPCustomerID, authuser, "CUSTOMISATIONINITIATION", DateTime.Now); //Email Notification-1. Customization – Initiate Start CEmailDAL.SendEmailForInitateCustomization(OrderID, authuser); //Email Notification-1. Customization – Initiate END Info.errormessage = "Order Initiated Succesfully"; Info.errorcode = 0; APIResult.Content = new JsonContent(new { result = OrderID, info = Info }); return APIResult; } catch (Exception ex) { excepton.RecordUnHandledException(ex); Info.errorcode = 1; Info.errormessage = "Order Cannot be Initiated"; APIResult.Content = new JsonContent(new { result = string.Empty, info = Info }); return APIResult; } } public SuccessInfo InitiateOrderValidation(JObject TEData) { SuccessInfo ValidationMessage = new SuccessInfo { errorcode = 0, errormessage = "VALID"}; if (TEData == null) { ValidationMessage.errorcode = 1; ValidationMessage.errormessage = "Mandatory info are Missing"; return ValidationMessage; } if (TEData["OrderID"] == null) { ValidationMessage.errorcode = 1; ValidationMessage.errormessage = "Order is Mandatory"; return ValidationMessage; } if (TEData["SAPCustomerID"] == null) { ValidationMessage.errorcode = 1; ValidationMessage.errormessage = "SAP CustomerID is Mandatory"; return ValidationMessage; } if (TEData["SaleOrderID"] == null) { ValidationMessage.errorcode = 1; ValidationMessage.errormessage = "SAP OrderID is Mandatory"; return ValidationMessage; } if (TEData["CurrentCusOption"] == null) { ValidationMessage.errorcode = 1; ValidationMessage.errormessage = "Current Customisation Option is Mandatory"; return ValidationMessage; } if (TEData["ChooseCusOption"] == null) { ValidationMessage.errorcode = 1; ValidationMessage.errormessage = "New Customisation Option is Mandatory"; return ValidationMessage; } if (TEData["CustDesignFee"] == null) { ValidationMessage.errorcode = 1; ValidationMessage.errormessage = "Customisation Design Fee is Mandatory"; return ValidationMessage; } if (TEData["CustomisationPlatform"] == null) { ValidationMessage.errorcode = 1; ValidationMessage.errormessage = "Customisation Platform is Mandatory"; return ValidationMessage; } return ValidationMessage; } #endregion #region Launch Customisation Order public HttpResponseMessage LaunchOrder(JObject TEData, int authuser) { try { if (authuser == 0) { Info.errormessage = "Login User is Mandatory"; Info.errorcode = 1; APIResult.Content = new JsonContent(new { result = string.Empty, info = Info }); return APIResult; } //Validate the Request Object Starts Info = LaunchOrderValidation(TEData); if (Info.errorcode == 1) { APIResult.Content = new JsonContent(new { result = string.Empty, info = Info }); return APIResult; } //Validate the Request Object Ends int CustomerBOQID = TEData["CustomerBoqID"].ToObject<int>(); DateTime CustomisationLaunchDate = TEData["CustomisationLaunchDate"].ToObject<DateTime>(); int? CustomisationManager = TEData["CustomisationManager"].ToObject<int?>(); int? CustomisationArchitect = TEData["CustomisationArchitect"].ToObject<int?>(); TECustomisationOrderDAL DAL = new TECustomisationOrderDAL(); TECustomerBOQ COrderDet = new TECustomerBOQ(); COrderDet=DAL.OrderBasicDetails(CustomerBOQID); if (COrderDet == null) { Info.errormessage = "Could Not Find Order Details"; Info.errorcode = 1; APIResult.Content = new JsonContent(new { result = string.Empty, info = Info }); return APIResult; } int LaunchStatus = DAL.LaunchOrder(authuser, CustomerBOQID, CustomisationLaunchDate, CustomisationManager, CustomisationArchitect); if (LaunchStatus <= 0) { Info.errormessage = "Failed To launch Order"; Info.errorcode = 1; APIResult.Content = new JsonContent(new { result = string.Empty, info = Info }); return APIResult; } DAL.MainOrderEvents(COrderDet.CustomerID, authuser, "CUSTOMISATIONLAUNCH", DateTime.Now); DAL.EmailNotification(CustomerBOQID, authuser, "LAUNCH"); //Email Notification-2. Customization – Launch Start CEmailDAL.SendEmailForLaunchCustomization(CustomerBOQID, authuser); //Email Notification-2. Customization – Launch END Info.errormessage = "Order Launched Succesfully"; Info.errorcode = 0; APIResult.Content = new JsonContent(new { result = string.Empty, info = Info }); return APIResult; } catch (Exception ex) { excepton.RecordUnHandledException(ex); Info.errorcode = 1; Info.errormessage = "Order Cannot be Launched"; APIResult.Content = new JsonContent(new { result = string.Empty, info = Info }); return APIResult; } } public SuccessInfo LaunchOrderValidation(JObject TEData) { SuccessInfo ValidationMessage = new SuccessInfo { errorcode = 0, errormessage = "VALID" }; if (TEData == null) { ValidationMessage.errorcode = 1; ValidationMessage.errormessage = "Mandatory info are Missing"; return ValidationMessage; } if (TEData["CustomerBoqID"] == null) { ValidationMessage.errorcode = 1; ValidationMessage.errormessage = "Order is Mandatory"; return ValidationMessage; } if (TEData["SAPCustomerID"] == null) { ValidationMessage.errorcode = 1; ValidationMessage.errormessage = "SAP Customer ID is Mandatory"; return ValidationMessage; } if (TEData["SaleOrderID"] == null) { ValidationMessage.errorcode = 1; ValidationMessage.errormessage = "SAP Order ID is Mandatory"; return ValidationMessage; } if (TEData["CustomisationLaunchDate"] == null) { ValidationMessage.errorcode = 1; ValidationMessage.errormessage = "Launch Date is Mandatory"; return ValidationMessage; } if (TEData["CustomisationManager"] == null) { ValidationMessage.errorcode = 1; ValidationMessage.errormessage = "Customisation Manager is Mandatory"; return ValidationMessage; } if (TEData["CustomisationArchitect"] == null) { ValidationMessage.errorcode = 1; ValidationMessage.errormessage = "Architect is Mandatory"; return ValidationMessage; } int CustomerBOQID = TEData["CustomerBoqID"].ToObject<int>(); TECustomisationOrderDAL DAL = new TECustomisationOrderDAL(); string RuleValue= DAL.GetRule("CustomisationLaunchCheck", CustomerBOQID); if (RuleValue.ToLower() != "true") { ValidationMessage.errorcode = 1; ValidationMessage.errormessage = "Customisation Launch Check Rule not set Properly"; return ValidationMessage; } string SAPCustomerID = TEData["SAPCustomerID"].ToObject<string>(); string SaleOrderID = TEData["SaleOrderID"].ToObject<string>(); int PendingInvouces=DAL.CheckPendingCustomisationInvoices(SAPCustomerID, SaleOrderID); if (PendingInvouces > 0) { ValidationMessage.errorcode = 1; ValidationMessage.errormessage = "Invoice posting is pending. Post and clear the Invoice Amount before Launch Customisation."; return ValidationMessage; } bool UnPaidInvoices = DAL.CheckForUnPaidInvoices(SAPCustomerID, SaleOrderID); if (UnPaidInvoices==false) { ValidationMessage.errorcode = 1; ValidationMessage.errormessage = "Please clear the Invoice Amount before Launch Customisation."; return ValidationMessage; } return ValidationMessage; } # endregion #region Setup Customer Account public HttpResponseMessage SetupCustomerAccount(JObject TEData, int authuser) { try { if (authuser == 0) { Info.errormessage = "Login User is Mandatory"; Info.errorcode = 1; APIResult.Content = new JsonContent(new { result = string.Empty, info = Info }); return APIResult; } //Validate the Request Object Starts Info = SetupAccountValidation(TEData); if (Info.errorcode == 1) { APIResult.Content = new JsonContent(new { result = string.Empty, info = Info }); return APIResult; } Info = SetupCustomerUnitValidation(TEData); if (Info.errorcode == 1) { APIResult.Content = new JsonContent(new { result = string.Empty, info = Info }); return APIResult; } //Validate the Request Object Ends int CustomerBOQID = TEData["CustomerBoqID"].ToObject<int>(); string SAPCustomerID = TEData["SAPCustomerID"].ToObject<string>(); string SaleOrderID = TEData["SaleOrderID"].ToObject<string>(); TECustomisationOrderDAL DAL = new TECustomisationOrderDAL(); TECustomerBOQ COrderDet = new TECustomerBOQ(); COrderDet = DAL.OrderBasicDetails(CustomerBOQID); if (COrderDet == null) { Info.errormessage = "Could Not Find Order Details"; Info.errorcode = 1; APIResult.Content = new JsonContent(new { result = string.Empty, info = Info }); return APIResult; } TECustomerB2CAccountDetails Adetails = new TECustomerB2CAccountDetails(); Adetails = DAL.CustomerB2CDetails(SAPCustomerID, SaleOrderID, authuser); if (Adetails == null) { Info.errormessage = "Cannot Get Customer B2C Key"; Info.errorcode = 1; APIResult.Content = new JsonContent(new { result = string.Empty, info = Info }); return APIResult; } int OrderID = TEData["OrderID"].ToObject<int>(); string landscapeOrientation = TEData["landscapeOrientation"].ToObject<string>(); string modelRevisionId = TEData["modelRevisionId"].ToObject<string>(); string Revision = TEData["Revision"].ToObject<string>(); string OrientationAngle = TEData["OrientationAngle"].ToObject<string>(); string GardenType = TEData["GardenType"].ToObject<string>(); UnitSetupEDesign USData = new UnitSetupEDesign(); USData = DAL.GetFullDetailsForUnitSetUp(CustomerBOQID, OrderID, landscapeOrientation, modelRevisionId, Revision, OrientationAngle, GardenType); if (USData == null) { Info.errormessage = "Could Not Find Order Details"; Info.errorcode = 1; APIResult.Content = new JsonContent(new { result = string.Empty, info = Info }); return APIResult; } int HistoryID = DAL.InsertInEDesignUnitSync(USData, authuser); if (HistoryID <= 0) { Info.errormessage = "Failed to Setup Customer Unit"; Info.errorcode = 1; APIResult.Content = new JsonContent(new { result = string.Empty, info = Info }); return APIResult; } bool EDesignSyncStatus = DAL.SetupCustomerAccount(SAPCustomerID, SaleOrderID, Adetails.CustomerB2CAccountDtlsId, authuser, HistoryID); if (EDesignSyncStatus == false) { Info.errormessage = "Customer Account Setup Failed"; Info.errorcode = 1; APIResult.Content = new JsonContent(new { result = string.Empty, info = Info }); return APIResult; } DAL.MainOrderEvents(COrderDet.CustomerID, authuser, "CUSTOMERACCOUNTSETUP", DateTime.Now); Info.errormessage = "Customer Account Set Succesfully"; Info.errorcode = 0; APIResult.Content = new JsonContent(new { result = string.Empty, info = Info }); return APIResult; } catch (Exception ex) { excepton.RecordUnHandledException(ex); Info.errorcode = 1; Info.errormessage = "Failed to Setup Customer Account"; APIResult.Content = new JsonContent(new { result = string.Empty, info = Info }); return APIResult; } } public SuccessInfo SetupAccountValidation(JObject TEData) { SuccessInfo ValidationMessage = new SuccessInfo { errorcode = 0, errormessage = "VALID" }; if (TEData == null) { ValidationMessage.errorcode = 1; ValidationMessage.errormessage = "Mandatory info are Missing"; return ValidationMessage; } if (TEData["CustomerBoqID"] == null) { ValidationMessage.errorcode = 1; ValidationMessage.errormessage = "Order is Mandatory"; return ValidationMessage; } if (TEData["SAPCustomerID"] == null) { ValidationMessage.errorcode = 1; ValidationMessage.errormessage = "SAP Customer ID is Mandatory"; return ValidationMessage; } if (TEData["SaleOrderID"] == null) { ValidationMessage.errorcode = 1; ValidationMessage.errormessage = "SAP Order ID is Mandatory"; return ValidationMessage; } int CustomerBOQID = TEData["CustomerBoqID"].ToObject<int>(); TECustomisationOrderDAL DAL = new TECustomisationOrderDAL(); string RuleValue = DAL.GetRule("CustomisationLaunchCheck", CustomerBOQID); if (RuleValue.ToLower() != "true") { ValidationMessage.errorcode = 1; ValidationMessage.errormessage = "Customisation Launch Check Rule not set Properly"; return ValidationMessage; } string SAPCustomerID = TEData["SAPCustomerID"].ToObject<string>(); string SaleOrderID = TEData["SaleOrderID"].ToObject<string>(); int PendingInvouces = DAL.CheckPendingCustomisationInvoices(SAPCustomerID, SaleOrderID); if (PendingInvouces > 0) { ValidationMessage.errorcode = 1; ValidationMessage.errormessage = "Invoice posting is pending. Post and clear the Invoice Amount before Launch Customisation."; return ValidationMessage; } bool UnPaidInvoices = DAL.CheckForUnPaidInvoices(SAPCustomerID, SaleOrderID); if (UnPaidInvoices == false) { ValidationMessage.errorcode = 1; ValidationMessage.errormessage = "Please clear the Invoice Amount before Launch Customisation."; return ValidationMessage; } return ValidationMessage; } # endregion #region Setup Customer Account public HttpResponseMessage SetupCustomerUnit(JObject TEData, int authuser) { try { if (authuser == 0) { Info.errormessage = "Login User is Mandatory"; Info.errorcode = 1; APIResult.Content = new JsonContent(new { result = string.Empty, info = Info }); return APIResult; } //Validate the Request Object Starts Info = SetupAccountValidation(TEData); if (Info.errorcode == 1) { APIResult.Content = new JsonContent(new { result = string.Empty, info = Info }); return APIResult; } //Validate the Request Object Ends int CustomerBOQID = TEData["CustomerBoqID"].ToObject<int>(); int OrderID = TEData["OrderID"].ToObject<int>(); string landscapeOrientation = TEData["landscapeOrientation"].ToObject<string>(); string modelRevisionId = TEData["modelRevisionId"].ToObject<string>(); string Revision = TEData["Revision"].ToObject<string>(); string OrientationAngle = TEData["OrientationAngle"].ToObject<string>(); string GardenType = TEData["GardenType"].ToObject<string>(); TECustomisationOrderDAL DAL = new TECustomisationOrderDAL(); UnitSetupEDesign USData = new UnitSetupEDesign(); USData = DAL.GetFullDetailsForUnitSetUp(CustomerBOQID, OrderID, landscapeOrientation, modelRevisionId, Revision, OrientationAngle, GardenType); if (USData == null) { Info.errormessage = "Could Not Find Order Details"; Info.errorcode = 1; APIResult.Content = new JsonContent(new { result = string.Empty, info = Info }); return APIResult; } int HistoryID = DAL.InsertInEDesignUnitSync(USData, authuser); if (HistoryID >=0) { Info.errormessage = "Failed to Setup Customer Unit"; Info.errorcode = 1; APIResult.Content = new JsonContent(new { result = string.Empty, info = Info }); return APIResult; } bool EDesignSyncStatus = DAL.SetupCustomerUnit(HistoryID, USData.SAPCustomerID, USData.SaleOrderID, authuser); if (EDesignSyncStatus == false) { Info.errormessage = "Customer Unit Setup Failed"; Info.errorcode = 1; APIResult.Content = new JsonContent(new { result = string.Empty, info = Info }); return APIResult; } DAL.MainOrderEvents(USData.SAPCustomerID, authuser, "CUSTOMERUNITSETUP", DateTime.Now); Info.errormessage = "Customer Unit Setup Succesfully"; Info.errorcode = 0; APIResult.Content = new JsonContent(new { result = string.Empty, info = Info }); return APIResult; } catch (Exception ex) { excepton.RecordUnHandledException(ex); Info.errorcode = 1; Info.errormessage = "Failed to Setup Customer Unit"; APIResult.Content = new JsonContent(new { result = string.Empty, info = Info }); return APIResult; } } public SuccessInfo SetupCustomerUnitValidation(JObject TEData) { SuccessInfo ValidationMessage = new SuccessInfo { errorcode = 0, errormessage = "VALID" }; if (TEData == null) { ValidationMessage.errorcode = 1; ValidationMessage.errormessage = "Mandatory info are Missing"; return ValidationMessage; } if (TEData["CustomerBoqID"] == null) { ValidationMessage.errorcode = 1; ValidationMessage.errormessage = "Order is Mandatory"; return ValidationMessage; } if (TEData["OrderID"] == null) { ValidationMessage.errorcode = 1; ValidationMessage.errormessage = "Order is Mandatory"; return ValidationMessage; } if (TEData["Revision"] == null) { ValidationMessage.errorcode = 1; ValidationMessage.errormessage = "SAP Order ID is Mandatory"; return ValidationMessage; } if (TEData["OrientationAngle"] == null) { ValidationMessage.errorcode = 1; ValidationMessage.errormessage = "SAP Order ID is Mandatory"; return ValidationMessage; } if (TEData["GardenType"] == null) { ValidationMessage.errorcode = 1; ValidationMessage.errormessage = "SAP Order ID is Mandatory"; return ValidationMessage; } return ValidationMessage; } # endregion } }
namespace P08MilitaryElite.Factories { using System; using System.Collections.Generic; using System.Linq; using Interfaces; using Interfaces.Factories; public class FactoryMethod<T> : IFactoryMethod<T> where T : ISoldier { private ICollection<IPrivate> currentPrivates; public IAbstractFactory<T> CreateFactory( string type, ICollection<ISoldier> soldiers, params object[] arguments) { if (soldiers != null) { this.currentPrivates = soldiers.OfType<IPrivate>().ToArray(); } switch (type) { case "Private": return this.CreatePrivateFactory(arguments); case "Commando": return this.CreateCommandoFactory(arguments); case "Engineer": return this.CreateEngineerFactory(arguments); case "LeutenantGeneral": return this.CreateLeutenantGeneralFactory(arguments); case "Spy": return this.CreateSpyFactory(arguments); default: throw new ArgumentException("Unknown type."); } } private IAbstractFactory<T> CreatePrivateFactory(object[] arguments) { return new PrivateFactory( arguments[0].ToString(), arguments[1].ToString(), arguments[2].ToString(), double.Parse(arguments[3].ToString())) as IAbstractFactory<T>; } private IAbstractFactory<T> CreateCommandoFactory(object[] arguments) { var missionCollection = arguments .Skip(5).Take(arguments.Length - 5) .Select(a => a.ToString()).ToArray(); return new CommandoFactory( arguments[0].ToString(), arguments[1].ToString(), arguments[2].ToString(), double.Parse(arguments[3].ToString()), arguments[4].ToString(), missionCollection) as IAbstractFactory<T>; } private IAbstractFactory<T> CreateEngineerFactory(object[] arguments) { var partCollection = arguments .Skip(5).Take(arguments.Length - 5) .Select(a => a.ToString()).ToArray(); return new EngineerFactory( arguments[0].ToString(), arguments[1].ToString(), arguments[2].ToString(), double.Parse(arguments[3].ToString()), arguments[4].ToString(), partCollection) as IAbstractFactory<T>; } private IAbstractFactory<T> CreateLeutenantGeneralFactory(object[] arguments) { var privateCollection = arguments .Skip(4).Take(arguments.Length - 4) .Select(a => a.ToString()).ToArray(); return new LeutenantGeneralFactory( arguments[0].ToString(), arguments[1].ToString(), arguments[2].ToString(), double.Parse(arguments[3].ToString()), this.currentPrivates, privateCollection) as IAbstractFactory<T>; } private IAbstractFactory<T> CreateSpyFactory(object[] arguments) { return new SpyFactory( arguments[0].ToString(), arguments[1].ToString(), arguments[2].ToString(), int.Parse(arguments[3].ToString())) as IAbstractFactory<T>; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace CIS016_2.Week3.Enums { public enum ClockHandEnum { HourHand, MinuteHand, SecondHand } }
using System; using System.Collections.Generic; using System.Text; namespace MoqTest.Model { class Employee : IEmployee { private string _fistName; private string _lastName; public Employee(string firstName, string lastName) { _fistName = firstName; _lastName = lastName; } public string GetFullName() { throw new NotImplementedException(); } public void ToCSV(string firstName, string lastName) { throw new NotImplementedException(); } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using OcTur.Control; using OcTur.DTO; namespace OcTur.View { public partial class FrmCompraPassagens : Form { public FrmCompraPassagens() { InitializeComponent(); dgvPassagens.AutoGenerateColumns = false; AtualizarGrid(); } private void AtualizarGrid() { CompraPassagensControl controle = new CompraPassagensControl(); UsuarioColecao usuarioColecao = new UsuarioColecao(); usuarioColecao = controle.ConsultaPorTurma(); dgvPassagens.DataSource = null; dgvPassagens.DataSource = usuarioColecao; dgvPassagens.Update(); dgvPassagens.Refresh(); } } }
using System; using System.Threading.Tasks; namespace FeriaVirtual.Domain.SeedWork.Commands { public abstract class CommandHandlerWrapper { public abstract Task Handle (Command command, IServiceProvider provider); } public class CommandHandlerWrapper<TCommand> : CommandHandlerWrapper where TCommand : Command { public override async Task Handle(Command command, IServiceProvider provider) { var handler = (ICommandHandler<TCommand>)provider.GetService(typeof(ICommandHandler<TCommand>)); await handler.Handle((TCommand)command); } } }
using System; using System.Collections.Generic; using NUnit.Framework; [TestFixture] class EntpTests41 { [Test] public void SearchByNameAndPositionEmptyCollection() { IEnterprise enterprise = new Enterprise(); Employee employee = new Employee("a", "123", 62342, Position.Hr, DateTime.Now); Employee employee1 = new Employee("b", "321", 51255, Position.Owner, DateTime.Now); Employee employee2 = new Employee("c", "111", 11266, Position.Hr, DateTime.Now); Employee employee3 = new Employee("d", "11111", 1156123, Position.Developer, DateTime.Now); Employee employee4 = new Employee("e", "11111", 126126, Position.Developer, DateTime.Now); Employee[] employees = new Employee[]{ employee1, employee2, employee3, employee4, employee, }; foreach (Employee employee5 in employees) { enterprise.Add(employee5); } IEnumerable<Employee> employees1 = enterprise.SearchByNameAndPosition("gosho", "pesho", Position.TeamLead); foreach (Employee employee5 in employees1) { Assert.Fail(); } } }
using System; using System.Collections.Generic; using System.Threading.Tasks; using Xamarin.Forms; namespace LoLInfo.Custom { public partial class CustomImageCell : ViewCell { public CustomImageCell() { InitializeComponent(); } } }
public class Solution { public int LongestValidParentheses(string s) { int res = 0; int[] dp = new int[s.Length]; for (int i = 1; i < s.Length; i++) { if (s[i] == '(') { dp[i] = 0; } else { if (s[i-1] == '(') { dp[i] = i>=2 ? dp[i-2]+2 : 2; } else if (i-dp[i-1] > 0 && s[i-dp[i-1]-1] == '(') { dp[i] = dp[i-1] + 2 + (((i-dp[i-1]) >= 2) ? dp[i-dp[i-1]-2] : 0); } else { dp[i] = 0; } res = Math.Max(res, dp[i]); } } return res; } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Data { public enum CardType { Visa, MasterCard, Amex } [Serializable()] public class CreditCard { public CardType CardType { get; set; } public string CardNumber { get; set; } public string HoldersName { get; set; } public int ValidMonth { get; set; } public int ValidYear { get; set; } public int VerificationCode { get; set; } } }
//using System.Collections; //using System.Collections.Generic; //using UnityEngine; //[CreateAssetMenu] //public class StatConstraintEvent : RandomEncounterEvent //{ // [SerializeField] // private StatConstraint[] statConstraints; // [Tooltip("[0] = 1 option 0은 case 1개를 사용")] // [SerializeField] // private int[] _casePerOption; // [Tooltip("[0] = 1 option 0은 constraint 1개를 사용")] // [SerializeField] // private int[] _constraintPerOption; // [Tooltip("[0] = 1 case 0은 constraint 1개를 사용")] // [SerializeField] // private int[] _constraintPerCase; // public override bool GetOptionEnable(int optionIndex) // { // return true; // } // public override void Option0() // { // int caseNumber = GetOptionCaseNumber(0); // optionResultTexts[0] = option0CaseResult[caseNumber]; // ExplorationUIManager.Inst.NoticeResultText(optionResultTexts[0]); // FinishEvent(resultEvent[caseNumber]); // } // public override void Option1() // { // Debug.Log(GetOptionCaseNumber(1)); // } // public override void Option2() // { // throw new System.NotImplementedException(); // } // public override void Option3() // { // throw new System.NotImplementedException(); // } // protected int GetOptionCaseNumber(int optionNumber) // { // if(!OptionLengthMatched()) // { // Debug.LogError("option length mismatched"); // return 0; // } // if(!CaseLengthMatched()) // { // Debug.LogError("case lenfth mismatched"); // return 0; // } // if(!ConstraintLengthMatched()) // { // Debug.LogError("constraint number mismatched"); // return 0; // } // int constraintBase = 0; // int caseBase = 0; // for(int i=optionNumber; i > 0 ;i--) // { // constraintBase += _constraintPerCase[optionNumber - 1]; // caseBase += _casePerOption[optionNumber - 1]; // } // Debug.Log("constraing Base : " + constraintBase + " caseBase : " + caseBase); // switch(_casePerOption[optionNumber]) // { // case 0: // case 1: // return 0; // case 2: // if (CalConstraints(constraintBase, _constraintPerCase[caseBase], statConstraints)) // return 0; // else // return 1; // case 3: // //Debug.Log("CalConstraints("+ (constraintBase + _constraintPerCase[caseBase]) + ", " + _constraintPerCase[caseBase + 1]+", " +statConstraints+")"); // if (CalConstraints(constraintBase, _constraintPerCase[caseBase], statConstraints)) // return 0; // else if (CalConstraints(constraintBase + _constraintPerCase[caseBase], _constraintPerCase[caseBase + 1], statConstraints)) // return 1; // else // return 2; // } // return 0; // } // /// <summary> // /// statConstraints의 [i, i + n)구간의 constraint를 계산하여 결과를 return한다. // /// </summary> // private bool CalConstraints(int i, int n, StatConstraint[] statConstraints) // { // if (i + n - 1>= statConstraints.Length) // { // Debug.Log("out of index i+n : " + (i+n) + " length : " + statConstraints.Length); // return true; // } // for(int t = i; t < i+n ; t++ ) // { // if (!CalConstraint(statConstraints[t])) // return false; // } // return true; // } // private bool OptionLengthMatched() // { // if (optionResultTexts.Count == optionTexts.Count) // if (optionTexts.Count == _constraintPerOption.Length) // if (_constraintPerOption.Length == _casePerOption.Length) // return true; // return false; // } // private bool CaseLengthMatched() // { // int a = 0; // for(int i=0;i<_casePerOption.Length;i++) // { // a += _casePerOption[i]; // } // if(a == _constraintPerCase.Length && a == resultEvent.Length) // return true; // return false; // } // private bool ConstraintLengthMatched() // { // int a = 0; // for(int i=0;i<_constraintPerCase.Length;i++) // { // a += _constraintPerCase[i]; // } // int b = 0; // for(int i=0;i<_constraintPerOption.Length;i++) // { // b += _constraintPerOption[i]; // } // if (statConstraints.Length == a && a == b) // return true; // return false; // } //}
using Microsoft.EntityFrameworkCore; using Sentry.Internal.DiagnosticSource; using Sentry.PlatformAbstractions; namespace Sentry.DiagnosticSource.Tests.Integration.SQLite; public class SentryDiagnosticListenerTests { private class Fixture { private readonly Database _database; public IHub Hub { get; set; } internal SentryScopeManager ScopeManager { get; } public Fixture() { // We're skipping not just the tests but here too. // Fixture creation breaks on Mono due to `Library e_sqlite3 not found`. if (RuntimeInfo.GetRuntime().IsMono()) { return; } var options = new SentryOptions { TracesSampleRate = 1.0, IsGlobalModeEnabled = false }; var client = Substitute.For<ISentryClient>(); ScopeManager = new SentryScopeManager(options, client); Hub = Substitute.For<IHub>(); Hub.GetSpan().ReturnsForAnyArgs(_ => GetSpan()); Hub.StartTransaction(Arg.Any<ITransactionContext>(), Arg.Any<IReadOnlyDictionary<string, object>>()) .ReturnsForAnyArgs(callinfo => StartTransaction(Hub, callinfo.Arg<ITransactionContext>())); Hub.When(hub => hub.ConfigureScope(Arg.Any<Action<Scope>>())) .Do(callback => callback.Arg<Action<Scope>>().Invoke(ScopeManager.GetCurrent().Key)); DiagnosticListener.AllListeners.Subscribe(new SentryDiagnosticSubscriber(Hub, options)); _database = new Database(); _database.Seed(); } public ItemsContext NewContext() => new(_database.ContextOptions); public ISpan GetSpan() => ScopeManager.GetCurrent().Key.Span; public ITransaction StartTransaction(IHub hub, ITransactionContext context) { var transaction = new TransactionTracer(hub, context) { IsSampled = true }; var (currentScope, _) = ScopeManager.GetCurrent(); currentScope.Transaction = transaction; return transaction; } } private readonly Fixture _fixture = new(); [SkippableFact] public void EfCoreIntegration_RunSynchronousQueryWithIssue_TransactionWithSpans() { Skip.If(RuntimeInfo.GetRuntime().IsMono()); // Arrange var hub = _fixture.Hub; var transaction = hub.StartTransaction("test", "test"); var spans = transaction.Spans; var context = _fixture.NewContext(); Exception exception = null; // Act try { _ = context.Items.FromSqlRaw("SELECT * FROM Items :)").ToList(); } catch (Exception ex) { exception = ex; } // Assert Assert.NotNull(exception); #if NETFRAMEWORK Assert.Single(spans); //1 command #else Assert.Equal(2, spans.Count); //1 query compiler, 1 command Assert.Single(spans.Where(s => s.Status == SpanStatus.Ok && s.Operation == "db.query.compile")); #endif Assert.Single(spans.Where(s => s.Status == SpanStatus.InternalError && s.Operation == "db.query")); Assert.All(spans, span => Assert.True(span.IsFinished)); } [SkippableFact] public void EfCoreIntegration_RunSynchronousQuery_TransactionWithSpans() { Skip.If(RuntimeInfo.GetRuntime().IsMono()); // Arrange var hub = _fixture.Hub; var transaction = hub.StartTransaction("test", "test"); var spans = transaction.Spans; var context = _fixture.NewContext(); // Act var result = context.Items.FromSqlRaw("SELECT * FROM Items").ToList(); // Assert Assert.Equal(3, result.Count); #if NETFRAMEWORK Assert.Single(spans); //1 command #else Assert.Equal(2, spans.Count); //1 query compiler, 1 command #endif Assert.All(spans, span => Assert.True(span.IsFinished)); } [SkippableFact] public async Task EfCoreIntegration_RunAsyncQuery_TransactionWithSpansWithOneCompiler() { Skip.If(RuntimeInfo.GetRuntime().IsMono()); // Arrange var context = _fixture.NewContext(); var commands = new List<int>(); var totalCommands = 50; for (var j = 0; j < totalCommands; j++) { var i = j + 4; context.Items.Add(new Item { Name = $"Number {i}" }); context.Items.Add(new Item { Name = $"Number2 {i}" }); context.Items.Add(new Item { Name = $"Number3 {i}" }); commands.Add(i * 2); } // Save before the Transaction creation to avoid storing junk. //Dont async here since it will fail in mac+linux with // The type initializer for 'System.Data.Common.DbConnectionExtensions' threw an exception. // Expression of type 'ValueTask[System.Data.Common.DbTransaction]' cannot be used... // ReSharper disable once MethodHasAsyncOverload context.SaveChanges(); var hub = _fixture.Hub; var transaction = hub.StartTransaction("test", "test"); var spans = transaction.Spans; var itemsList = new ConcurrentBag<List<Item>>(); // Act var tasks = commands.Select(async limit => { var command = $"SELECT * FROM Items LIMIT {limit}"; itemsList.Add(await _fixture.NewContext().Items.FromSqlRaw(command).ToListAsync()); }); await Task.WhenAll(tasks); // Assert Assert.Equal(totalCommands, itemsList.Count); Assert.Equal(totalCommands, spans.Count(s => s.Operation == "db.query")); #if NET5_0_OR_GREATER Assert.Equal(totalCommands, spans.Count(s => s.Operation == "db.query.compile")); #endif Assert.All(spans, span => { Assert.True(span.IsFinished); Assert.Equal(SpanStatus.Ok, span.Status); Assert.Equal(transaction.SpanId, span.ParentSpanId); }); } [SkippableFact] public async Task EfCoreIntegration_RunAsyncQuery_TransactionWithSpans() { Skip.If(RuntimeInfo.GetRuntime().IsMono()); // Arrange var context = _fixture.NewContext(); var hub = _fixture.Hub; var transaction = hub.StartTransaction("test", "test"); var spans = transaction.Spans; // Act var result = new[] { context.Items.FromSqlRaw("SELECT * FROM Items WHERE 1=1 LIMIT 10").ToListAsync(), context.Items.FromSqlRaw("SELECT * FROM Items WHERE 1=1 LIMIT 9").ToListAsync(), context.Items.FromSqlRaw("SELECT * FROM Items WHERE 1=1 LIMIT 8").ToListAsync(), context.Items.FromSqlRaw("SELECT * FROM Items WHERE 1=1 LIMIT 7").ToListAsync(), }; await Task.WhenAll(result); // Assert Assert.Equal(3, result[0].Result.Count); Assert.Equal(4, spans.Count(s => s.Operation == "db.query")); #if NET5_0_OR_GREATER Assert.Equal(4, spans.Count(s => s.Operation == "db.query.compile")); #endif Assert.All(spans, span => { Assert.True(span.IsFinished); Assert.Equal(SpanStatus.Ok, span.Status); Assert.Equal(transaction.SpanId, span.ParentSpanId); }); } }
using Beeffective.Data; using Beeffective.Data.Entities; using Beeffective.Models; using NUnit.Framework; namespace Beeffective.Tests.Models.HoneycombModelTests { class TestFixture { [SetUp] public virtual void SetUp() { Repository = new CellRepository(); Repository.RemoveAll(); Sut = new HoneycombModel(Repository); CellModel1 = new CellModel {Title = "test cell model 1"}; CellModel2 = new CellModel {Title = "test cell model 2"}; CellModel3 = new CellModel {Title = "test cell model 3"}; } protected CellModel CellModel1 { get; set; } protected CellModel CellModel2 { get; set; } protected CellModel CellModel3 { get; set; } protected HoneycombModel Sut { get; set; } protected IRepository<CellEntity> Repository { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; namespace iSukces.Code.Interfaces { public interface ITypeNameResolver { string GetTypeName(Type type); } public static class TypeToNameResolverExtensions { public static string GetEnumFlagsValueCode<T>(this ITypeNameResolver resolver, T value, Func<IReadOnlyList<string>, string> joinFunc = null) where T : Enum { var c = resolver.GetTypeName<T>(); var e = CsEnumHelper.Get(typeof(T)); var names = e.GetFlagStrings(value, c); string result; if (joinFunc != null) result = joinFunc(names.ToArray()); else result = string.Join(" | ", names); return result; } public static string GetEnumValueCode<T>(this ITypeNameResolver resolver, T value) where T : Enum { var c = resolver.GetTypeName<T>(); var value2 = c + "." + value; return value2; } public static string GetMemeberName(this ITypeNameResolver resolver, Type type, string instanceName) => resolver.GetTypeName(type) + "." + instanceName; public static string GetMemeberName<T>(this ITypeNameResolver resolver, string instanceName) => resolver.GetTypeName<T>() + "." + instanceName; public static string GetTypeName<T>(this ITypeNameResolver resolver) => resolver.GetTypeName(typeof(T)); [Obsolete("Use GetTypeName")] public static string TypeName(this ITypeNameResolver resolver, Type type) => resolver.GetTypeName(type); } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace FactoryProject { class Employee { private string firstName; public string FirstName { get { return firstName; } set { firstName = value; } } private string lastName; public string LastName { get { return lastName; } set { lastName = value; } } public List<IWorkplace> WorkPlaces { get; set; } public Employee(IWorkplace workplace, string firstName, string lastName) { FirstName = firstName; LastName = lastName; WorkPlaces = new List<IWorkplace>(); WorkPlaces.Add(workplace); } } }
using TodoApp.DataContracts; namespace TodoApp.Data { public class UnitOfWork: IUnitOfWork { private readonly AppDbContext _dbContext; public UnitOfWork(AppDbContext dbContext) { _dbContext = dbContext; } public void Commit() { _dbContext.SaveChanges(); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class OrbitCode : MonoBehaviour { GameObject flyingObject; public Transform orbitpt; enemyScript flying; Rigidbody2D rb; Animator anim; // Use this for initialization void Start () { flyingObject = transform.parent.gameObject; transform.position = flyingObject.transform.position; flying = flyingObject.GetComponent<enemyScript>(); rb = GetComponent<Rigidbody2D>(); anim = GetComponent<Animator>(); } void Update() { if (flying.health>0) transform.position = orbitpt.transform.position; if (flying.dieTrigger == true) { transform.parent = null; rb.gravityScale = 1; anim.SetBool("Fall",true); } if (flyingObject == null) Destroy(this.gameObject); } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace LightBoxRectSubForm.data { public class LBMsg : ICloneable { public event EventHandler EventIdChanged; public bool runAble; private int id; /// <summary> /// 灯箱信息类 /// </summary> public LBMsg() { } public LBMsg(int id) { Id = id; } /// <summary> /// 灯箱的ID /// </summary> /// <value>The identifier.</value> public int Id { get { return id; } set { if (id != value) { id = value; if (null != EventIdChanged) { EventIdChanged(this, null); } } } } /// <summary> /// 延迟时间,单位s /// </summary> /// <value>The wait time.</value> public double WaitTime { get; set; } public int Row1 { get; set; } public int Column { get; set; } public int GroupId { get; set; } private double keepTime = 4; private double runTime = 8; private double repeatCount = 1; /// <summary> /// 灯箱正转的时间, 单位秒 /// </summary> public double RunTime { get { return runTime; } set { runTime = value; } } /// <summary> /// 灯箱正转完成后维持现状的时间, 单位秒 /// </summary> public double KeepTime { get { return keepTime; } set { keepTime = value; } } /// <summary> /// 重复几次 /// </summary> public double RepeatCount { get => repeatCount; set => repeatCount = value; } #region ICloneable implementation public object Clone() { return this.MemberwiseClone(); } #endregion } }
using System; namespace gView.GraphicsEngine.Abstraction { public interface IPen : IDisposable { ArgbColor Color { get; set; } float Width { get; set; } LineDashStyle DashStyle { get; set; } LineCap StartCap { get; set; } LineCap EndCap { get; set; } LineJoin LineJoin { get; set; } object EngineElement { get; } } }
using System.Web.Mvc; namespace DevExpress.Web.Demos { public partial class GridViewController : DemoController { public ActionResult Paging() { return DemoView("Paging", NorthwindDataProvider.GetCustomers()); } public ActionResult PagingPartial() { return PartialView("PagingPartial", NorthwindDataProvider.GetCustomers()); } } }
using System; using System.Collections.Generic; using System.Text; namespace TestHouse.DTOs.DTOs { public class SuitDto { public long Id { get; set; } public IEnumerable<SuitDto> Suits { get; set; } public IEnumerable<TestCaseDto> TestCases { get; set; } public string Name { get; set; } public string Description { get; set; } public bool IsSelected { get; set; } } }
using System; /** * 请求服务地址 配置 * */ namespace CRL.Business.OnlinePay.Company.Lianlian { public class ServerURLConfig { public static string PAY_URL = "https://yintong.com.cn/payment/bankgateway.htm"; // 连连支付WEB收银台支付服务地址 public static string QUERY_USER_BANKCARD_URL = "https://yintong.com.cn/traderapi/userbankcard.htm"; // 用户已绑定银行卡列表查询 public static string QUERY_BANKCARD_URL = "https://yintong.com.cn/traderapi/bankcardquery.htm"; //银行卡卡bin信息查询 } }
using Microsoft.EntityFrameworkCore; using MyNiceBlog.Models; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace MyNiceBlog.DataLayer { public class PostdbContext : DbContext { public PostdbContext(DbContextOptions <PostdbContext> options) : base(options) { } public DbSet<Post> Post { get; set; } public DbSet<Author> Author { get; set; } public DbSet<Tag> Tag { get; set; } protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.Entity<PostTag>().HasKey(sc => new { sc.TagId, sc.PostId }); } } }
namespace Processing.Activities.Retrieve { using System; public interface ReservationLog { Guid ReservationId { get; } Guid RequestId { get; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace GodaddyWrapper.Responses { public class CloudServerActionResponse { public string Status { get; set; } public string ServerActionId { get; set; } public bool CreatedAt { get; set; } public string ModifiedAt { get; set; } public string Type { get; set; } public string CompletedAt { get; set; } public string ServerId { get; set; } } }
using NASTYADANYA; using NUnit.Framework; namespace NASTYADANYATest { [TestFixture] public class AbsTests { [TestCase(-6, 6)] [TestCase(98, 98)] [TestCase(-144, 144)] public void CalculateTest(double firstValue, double expected) { var calculator = new Abs(); var actualResult = calculator.Calculate(firstValue); Assert.AreEqual(expected, actualResult); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace MarioKart { public class Corredor { public Corredor(string nome, Habilidade habilidade) { this.Nome = nome; this.NivelHabilidade = habilidade; } public string Nome { get; } public Habilidade NivelHabilidade { get; set; } public int GetBonusHabilidade() { if (NivelHabilidade == Habilidade.Noob) return 3; else if (NivelHabilidade == Habilidade.Mediano) return 5; return 6; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using ApartmentApps.Client.Models; using ResidentAppCross.Extensions; namespace ResidentAppCross.ViewModels.Screens { public class MaintenanceCheckinDetailsViewModel : ViewModelBase { private MaintenanceCheckinBindingModel _checkin; private ImageBundleViewModel _checkinPhotos; public MaintenanceCheckinBindingModel Checkin { get { return _checkin; } set { SetProperty(ref _checkin, value); var photos = new ImageBundleViewModel(); photos.RawImages.AddRange(Checkin.Photos.Select(p => new ImageBundleItemViewModel() { Uri = new Uri(p.Url) })); CheckinPhotos = photos; } } public ImageBundleViewModel CheckinPhotos { get { return _checkinPhotos; } set { SetProperty(ref _checkinPhotos, value); } } } }
#region copyright // ****************************************************************** // Copyright (c) Microsoft. All rights reserved. // This code is licensed under the MIT License (MIT). // THE CODE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. // IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, // TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH // THE CODE OR THE USE OR OTHER DEALINGS IN THE CODE. // ****************************************************************** #endregion using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.EntityFrameworkCore; namespace Inventory.Data.Services { abstract public partial class DataServiceBase : IDataService, IDisposable { #region Private fields private readonly IDataSource _dataSource = null; #endregion #region Ctor public DataServiceBase(IDataSource dataSource) { _dataSource = dataSource; } #endregion #region Dictionaries public async Task<MenuFolder> GetMenuFolderAsync(int? id) { return await _dataSource.MenuFolders.FirstOrDefaultAsync(x => x.Id == id); } public async Task<MenuFolder> GetMenuFolderAsync(Guid rowGuid) { return await _dataSource.MenuFolders.FirstOrDefaultAsync(x => x.RowGuid == rowGuid); } public async Task<IList<MenuFolder>> GetMenuFoldersAsync() { return await _dataSource.MenuFolders.ToListAsync(); } public async Task<OrderStatus> GetOrderStatusAsync(int? id) { return await _dataSource.OrderStatuses.FirstOrDefaultAsync(x => x.Id == id); } public async Task<IList<OrderStatus>> GetOrderStatusesAsync() { return await _dataSource.OrderStatuses.ToListAsync(); } public async Task<DeliveryType> GetDeliveryTypeAsync(int? id) { return await _dataSource.DeliveryTypes.FirstOrDefaultAsync(x => x.Id == id); } public async Task<IList<DeliveryType>> GetDeliveryTypesAsync() { return await _dataSource.DeliveryTypes.ToListAsync(); } public async Task<IList<City>> GetCitiesAsync() { return await _dataSource.Cities.ToListAsync(); } public async Task<City> GetCityAsync(int? id) { return await _dataSource.Cities.Where(r => r.Id == id).FirstOrDefaultAsync(); } public async Task<OrderType> GetOrderTypeAsync(int? id) { return await _dataSource.OrderTypes.FirstOrDefaultAsync(x => x.Id == id); } public async Task<IList<OrderType>> GetOrderTypesAsync() { return await _dataSource.OrderTypes.ToListAsync(); } public async Task<Source> GetOrderSourceAsync(int? id) { return await _dataSource.Sources.FirstOrDefaultAsync(x => x.Id == id); } public async Task<IList<Source>> GetOrderSourcesAsync() { return await _dataSource.Sources.ToListAsync(); } public async Task<PaymentType> GetPaymentTypeAsync(int? id) { return await _dataSource.PaymentTypes.FirstOrDefaultAsync(x => x.Id == id); } public async Task<IList<PaymentType>> GetPaymentTypesAsync() { return await _dataSource.PaymentTypes.ToListAsync(); } public async Task<Restaurant> GetRestaurantAsync(int? id) { return await _dataSource.Restaurants.FirstOrDefaultAsync(x => x.Id == id); } public async Task<IList<Restaurant>> GetRestaurantsAsync() { return await _dataSource.Restaurants.ToListAsync(); } public async Task<TaxType> GetTaxTypeAsync(int? id) { return await _dataSource.TaxTypes.FirstOrDefaultAsync(x => x.Id == id); } public async Task<IList<TaxType>> GetTaxTypesAsync() { return await _dataSource.TaxTypes.ToListAsync(); } #endregion #region Dispose public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { if (disposing) { if (_dataSource != null) { _dataSource.Dispose(); } } } #endregion } }
//********************************************************************************** //* Copyright (C) 2007,2016 Hitachi Solutions,Ltd. //********************************************************************************** #region Apache License // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #endregion //********************************************************************************** //* クラス名 :EmbeddedResourceLoader //* クラス日本語名 :[埋め込まれたリソース ファイル]の読み込みクラス //* //* 作成者 :生技 西野 //* 更新履歴 : //* //* 日時 更新者 内容 //* ---------- ---------------- ------------------------------------------------- //* 2009/04/05 西野 大介 新規作成(XBAP、ClickOnce対応) //* 2009/04/20 西野 大介 XMLロード時のエンコーディング指定を不要に //* 2009/06/02 西野 大介 sln - IR版からの修正 //* ・#4 : 対象ファイルが存在しない場合、NullReference //* 2011/05/18 西野 大介 Azure対応(アセンブリの取得方法の変更) //* 2012/07/20 西野 大介 Azureで動作しない状態になっていたので修正 //* 2012/10/23 西野 大介 Azureで別のアセンブリからロード可能に修正 //********************************************************************************** using System; using System.IO; using System.Xml; using System.Text; using System.Reflection; using Touryo.Infrastructure.Public.Util; namespace Touryo.Infrastructure.Public.IO { /// <summary>[埋め込まれたリソース ファイル]の読み込みクラス</summary> /// <remarks>自由に利用できる。</remarks> public static class EmbeddedResourceLoader { /// <summary>[埋め込まれたリソース ファイル]を含むアセンブリを取得する</summary> /// <param name="assemblyString"> /// アセンブリ名 /// http://msdn.microsoft.com/ja-jp/library/k8xx4k69.aspx /// </param> /// <returns>Assembly</returns> private static Assembly GetEntryAssembly(string assemblyString) { // Azureスイッチ string azure = GetConfigParameter.GetConfigValue("Azure"); if (string.IsNullOrEmpty(azure)) { // 通常時 if (string.IsNullOrEmpty(assemblyString)) { // assemblyString 指定なし return Assembly.GetEntryAssembly(); } else { // assemblyString 指定あり return Assembly.Load(assemblyString); } } else { // Azureスイッチ・オンの場合 if (string.IsNullOrEmpty(assemblyString)) { // assemblyString 指定なし return Assembly.Load(azure); } else { // assemblyString 指定あり return Assembly.Load(assemblyString); } } } // #4-start #region 存在チェック /// <summary>存在チェックのみのメソッド</summary> /// <param name="loadfileName">[埋め込まれたリソース ファイル]の名前(名前空間付き)</param> /// <param name="throwException">存在しない場合例外をスローするかどうかを指定</param> /// <returns>存在する:true、存在しない:false</returns> /// <remarks>自由に利用できる。</remarks> public static bool Exists(string loadfileName, bool throwException) { // オーバーロードを[assemblyString = string.Empty]で呼ぶ。 return EmbeddedResourceLoader.Exists(string.Empty, loadfileName, throwException); } /// <summary>存在チェックのみのメソッド</summary> /// <param name="assemblyString"> /// アセンブリ名 /// http://msdn.microsoft.com/ja-jp/library/k8xx4k69.aspx /// </param> /// <param name="loadfileName">[埋め込まれたリソース ファイル]の名前(名前空間付き)</param> /// <param name="throwException">存在しない場合例外をスローするかどうかを指定</param> /// <returns>存在する:true、存在しない:false</returns> /// <remarks>自由に利用できる。</remarks> public static bool Exists(string assemblyString, string loadfileName, bool throwException) { // エントリのアセンブリ Assembly thisAssembly = null; ManifestResourceInfo manifestResourceInfo = null; // 例外処理 try { thisAssembly = EmbeddedResourceLoader.GetEntryAssembly(assemblyString); manifestResourceInfo = thisAssembly.GetManifestResourceInfo(loadfileName); } catch (Exception) { // なにもしない。 } // 存在チェック if (manifestResourceInfo != null) { if (0 != (manifestResourceInfo.ResourceLocation & (ResourceLocation.ContainedInManifestFile | ResourceLocation.Embedded))) { // 存在する。 return true; } } // 存在しない。 if (throwException) { throw new ArgumentException(String.Format( PublicExceptionMessage.RESOURCE_FILE_NOT_FOUND, loadfileName)); } else { return false; } } #endregion #region [埋め込まれたリソース ファイル]から文字列を読込 /// <summary>[埋め込まれたリソース ファイル]から文字列を読み込む。</summary> /// <param name="loadfileName">[埋め込まれたリソース ファイル]の名前(名前空間付き)</param> /// <param name="enc">エンコード</param> /// <returns>[埋め込まれたリソース ファイル]から読み込んだ文字列</returns> /// <remarks>自由に利用できる。</remarks> public static string LoadAsString(string loadfileName, Encoding enc) { // オーバーロードを[assemblyString = string.Empty]で呼ぶ。 return EmbeddedResourceLoader.LoadAsString(string.Empty, loadfileName, enc); } /// <summary>[埋め込まれたリソース ファイル]から文字列を読み込む。</summary> /// <param name="assemblyString"> /// アセンブリ名 /// http://msdn.microsoft.com/ja-jp/library/k8xx4k69.aspx /// </param> /// <param name="loadfileName">[埋め込まれたリソース ファイル]の名前(名前空間付き)</param> /// <param name="enc">エンコード</param> /// <returns>[埋め込まれたリソース ファイル]から読み込んだ文字列</returns> /// <remarks>自由に利用できる。</remarks> public static string LoadAsString(string assemblyString, string loadfileName, Encoding enc) { // エントリのアセンブリ Assembly thisAssembly = null; ManifestResourceInfo manifestResourceInfo = null; // ストリーム StreamReader sr = null; // 例外処理 try { thisAssembly = EmbeddedResourceLoader.GetEntryAssembly(assemblyString); manifestResourceInfo = thisAssembly.GetManifestResourceInfo(loadfileName); } catch (Exception) { // なにもしない。 } try { // 存在チェック if (manifestResourceInfo != null) { if (0 != (manifestResourceInfo.ResourceLocation & (ResourceLocation.ContainedInManifestFile | ResourceLocation.Embedded))) { // 存在する。 } else { // 存在しない。 throw new ArgumentException(String.Format( PublicExceptionMessage.RESOURCE_FILE_NOT_FOUND, loadfileName)); } } else { // 存在しない。 throw new ArgumentException(String.Format( PublicExceptionMessage.RESOURCE_FILE_NOT_FOUND, loadfileName)); } // 開く sr = new StreamReader(thisAssembly.GetManifestResourceStream(loadfileName), enc); // 読む return sr.ReadToEnd(); } finally { // nullチェック if (sr == null) { // 何もしない。 } else { // 閉じる sr.Close(); } } } #endregion #region [埋め込まれたリソースXMLファイル]から文字列を読込 /// <summary>[埋め込まれたリソースXMLファイル]から文字列を読み込む。</summary> /// <param name="loadfileName">[埋め込まれたリソースXMLファイル]の名前(名前空間付き)</param> /// <returns>[埋め込まれたリソースXMLファイル]から読み込んだ文字列</returns> /// <remarks>自由に利用できる。</remarks> public static string LoadXMLAsString(string loadfileName) { // オーバーロードを[assemblyString = string.Empty]で呼ぶ。 return EmbeddedResourceLoader.LoadXMLAsString(string.Empty, loadfileName); } /// <summary>[埋め込まれたリソースXMLファイル]から文字列を読み込む。</summary> /// <param name="assemblyString"> /// アセンブリ名 /// http://msdn.microsoft.com/ja-jp/library/k8xx4k69.aspx /// </param> /// <param name="loadfileName">[埋め込まれたリソースXMLファイル]の名前(名前空間付き)</param> /// <returns>[埋め込まれたリソースXMLファイル]から読み込んだ文字列</returns> /// <remarks>自由に利用できる。</remarks> public static string LoadXMLAsString(string assemblyString, string loadfileName) { // エントリのアセンブリ Assembly thisAssembly = null; ManifestResourceInfo manifestResourceInfo = null; // ストリーム StreamReader sr = null; // リーダ(XML) XmlTextReader xtr = null; // 例外処理 try { thisAssembly = EmbeddedResourceLoader.GetEntryAssembly(assemblyString); manifestResourceInfo = thisAssembly.GetManifestResourceInfo(loadfileName); } catch (Exception) { // なにもしない。 } try { // 存在チェック if (manifestResourceInfo != null) { if (0 != (manifestResourceInfo.ResourceLocation & (ResourceLocation.ContainedInManifestFile | ResourceLocation.Embedded))) { // 存在する。 } else { // 存在しない。 throw new ArgumentException(String.Format( PublicExceptionMessage.RESOURCE_FILE_NOT_FOUND, loadfileName)); } } else { // 存在しない。 throw new ArgumentException(String.Format( PublicExceptionMessage.RESOURCE_FILE_NOT_FOUND, loadfileName)); } // 既定のエンコーディングでロードして、 sr = new StreamReader(thisAssembly.GetManifestResourceStream(loadfileName)); // XML宣言を取得して、 // <?xml version="1.0" encoding="xxxx" ?> string xmlDeclaration = sr.ReadLine(); sr.Close(); // エンコーディング オブジェクトの取得 Encoding enc; try { // エンコーディング文字列を取得し、 string searchString = "encoding=\""; int start = xmlDeclaration.IndexOf(searchString, 0) + searchString.Length; int end = xmlDeclaration.IndexOf('\"', start); // エンコーディング オブジェクトに変換 enc = Encoding.GetEncoding(xmlDeclaration.Substring(start, end - start)); } catch(Exception) { // ここでエラーとなった場合、 throw new ArgumentException(String.Format( PublicExceptionMessage.XML_DECLARATION_ERROR, xmlDeclaration)); } // 指定のエンコーディングで再ロード sr = new StreamReader(thisAssembly.GetManifestResourceStream(loadfileName), enc); // 読む return sr.ReadToEnd(); } finally { // nullチェック if (xtr == null) { // 何もしない。 } else { // 閉じる xtr.Close(); } // nullチェック if (sr == null) { // 何もしない。 } else { // 閉じる sr.Close(); } } } #endregion // #4-end } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; using AspNetAngular.Model; namespace AspNetAngular.Controllers { [Route("api/controllers")] [ApiController] public class RepCompletion : ControllerBase { private readonly AtlanticContext _context; public RepCompletion(AtlanticContext context) { _context = context; } [HttpGet("getReportCompletion")] public async Task<ActionResult<IEnumerable<ReportCompletion>>> getReportCompletion(string branch) { var reportCompletionQuery = @" select case when A.DocStatus = 'O' then 'Open' else 'Close' end 'DocStatus', a.DocNum, '' 'ITRNo', A.U_BranchCode 'BranchName', A.DocDate, '' 'Status', (select datediff(d, z.DocDate, GETDATE()) from OIGN z where z.DocEntry = A.DocEntry and z.DocStatus = 'O') 'DaysDue', '' 'InvTransferNo', A.U_Remarks 'DocRemarks' from OIGN A --inner join IGE1 B on A.DocEntry = B.DocEntry left join [@BOCODE] D on A.U_BranchCode = D.Code where --A.DocStatus = 'O' --A.DocDate between '2019-08-01' and '2019-08-01' D.Name = {0} "; var reportCompletion = await _context.ReportCompletion.FromSql(reportCompletionQuery, branch).ToListAsync(); return reportCompletion; } [HttpGet("getRepCompletionDetails")] public async Task<ActionResult<IEnumerable<RepCompletionDetails>>> GetRepCompletionDetails(int docnum) { var rawQuery = @" select b.ItemCode, b.Dscription 'Description', b.Quantity from OIGN a inner join IGN1 b on a.DocEntry = b.DocEntry where a.DocNum = {0} "; var repCompDetails = await _context.RepCompletionDetails.FromSql(rawQuery, docnum).ToListAsync(); return repCompDetails; } } }