text
stringlengths
13
6.01M
using System.Collections; using System.Collections.Generic; using UnityEngine; public class ParticleManager : Singleton<ParticleManager> { public GameObject bloodParticle; public void PlayBlood(Vector2 position) { Instantiate(bloodParticle, position, Quaternion.identity); } }
using NUnit.Framework; namespace HomeWorkDoublyLinkedList.Test { public class DoublyLinkedListTest { [SetUp] public void Setup() { } [TestCase(new int[] { 1, 2, 3 }, 5, new int[] { 5, 1, 2, 3 })] [TestCase(new int[] {}, 5, new int[] { 5 })] [TestCase(new int[] { 0 }, 5, new int[] { 5, 0 })] [TestCase(new int[] { 101, 101, 101 }, 101, new int[] { 101, 101, 101, 101 })] [TestCase(new int[] { 5 }, 0, new int[] { 0, 5})] public void AddFirstTest(int[] array, int value, int[] expected) { DoublyLinkedList a = new DoublyLinkedList(array); a.AddFirst(value); int[] actual = a.ToArray(); Assert.AreEqual(expected, actual); } [TestCase(new int[] { 3, 4, 5 }, new int[] { 1, 2, 3 }, new int[] { 1, 2, 3, 3, 4, 5 })] [TestCase(new int[] { }, new int[] { 1, 2, 3 }, new int[] { 1, 2, 3 })] [TestCase(new int[] { 5 }, new int[] { 5 }, new int[] { 5, 5 })] [TestCase(new int[] { 3, 4, 5 }, new int[] { }, new int[] { 3, 4, 5 })] [TestCase(new int[] { 0, 0, 0, 0, 0 }, new int[] { 0 }, new int[] { 0, 0, 0, 0, 0, 0 })] public void AddFirstArrayTest(int[] array, int[] value, int[] expected) { DoublyLinkedList a = new DoublyLinkedList(array); a.AddFirst(value); int[] actual = a.ToArray(); Assert.AreEqual(expected, actual); } [TestCase(new int[] { 1, 2, 3 }, 5, new int[] { 1, 2, 3, 5 })] [TestCase(new int[] { }, 5, new int[] { 5 })] [TestCase(new int[] { 1 }, 5, new int[] { 1, 5 })] [TestCase(new int[] { 1, 2, 3 }, 0, new int[] { 1, 2, 3, 0 })] [TestCase(new int[] { 101, 101 }, 101, new int[] { 101, 101, 101 })] public void AddLastTest(int[] array, int value, int[] expected) { DoublyLinkedList a = new DoublyLinkedList(array); a.AddLast(value); int[] actual = a.ToArray(); Assert.AreEqual(expected, actual); } [TestCase(new int[] { 3, 4, 5 }, new int[] { 1, 2, 3 }, new int[] { 3, 4, 5, 1, 2, 3 })] [TestCase(new int[] { 3, 4, 5 }, new int[] { }, new int[] { 3, 4, 5 })] [TestCase(new int[] { }, new int[] { 1, 2, 3 }, new int[] { 1, 2, 3 })] [TestCase(new int[] { 1 }, new int[] { 2 }, new int[] { 1, 2 })] [TestCase(new int[] { 101, 101, 101 }, new int[] { 101, 101 }, new int[] { 101, 101, 101, 101, 101 })] public void AddLastArrayTest(int[] array, int[] value, int[] expected) { DoublyLinkedList a = new DoublyLinkedList(array); a.AddLast(value); int[] actual = a.ToArray(); Assert.AreEqual(expected, actual); } [TestCase(new int[] { 1, 2, 3 }, 0, 5, new int[] { 5, 1, 2, 3, })] [TestCase(new int[] { }, 0, 1, new int[] { 1 })] [TestCase(new int[] { 1 }, 0, 5, new int[] { 5, 1 })] [TestCase(new int[] { 0, 1, 2 }, 15, 5, new int[] { 0, 1, 2 })] [TestCase(new int[] { 101, 101, 101 }, 2, 0, new int[] { 101, 101, 0, 101 })] public void AddAtTest(int[] array, int index, int value, int[] expected) { DoublyLinkedList a = new DoublyLinkedList(array); if (index < 0 || index >= array.Length) { Assert.Throws<System.Exception>(() => a.AddAt(index, value)); } else { a.AddAt(index, value); int[] actual = a.ToArray(); Assert.AreEqual(expected, actual); } } [TestCase(new int[] { }, 0, new int[] { }, new int[] { })] [TestCase(new int[] { 3, 4, 5 }, 2, new int[] { 1, 2, 3 }, new int[] { 3, 4, 1, 2, 3, 5 })] [TestCase(new int[] { }, 2, new int[] { 1, 2, 3 }, new int[] { 1, 2, 3 })] [TestCase(new int[] { 1 }, 0, new int[] { 1, 2, 3 }, new int[] { 1, 2, 3, 1 })] [TestCase(new int[] { 101, 101, 101 }, 0, new int[] { 101, 101 }, new int[] { 101, 101, 101, 101, 101 })] public void AddAtArrayTest(int[] array, int index, int[] value, int[] expected) { DoublyLinkedList a = new DoublyLinkedList(array); if (index < 0 || index >= array.Length) { Assert.Throws<System.Exception>(() => a.AddAt(index, value)); } else { a.AddAt(index, value); int[] actual = a.ToArray(); Assert.AreEqual(expected, actual); } } [TestCase(new int[] { 0, 0, 0, 0, 0, 0, 0, 0 }, 8)] [TestCase(new int[] { 0, 1 }, 2)] [TestCase(new int[] { }, 0)] [TestCase(new int[] { 0, 1, 2, 3, 4 }, 5)] [TestCase(new int[] { 1 }, 1)] public void GetSizeTest(int[] value, int expected) { DoublyLinkedList a = new DoublyLinkedList(value); int actual = a.GetSize(); Assert.AreEqual(expected, actual); } [TestCase(new int[] { 3, 4, 5 }, 0, 555, new int[] { 555, 4, 5 })] [TestCase(new int[] { 3, 4, 5 }, 2, 1, new int[] { 3, 4, 1 })] [TestCase(new int[] { }, 0, 555, new int[] { 555 })] [TestCase(new int[] { 3, 4, 5 }, 555, 555, new int[] { 3, 4, 5 })] [TestCase(new int[] { 3, 4, 5 }, 0, 555, new int[] { 555, 4, 5 })] public void SetTest(int[] array, int index, int value, int[] expected) { DoublyLinkedList a = new DoublyLinkedList(array); if (index < 0 || index >= array.Length) { Assert.Throws<System.Exception>(() => a.Set(index, value)); } else { a.Set(index, value); int[] actual = a.ToArray(); Assert.AreEqual(expected, actual); } } [TestCase(new int[] { 3, 4, 5 }, new int[] { 4, 5 })] [TestCase(new int[] { 0, 1, 2, 3, 4, 5 }, new int[] { 1, 2, 3, 4, 5 })] [TestCase(new int[] { 0 }, new int[] { })] [TestCase(new int[] { 1, 1, 1, 1, 1 }, new int[] { 1, 1, 1, 1 })] [TestCase(new int[] { 101, 101, 101 }, new int[] { 101, 101 })] public void RemoveFirstTest(int[] array, int[] expected) { DoublyLinkedList a = new DoublyLinkedList(array); a.RemoveFirst(); int[] actual = a.ToArray(); Assert.AreEqual(expected, actual); } [TestCase(new int[] { 3, 4, 5 }, new int[] { 3, 4 })] [TestCase(new int[] { 1, 2, 3, 4, 5 }, new int[] { 1, 2, 3, 4 })] [TestCase(new int[] { 0 }, new int[] { })] [TestCase(new int[] { 1, 1, 1, 1, 1 }, new int[] { 1, 1, 1, 1 })] [TestCase(new int[] { 101, 101, 101 }, new int[] { 101, 101 })] public void RemoveLastTest(int[] array, int[] expected) { DoublyLinkedList a = new DoublyLinkedList(array); a.RemoveLast(); int[] actual = a.ToArray(); Assert.AreEqual(expected, actual); } [TestCase(new int[] { 3, 4, 5 }, 1, new int[] { 3, 5 })] [TestCase(new int[] { 3, 4, 5 }, 0, new int[] { 4, 5 })] [TestCase(new int[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }, 5, new int[] { 0, 1, 2, 3, 4, 6, 7, 8, 9 })] [TestCase(new int[] { 3, 4, 5 }, 5555, new int[] { 3, 4, 5 })] [TestCase(new int[] { 3 }, 0, new int[] { })] public void RemoveAtTest(int[] array, int index, int[] expected) { DoublyLinkedList a = new DoublyLinkedList(array); if (index < 0 || index >= array.Length) { Assert.Throws<System.Exception>(() => a.RemoveAt(index)); } else { a.RemoveAt(index); int[] actual = a.ToArray(); Assert.AreEqual(expected, actual); } } [TestCase(new int[] { 1, 2, 3, 4, 9, 9, 5, 1 }, 9, new int[] { 1, 2, 3, 4, 5, 1 })] [TestCase(new int[] { 3, 4, 5 }, 0, new int[] { 3, 4, 5 })] [TestCase(new int[] { 55 }, 55, new int[] { })] [TestCase(new int[] { 1, 2, 3, 4 }, 2, new int[] { 1, 3, 4 })] [TestCase(new int[] { 1 }, 2, new int[] { 1 })] public void RemoveAllTest(int[] array, int value, int[] expected) { DoublyLinkedList a = new DoublyLinkedList(array); a.RemoveAll(value); int[] actual = a.ToArray(); Assert.AreEqual(expected, actual); } [TestCase(new int[] { 3, 4, 5 }, 1, false)] [TestCase(new int[] { 3, 4, 5 }, 5, true)] [TestCase(new int[] { 1, 2, 3, 4, 9, 9, 5, 1 }, 9, true)] [TestCase(new int[] { 0 }, 100, false)] [TestCase(new int[] { }, 9, false)] public void ContainsTest(int[] array, int value, bool expected) { DoublyLinkedList a = new DoublyLinkedList(array); bool actual = a.Contains(value); Assert.AreEqual(expected, actual); } [TestCase(new int[] { 1, 2, 3, 4, 9, 9, 5, 1 }, 9, 4)] [TestCase(new int[] { 3, 4, 5 }, 0, -1)] [TestCase(new int[] { 55 }, 55, 0)] [TestCase(new int[] { 1, 2, 3, 4 }, 2, 1)] [TestCase(new int[] { 1, 2, 3, 4 }, 3, 2)] public void IndexOfTest(int[] array, int value, int expected) { DoublyLinkedList a = new DoublyLinkedList(array); int actual = a.IndexOf(value); Assert.AreEqual(expected, actual); } [TestCase(new int[] { 1, 2, 3, 4, 9, 9, 5, 1 }, new int[] { 1, 2, 3, 4, 9, 9, 5, 1 })] [TestCase(new int[] { 3, 4, 5 }, new int[] { 3, 4, 5 })] [TestCase(new int[] { }, new int[] { })] [TestCase(new int[] { 1 }, new int[] { 1 })] [TestCase(new int[] { 5, 5, 5, 5, 5 }, new int[] { 5, 5, 5, 5, 5 })] public void ToArrayTest(int[] array, int[] expected) { DoublyLinkedList a = new DoublyLinkedList(array); int[] actual = a.ToArray(); Assert.AreEqual(expected, actual); } [TestCase(new int[] { 1, 2, 3, 4, 9, 9, 5, 1 }, 1)] [TestCase(new int[] { 3, 4, 5 }, 3)] [TestCase(new int[] { 55 }, 55)] [TestCase(new int[] { 1, 2, 3, 4 }, 1)] [TestCase(new int[] { }, 0)] public void GetFirstTest(int[] array, int expected) { DoublyLinkedList a = new DoublyLinkedList(array); if (array.Length == 0) { Assert.Throws<System.Exception>(() => a.GetFirst()); } else { int actual = a.GetFirst(); Assert.AreEqual(expected, actual); } } [TestCase(new int[] { 1, 2, 3, 4, 9, 9, 5, 1 }, 1)] [TestCase(new int[] { 3, 4, 5 }, 5)] [TestCase(new int[] { 55 }, 55)] [TestCase(new int[] { 1, 2, 3, 4 }, 4)] [TestCase(new int[] { }, 0)] public void GetLastTest(int[] array, int expected) { DoublyLinkedList a = new DoublyLinkedList(array); if (array.Length == 0) { Assert.Throws<System.Exception>(() => a.GetLast()); } else { int actual = a.GetLast(); Assert.AreEqual(expected, actual); } } [TestCase(new int[] { 1, 2, 3, 4, 9, 9, 5, 1 }, 5, 9)] [TestCase(new int[] { 3, 4, 5 }, 0, 3)] [TestCase(new int[] { 55 }, 0, 55)] [TestCase(new int[] { }, 0, 0)] [TestCase(new int[] { 1, 2, 3, 4 }, 3, 4)] public void GetTest(int[] array, int index, int expected) { DoublyLinkedList a = new DoublyLinkedList(array); if (array.Length == 0) { Assert.Throws<System.Exception>(() => a.Get(index)); } else { int actual = a.Get(index); Assert.AreEqual(expected, actual); } } [TestCase(new int[] { 1, 2, 3, 4, 9, 9, 5, 1 }, new int[] { 1, 5, 9, 9, 4, 3, 2, 1 })] [TestCase(new int[] { 3, 4, 5 }, new int[] { 5, 4, 3 })] [TestCase(new int[] { 1, 2, 3, 4 }, new int[] { 4, 3, 2, 1 })] [TestCase(new int[] { }, new int[] { })] [TestCase(new int[] { 1 }, new int[] { 1 })] public void ReverseTest(int[] array, int[] expected) { DoublyLinkedList a = new DoublyLinkedList(array); a.Reverse(); int[] actual = a.ToArray(); Assert.AreEqual(expected, actual); } [TestCase(new int[] { 1, 2, 3, 4, 9, 9, 5, 1 }, 9)] [TestCase(new int[] { 3, 4, 5 }, 5)] [TestCase(new int[] { 55 }, 55)] [TestCase(new int[] { 1, 2, 3, 4 }, 4)] [TestCase(new int[] { }, 0)] public void MaxTest(int[] array, int expected) { DoublyLinkedList a = new DoublyLinkedList(array); if (array.Length == 0) { Assert.Throws<System.Exception>(() => a.Max()); } else { int actual = a.Max(); Assert.AreEqual(expected, actual); } } [TestCase(new int[] { 1, 2, 3, 4, 9, 9, 5, 1 }, 1)] [TestCase(new int[] { 3, 4, 5 }, 3)] [TestCase(new int[] { 55 }, 55)] [TestCase(new int[] { 1, 2, 3, 4 }, 1)] [TestCase(new int[] { }, 0)] public void MinTest(int[] array, int expected) { DoublyLinkedList a = new DoublyLinkedList(array); if (array.Length == 0) { Assert.Throws<System.Exception>(() => a.Min()); } else { int actual = a.Min(); Assert.AreEqual(expected, actual); } } [TestCase(new int[] { 1, 2, 3, 4, 9, 9, 5, 1 }, 4)] [TestCase(new int[] { 3, 4, 5 }, 2)] [TestCase(new int[] { 55 }, 0)] [TestCase(new int[] { 1, 2, 3, 4 }, 3)] [TestCase(new int[] { }, 0)] public void IndexOfMaxTest(int[] array, int expected) { DoublyLinkedList a = new DoublyLinkedList(array); if (array.Length == 0) { Assert.Throws<System.Exception>(() => a.IndexOfMax()); } else { int actual = a.IndexOfMax(); Assert.AreEqual(expected, actual); } } [TestCase(new int[] { 1, 2, 3, 4, 9, 9, 5, 1 }, 0)] [TestCase(new int[] { 5, 4, 3 }, 2)] [TestCase(new int[] { 55 }, 0)] [TestCase(new int[] { 56, 846, 55, 1000 }, 2)] [TestCase(new int[] { }, 0)] public void IndexOfMinTest(int[] array, int expected) { DoublyLinkedList a = new DoublyLinkedList(array); if (array.Length == 0) { Assert.Throws<System.Exception>(() => a.IndexOfMin()); } else { int actual = a.IndexOfMin(); Assert.AreEqual(expected, actual); } } [TestCase(new int[] { 1, 2, 3, 4, 9, 9, 5, 1 }, new int[] { 1, 1, 2, 3, 4, 5, 9, 9 })] [TestCase(new int[] { 3, 5, 4 }, new int[] { 3, 4, 5 })] [TestCase(new int[] { 0 }, new int[] { 0 })] [TestCase(new int[] { 1, 2, 3, 4 }, new int[] { 1, 2, 3, 4 })] [TestCase(new int[] { }, new int[] { })] public void SortTest(int[] array, int[] expected) { DoublyLinkedList a = new DoublyLinkedList(array); a.Sort(); int[] actual = a.ToArray(); Assert.AreEqual(expected, actual); } [TestCase(new int[] { 1, 2, 3, 4, 9, 9, 5, 1 }, new int[] { 9, 9, 5, 4, 3, 2, 1, 1 })] [TestCase(new int[] { 3, 4, 5 }, new int[] { 5, 4, 3 })] [TestCase(new int[] { 0 }, new int[] { 0 })] [TestCase(new int[] { 1, 2, 3, 4 }, new int[] { 4, 3, 2, 1 })] [TestCase(new int[] { }, new int[] { })] public void SortDescTest(int[] array, int[] expected) { DoublyLinkedList a = new DoublyLinkedList(array); a.SortDesc(); int[] actual = a.ToArray(); Assert.AreEqual(expected, actual); } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Data; using System.Linq; using System.Text; using System.Windows.Forms; using KartLib.Views; using KartObjects; using System.IO; using FastReport; using KartLib; using Excel = Microsoft.Office.Interop.Excel; using System.Threading; namespace AxiReports { public partial class DiscountReportView : KartUserControl { public DiscountReportView() { InitializeComponent(); ViewObjectType = ObjectType.DiscountReport; ReportRecords = new List<DiscountReportRecord>(); deTo.DateTime = DateTime.Today; deFrom.DateTime = DateTime.Today; /*string query = "select c.id as id_clients, c.name as name_clients from v_warehouses c " + @"where c.NAME like '%\_%' escape '\' " + "and c.NAME not in ('00_ГЛАВНЫЙ СКЛАД', '18_ОПТОВЫЙ СКЛАД', '99_ИНТЕРНЕТ-МАГАЗИН') order by c.name"; DataTable dataTable = new DataTable(); Loader.DataContext.Fill(query, ref dataTable); DataRow newRow = dataTable.NewRow(); newRow[0] = -2; newRow[1] = "Все"; dataTable.Rows.InsertAt(newRow, 0); lueStore.Properties.DataSource = dataTable; lueStore.Properties.DisplayMember = "NAME_CLIENTS"; lueStore.Properties.ValueMember = "ID_CLIENTS"; lueStore.EditValue = -2;*/ storeBindingSource.DataSource = Loader.DbLoad<Store>(""); } List<DiscountReportRecord> ReportRecords; FormWait frmWait; private void openButton_Click(object sender, EventArgs e) { frmWait = new FormWait("Подготовка данных ..."); // Процесс формирования запускаем отдельным потоком Thread thread = new Thread(LoadReport) { IsBackground = true }; thread.Start(); frmWait.ShowDialog(); frmWait.Dispose(); frmWait = null; discountReportRecordBindingSource.DataSource = ReportRecords; gvDiscountReport.RefreshData(); } /// <summary> /// Печать /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void printButton_Click(object sender, EventArgs e) { /*Excel.Application xlsApp = GetExcel(); xlsApp.ActiveWorkbook.PrintOutEx(); xlsApp.ActiveWorkbook.Close(false); xlsApp.Quit();*/ using (Report report = new Report()) { string _ReportPath = Settings.GetExecPath() + @"\Reports"; if (!File.Exists(_ReportPath + @"\DiscountReport.frx")) { MessageBox.Show(@"Не найдена форма печати DiscountReport.frx.", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } report.Load(_ReportPath + @"\DiscountReport.frx"); if (report == null) return; if (discountReportRecordBindingSource.Count == 0) LoadReport(); discountReportRecordBindingSource.DataSource = ReportRecords; report.RegisterData(discountReportRecordBindingSource, "discountReportRecordBindingSource"); report.GetDataSource("discountReportRecordBindingSource").Enabled = true; TextObject Date = (TextObject)report.FindObject("Date"); if (Date != null) Date.Text = " за период с " + deFrom.Text + " по " + deTo.Text; TextObject Store = (TextObject)report.FindObject("Store"); if (Store != null) Store.Text = lueStore.Text; if (report.Prepare()) report.ShowPrepared(true); } } private void excelButton_Click(object sender, EventArgs e) { GetExcel().Visible = true; } private Excel.Application GetExcel() { Excel.Application xlsApp = new Excel.Application(); Excel.Workbook xlsWB = xlsApp.Workbooks.Add(); Excel.Worksheet xlsWSh = xlsWB.ActiveSheet; xlsWSh.get_Range("D1", "D1").Value = "Отчет по скидке"; xlsWSh.get_Range("D1", "D1").Font.Size = 16; xlsWSh.get_Range("A2", "A2").Value = "Период: с " + deFrom.DateTime.ToShortDateString() + " по " + deTo.DateTime.ToShortDateString() + "; место хранения: " + lueStore.Text; xlsWSh.get_Range("A4", "A4").Value = "Место хранения"; xlsWSh.get_Range("A4", "A4").ColumnWidth = 23; xlsWSh.get_Range("B4", "B4").Value = "Номер кассы"; xlsWSh.get_Range("B4", "B4").ColumnWidth = 7; xlsWSh.get_Range("C4", "C4").Value = "Кассир"; xlsWSh.get_Range("C4", "C4").ColumnWidth = 22; xlsWSh.get_Range("D4", "D4").Value = "Дата чека"; xlsWSh.get_Range("D4", "D4").ColumnWidth = 13; xlsWSh.get_Range("E4", "E4").Value = "Товар"; xlsWSh.get_Range("E4", "E4").ColumnWidth = 30; xlsWSh.get_Range("F4", "F4").Value = "Кол-во"; xlsWSh.get_Range("F4", "F4").ColumnWidth = 5; xlsWSh.get_Range("G4", "G4").Value = "Сумма до скидки"; xlsWSh.get_Range("H4", "H4").Value = "Скидка, %"; xlsWSh.get_Range("H4", "H4").ColumnWidth = 5; xlsWSh.get_Range("I4", "I4").Value = "Сумма после скидки"; xlsWSh.get_Range("A4", "I4").WrapText = true; xlsWSh.get_Range("A4", "I4").VerticalAlignment = Excel.XlVAlign.xlVAlignTop; xlsWSh.get_Range("A4", "I4").HorizontalAlignment = Excel.XlHAlign.xlHAlignCenter; int i = 4; foreach (DiscountReportRecord record in ReportRecords) { i++; xlsWSh.get_Range("A" + i, "A" + i).Value = record.StoreName; xlsWSh.get_Range("B" + i, "B" + i).Value = record.POSDeviceName; xlsWSh.get_Range("C" + i, "C" + i).Value = record.Cashier; xlsWSh.get_Range("D" + i, "D" + i).Value = record.ReceiptDate == null ? "" : record.ReceiptDate.Value.ToString("dd.MM.yyyy HH:mm"); xlsWSh.get_Range("E" + i, "E" + i).Value = record.ArticulName; xlsWSh.get_Range("F" + i, "F" + i).Value = record.Quantity == null ? "" : record.Quantity.Value.ToString("0.00"); xlsWSh.get_Range("G" + i, "G" + i).Value = record.SumBeforeDiscount.ToString("0.00"); xlsWSh.get_Range("H" + i, "H" + i).Value = record.DiscountPercent == null ? "" : record.DiscountPercent.Value.ToString("0.00"); xlsWSh.get_Range("I" + i, "I" + i).Value = record.SumAfterDiscount.ToString("0.00"); } xlsWSh.get_Range("A4", "I" + i).Borders.Value = 1; if (i > 4) { xlsWSh.get_Range("A5", "I" + i).Font.Size = 9; xlsWSh.get_Range("F5", "I" + i).HorizontalAlignment = Excel.XlHAlign.xlHAlignRight; } xlsWSh.PageSetup.Orientation = Excel.XlPageOrientation.xlLandscape; xlsWSh.PageSetup.PrintTitleRows = "4:4"; xlsWSh.PageSetup.RightFooter = "&P"; return xlsApp; } private void LoadReport() { try { decimal allSumBeforeDiscount = 0; decimal allSumAfterDiscount = 0; ReportRecords = new List<DiscountReportRecord>(); ReportRecords = Loader.DbLoad<DiscountReportRecord>("", 0, deFrom.Text, deTo.DateTime.AddDays(1).ToShortDateString(), lueStore.EditValue); if (ReportRecords != null) { allSumBeforeDiscount = Convert.ToDecimal(ReportRecords.Sum(q => q.SumBeforeDiscount)); allSumAfterDiscount = Convert.ToDecimal(ReportRecords.Sum(q => q.SumAfterDiscount)); ReportRecords.Add(new DiscountReportRecord() { POSDeviceName = "", Cashier = "", ReceiptDate = null, ArticulName = "", Quantity = null, SumBeforeDiscount = allSumBeforeDiscount, DiscountPercent = null, SumAfterDiscount = allSumAfterDiscount, StoreName = "ИТОГО" }); } } catch (Exception exc) { throw (exc); } finally { frmWait.CloseWaitForm(); } } public override void SaveSettings() { DiscountReportSettings s = new DiscountReportSettings(); s.BeginPerod = deFrom.DateTime; s.EndPerod = deTo.DateTime; s.IdStore = (long?)lueStore.EditValue; SaveSettings<DiscountReportSettings>(s); gvDiscountReport.SaveLayoutToXml(gvSettingsFileName()); } public override void LoadSettings() { DiscountReportSettings s = (DiscountReportSettings)LoadSettings<DiscountReportSettings>(); if (s != null) { deFrom.DateTime = s.BeginPerod; deTo.DateTime = s.EndPerod; lueStore.EditValue = s.IdStore; } if (File.Exists(gvSettingsFileName())) gvDiscountReport.RestoreLayoutFromXml(gvSettingsFileName()); } } }
using System; using System.Collections.Generic; using System.Text.Json.Serialization; namespace SmartStocksImporter.Models { public class Children { [JsonPropertyName("name")] public string name { get; set; } [JsonPropertyName("children")] public List<Children> children { get; set; } [JsonPropertyName("size")] public decimal size { get; set; } [JsonPropertyName("slug")] public string slug { get; set; } [JsonPropertyName("sum")] public decimal sum { get; set; } } }
using MySql.Data.MySqlClient; using System; using System.Collections.Generic; using System.Text; using Trades.src; namespace Trades.src { class TradeMigrate { public static void Migrate() { MySqlConnection con = new MySqlConnection(TradesContext.GetMYSQLStringLink()); string query = @"CREATE TABLE trades ( id int NOT NULL PRIMARY KEY, price DOUBLE NOT NULL, quantity DOUBLE NOT NULL, side VARCHAR(255) NOT NULL, timestamp DATETIME NOT NULL );"; MySqlCommand cmd = new MySqlCommand(query, con); try { con.Open(); cmd.ExecuteNonQuery(); Console.WriteLine("Table Created Successfully"); } catch (MySqlException e) { Console.WriteLine("Error Generated. Details: " + e.ToString()); } finally { con.Close(); } } } }
using Discord; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Discord.Audio; namespace TestCommons.DiscordImpls { public class MockGuild : IGuild { public ulong? AFKChannelId { get { throw new NotImplementedException(); } } public int AFKTimeout { get { throw new NotImplementedException(); } } public IAudioClient AudioClient { get { throw new NotImplementedException(); } } public bool Available { get { throw new NotImplementedException(); } } public DateTimeOffset CreatedAt { get { throw new NotImplementedException(); } } public ulong DefaultChannelId { get { throw new NotImplementedException(); } } public DefaultMessageNotifications DefaultMessageNotifications { get { throw new NotImplementedException(); } } public ulong? EmbedChannelId { get { throw new NotImplementedException(); } } public IReadOnlyCollection<GuildEmoji> Emojis { get { throw new NotImplementedException(); } } public IRole EveryoneRole { get { throw new NotImplementedException(); } } public IReadOnlyCollection<string> Features { get { throw new NotImplementedException(); } } public string IconId { get { throw new NotImplementedException(); } } public string IconUrl { get { throw new NotImplementedException(); } } public ulong Id { get { throw new NotImplementedException(); } } public bool IsEmbeddable { get { throw new NotImplementedException(); } } public MfaLevel MfaLevel { get { throw new NotImplementedException(); } } public string Name { get; set; } public ulong OwnerId { get { throw new NotImplementedException(); } } public IReadOnlyCollection<IRole> Roles { get { throw new NotImplementedException(); } } public string SplashId { get { throw new NotImplementedException(); } } public string SplashUrl { get { throw new NotImplementedException(); } } public VerificationLevel VerificationLevel { get { throw new NotImplementedException(); } } public string VoiceRegionId { get { throw new NotImplementedException(); } } public Task AddBanAsync(ulong userId, int pruneDays = 0, RequestOptions options = null) { throw new NotImplementedException(); } public Task AddBanAsync(IUser user, int pruneDays = 0, RequestOptions options = null) { throw new NotImplementedException(); } public Task<IGuildIntegration> CreateIntegrationAsync(ulong id, string type, RequestOptions options = null) { throw new NotImplementedException(); } public Task<IRole> CreateRoleAsync(string name, GuildPermissions? permissions = default(GuildPermissions?), Color? color = default(Color?), bool isHoisted = false, RequestOptions options = null) { throw new NotImplementedException(); } public Task<ITextChannel> CreateTextChannelAsync(string name, RequestOptions options = null) { throw new NotImplementedException(); } public Task<IVoiceChannel> CreateVoiceChannelAsync(string name, RequestOptions options = null) { throw new NotImplementedException(); } public Task DeleteAsync(RequestOptions options = null) { throw new NotImplementedException(); } public Task DownloadUsersAsync() { throw new NotImplementedException(); } public Task<IVoiceChannel> GetAFKChannelAsync(CacheMode mode = CacheMode.AllowDownload, RequestOptions options = null) { throw new NotImplementedException(); } public Task<IReadOnlyCollection<IBan>> GetBansAsync(RequestOptions options = null) { throw new NotImplementedException(); } public Task<IGuildChannel> GetChannelAsync(ulong id, CacheMode mode = CacheMode.AllowDownload, RequestOptions options = null) { throw new NotImplementedException(); } public Task<IReadOnlyCollection<IGuildChannel>> GetChannelsAsync(CacheMode mode = CacheMode.AllowDownload, RequestOptions options = null) { throw new NotImplementedException(); } public Task<IGuildUser> GetCurrentUserAsync(CacheMode mode = CacheMode.AllowDownload, RequestOptions options = null) { throw new NotImplementedException(); } public Task<ITextChannel> GetDefaultChannelAsync(CacheMode mode = CacheMode.AllowDownload, RequestOptions options = null) { throw new NotImplementedException(); } public Task<IVoiceChannel> GetEmbedChannelAsync(CacheMode mode = CacheMode.AllowDownload, RequestOptions options = null) { throw new NotImplementedException(); } public Task<IReadOnlyCollection<IGuildIntegration>> GetIntegrationsAsync(RequestOptions options = null) { throw new NotImplementedException(); } public Task<IReadOnlyCollection<IInviteMetadata>> GetInvitesAsync(RequestOptions options = null) { throw new NotImplementedException(); } public Task<IGuildUser> GetOwnerAsync(CacheMode mode = CacheMode.AllowDownload, RequestOptions options = null) { throw new NotImplementedException(); } public IRole GetRole(ulong id) { throw new NotImplementedException(); } public Task<ITextChannel> GetTextChannelAsync(ulong id, CacheMode mode = CacheMode.AllowDownload, RequestOptions options = null) { throw new NotImplementedException(); } public Task<IReadOnlyCollection<ITextChannel>> GetTextChannelsAsync(CacheMode mode = CacheMode.AllowDownload, RequestOptions options = null) { throw new NotImplementedException(); } public Task<IGuildUser> GetUserAsync(ulong id, CacheMode mode = CacheMode.AllowDownload, RequestOptions options = null) { throw new NotImplementedException(); } public Task<IReadOnlyCollection<IGuildUser>> GetUsersAsync(CacheMode mode = CacheMode.AllowDownload, RequestOptions options = null) { throw new NotImplementedException(); } public Task<IVoiceChannel> GetVoiceChannelAsync(ulong id, CacheMode mode = CacheMode.AllowDownload, RequestOptions options = null) { throw new NotImplementedException(); } public Task<IReadOnlyCollection<IVoiceChannel>> GetVoiceChannelsAsync(CacheMode mode = CacheMode.AllowDownload, RequestOptions options = null) { throw new NotImplementedException(); } public Task LeaveAsync(RequestOptions options = null) { throw new NotImplementedException(); } public Task ModifyAsync(Action<GuildProperties> func, RequestOptions options = null) { throw new NotImplementedException(); } public Task ModifyChannelsAsync(IEnumerable<BulkGuildChannelProperties> args, RequestOptions options = null) { throw new NotImplementedException(); } public Task ModifyEmbedAsync(Action<GuildEmbedProperties> func, RequestOptions options = null) { throw new NotImplementedException(); } public Task ModifyRolesAsync(IEnumerable<BulkRoleProperties> args, RequestOptions options = null) { throw new NotImplementedException(); } public Task<int> PruneUsersAsync(int days = 30, bool simulate = false, RequestOptions options = null) { throw new NotImplementedException(); } public Task RemoveBanAsync(ulong userId, RequestOptions options = null) { throw new NotImplementedException(); } public Task RemoveBanAsync(IUser user, RequestOptions options = null) { throw new NotImplementedException(); } } }
namespace Exercises.Models.Queries { using System.Linq; using CodeFirstFromDatabase; /// <summary> /// Problem04 - Employees with Salary Over 50 000 /// </summary> public class EmployeesWithSalaryOver50000 : Query<SoftuniContext> { public override string QueryResult(SoftuniContext context) { var employees = context .Employees .Where(e => e.Salary > 50000) .Select(e => e.FirstName); foreach (var employee in employees) { this.Result.AppendLine(employee); } return this.Result.ToString(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace PointInterface { class Program { //public int result; static void Main(string[] args) { CenterPoint centerPoint = new CenterPoint(3, 0); int result = centerPoint.Addition(centerPoint.x,centerPoint.y); PrintPoint(centerPoint, result); result = centerPoint.Subtraction(centerPoint.x, centerPoint.y); PrintPoint(centerPoint, result); result = centerPoint.Multiplication(centerPoint.x, centerPoint.y); PrintPoint(centerPoint, result); result = centerPoint.Division(centerPoint.x, centerPoint.y); if (result != -99999) { PrintPoint(centerPoint, result); } else { Console.WriteLine(" invalid operation ! divide by zero"); } Console.ReadLine(); } private static void PrintPoint(CenterPoint centerPoint, int result) { Console.WriteLine($" Point: x = {centerPoint.x} and y = {centerPoint.y}"); Console.WriteLine($" Result: = {result}"); } } }
using FBS.Domain.Core; using System; namespace FBS.Domain.Booking { public class RejectBookingCommand : ICommand { public Guid Id { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using KartObjects; namespace KartSystem { public interface IDCTDocumentEditView : IDocumentEditView { DCTDocument DCTDocument { get; set; } IList<DCTDocGoodSpecRecord> DCTDocGoodSpecRecords { get; set; } DCTDocGoodSpecRecord CurrDCTDocGoodSpecRecord { get; set; } } }
using System.Collections.Generic; namespace PatternsCore.FrameWorkStyleFactory.AbstractFactory { public class ChicagoPizzaIngreadientsFactory:IPizzaIngredientsFactory { public IDough CreateDough() { return new ChicagoDough(); } public ISauce CreateSauce() { return new TomatoSouce(); } public ICheese CreateCheese() { return new MozerellaCheese(); } public IList<ITopping> CreateVeggies() { IList<ITopping> list = new List<ITopping>(); list.Add(new OnionVeggie()); return list; } public IList<ITopping> CreatePepperoni() { IList<ITopping> list = new List<ITopping>(); list.Add(new ChicagoPepperoni()); return list; } } }
namespace SharpStore.Services.Contracts { public interface IService { void Process(); } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using BLL.DLib; public partial class Controls_LibCmsForm_FormData : System.Web.UI.Page { #region vars public int FormID { get { return Request["FormID"] == "" ? 0 : Convert.ToInt32(Request["FormID"]); } } #endregion protected void Page_Load(object sender, EventArgs e) { if (FormID > 0) { var form = CmsForm.GetCmsForm(FormID); RadGrid1.DataSource = form.GetData(); RadGrid1.DataBind(); } } }
using System; using System.Text; using System.Threading; using System.Globalization; public static class Utility { private static CultureInfo culture = new CultureInfo("ms-MY"); public static decimal GetValidDecimalInputAmt(string input) { bool valid = false; string rawInput; decimal amount = 0; // Get user's input input type is valid while (!valid) { rawInput = GetRawInput(input); valid = decimal.TryParse(rawInput, out amount); if (!valid) PrintMessage("Invalid input. Try again.", false); } return amount; } public static Int64 GetValidIntInputAmt(string input) { bool valid = false; string rawInput; Int64 amount = 0; // Get user's input input type is valid while (!valid) { rawInput = GetRawInput(input); valid = Int64.TryParse(rawInput, out amount); if (!valid) PrintMessage("Invalid input. Try again.", false); } return amount; } // public static Object GetInput(string input, int validationLength, DataType _dataType) // { // bool valid = false; // string rawInput; // Object amount1 = null; // // If required validation length more than 0, only validate // if (validationLength > 0) // // Validate until input length pass // while (!valid) // { // rawInput = GetRawInput(input); // valid = ValidateLength(rawInput, validationLength); // if (!valid) // { // ATMScreen.PrintMessage("Invalid input length.", false); // continue; // } // switch (_dataType) // { // case DataType.typeInt64: // valid = decimal.TryParse(rawInput, out amount1); // amount1 = Convert.ToInt64(rawInput); // break; // case DataType.typeDecimal: // amount1 = Convert.ToDecimal(rawInput); // // decimal amount2 = 0; // // valid = decimal.TryParse(rawInput, out amount2) && amount2 > 0; // break; // default: // break; // } // //Check for valid data type // // if (rawInput.GetType().Equals(typeof(Int64))) // // { // // Int64 amount = 0; // // valid = Int64.TryParse(rawInput, out amount) && amount > 0; // // // amount1 = amount; // // } // // else if (rawInput.GetType().Equals(typeof(decimal))) // // { // // decimal amount = 0; // // valid = decimal.TryParse(rawInput, out amount) && amount > 0; // // // amount1 = amount; // // } // // else if (rawInput.GetType().Equals(typeof(String))) // // { // // valid = true; // // // amount1 = rawInput; // // } // // else // // { // // ATMScreen.PrintMessage("Unhandle input type validation. Please contact the bank.", false); // // valid = false; // // } // } // else // { // rawInput = GetRawInput(input); // } // return amount1; // } // private static bool ValidateNumber(string message, DataType _dataType, out Int64 amount) // { // //Console.WriteLine(message); // return Int64.TryParse(message, out amount) && amount > 0; // } // private static bool ValidateLength(string message, int validationLength = 0) // { // return (message.Length == validationLength) ? true : false; // } public static string GetRawInput(string message) { Console.Write($"Enter {message}: "); return Console.ReadLine(); } public static string GetHiddenConsoleInput() { StringBuilder input = new StringBuilder(); while (true) { var key = Console.ReadKey(true); if (key.Key == ConsoleKey.Enter) break; if (key.Key == ConsoleKey.Backspace && input.Length > 0) input.Remove(input.Length - 1, 1); else if (key.Key != ConsoleKey.Backspace) input.Append(key.KeyChar); } return input.ToString(); } #region UIOutput - UX and output format public static void printDotAnimation(int timer = 10) { for (var x = 0; x < timer; x++) { System.Console.Write("."); Thread.Sleep(100); } Console.WriteLine(); } public static string FormatAmount(decimal amt) { return String.Format(culture, "{0:C2}", amt); } public static void PrintMessage(string msg, bool success) { if (success) Console.ForegroundColor = ConsoleColor.Yellow; else Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine(msg); Console.ResetColor(); Console.WriteLine("Press any key to continue"); Console.ReadKey(); } #endregion }
using System; using System.Linq; using System.Runtime.Serialization; using System.ServiceModel; using System.ServiceModel.Activation; using System.Collections.Generic; using System.Xml.Linq; namespace GeoSearch.Web { [ServiceContract(Namespace = "cisc.gmu.edu/OtherQueryFunctionsService")] [SilverlightFaultBehavior] [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)] public class OtherQueryFunctionsService { private const string string_unknown = "Unknown"; [OperationContract] public string getRecordDetailMetadata(string MetadataAccessURL) { string detail = null; if (MetadataAccessURL == null || MetadataAccessURL.Trim().Equals("")) return null; /*Both HTTP Post and Get request, they both can work well*/ //string postRequest = "<?xml version='1.0' encoding='UTF-8'?>" // + "<csw:GetRecordById xmlns:csw='http://www.opengis.net/cat/csw/2.0.2' service='CSW' version='2.0.2' outputSchema='csw:IsoRecord'>" // + "<csw:Id>" // + id // + "</csw:Id>" // +"<csw:ElementSetName>full</csw:ElementSetName>" // + "</csw:GetRecordById>"; //object[] parameters = new object[2]; //parameters[0] = clearingHouseUrlString; //parameters[1] = postRequest; //detail = HttpPost(CSWURL, postRequest); //string urlString = CLHCSWURLString + "?request=GetRecordById&service=CSW&version=2.0.2&ElementSetName=full&outputSchema=csw:IsoRecord&Id=" + id; //detail = HttpGet(urlString); ////Micrcosoft .Net only support XSLT 1.0, don't support XSLT 2.0 and further version, so we can not use xslTransform to do xml transform. //if (MetadataAccessURL.StartsWith(GOSCSWURLString)) //{ // try // { // //string // XPathDocument myXPathDocument = new XPathDocument(MetadataAccessURL); // XslCompiledTransform myXslTransform = new XslCompiledTransform(); // StringWriter strWriter = new StringWriter(); // XmlTextWriter writer = new XmlTextWriter(strWriter); // myXslTransform.Load(CSDGM2ISO19115Stylesheet); // myXslTransform.Transform(myXPathDocument, null, writer); // writer.Close(); // detail = strWriter.ToString(); // //StreamReader stream = new StreamReader(resultDoc); // //Console.Write("**This is result document**\n\n"); // //Console.Write(stream.ReadToEnd()); // } // catch (Exception e) // { // e.GetType(); // } //} detail = BaseHttpFunctions.HttpGet(MetadataAccessURL); return detail; } [OperationContract] public WMSLayers getAllLayerNamesOfWMS(string urlstring) { WMSLayers wms_layers = new WMSLayers(); List<WMSLayer> layerList = new List<WMSLayer>(); wms_layers.layersList = layerList; wms_layers.WMSURL = urlstring; if (!urlstring.ToLower().Contains("service=")) { if (urlstring.Contains("?")) if (urlstring.EndsWith("&")) urlstring += "SERVICE=WMS&REQUEST=GetCapabilities&VERSION=1.1.1"; else urlstring += "&SERVICE=WMS&REQUEST=GetCapabilities&VERSION=1.1.1"; else { urlstring += "?SERVICE=WMS&REQUEST=GetCapabilities&VERSION=1.1.1"; } } XDocument doc = null; try { string response = BaseHttpFunctions.HttpGet(urlstring); doc = XDocument.Parse(response); } catch (Exception e) { e.GetType(); return null; } if (doc != null) { XElement rootElement = doc.Root; IEnumerable<XElement> Services = rootElement.Descendants(XName.Get("Service")); if (Services != null) { foreach (XElement Service in Services) { string name = null; string title = null; XElement nameElement = Service.Element(XName.Get("Name")); if (nameElement != null) { name = nameElement.Value; if (name != null && !(name.Trim().Equals(""))) wms_layers.name = name; } XElement titleElement = Service.Element(XName.Get("Title")); if (titleElement != null) { title = titleElement.Value; if (title != null && !(title.Trim().Equals(""))) wms_layers.title = title; } } } Dictionary<XElement, BBox> layer_bbox_map = new Dictionary<XElement, BBox>(); IEnumerable<XElement> Layers = rootElement.Descendants(XName.Get("Layer")); if (Layers != null) { foreach (XElement layer in Layers) { string name = null; string title = null; XElement nameElement = layer.Element(XName.Get("Name")); XElement LatLonBoundingBoxElement = layer.Element(XName.Get("LatLonBoundingBox")); WMSLayer layerObject = new WMSLayer(); BBox bbox = null; if (LatLonBoundingBoxElement != null) { bbox = new BBox(); XAttribute a = LatLonBoundingBoxElement.Attribute(XName.Get("maxy")); if (a != null) { string value = a.Value; if (value != null) bbox.BBox_Upper_Lat = Double.Parse(value); } a = LatLonBoundingBoxElement.Attribute(XName.Get("miny")); if (a != null) { string value = a.Value; if (value != null) bbox.BBox_Lower_Lat = Double.Parse(value); } a = LatLonBoundingBoxElement.Attribute(XName.Get("maxx")); if (a != null) { string value = a.Value; if (value != null) bbox.BBox_Upper_Lon = Double.Parse(value); } a = LatLonBoundingBoxElement.Attribute(XName.Get("minx")); if (a != null) { string value = a.Value; if (value != null) bbox.BBox_Lower_Lon = Double.Parse(value); } layerObject.box = bbox; layer_bbox_map.Add(layer, bbox); } //if current layer don't contain LatLonBoundingBox and Parent Layer is not exist or do not contain LatLonBoundingBox either, current layer is not accessible else { if (layer.Parent.Name.Equals(XName.Get("Layer"))) { if (layer_bbox_map.ContainsKey(layer.Parent)) { bbox = BBox.CreateBBox(layer_bbox_map[layer.Parent]); layerObject.box = bbox; layer_bbox_map.Add(layer, bbox); } else continue; } else continue; } //if there is not Layer name or LatLonBoundingBox element exist, the layer is not accessible if (nameElement == null) continue; else { name = nameElement.Value; if (name != null && !(name.Trim().Equals(""))) layerObject.name = name; XElement titleElement = layer.Element(XName.Get("Title")); if (titleElement != null) { title = titleElement.Value; if (title != null && !(title.Trim().Equals(""))) layerObject.title = title; } //we want to show title, which provide us more inforamtion than layer name, but when there is not layer title, we still show layer name as title if (layerObject.title == null && layerObject.name != null) layerObject.title = layerObject.name; layerList.Add(layerObject); } } } } return wms_layers; } [OperationContract] public HierachicalWMSLayers getHierachicalLayersOfWMS(string urlstring) { HierachicalWMSLayers wms_layers = new HierachicalWMSLayers(); wms_layers.layersList = new List<CascadedWMSLayer>(); wms_layers.WMSURL = urlstring; if (!urlstring.ToLower().Contains("service=")) { if (urlstring.Contains("?")) if (urlstring.EndsWith("&")) urlstring += "SERVICE=WMS&REQUEST=GetCapabilities&VERSION=1.1.1"; else urlstring += "&SERVICE=WMS&REQUEST=GetCapabilities&VERSION=1.1.1"; else { urlstring += "?SERVICE=WMS&REQUEST=GetCapabilities&VERSION=1.1.1"; } } XDocument doc = null; try { string response = BaseHttpFunctions.HttpGet(urlstring); doc = XDocument.Parse(response); } catch (Exception e) { e.GetType(); return null; } if (doc != null) { XElement rootElement = doc.Root; IEnumerable<XElement> Services = rootElement.Descendants(XName.Get("Service")); if (Services != null) { foreach (XElement Service in Services) { string name = null; string title = null; XElement nameElement = Service.Element(XName.Get("Name")); if (nameElement != null) { name = nameElement.Value; if (name != null && !(name.Trim().Equals(""))) wms_layers.serviceName = name; } XElement titleElement = Service.Element(XName.Get("Title")); if (titleElement != null) { title = titleElement.Value; if (title != null && !(title.Trim().Equals(""))) wms_layers.serviceTitle = title; } } } Dictionary<XElement, BBox> layer_bbox_map = new Dictionary<XElement, BBox>(); XElement Capability = rootElement.Element(XName.Get("Capability")); XElement firstLevel_Layer = Capability.Element(XName.Get("Layer")); if (firstLevel_Layer != null) { IEnumerable<XElement> secondLevel_Layers = firstLevel_Layer.Elements(XName.Get("Layer")); if (wms_layers.serviceName == null || wms_layers.serviceName.Trim().Equals("")) { XElement nameElement = firstLevel_Layer.Element(XName.Get("Name")); if (nameElement == null || nameElement.Value.Trim().Equals("")) wms_layers.serviceName = string_unknown; else wms_layers.serviceName = nameElement.Value; } if (wms_layers.serviceTitle == null || wms_layers.serviceTitle.Trim().Equals("")) { XElement titleElement = firstLevel_Layer.Element(XName.Get("Title")); if (titleElement == null || titleElement.Value.Trim().Equals("")) wms_layers.serviceTitle = string_unknown; else wms_layers.serviceTitle = titleElement.Value; } //get BBOX information BBox bbox = getBBoxInformation(firstLevel_Layer); if (bbox != null) { wms_layers.latLonBBox = bbox; layer_bbox_map.Add(firstLevel_Layer, bbox); } wms_layers.subLayers_Number = secondLevel_Layers.Count(); foreach (XElement layer in secondLevel_Layers) { wms_layers.layersList.Add(getLayerInfomation(layer, layer_bbox_map, wms_layers)); } } } return wms_layers; } //get BBOX information private BBox getBBoxInformation(XElement layer) { BBox bbox = null; XElement LatLonBoundingBoxElement = layer.Element(XName.Get("LatLonBoundingBox")); if (LatLonBoundingBoxElement != null) { bbox = new BBox(); XAttribute a = LatLonBoundingBoxElement.Attribute(XName.Get("maxy")); if (a != null) { string value = a.Value; if (value != null) bbox.BBox_Upper_Lat = Double.Parse(value); } a = LatLonBoundingBoxElement.Attribute(XName.Get("miny")); if (a != null) { string value = a.Value; if (value != null) bbox.BBox_Lower_Lat = Double.Parse(value); } a = LatLonBoundingBoxElement.Attribute(XName.Get("maxx")); if (a != null) { string value = a.Value; if (value != null) bbox.BBox_Upper_Lon = Double.Parse(value); } a = LatLonBoundingBoxElement.Attribute(XName.Get("minx")); if (a != null) { string value = a.Value; if (value != null) bbox.BBox_Lower_Lon = Double.Parse(value); } } return bbox; } private CascadedWMSLayer getLayerInfomation(XElement layer, Dictionary<XElement, BBox> layer_bbox_map, HierachicalWMSLayers wms) { CascadedWMSLayer layerObject = new CascadedWMSLayer(); string name = null; string title = null; XElement nameElement = layer.Element(XName.Get("Name")); //XElement LatLonBoundingBoxElement = layer.Element(XName.Get("LatLonBoundingBox")); XElement Extent = layer.Element(XName.Get("Extent")); IEnumerable<XElement> cascadedLayers = layer.Elements(XName.Get("Layer")); //get BBOX information BBox bbox = getBBoxInformation(layer); if (bbox != null) { layerObject.latLonBBox = bbox; layer_bbox_map.Add(layer, bbox); } //if current layer don't contain LatLonBoundingBox and Parent Layer is not exist or do not contain LatLonBoundingBox either, current layer is not accessible else { XElement parent = layer.Parent; while (parent.Name.Equals(XName.Get("Layer"))) { if (layer_bbox_map.ContainsKey(layer.Parent)) { bbox = BBox.CreateBBox(layer_bbox_map[layer.Parent]); layerObject.latLonBBox = bbox; layer_bbox_map.Add(layer, bbox); break; } else parent = parent.Parent; } } //if there is not Layer name or LatLonBoundingBox element exist, the layer is not accessible if (nameElement != null && layerObject.latLonBBox != null) { layerObject.canGetMap = true; wms.allGetMapEnabledLayers_Number++; } else layerObject.canGetMap = false; if (nameElement == null) layerObject.name = string_unknown; else { name = nameElement.Value; if (name != null && !(name.Trim().Equals(""))) layerObject.name = name; } XElement titleElement = layer.Element(XName.Get("Title")); if (titleElement != null) { title = titleElement.Value; if (title != null && !(title.Trim().Equals(""))) layerObject.title = title; else layerObject.title = string_unknown; } //we want to show title, which provide us more inforamtion than layer name, but when there is not layer title, we still show layer name as title //if (layerObject.title == null && layerObject.name != null) // layerObject.title = layerObject.name; //add time extent if (Extent != null && Extent.Attribute(XName.Get("name")).Value.Equals("time")) { layerObject.extent_time_default = Extent.Attribute(XName.Get("default")).Value; layerObject.extent_time = Extent.Value; layerObject.timeEnabled = true; } else layerObject.timeEnabled = false; //get the legend for the layer XElement style = layer.Element(XName.Get("Style")); if (style != null) { XElement legendURL = style.Element(XName.Get("LegendURL")); if (legendURL != null) { XElement OnlineResource = legendURL.Element(XName.Get("OnlineResource")); if (OnlineResource != null) { XAttribute url = OnlineResource.Attribute(XName.Get("href", "http://www.w3.org/1999/xlink")); if (url != null) { layerObject.legendURL = url.Value; } } } } //add children layers if (cascadedLayers != null) { layerObject.Children = new System.Collections.ObjectModel.ObservableCollection<CascadedWMSLayer>(); foreach (XElement childLayer in cascadedLayers) { layerObject.Children.Add(getLayerInfomation(childLayer, layer_bbox_map, wms)); } } //get queryable information XAttribute queryable = layer.Attribute(XName.Get("queryable")); if (queryable != null && queryable.Value.Equals("1")) layerObject.queryable = true; else layerObject.queryable = false; return layerObject; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace TorrentDotNet.Util { public static class Formatter { public static string BytesToEnglish(long bytes) { // Took Algorithm From: // https://tinyurl.com/ybdrtzur int index = (int)Math.Floor(Math.Log(bytes) / Math.Log(1024)); string[] sizes = { "B", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB" }; return Math.Round(bytes / Math.Pow(1024, index), 2).ToString() + " " + sizes[index]; } public static string HashToPercentEncoding(string hash) { var pe = new StringBuilder(); for (int i = 0; i < hash.Length; i++) { if (i % 2 == 0) { pe.Append("%"); } pe.Append(hash[i]); //System.Threading.Thread.Sleep(10); } return pe.ToString(); } public static string HashFormatter(string hash) { var newhash = new StringBuilder(); for (int i = 0; i < hash.Length; i++) { if (char.IsLetter(hash[i]) && char.IsUpper(hash[i])) newhash.Append(char.ToLower(hash[i])); else newhash.Append(hash[i]); } return newhash.ToString(); } } }
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Threading.Tasks; namespace GodaddyWrapper.Requests { public class AbuseTicketCreate { public string type { get; set; } public string source { get; set; } public string target { get; set; } public string proxy { get; set; } public string intentional { get; set; } public string info { get; set; } public string infoUrl { get; set; } } }
using System; public class UnionFind { public static void Main() { var uft = new UnionFindTree(10); Console.WriteLine(uft.is_same_set(1, 3)); uft.unite(1, 2); Console.WriteLine(uft.is_same_set(1, 3)); uft.unite(2, 3); Console.WriteLine(uft.is_same_set(1, 3)); } } class UnionFindTree{ private int[] tree; public UnionFindTree(int n){ tree = new int[n]; for(int i=0; i<n; i++) tree[i] = i; } public int root(int a){ if(tree[a] == a) return a; return (tree[a]=root(tree[a])); } public bool is_same_set(int a, int b){ return tree[root(a)] == root(b); } public void unite(int a, int b){ tree[root(a)] = root(b); } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using Business.Models; namespace MooversCRM.Controllers { public class NewCaseController : BaseControllers.SecureBaseController { // // GET: /NewCase/ public ActionResult Index() { var repo = new Business.Models.AccountRepository() ; // var inventoryitems = repo.GetAccountByUserId(AspUserID).StorageWorkOrders.FirstOrDefault().StorageWorkOrder_InventoryItem_Rel.FirstOrDefault().InventoryItem; var claimlistmodel = new Business.ViewModels.ClaimListModel(); return View("../Case/NewCase" , claimlistmodel); } [HttpPost] public ActionResult AddCase(Business.ViewModels.ClaimListModel modal) { var caserespo = new Business.Models.CaseRepository(); var repo = new Business.Models.AccountRepository(); var inventoryitems = repo.GetAccountByUserId(AspUserID); var rel = new Case { Status = (int)Business.ViewModels.CaseStatus.Pending, Created = DateTime.Now, Updated = DateTime.Now, }; //rel.Claims.Add(modal.CustomerClaim); caserespo.Add(rel); caserespo.Save(); return View(); } } }
namespace Backpressure { using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; internal interface IBackpressureOperator { void Request(int count); } }
using System; using Microsoft.Ajax.Utilities; using WebApplication1.Helpers; namespace WebApplication1.Models { public class Customer { #region private properties #endregion #region Public properties public string CustomerID { get; set; } public int RecordID { get; set; } public string FirstName { get; set; } public string MiddleInitial { get; set; } public string LastName { get; set; } public string Company { get; set; } public string Address1 { get; set; } public string Address2 { get; set; } public string City { get; set; } public string Zip { get; set; } public string State { get; set; } public string Country { get; set; } public string HomePhone { get; set; } public string PhoneExt { get; set; } public string CellPhone { get; set; } public string Misc2 { get; set; } public string Email { get; set; } public string ShipName { get; set; } public string CellEmail { get; set; } public DateTime LastUpdate { get; set; } public double OnAccount { get; set; } public DateTime DateCreated { get; set; } public bool doesThisMatch(string inputString) { if (HomePhone == inputString) { return true; } if (CellPhone == inputString) { return true; } if (CustomerID == inputString) { return true; } return false; } public override string ToString() { return string.Format("{0} {1}", FirstName.UppercaseFirst(), LastName.UppercaseFirst()); } #endregion } }
using Properties.Core.Interfaces; using Properties.Core.Objects; namespace Properties.Infrastructure.Data.Mappers { public class PropertyDetailMapper : IMapToExisting<PropertyDetail, PropertyDetail> { public bool Map(PropertyDetail source, PropertyDetail target) { target.MarkClean(); target.DetailType = source.DetailType; target.DetailValue = source.DetailValue; return target.IsDirty; } } }
using System; using System.Collections.Generic; using System.Windows; using System.Windows.Documents; using System.Windows.Media; using CODE.Framework.Core.Utilities; namespace CODE.Framework.Wpf.Documents { /// <summary> /// This helper class provides various extension methods useful in converting HMTL to XAML /// </summary> public static class HtmlToXamlHelper { /// <summary> /// Converts HTML to a simple text version presented as WPF inlines /// </summary> /// <param name="html">The HTML.</param> /// <param name="leadingHtml">The leading HTML.</param> /// <param name="trailingHtml">The trailing HTML.</param> /// <param name="trimLeadingSpaces">if set to <c>true</c> [trim leading spaces].</param> /// <param name="trimLeadingTabs">if set to <c>true</c> [trim leading tabs].</param> /// <returns>IEnumerable{Inline}.</returns> public static IEnumerable<Inline> ToSimplifiedInlines(this string html, string leadingHtml = "", string trailingHtml = "", bool trimLeadingSpaces = true, bool trimLeadingTabs = true) { var blocks = new List<Inline>(); var hasParagraphTags = html.IndexOf("<p>", StringComparison.Ordinal) > -1 || html.IndexOf("<P>", StringComparison.Ordinal) > -1; if (!hasParagraphTags) return html.ToInlines(); html = html.Replace("<P>", "<p>"); html = html.Replace("</P>", "</p>"); if (!html.StartsWith("<p>")) html = "<p>" + html; if (!html.EndsWith("</p>")) html += "</p>"; var paragraphs = new List<string>(); while (!string.IsNullOrEmpty(html)) { var at = html.IndexOf("</p>", StringComparison.Ordinal); if (at > -1) { var paragraphHtml = html.Substring(0, at + 4); paragraphs.Add(paragraphHtml); html = html.Length > at + 4 ? html.Substring(at + 4) : string.Empty; } else { paragraphs.Add(html); html = string.Empty; } } foreach (var paragraph in paragraphs) { if (blocks.Count > 0) blocks.Add(new LineBreak()); var innerParagraph = paragraph.Replace("<p>", string.Empty).Replace("</p>", string.Empty); blocks.AddRange(innerParagraph.ToInlines()); } return blocks; } /// <summary> /// Converts HTML to WPF blocks /// </summary> /// <param name="html">The HTML.</param> /// <param name="leadingHtml">The leading HTML.</param> /// <param name="trailingHtml">The trailing HTML.</param> /// <param name="trimLeadingSpaces">if set to <c>true</c> [trim leading spaces].</param> /// <param name="trimLeadingTabs">if set to <c>true</c> [trim leading tabs].</param> /// <returns>IEnumerable{Block}.</returns> public static IEnumerable<Block> ToBlocks(this string html, string leadingHtml = "", string trailingHtml = "", bool trimLeadingSpaces = true, bool trimLeadingTabs = false) { var blocks = new List<Block>(); //if (html == null) html = string.Empty; if (string.IsNullOrEmpty(html)) return blocks; var hasParagraphTags = html.IndexOf("<p>", StringComparison.Ordinal) > -1 || html.IndexOf("<P>", StringComparison.Ordinal) > -1; if (!hasParagraphTags) { var para = new Paragraph(); if (!string.IsNullOrEmpty(leadingHtml)) para.Inlines.AddRange(leadingHtml.ToInlines()); para.Inlines.AddRange(html.ToInlines()); if (!string.IsNullOrEmpty(trailingHtml)) para.Inlines.AddRange(trailingHtml.ToInlines()); blocks.Add(para); } else { html = html.Replace("<P>", "<p>"); html = html.Replace("</P>", "</p>"); if (!html.StartsWith("<p>")) html = "<p>" + html; if (!html.EndsWith("</p>")) html += "</p>"; var paragraphs = new List<string>(); while (!string.IsNullOrEmpty(html)) { var at = html.IndexOf("</p>", StringComparison.Ordinal); if (at > -1) { var paragraphHtml = html.Substring(0, at + 4); paragraphs.Add(paragraphHtml); html = html.Length > at + 4 ? html.Substring(at + 4) : string.Empty; } else { paragraphs.Add(html); html = string.Empty; } } for (var paragraphCounter = 0; paragraphCounter < paragraphs.Count; paragraphCounter++) { var paragraph = paragraphs[paragraphCounter]; var para = new Paragraph(); if (paragraphCounter == 0 && !string.IsNullOrEmpty(leadingHtml)) para.Inlines.AddRange(leadingHtml.ToInlines()); var innerParagraph = paragraph.Replace("<p>", string.Empty).Replace("</p>", string.Empty); para.Inlines.AddRange(innerParagraph.ToInlines()); if (paragraphCounter == paragraphs.Count - 1 && !string.IsNullOrEmpty(trailingHtml)) para.Inlines.AddRange(trailingHtml.ToInlines()); blocks.Add(para); } } return blocks; } /// <summary> /// Converts HTML to WPF inlines /// </summary> /// <param name="html">The HTML.</param> /// <param name="trimLeadingSpaces">if set to <c>true</c> [trim leading spaces].</param> /// <param name="trimLeadingTabs">if set to <c>true</c> [trim leading tabs].</param> /// <returns>IEnumerable{Inline}.</returns> public static IEnumerable<Inline> ToInlines(this string html, bool trimLeadingSpaces = true, bool trimLeadingTabs = false) { var inlines = new List<Inline>(); if (string.IsNullOrEmpty(html)) return inlines; var htmlBytes = html.ToCharArray(); var currentRun = new Run(); inlines.Add(currentRun); // We count how many open tags of specific meaning we are currently in. var boldCount = 0; var italicCount = 0; var underliniedCount = 0; var inMeaningfulTag = false; for (var charCounter = 0; charCounter < htmlBytes.Length; charCounter++) { var addChar = false; if (!inMeaningfulTag) // Checking for open tags if (htmlBytes[charCounter] == '<') { // This may be either an open or close HTML tag. if (IsStartOf("/", htmlBytes, charCounter + 1)) { // We are in a closing tag if (IsStartOf("b", htmlBytes, charCounter + 2)) { inMeaningfulTag = true; boldCount--; } else if (IsStartOf("strong", htmlBytes, charCounter + 2)) { inMeaningfulTag = true; boldCount--; } else if (IsStartOf("i", htmlBytes, charCounter + 2)) { inMeaningfulTag = true; italicCount--; } else if (IsStartOf("u", htmlBytes, charCounter + 2)) { inMeaningfulTag = true; underliniedCount--; } else if (IsStartOf("br", htmlBytes, charCounter + 2)) { inMeaningfulTag = true; inlines.Add(new LineBreak()); currentRun = GetNewRunForSettings(boldCount, italicCount, underliniedCount); inlines.Add(currentRun); } } else { // Probably in an open tag if (IsStartOf("b", htmlBytes, charCounter + 1)) { inMeaningfulTag = true; boldCount++; } else if (IsStartOf("strong", htmlBytes, charCounter + 1)) { inMeaningfulTag = true; boldCount++; } else if (IsStartOf("i", htmlBytes, charCounter + 1)) { inMeaningfulTag = true; italicCount++; } else if (IsStartOf("u", htmlBytes, charCounter + 1)) { inMeaningfulTag = true; underliniedCount++; } } if (!inMeaningfulTag) addChar = true; } else addChar = true; else if (htmlBytes[charCounter] == '>') { inMeaningfulTag = false; // We are not in the tag anymore, so we can now process the text as regular text again. // We also start a new run currentRun = GetNewRunForSettings(boldCount, italicCount, underliniedCount); inlines.Add(currentRun); } if (addChar) currentRun.Text += htmlBytes[charCounter]; } var inlineCounter = -1; var inlinesToRemove = new List<int>(); foreach (var inline in inlines) { inlineCounter++; var inlineRun = inline as Run; if (inlineRun == null) continue; if (inlineRun.Text.Length == 0) { inlinesToRemove.Add(inlineCounter); inlineCounter--; // This is right and it is done because as we go through the removal loop, the prior items will be gone } else if (inlineCounter == 0 && string.IsNullOrEmpty(inlineRun.Text)) { inlinesToRemove.Add(inlineCounter); inlineCounter--; // This is right and it is done because as we go through the removal loop, the prior items will be gone } } foreach (var index in inlinesToRemove) inlines.RemoveAt(index); if (inlines.Count > 0) If.Real<Run>(inlines[0], r => { while ((trimLeadingSpaces && r.Text.StartsWith(" ")) || (trimLeadingTabs && r.Text.StartsWith("\t"))) r.Text = r.Text.Substring(1); // The very first run should never start with spaces }); return inlines; } /// <summary> /// Gets the new run for settings. /// </summary> /// <param name="boldCount">The bold count.</param> /// <param name="italicCount">The italic count.</param> /// <param name="underliniedCount">The underlinied count.</param> /// <returns>Run.</returns> private static Run GetNewRunForSettings(int boldCount, int italicCount, int underliniedCount) { var run = new Run(); if (boldCount > 0) run.FontWeight = FontWeights.Bold; if (italicCount > 0) run.FontStyle = FontStyles.Italic; if (underliniedCount > 0) run.TextDecorations.Add(new TextDecoration(TextDecorationLocation.Underline, new Pen(Brushes.Black, 1), 0d, TextDecorationUnit.Pixel, TextDecorationUnit.Pixel)); return run; } /// <summary> /// Checks whether the provided textis the start of a specified tag /// </summary> /// <param name="text">The text.</param> /// <param name="chars">The chars.</param> /// <param name="startIndex">The start index.</param> /// <returns><c>true</c> if [is start of] [the specified text]; otherwise, <c>false</c>.</returns> private static bool IsStartOf(string text, char[] chars, int startIndex) { if (chars.Length < startIndex + text.Length) return false; // Couldn't possibly be a match text = text.ToLower(); var text2 = string.Empty; for (var counter = startIndex; counter < text.Length + startIndex; counter++) text2 += chars[counter]; text2 = text2.ToLower(); return text == text2; } } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Windows; using System.Windows.Data; using PlanMGMT.Model; using PlanMGMT.Module; using System.Windows.Input; using PlanMGMT.Utility; namespace PlanMGMT.ViewModel { /// <summary> /// /// </summary> public class ReportViewModel : ViewModelBase { /// <summary> /// 构造 /// </summary> public ReportViewModel() { this.UserCode = ProU.Instance.PspUser.UserCode; if (!IsInDesignMode) { DateTime dt = DateTime.Now; Load(dt); this.LoadCommand = new ViewModelCommand((Object parameter) => { Load(parameter); }); this.CommitCommand = new ViewModelCommand((Object parameter) => { Commit(); }); } } public string UserCode { get;set; } public List<DateTime> CommitDates { get { return BLL.ReportBLL.Instance.CurrentCommitDates; } set { base.RaisePropertyChanged("CommitDates"); } } private string _daily=""; private string _tomorrowdaily=""; private DateTime _selectedDate; public DateTime SelectedDate { get { return _selectedDate; } set { _selectedDate = value; base.RaisePropertyChanged("SelectedDate"); } } public string Daily { get { return _daily; } set { _daily = value; base.RaisePropertyChanged("Daily"); } } public string TomorrowDaily { get { return _tomorrowdaily; } set { _tomorrowdaily = value; base.RaisePropertyChanged("TomorrowDaily"); } } public ICommand LoadCommand { get; set; } public void Load(object param) { DateTime dt = Convert.ToDateTime(param); SelectedDate = dt; CommitDates = BLL.ReportBLL.Instance.GetCurCommitDates(dt); Entity.WorkLog log = BLL.ReportBLL.Instance.GetCurLog(dt); if (log != null) { Daily = log.Daily; TomorrowDaily = log.TomorrowDaily; } else { Daily = ""; TomorrowDaily = ""; } } public ICommand CommitCommand { get; set; } public void Commit() { if (string.IsNullOrEmpty(Daily)) { Helper.Instance.AlertError("您的今日总结不能为空"); return; } Error error = BLL.ReportBLL.Instance.Commit(Daily, TomorrowDaily, SelectedDate); if (error.ErrCode == 0) { Helper.Instance.AlertSuccess("提交成功"); Load(SelectedDate); } else { Helper.Instance.AlertError("提交日志失败" + error.ErrText); } } } }
using System; using System.Runtime.Serialization; namespace pjank.BossaAPI.Fixml { public class BizMessageRejectException : FixmlErrorMsgException { public new BizMessageRejectMsg Msg { get { return msg as BizMessageRejectMsg; } } public BizMessageRejectException(string str, BizMessageRejectMsg msg) : base(str, msg) { } public BizMessageRejectException(BizMessageRejectMsg msg) : base(msg) { } protected BizMessageRejectException(SerializationInfo info, StreamingContext context) : base(info, context) { } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ET.Main { class ModuleTypeTreeNode : ModuleTreeNode { //对应模块的ShowName属性 public override string TreeNodeName { get; set; } //对应模块的Key属性 public string ModuleKey { get; set; } //对应模块的isOnlyOneFile属性 public bool IsOnlyOneFile { get; set; } public override object Icon { get { return null; } } public override object ExpandedIcon { get { return null; } } public override bool CanContainSubNodes { get { return !IsOnlyOneFile; } } } }
using System; using System.Drawing; namespace StartApp { public enum STAAdOrigin { _Top = 1, _Bottom = 2 } public enum STAAdType { _FullScreen = 1, _OfferWall = 2, _Automatic = 3, _AppWall = 4, _Overlay = 5 } public enum STAGender { _Undefined = 0, _Female = 1, _Male = 2 } public struct STABannerSize { public SizeF size; public bool isAuto; } }
using System.Collections.Generic; using System.Net.Sockets; using Phenix.Core.Message; using Phenix.Core.Net; using Phenix.Core.Security; using Phenix.Services.Contract; namespace Phenix.Services.Client.Library { internal class MessageProxy : IMessage { #region 属性 private IMessage _service; private IMessage Service { get { if (_service == null) { RemotingHelper.RegisterClientChannel(); _service = (IMessage)RemotingHelper.CreateRemoteObjectProxy(typeof(IMessage), ServicesInfo.MESSAGE_URI); } return _service; } } #endregion #region 方法 private void InvalidateCache() { _service = null; } #region IMessage 成员 public void Send(string receiver, string content, UserIdentity identity) { NetConfig.InitializeSwitch(); do { try { Service.Send(receiver, content, identity); break; } catch (SocketException) { InvalidateCache(); if (!NetConfig.SwitchServicesAddress()) return; } } while (true); } public IDictionary<long, string> Receive(UserIdentity identity) { NetConfig.InitializeSwitch(); do { try { return Service.Receive(identity); } catch (SocketException) { InvalidateCache(); if (!NetConfig.SwitchServicesAddress()) throw; } } while (true); } public void AffirmReceived(long id, bool burn, UserIdentity identity) { NetConfig.InitializeSwitch(); do { try { Service.AffirmReceived(id, burn, identity); break; } catch (SocketException) { InvalidateCache(); if (!NetConfig.SwitchServicesAddress()) return; } } while (true); } #endregion #endregion } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using Photon.Pun; public class PlayerCtrl : MonoBehaviourPun { [SerializeField] private Animator animator; [SerializeField] private float directionDampTime = .25f; //private float speed = 0.0f; private float h = 0.0f; private float v = 0.0f; private bool isStanding; RaycastHit hit; private readonly float MaxDistance = 350f; //Ray의 거리(길이) [Header("IK")] [Tooltip("If true then this script will control IK configuration of the character.")] public bool isIKActive = false; [Header("Interaction Offsets")] [SerializeField, Tooltip("An offset applied to the position of the character when they sit.")] float sittingOffset = -80f; //public Transform leftFootPosition = default; //public Transform rightFootPosition = default; private GameObject target; private void Start() { animator = GetComponent<Animator>(); isStanding = true; if (!animator) { Debug.LogError("PlayerAnimatorManager is Missing Animator Component", this); } } // Update is called once per frame void Update() { if (photonView.IsMine) { h = Input.GetAxis("Horizontal"); v = Input.GetAxis("Vertical"); if (Input.GetKeyDown(KeyCode.Q)) { transform.Rotate(new Vector3(0, -45, 0)); } if (Input.GetKeyDown(KeyCode.E)) { transform.Rotate(new Vector3(0, 45, 0)); } //speed = new Vector2(h, v).sqrMagnitude; animator.SetFloat("Speed", v); animator.SetFloat("Direction", h, directionDampTime, Time.deltaTime); if (Input.GetKeyDown(KeyCode.Space)) { if (isStanding) { //Debug.DrawRay(transform.position, transform.forward * MaxDistance, Color.yellow, 300f); if (Physics.Raycast(transform.position, transform.forward, out hit, MaxDistance) && hit.collider.gameObject.tag == "chair") { target = hit.collider.gameObject; Vector3 pos = target.transform.position; pos.z -= sittingOffset; transform.position = pos; transform.rotation = hit.collider.gameObject.transform.rotation; isIKActive = true; animator.SetBool("isSitting", true); Debug.Log(hit.collider.gameObject.name); isStanding = false; } else { Debug.Log("There's no chair to sit around you!"); return; } } else { animator.SetBool("isSitting", false); isStanding = true; } } //if (animator) photonView.RPC("FlipRPC", RpcTarget.AllBuffered); } //else //{ // Debug.Log("photonView Error"); // return; //} } //[PunRPC] //void FlipRPC() //{ //} //void OnAnimatorIK() //{ // if (!isIKActive) return; // Debug.Log("gooood IK"); // if (rightFootPosition != null) // { // animator.SetIKPositionWeight(AvatarIKGoal.RightFoot, 1); // animator.SetIKRotationWeight(AvatarIKGoal.RightFoot, 1); // animator.SetIKPosition(AvatarIKGoal.RightFoot, rightFootPosition.position); // animator.SetIKRotation(AvatarIKGoal.RightFoot, rightFootPosition.rotation); // } // if (leftFootPosition != null) // { // animator.SetIKPositionWeight(AvatarIKGoal.LeftFoot, 1); // animator.SetIKRotationWeight(AvatarIKGoal.LeftFoot, 1); // animator.SetIKPosition(AvatarIKGoal.LeftFoot, leftFootPosition.position); // animator.SetIKRotation(AvatarIKGoal.LeftFoot, leftFootPosition.rotation); // } //} }
using System; using System.Collections.Generic; using XH.Infrastructure.Domain; using XH.Infrastructure.Domain.Models; using XH.Infrastructure.Identity.MongoDb; namespace XH.Domain.Security { public class User : IdentityUser, IFullAuditableEntity, IEntity, IAggregateRoot, IMayHaveTenant { public User(string email) : base(email) { } public string Name { get; set; } public string Remark { get; set; } public UserType UserType { get; protected set; } public DateTime UtcCreatedOn { get; set; } public string CreatedBy { get; set; } public DateTime? UtcModifiedOn { get; set; } public string ModifiedBy { get; set; } public bool IsDeleted { get; set; } public DateTime? UtcDeletedOn { get; set; } public string DeletedByUserId { get; set; } public bool IsEnterprise { get; set; } public ICollection<string> Permissions { get; set; } public bool IsTransient() { return !string.IsNullOrEmpty(Id); } } }
using System.Collections; using System.Collections.Generic; using System.Runtime.Serialization; namespace Ricky.Infrastructure.Core.DataTables { public class DataTableJsResult<T> { /// <summary> /// Gets the Draw counter for DataTables. /// </summary> //[DataMember(Name = "draw")] public int draw { get; private set; } /// <summary> /// Gets the Data collection. /// </summary> public IEnumerable<T> data { get; set; } /// <summary> /// Gets the total number of records (without filtering - total dataset). /// </summary> public int recordsTotal { get; private set; } /// <summary> /// Gets the resulting number of records after filtering. /// </summary> public int recordsFiltered { get; private set; } //public Paging Paging //{ // get // { // var pagedList = new PagedList<T>(Data,); // return new Paging // { // }; // } //} /// <summary> /// Creates a new DataTables response object with it's elements. /// </summary> /// <param name="draw">The Draw counter as received from the DataTablesRequest.</param> /// <param name="data">The Data collection (data page).</param> /// <param name="recordsFiltered">The resulting number of records after filtering.</param> /// <param name="recordsTotal">The total number of records (total dataset).</param> public DataTableJsResult(int draw, IEnumerable<T> data, int recordsFiltered, int recordsTotal) { this.draw = draw; this.data = data; this.recordsFiltered = recordsFiltered; this.recordsTotal = recordsTotal; } } }
using System; using System.Collections.Generic; namespace DDMedi { internal static class TypeConstant { internal readonly static Type IGenericAsyncSupplierOutputType = typeof(IAsyncSupplier<,>); internal readonly static Type IGenericAsyncSupplierType = typeof(IAsyncSupplier<>); internal readonly static Type IGenericSupplierOutputType = typeof(ISupplier<,>); internal readonly static Type IGenericSupplierType = typeof(ISupplier<>); internal readonly static IReadOnlyList<Type> IGenericSupplierTypes = new Type[] { IGenericAsyncSupplierOutputType, IGenericAsyncSupplierType, IGenericSupplierOutputType, IGenericSupplierType }; internal readonly static Type IGeneralSupplierType = typeof(ISupplier); internal readonly static Type IGenericESupplierType = typeof(IESupplier<>); internal readonly static IReadOnlyList<Type> IGenericESupplierTypes = new Type[] { IGenericESupplierType }; internal readonly static Type IGeneralESupplierType = typeof(IESupplier); internal readonly static IReadOnlyDictionary<Type, IReadOnlyList<Type>> IGenericSupplierTypeDic = new Dictionary<Type, IReadOnlyList<Type>> { [IGeneralSupplierType] = IGenericSupplierTypes, [IGeneralESupplierType] = IGenericESupplierTypes }; internal readonly static Type IGeneralDecoratorType = typeof(IDecorator); internal readonly static Type IGenericAsyncDecoratorOutputType = typeof(IAsyncDecorator<,>); internal readonly static Type IGenericAsyncDecoratorType = typeof(IAsyncDecorator<>); internal readonly static Type IGenericDecoratorOutputType = typeof(IDecorator<,>); internal readonly static Type IGenericDecoratorType = typeof(IDecorator<>); internal readonly static Type IGenericEDecoratorType = typeof(IEDecorator<>); internal readonly static IReadOnlyDictionary<Type, Type> MappedSupplierToDecorator = new Dictionary<Type, Type> { [IGenericAsyncSupplierOutputType] = IGenericAsyncDecoratorOutputType, [IGenericAsyncSupplierType] = IGenericAsyncDecoratorType, [IGenericESupplierType] = IGenericEDecoratorType, [IGenericSupplierOutputType] = IGenericDecoratorOutputType, [IGenericSupplierType] = IGenericDecoratorType }; internal readonly static Type IDDBrokerType = typeof(IDDBroker); internal readonly static Type SupplierDescriptorType = typeof(SupplierDescriptor); internal readonly static Type IGeneralEInputType = typeof(IEInputs); internal readonly static Type ExceptionEInputType = typeof(ExceptionEInputs); } }
using System; using System.Linq; using System.Text; using System.Data; using System.Reflection; using System.Collections.Concurrent; using System.Collections; using System.Collections.Generic; using Dapper; using Dapper.Contrib.Extensions; using System.Configuration; using System.Threading.Tasks; using System.Data.OleDb; using IconCreator.Core.Models.Interfaces; namespace IconCreator.Core.DataAccess { /// <summary> /// Extension class for Dapper with basic Insert, Update and Delete that works on OleDB /// @Author: Federico Ramírez /// @Copyright: Paradigma <http://paradigma.com.ar> /// </summary> public class GenericRepository<T> : IRepository<T> where T : class { #region Properties private bool TransactionActive = true; private OleDbConnection _conn; public OleDbConnection Connection { get { return _conn; } } private string _connectionString; private static readonly ConcurrentDictionary<RuntimeTypeHandle, string> TypeTableName = new ConcurrentDictionary<RuntimeTypeHandle, string>(); private OleDbTransaction transaction; public enum CascadeStyle { Collection, Single, All, None } #endregion public GenericRepository(IUnitOfWork unitOfWork) { unitOfWork.Register(this); } public void Dispose() { if (_conn != null) { if (_conn.State == ConnectionState.Open) { transaction.Dispose(); _conn.Close(); } _conn.Dispose(); } } public async Task<IEnumerable<T>> GetAllAsync() { Type type = typeof(T); string tableName = GetTableName(type); return await this.Connection.QueryAsync<T>("SELECT * FROM [" + tableName + "]", null, transaction); } /// <summary> /// Updates an object on the database when the SubmitChanges method is called /// </summary> /// <typeparam name="T"></typeparam> /// <param name="obj">The object to update</param> /// <param name="cascade">Whether to update child/parent objects too</param> public async Task UpdateOnSubmitAsync(T obj) { CascadeStyle cascade = CascadeStyle.None; if (obj == null) return; if (!TransactionActive) { transaction = _conn.BeginTransaction(); TransactionActive = true; } Type type = typeof(T); string tableName = GetTableName(type); List<string> fields = new List<string>(); List<string> values = new List<string>(); List<object> data = new List<object>(); string pk = "id"; object pkValue = null; foreach (PropertyInfo pi in type.GetProperties()) { bool ispk = (from a in pi.GetCustomAttributes(false) where a.GetType().Name.Equals("KeyAttribute") select a).Any(); if (ispk || pi.Name.Equals(pk, StringComparison.OrdinalIgnoreCase)) { pk = pi.Name; pkValue = pi.GetValue(obj, null); } else { if ((cascade == CascadeStyle.All || cascade == CascadeStyle.Collection) && IsCollection(pi.PropertyType) && pi.GetValue(obj, null) != null) { foreach (var child in pi.GetValue(obj, null) as ICollection) { MethodInfo mi = typeof(GenericRepository<T>).GetMethod("UpdateOnSubmit"); MethodInfo genericMethod = mi.MakeGenericMethod(new Type[] { child.GetType() }); genericMethod.Invoke(this, new Object[] { child, cascade }); } } else if ((cascade == CascadeStyle.All || cascade == CascadeStyle.Single) && !IsPrimitive(pi.PropertyType)) { // If it's not a primitive I'll try to insert it as a child object MethodInfo mi = typeof(GenericRepository<T>).GetMethod("UpdateOnSubmit"); MethodInfo genericMethod = mi.MakeGenericMethod(new Type[] { pi.PropertyType }); genericMethod.Invoke(this, new Object[] { pi.GetValue(obj, null), cascade }); } else { fields.Add("[" + pi.Name + "] = @" + pi.Name); values.Add("@" + pi.Name); data.Add(pi.GetValue(obj, null)); } } } if (pkValue == null) { throw new Exception("Could not find primary key"); } OleDbCommand com = _conn.CreateCommand(); com.Transaction = transaction; com.CommandText = string.Format("UPDATE {0} SET {1} WHERE {2} = {3}", tableName, string.Join(", ", fields), pk, "@" + pk); for (int i = 0; i < values.Count; i++) { com.Parameters.AddWithValue(values[i], data[i]); } com.Parameters.AddWithValue(pk, pkValue); try { await com.ExecuteNonQueryAsync(); } catch { throw; } } /// <summary> /// Deletes the object from the database when the method SubmitChanges is called /// </summary> /// <typeparam name="T"></typeparam> /// <param name="obj"></param> /// <param name="cascade">Whether the child/parent objects will also be deleted /// Note: It's recommended to leave that kind of logic to the database engine</param> public async Task DeleteOnSubmitAsync(T obj) { CascadeStyle cascade = CascadeStyle.None; if (!TransactionActive) { transaction = _conn.BeginTransaction(); TransactionActive = true; } Type type = typeof(T); string tableName = GetTableName(type); string pk = "id"; object pkValue = null; foreach (PropertyInfo pi in type.GetProperties()) { bool ispk = (from a in pi.GetCustomAttributes(false) where a.GetType().Name.Equals("KeyAttribute") select a).Any(); if (ispk || pi.Name.Equals(pk, StringComparison.OrdinalIgnoreCase)) { pk = pi.Name; pkValue = pi.GetValue(obj, null); } else if (cascade != CascadeStyle.None) { if (pi.GetValue(obj, null) == null) continue; if ((cascade == CascadeStyle.Collection || cascade == CascadeStyle.All) && IsCollection(pi.PropertyType)) { foreach (var child in pi.GetValue(obj, null) as ICollection) { MethodInfo mi = typeof(GenericRepository<T>).GetMethod("DeleteOnSubmit"); MethodInfo genericMethod = mi.MakeGenericMethod(new Type[] { child.GetType() }); genericMethod.Invoke(this, new Object[] { child, cascade }); } } else if ((cascade == CascadeStyle.Single || cascade == CascadeStyle.All) && !IsPrimitive(pi.PropertyType)) { MethodInfo mi = typeof(GenericRepository<T>).GetMethod("DeleteOnSubmit"); MethodInfo genericMethod = mi.MakeGenericMethod(new Type[] { pi.PropertyType }); genericMethod.Invoke(this, new Object[] { pi.GetValue(obj, null), cascade }); } } } OleDbCommand com = _conn.CreateCommand(); com.Transaction = transaction; com.CommandText = "DELETE FROM " + tableName + " WHERE [" + pk + "] = " + pkValue; await com.ExecuteNonQueryAsync(); } // TODO: Use MSIL or something better than default reflection... /// <summary> /// Adds an object to the insertion queue /// </summary> /// <typeparam name="T"></typeparam> /// <param name="obj"></param> /// <returns>The id of the inserted object</returns> public async Task InsertOnSubmitAsync(T obj) { if (!TransactionActive) { transaction = _conn.BeginTransaction(); TransactionActive = true; } Type type = typeof(T); string tableName = GetTableName(type); List<string> names = new List<string>(); List<string> values = new List<string>(); List<object> data = new List<object>(); foreach (PropertyInfo pi in type.GetProperties()) { bool ispk = (from a in pi.GetCustomAttributes(false) where a.GetType().Name.Equals("KeyAttribute") select a).Any(); if (IsCollection(pi.PropertyType) && pi.GetValue(obj, null) != null) { foreach (var child in pi.GetValue(obj, null) as ICollection) { MethodInfo mi = typeof(GenericRepository<T>).GetMethod("InsertOnSubmit"); MethodInfo genericMethod = mi.MakeGenericMethod(new Type[] { child.GetType() }); genericMethod.Invoke(this, new Object[] { child }); } } else if (!IsPrimitive(pi.PropertyType)) { // If it's not a primitive I'll try to insert it as a child object MethodInfo mi = typeof(GenericRepository<T>).GetMethod("InsertOnSubmit"); MethodInfo genericMethod = mi.MakeGenericMethod(new Type[] { pi.PropertyType }); int id = (int)genericMethod.Invoke(this, new Object[] { pi.GetValue(obj, null) }); if (id > 0) { // If the value was not null // Check the foreign key var fk = (from a in pi.GetCustomAttributes(false) where a.GetType().Name.Equals("ForeignKeyAttribute") select a).FirstOrDefault() as dynamic; string fkString = pi.Name + "Id"; if (fk != null) fkString = fk.Name; names.Add("[" + fkString + "]"); values.Add("?"); data.Add(id); } } else { names.Add("[" + pi.Name + "]"); values.Add("?"); data.Add(pi.GetValue(obj, null)); } } var query = string.Format("INSERT INTO {0} ({1}) VALUES ({2})", tableName, string.Join(", ", names), string.Join(", ", values)); OleDbCommand com = new OleDbCommand(query, _conn); com.Transaction = transaction; for (int i = 0; i < values.Count; i++) { IDbDataParameter p = com.CreateParameter(); p.ParameterName = values[i]; p.Value = data[i]; com.Parameters.Add(p); } try { await com.ExecuteNonQueryAsync(); } catch { throw; } } public async Task<T> GetAsync(string pkValue, string pkField = null) { Type type = typeof(T); string tableName = GetTableName(type); // get the primary key field string pk; if (!string.IsNullOrEmpty(pkField)) { pk = pkField; } else { pk = "id"; foreach (PropertyInfo pi in type.GetProperties()) { bool ispk = (from a in pi.GetCustomAttributes(false) where a.GetType().Name.Equals("KeyAttribute") select a).Any(); if (ispk || pi.Name.Equals(pk, StringComparison.OrdinalIgnoreCase)) { pk = pi.Name; break; } } } var obj = await this.Connection.QueryAsync<T>("SELECT * FROM [" + tableName + "] WHERE [" + pk + "] = '" + pkValue + "'", null, transaction); return obj.FirstOrDefault(); } public bool SubmitChanges() { if (TransactionActive) { try { transaction.Commit(); } catch { transaction.Rollback(); throw; } } TransactionActive = false; transaction.Dispose(); return true; } private bool IsCollection(System.Type type) { return type.IsGenericType && type.GetGenericTypeDefinition() == typeof(ICollection<>); } private bool IsPrimitive(System.Type type) { return type.IsPrimitive || type == typeof(Char) || type == typeof(String) || type == typeof(Decimal) || type == typeof(DateTime); } private string GetTableName(Type type) { string name; if (!TypeTableName.TryGetValue(type.TypeHandle, out name)) { name = type.Name + "s"; if (type.IsInterface && name.StartsWith("I")) name = name.Substring(1); //NOTE: This as dynamic trick should be able to handle both our own Table-attribute as well as the one in EntityFramework var tableattr = type.GetCustomAttributes(false).Where(attr => attr.GetType().Name == "TableAttribute").SingleOrDefault() as dynamic; if (tableattr != null) name = tableattr.Name; TypeTableName[type.TypeHandle] = name; } return name; } public void SetConnectionString(string connectionString) { if (!string.IsNullOrWhiteSpace(connectionString)) { _connectionString = connectionString; _conn = new System.Data.OleDb.OleDbConnection(_connectionString); _conn.Open(); transaction = _conn.BeginTransaction(); } } } #region Attributes for classes and properties [AttributeUsage(AttributeTargets.Class)] public class TableAttribute : Attribute { public TableAttribute(string tableName) { Name = tableName; } public string Name { get; private set; } } [AttributeUsage(AttributeTargets.Property)] public class KeyAttribute : Attribute { } [AttributeUsage(AttributeTargets.Property)] public class ForeignKeyAttribute : Attribute { public ForeignKeyAttribute(string fkName) { Name = fkName; } public string Name { get; private set; } } #endregion }
using System; using System.IO; public class GClass0 { public Stream stream_0; public GClass0(Stream stream_1) { this.stream_0 = stream_1; } public virtual int vmethod_0() { throw new NotImplementedException(); } public virtual uint vmethod_1() { throw new NotImplementedException(); } public virtual void vmethod_2(int int_0) { throw new NotImplementedException(); } public virtual void vmethod_3(uint uint_0) { throw new NotImplementedException(); } public byte method_0() { return (byte)this.stream_0.ReadByte(); } public void method_1(byte byte_0) { this.stream_0.WriteByte(byte_0); } public void method_2(byte[] byte_0) { this.stream_0.Write(byte_0, 0, byte_0.Length); } public byte[] method_3(int int_0) { byte[] array = new byte[int_0]; this.stream_0.Read(array, 0, int_0); return array; } public void method_4(byte[] byte_0, int int_0, int int_1) { this.stream_0.Write(byte_0, int_0, int_1); } public long method_5() { return this.stream_0.Position; } public void method_6(long long_0) { this.stream_0.Position = long_0; } public void method_7(long long_0) { byte[] byte_ = new byte[256]; while (long_0 > 0L) { int num = (int)Math.Min(256L, long_0); this.method_4(byte_, 0, num); long_0 -= (long)num; } } public void method_8(long long_0) { if (long_0 < this.method_5()) { throw new ArgumentException(); } this.method_7(long_0 - this.method_5()); } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class OneWayDropDown : MonoBehaviour { [SerializeField] BoxCollider2D box; //TODO add a trigger to use instead to see if it is more consistent private void OnCollisionStay2D(Collision2D collision) { if(collision.gameObject.tag == "Player") { if (collision.gameObject.GetComponent<PlayerController>().dropDown == true) { Physics2D.IgnoreCollision(box, collision.gameObject.GetComponent<CapsuleCollider2D>()); Debug.Log(Physics2D.GetIgnoreCollision(box, collision.gameObject.GetComponent<CapsuleCollider2D>())); } } } private void OnTriggerExit2D(Collider2D collision) { if(collision.gameObject.tag == "Player") { Physics2D.IgnoreCollision(box, collision.gameObject.GetComponent<CapsuleCollider2D>(), false); } } }
using ChannelMonitor.Models; using CHM_Site_V3_RedBox.Models; using ModelChannelMonitor; using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace CHM_Site_V3_RedBox.Controllers { public class SitesController : Controller { readonly Repository rep = new Repository(); public ActionResult Index() { return View(); } public ActionResult GetSites() { return Json(new { sites = rep.Sites() }, JsonRequestBehavior.AllowGet); } [HttpPost] public void SendPlataforma(tbl_Plataforma plataforma) { Session["plataforma"] = plataforma; } [HttpPost] public bool SaveSite(tbl_Sites site) { site.cadastro = DateTime.Now; return rep.SaveSite(site); } [HttpPost] public bool RemoveSite(tbl_Sites site) { return rep.RemoveSite(site); } } }
using Microsoft.EntityFrameworkCore; namespace ICE_API.models { public class DataContext : DbContext { public DataContext(DbContextOptions<DataContext> options) : base(options) { } public DbSet<Admin> Admins { get; set; } public DbSet<Status> Statuses { get; set; } public DbSet<Category> Categories { get; set; } public DbSet<Duration> Durations { get; set; } public DbSet<AgeCategory> AgeCategories { get; set; } public DbSet<Person> People { get; set; } public DbSet<Project> Projects { get; set; } public DbSet<Initiatif> Initiatifs { get; set; } public DbSet<Chalange> chalanges { get; set; } protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.Entity<Admin>().ToTable("Admin"); modelBuilder.Entity<Status>().ToTable("Status"); modelBuilder.Entity<Category>().ToTable("Category"); modelBuilder.Entity<Person>().ToTable("Person"); modelBuilder.Entity<Project>().ToTable("Project"); modelBuilder.Entity<Initiatif>().ToTable("Initiatif"); modelBuilder.Entity<Chalange>().ToTable("Chalange"); modelBuilder.Entity<AgeCategory>().ToTable("AgeCategory"); modelBuilder.Entity<Duration>().ToTable("Duration"); } } }
using CalculaJurosWebAPI.Models; using Microsoft.AspNetCore.Mvc; namespace CalculaJurosWebAPI.Controllers { [Route("[controller]")] [ApiController] public class CalculaJurosController : ControllerBase { [HttpGet] public CalculaJuros Get(string valorinicial, string meses) { CalculaJuros res = new CalculaJuros(); res.CalculaResultado(valorinicial, meses); return res; } } }
using System; using Utilities; namespace EddiEvents { [PublicAPI] public class SafeEvent : Event { public const string NAME = "Safe"; public const string DESCRIPTION = "Triggered when you are no longer in danger"; public const string SAMPLE = null; public SafeEvent(DateTime timestamp) : base(timestamp, NAME) { } } }
using System; using System.Windows.Input; using Inventory.Common; using Inventory.ViewModels; using Linphone; using Linphone.Model; using Windows.Devices.Enumeration; using Windows.Media.Devices; namespace Inventory.Services { public class AudioParametersViewModel : ViewModelBase { public AudioParametersViewModel(ICommonServices commonServices) : base(commonServices) { ReadLinphoneSoundDevice(); ReadSoundDevice(); } public ICommand SaveAudioParametrsCommand => new RelayCommand(OnSaveAudioParametrs); private bool _echocancellation; public bool Echocancellation { get { return _echocancellation; } set { Set(ref _echocancellation, value); } } private DeviceInformationCollection _speakersDevices; public DeviceInformationCollection SpeakersDevices { get { return _speakersDevices; } set { Set(ref _speakersDevices, value); } } private string _speakerDeviceId; public string SpeakerDeviceId { get { return _speakerDeviceId; } set { Set(ref _speakerDeviceId, value); } } private DeviceInformationCollection _microphoneDevices; public DeviceInformationCollection MicrophoneDevices { get { return _microphoneDevices; } set { Set(ref _microphoneDevices, value); } } private string _microphoneDeviceId; public string MicrophoneDeviceId { get { return _microphoneDeviceId; } set { Set(ref _microphoneDeviceId, value); } } private DeviceInformationCollection _ringerDevices; public DeviceInformationCollection RingerDevices { get { return _ringerDevices; } set { Set(ref _ringerDevices, value); } } private string _ringerDeviceId; public string RingerDeviceId { get { return _ringerDeviceId; } set { Set(ref _ringerDeviceId, value); } } private string _linphoneSpeakerDeviceName = ""; private string _linphoneMicrophoneDeviceName = ""; private string _linphoneRingerDeviceName = ""; private void OnSaveAudioParametrs() { //LinphoneManager.Instance.Core.Config.SetString("sound", "playback_dev_id", "WASAPI: " + SpeakerDeviceId); //LinphoneManager.Instance.Core.Config.SetString("sound", "capture_dev_id", "WASAPI: " + MicrophoneDeviceId); ////LinphoneManager.Instance.Core.Config.SetString("sound", "capture_dev_id", "WASAPI: " + "Microphone (A4TECH USB2.0 Camera (Audio))"); //LinphoneManager.Instance.Core.Config.SetString("sound", "ringer_dev_id", "WASAPI: " + RingerDeviceId); //LinphoneManager.Instance.Core.Config.SetString("sound", "playback_gain_db", "1.0"); //LinphoneManager.Instance.Core.Config.SetString("sound", "mic_gain_db", "1.0"); //LinphoneManager.Instance.Core.Config.SetString("sound", "echocancellation", (Echocancellation ? 1 : 0).ToString()); //LinphoneManager.Instance.Core.Config.SetString("sound", "ec_filter", "MSWebRTCAEC"); //LinphoneManager.Instance.Core.Config.Sync(); //string ss=LinphoneManager.Instance.Core.Config.GetString("sound", "capture_dev_id", "WASAPI: " + MicrophoneDeviceId); Core lc = LinphoneManager.Instance.Core; //ProxyConfig _cfg = lc.DefaultProxyConfig; lc.PlaybackDevice = "WASAPI: " + SpeakerDeviceId; lc.CaptureDevice = "WASAPI: " + MicrophoneDeviceId; // Микрофон (A4TECH USB2.0 Camera (Audio)) //lc.CaptureDevice = "WASAPI: Микрофон (Устройство с поддержкой High Definition Audio)"; //lc.CaptureDevice = "WASAPI: " + "Микрофон(A4TECH USB2.0 Camera (Audio))"; lc.RingerDevice = "WASAPI: " + RingerDeviceId; lc.PlaybackGainDb = 1.0F; lc.MicGainDb = 1.0F; lc.EchoCancellationEnabled = Echocancellation; lc.EchoCancellerFilterName = "MSWebRTCAEC"; lc.ReloadSoundDevices(); //LinphoneManager.Instance.SpeakerEnabled=true; } private void ReadLinphoneSoundDevice() { _linphoneMicrophoneDeviceName = LinphoneManager.Instance.Core.CaptureDevice; _linphoneRingerDeviceName = LinphoneManager.Instance.Core.RingerDevice; _linphoneSpeakerDeviceName = LinphoneManager.Instance.Core.PlaybackDevice; _echocancellation = LinphoneManager.Instance.Core.EchoCancellationEnabled; } private async void ReadSoundDevice() { AudioDeviceRole role = AudioDeviceRole.Default; string MicrophoneDeviceId_ = MediaDevice.GetDefaultAudioCaptureId(role); string SpeakerDeviceId_ = MediaDevice.GetDefaultAudioRenderId(role); string RingerDeviceId_ = MediaDevice.GetDefaultAudioRenderId(role); SpeakersDevices = await DeviceInformation.FindAllAsync(MediaDevice.GetAudioRenderSelector()); SpeakerDeviceId = ""; foreach (var dev in SpeakersDevices) { if (_linphoneSpeakerDeviceName == "WASAPI: " + dev.Name) SpeakerDeviceId = dev.Name; } if (String.IsNullOrEmpty(SpeakerDeviceId)) { foreach (var dev in SpeakersDevices) { if (SpeakerDeviceId_ == dev.Id) SpeakerDeviceId = dev.Name; } } RingerDevices = await DeviceInformation.FindAllAsync(MediaDevice.GetAudioRenderSelector()); RingerDeviceId = ""; foreach (var dev in RingerDevices) { if (_linphoneRingerDeviceName == "WASAPI: " + dev.Name) RingerDeviceId = dev.Name; } if (String.IsNullOrEmpty(RingerDeviceId)) foreach (var dev in RingerDevices) { { if (RingerDeviceId_ == dev.Id) RingerDeviceId = dev.Name; } } MicrophoneDevices = await DeviceInformation.FindAllAsync(MediaDevice.GetAudioCaptureSelector()); MicrophoneDeviceId = ""; foreach (var dev in MicrophoneDevices) { if (_linphoneMicrophoneDeviceName == "WASAPI: " + dev.Name) MicrophoneDeviceId = dev.Name; } if (String.IsNullOrEmpty(MicrophoneDeviceId)) { foreach (var dev in MicrophoneDevices) { if (MicrophoneDeviceId_ == dev.Id) MicrophoneDeviceId = dev.Name; } } } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class Shield : MonoBehaviour { [SerializeField] private Shader _shader; private Material _mat; [SerializeField] private Texture _texture; [SerializeField] private Color _color; [SerializeField] private float _tiling = 1, _fallOff = 1, _warp = 1, _timeMulti = 1, _noiseMulti = 1, _noisePow = 1; void Start () { _mat = new Material(_shader); SetUniforms(_mat); GetComponent<MeshRenderer>().material = _mat; } private void Update() { _mat.SetFloat("_time", Time.timeSinceLevelLoad * _timeMulti); } private void OnValidate() { if (!Application.isPlaying || _mat == null) return; SetUniforms(_mat); } private void SetUniforms(Material mat) { _mat.SetTexture("_MainTex", _texture); _mat.SetFloat("_tiling", _tiling); _mat.SetFloat("_fallOff", _fallOff); _mat.SetFloat("_warp", _warp); _mat.SetColor("_baseColor", _color); _mat.SetFloat("_noiseMulti", _noiseMulti); _mat.SetFloat("_noisePow", _noisePow); } public Color color { set {_color = value; OnValidate ();} } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Meshop.Framework.Model; namespace Meshop.Framework.Services { /// <summary> /// Front web page services /// </summary> public interface IFront { IEnumerable<MenuItem> Menu(); bool IsAdmin(System.Security.Principal.IPrincipal customer); IEnumerable<BasicCategory> CategoryTree(); } }
using BP12; using DChild.Gameplay.Environment; using Sirenix.OdinInspector; using System.Collections; using System.Collections.Generic; using UnityEngine; namespace DChild.Gameplay.Pathfinding { public class NavigationManager : SingletonBehaviour<NavigationManager> { [SerializeField] private PathFindingSerializationFile m_serializationFile; private static bool m_recalculatePathAfterScan; private static List<NavigationTracker> m_trackers; public void Load(Location location, uint zoneID) { var graph = m_serializationFile.GetGraphs(location, zoneID); AstarPath.active.data.DeserializeGraphs(graph.bytes); } public static void Register(NavigationTracker tracker) { if (m_trackers.Contains(tracker) == false) { m_trackers.Add(tracker); } } public static void Unregister(NavigationTracker tracker) { if (m_trackers.Contains(tracker)) { m_trackers.Remove(tracker); } } [Button("AdditiveTest")] private void AdditiveTest() { var graph = m_serializationFile.GetGraphs(Location.RealmOfNightmare, 0); AstarPath.active.data.DeserializeGraphsAdditive(graph.bytes); } protected override void Awake() { base.Awake(); m_trackers = new List<NavigationTracker>(); } private void Update() { if (AstarPath.active.isScanning) { m_recalculatePathAfterScan = true; } else if (m_recalculatePathAfterScan) { for (int i = 0; i < m_trackers.Count; i++) { m_trackers[i].RecalcuatePath(); } m_recalculatePathAfterScan = false; } } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using DG.Tweening; public class DestroyObject : MonoBehaviour { public void destroyobjects() { Destroy(this.gameObject); } }
using System.Collections; using System.Collections.Generic; using UnityEngine; [System.Serializable] public class MultiDimensionalInt { public int[] intArray; }
using HtmlAgilityPack; using Newtonsoft.Json; using System; using System.Collections; using System.Collections.Generic; using System.Collections.Specialized; using System.Configuration; using System.IO; using System.Linq; using System.Net; using System.Text; using System.Text.RegularExpressions; using System.Threading.Tasks; using System.Windows.Forms; namespace ConfluenceEditor { public class ConfluenceApiHelper { private static ConfluenceApiHelper _helper = new ConfluenceApiHelper(); private string _boundary = "---------------------------" + DateTime.Now.Ticks.ToString("x"); private const string _baseUri = "https://sageone.atlassian.net/wiki/"; private const string _uri = _baseUri + "rest/api"; private ArrayList _pages = new ArrayList(); private Dictionary<string, ConfluencePages> _pagesHash = new Dictionary<string, ConfluencePages>(); private string regExAmp = "&([^(nbsp;)(amp;)(eacute;)(egrave;)(agrave;)(acirc;)(ecirc;)(icirc;)(ucirc;)(ocirc;)(quot;)(raquo;)(laquo;)(rsquo;)])"; public ConfluenceApiHelper() { _readConfig(); } public static ConfluenceApiHelper Instance { get { return _helper; } } public ConfluencePages[] Pages { get { return _pages.Cast<ConfluencePages>().ToArray<ConfluencePages>(); } } private void _addAuth(HttpWebRequest request) { string authString = ConfluenceUser + ":" + ConfluencePass; string authHeader = System.Convert.ToBase64String(Encoding.UTF8.GetBytes(authString)); request.Headers.Add("Authorization", "Basic " + authHeader); } private static string ProxyUrl; private static string ProxyUser; private static string ProxyPass; private static string ConfluenceUser; private static string ConfluencePass; private static string ConfluenceSpace; private void _readConfig() { Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); foreach (string key in config.AppSettings.Settings.AllKeys) { if (key.Equals("Proxy.Url")) ProxyUrl = config.AppSettings.Settings[key].Value; else if (key.Equals("Proxy.User")) ProxyUser = config.AppSettings.Settings[key].Value; else if (key.Equals("Proxy.Pass")) ProxyPass = config.AppSettings.Settings[key].Value; else if (key.Equals("Confluence.User")) ConfluenceUser = config.AppSettings.Settings[key].Value; else if (key.Equals("Confluence.Pass")) ConfluencePass = config.AppSettings.Settings[key].Value; else if (key.Equals("Confluence.Space")) ConfluenceSpace = config.AppSettings.Settings[key].Value; } } private void _setProxy(HttpWebRequest request) { if (string.IsNullOrEmpty(ProxyUrl)) return; IWebProxy proxy = request.Proxy; WebProxy myProxy = new WebProxy(); Uri newUri = new Uri(ProxyUrl); myProxy.Address = newUri; myProxy.Credentials = new NetworkCredential(ProxyUser, ProxyPass); request.Proxy = myProxy; } public void Populate(int start) { //string url = _uri + "/content?spaceKey=" + ConfluenceSpace + "&limit=500"; string url = _uri + "/content?spaceKey=" + ConfluenceSpace + "&limit=500&start="+start; if (start==0) { _pages.Clear(); _pagesHash.Clear(); } HttpWebRequest wr = (HttpWebRequest)WebRequest.Create(url); wr.Method = "GET"; _addAuth(wr); _setProxy(wr); try { using (WebResponse wresp = wr.GetResponse()) { using (StreamReader reader = new StreamReader(wresp.GetResponseStream())) { string res = reader.ReadToEnd(); dynamic dynObj = JsonConvert.DeserializeObject(res); foreach (dynamic child in dynObj.results) { ConfluencePages page = new ConfluencePages(child.id.Value, child.title.Value); _pages.Add(page); _pagesHash[child.id.Value] = page; } } } } catch (Exception ex) { Console.Out.WriteLine("Error uploading file", ex); } } public dynamic GetExistingResource(string resId) { string url = _uri + "/content/" + resId + "?expand=body.storage,version"; string json = ""; HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url); _addAuth(request); _setProxy(request); using (HttpWebResponse response = (HttpWebResponse)request.GetResponse()) { using (StreamReader reader = new StreamReader(response.GetResponseStream())) { json = reader.ReadToEnd(); } } dynamic dynObj = JsonConvert.DeserializeObject(json); return dynObj; } public static string Beautifer(string input) { HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument(); doc.OptionWriteEmptyNodes = true; doc.OptionFixNestedTags = true; doc.LoadHtml(input); StringBuilder builder = new StringBuilder(); StringWriter wr = new StringWriter(builder); using (XmlHtmlFullIndentWriter writer = new XmlHtmlFullIndentWriter(wr)) { writer.Settings.OmitXmlDeclaration = true; writer.Settings.ConformanceLevel = System.Xml.ConformanceLevel.Fragment; writer.Settings.DoNotEscapeUriAttributes = true; //writer.Settings.OutputMethod = System.Xml.XmlOutputMethod.Html; writer.Settings.Encoding = Encoding.UTF8; writer.ForceFormat = true; writer.WriteXmlHeader = false; writer.Formatting = System.Xml.Formatting.Indented; doc.Save(writer); string st = builder.ToString(); int idx = st.IndexOf("\n"); st = st.Substring(idx + 1); st = specialEntityToCharAmp(st); return st; } } private static string specialEntityToCharAmp(string input) { input = input.Replace("_ac3a_", "ac:"); // A input = input.Replace("&amp;agrave;", "à"); input = input.Replace("&amp;aacute;", "á"); input = input.Replace("&amp;acirc,;", "â"); input = input.Replace("&amp;auml,;", "ä"); input = input.Replace("&amp;aelig,;", "æ"); input = input.Replace("&amp;Agrave;", "À"); input = input.Replace("&amp;Aacute;", "Á"); input = input.Replace("&amp;Acirc,;", "Â"); input = input.Replace("&amp;Auml,;", "Ä"); input = input.Replace("&amp;Aelig,;", "Æ"); // E input = input.Replace("&amp;eacute;", "é"); input = input.Replace("&amp;egrave;", "è"); input = input.Replace("&amp;ecirc;", "ê"); input = input.Replace("&amp;euml;", "ë"); input = input.Replace("&amp;Eacute;", "É"); input = input.Replace("&amp;Egrave;", "È"); input = input.Replace("&amp;Ecirc;", "Ê"); input = input.Replace("&amp;Euml;", "Ë"); // I input = input.Replace("&amp;icirc;", "î"); input = input.Replace("&amp;iuml;", "ï"); input = input.Replace("&amp;Icirc;", "Î"); input = input.Replace("&amp;Iuml;", "Ï"); // O input = input.Replace("&amp;ocirc;", "ô"); input = input.Replace("&amp;Ocirc;", "Ô"); // U input = input.Replace("&amp;ucirc;", "ù"); input = input.Replace("&amp;ucirc;", "û"); input = input.Replace("&amp;uuml;", "ü"); input = input.Replace("&amp;Ucirc;", "Ù"); input = input.Replace("&amp;Ucirc;", "Û"); input = input.Replace("&amp;Uuml;", "Ü"); // Ç input = input.Replace("&amp;ccedil;", "ç"); input = input.Replace("&amp;Ccedil;", "Ç"); // Miscellaneous input = input.Replace("&amp;nbsp;", "&nbsp;"); input = input.Replace("&amp;quot;", "\""); input = input.Replace("&amp;raquo;", "\""); input = input.Replace("&amp;laquo;", "\""); input = input.Replace("&amp;amp;", "&"); input = input.Replace("&amp;rsquo;", "'"); input = input.Replace("<!--DATA[", "<![CDATA["); input = input.Replace("-->", "]]>"); return input; } private static string specialEntityToChar(string input) { // A input = input.Replace("&agrave;", "à"); input = input.Replace("&aacute;", "á"); input = input.Replace("&acirc,;", "â"); input = input.Replace("&auml,;", "ä"); input = input.Replace("&aelig,;", "æ"); input = input.Replace("&Agrave;", "À"); input = input.Replace("&Aacute;", "Á"); input = input.Replace("&Acirc,;", "Â"); input = input.Replace("&Auml,;", "Ä"); input = input.Replace("&Aelig,;", "Æ"); // E input = input.Replace("&eacute;", "é"); input = input.Replace("&egrave;", "è"); input = input.Replace("&ecirc;", "ê"); input = input.Replace("&euml;", "ë"); input = input.Replace("&Eacute;", "É"); input = input.Replace("&Egrave;", "È"); input = input.Replace("&Ecirc;", "Ê"); input = input.Replace("&Euml;", "Ë"); // I input = input.Replace("&icirc;", "î"); input = input.Replace("&iuml;", "ï"); input = input.Replace("&Icirc;", "Î"); input = input.Replace("&Iuml;", "Ï"); // O input = input.Replace("&ocirc;", "ô"); input = input.Replace("&Ocirc;", "Ô"); // U input = input.Replace("&ucirc;", "ù"); input = input.Replace("&ucirc;", "û"); input = input.Replace("&uuml;", "ü"); input = input.Replace("&Ucirc;", "Ù"); input = input.Replace("&Ucirc;", "Û"); input = input.Replace("&Uuml;", "Ü"); // Ç input = input.Replace("&ccedil;", "ç"); input = input.Replace("&Ccedil;", "Ç"); // Miscellaneous input = input.Replace("&quot;", "\""); input = input.Replace("&raquo;", "\""); input = input.Replace("&laquo;", "\""); input = input.Replace("&amp;", "&"); input = input.Replace("&rsquo;", "'"); return input; } private static string charToSpecialEntity(string input) { // A input = input.Replace("à", "&agrave;"); input = input.Replace("á", "&aacute;"); input = input.Replace("â", "&acirc,;"); input = input.Replace("ä", "&auml,;"); input = input.Replace("æ", "&aelig,;"); input = input.Replace("À", "&Agrave;"); input = input.Replace("Á", "&Aacute;"); input = input.Replace("Â", "&Acirc,;"); input = input.Replace("Ä", "&Auml,;"); input = input.Replace("Æ", "&Aelig,;"); // E input = input.Replace("é", "&eacute;"); input = input.Replace("è", "&egrave;"); input = input.Replace("ê", "&ecirc;"); input = input.Replace("ë", "&euml;"); input = input.Replace("É", "&Eacute;"); input = input.Replace("È", "&Egrave;"); input = input.Replace("Ê", "&Ecirc;"); input = input.Replace("Ë", "&Euml;"); // I input = input.Replace("î", "&icirc;"); input = input.Replace("ï", "&iuml;"); input = input.Replace("Î", "&Icirc;"); input = input.Replace("Ï", "&Iuml;"); // O input = input.Replace("ô", "&ocirc;"); input = input.Replace("Ô", "&Ocirc;"); // U input = input.Replace("ù", "&ucirc;"); input = input.Replace("û", "&ucirc;"); input = input.Replace("ü", "&uuml;"); input = input.Replace("Ù", "&Ucirc;"); input = input.Replace("Û", "&Ucirc;"); input = input.Replace("Ü", "&Uuml;"); // Ç input = input.Replace("ç", "&ccedil;"); input = input.Replace("Ç", "&Ccedil;"); // Miscellaneous input = input.Replace("\"", "&quot;"); input = input.Replace("&", "&amp;"); input = input.Replace("'", "&rsquo;"); return input; } public string CreateNewEmptyDocument(string parent, string name) { string url = _uri + "/content/"; //This creates a page in a space. string json; if (parent == "") { json = "{\"type\":\"page\", \"title\":\"" + name + "\", \"space\":{\"key\":\"" + ConfluenceSpace + "\"}," + "\"body\":{\"storage\":{\"value\":\"<p>This is a new page</p>\",\"representation\":\"storage\"}}}"; } else { json = "{\"ancestors\": [{\"id\":"+ parent + "}], \"type\":\"page\", \"title\":\"" + name + "\", \"space\":{\"key\":\"" + ConfluenceSpace + "\"}," + "\"body\":{\"storage\":{\"value\":\"<p>This is a new page</p>\",\"representation\":\"storage\"}}}"; } dynamic dynObj = JsonConvert.DeserializeObject(json); System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding(); byte[] arr = encoding.GetBytes(json); HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url); _addAuth(request); _setProxy(request); request.ContentType = "application/json"; request.Method = "POST"; request.ContentLength = arr.Length; Stream dataStream = request.GetRequestStream(); dataStream.Write(arr, 0, arr.Length); dataStream.Close(); string sResponse = ""; try { using (HttpWebResponse response = (HttpWebResponse)request.GetResponse()) { using (StreamReader reader = new StreamReader(response.GetResponseStream())) { sResponse = reader.ReadToEnd(); dynamic dynObjRes = JsonConvert.DeserializeObject(sResponse); return dynObjRes.id.Value; } } } catch (Exception ex) { return null; } } public void SaveDoc(string id, string text) { string url = _uri + "/content/" + id + "?expand=body.storage,version"; dynamic dynObj = GetExistingResource(id); int currentVersion = dynObj.version.number; dynObj.version.number = currentVersion + 1; dynObj.body.storage.value = text; string json = JsonConvert.SerializeObject(dynObj); System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding(); byte[] arr = encoding.GetBytes(json); HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url); _addAuth(request); _setProxy(request); request.ContentType = "application/json"; request.Method = "PUT"; request.ContentLength = arr.Length; Stream dataStream = request.GetRequestStream(); dataStream.Write(arr, 0, arr.Length); dataStream.Close(); try { string sResponse = ""; using (HttpWebResponse response = (HttpWebResponse)request.GetResponse()) { using (StreamReader reader = new StreamReader(response.GetResponseStream())) { sResponse = reader.ReadToEnd(); } } } catch (Exception ex) { MessageBox.Show(ex.Message + " " + ex.ToString()); } } public void DeleteDoc(string nodeId) { string url = _uri + "/content/" + nodeId; HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url); _addAuth(request); _setProxy(request); request.Method = "DELETE"; Stream dataStream = request.GetRequestStream(); dataStream.Close(); string sResponse = ""; using (HttpWebResponse response = (HttpWebResponse)request.GetResponse()) { using (StreamReader reader = new StreamReader(response.GetResponseStream())) { sResponse = reader.ReadToEnd(); } } } public string LoadHtml(string id, string fullPath, bool loadAttachment) { string title = ""; return LoadHtml(id, fullPath, loadAttachment, ref title); } public string LoadHtml(string id, string fullPath, bool loadAttachment, ref string title) { HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument(); doc.OptionWriteEmptyNodes = true; doc.Load(fullPath, Encoding.UTF8); DirectoryInfo baseDir = new FileInfo(fullPath).Directory; // Manage <img> links HtmlNodeCollection imgNode = doc.DocumentNode.SelectNodes("//img[@src]"); if (imgNode != null) { StringCollection images = new StringCollection(); foreach (HtmlNode link in imgNode) { HtmlAttribute att = link.Attributes["src"]; string src = att.Value; string imageFileName = null; if (src.StartsWith("data:")) { // image is embeded in the html with a base 64 encoding. We must create a file and join it to the page imageFileName = Guid.NewGuid().ToString("B").ToLower().Substring(1, 36) + "." + src.Substring(src.IndexOf("/")+1,3); //StreamWriter imageFile = new StreamWriter(baseDir.FullName + "\\..\\temp\\" + imageFileName); File.WriteAllBytes(baseDir.FullName + "\\..\\temp\\" + imageFileName, Convert.FromBase64String(src.Substring(src.IndexOf(",")+1))); src = "../temp/" + imageFileName; } if ((src != "") && (!src.Contains("https://oursageplace"))) { MainForm.UpdateStatus("Start upload attachment : " + src); int posLastSlash = src.LastIndexOf("/"); string nameResource = src.Substring(posLastSlash + 1); if (src.StartsWith("http://open.sage.com/handler") || src.StartsWith("https://open.sage.com/handler")) { // Remove the URL and keep only the page id and the image name int posPrevLastSlash = src.Substring(0, posLastSlash - 1).LastIndexOf("/"); src = src.Substring(posPrevLastSlash + 1, posLastSlash - posPrevLastSlash - 1) + "\\" + src.Substring(posLastSlash + 1); } if (loadAttachment) if (!images.Contains(nameResource)) { UploadAttachment(id, nameResource, baseDir.FullName + "\\" + src, "image/jpeg"); MainForm.UpdateStatus("End upload attachment : " + src); images.Add(nameResource); } else { MainForm.UpdateStatus("Attachment already uploaded : " + src); } att.Value = _baseUri + "/download/attachments/" + id + "/" + nameResource; } if (imageFileName != null) File.Delete(baseDir.FullName + "\\..\\temp\\" + imageFileName); } } // Manage <link> links HtmlNode lastCssNode = null; HtmlNodeCollection hrefNode = doc.DocumentNode.SelectNodes("//link[@href]"); if (hrefNode != null) { StringCollection links = new StringCollection(); foreach (HtmlNode link in hrefNode) { HtmlAttribute att = link.Attributes["href"]; string src = att.Value; if ((src != "") && (!src.Contains("https://oursageplace"))) { int pos1 = src.LastIndexOf("/"); string nameResource = src.Substring(pos1 + 1); MainForm.UpdateStatus("Start upload css : " + src); if (loadAttachment) if (!links.Contains(nameResource)) { UploadAttachment(id, nameResource, baseDir.FullName + "\\" + src, "text/css"); MainForm.UpdateStatus("End upload css : " + src); links.Add(nameResource); } else { MainForm.UpdateStatus("css already uploaded : " + src); } att.Value = _baseUri + "/download/attachments/" + id + "/" + src; HtmlNode node = doc.DocumentNode.SelectNodes("//body")[0]; HtmlNode newNode = doc.CreateTextNode("" + "<ac:structured-macro ac:name=\"style\">\n" + "<ac:parameter ac:name=\"import\">" + _baseUri + "/download/attachments/" + id + "/" + nameResource + "\n" + "</ac:parameter>\n" + "<ac:plain-text-body>\n" + "<![CDATA[ ]]>\n" + "</ac:plain-text-body>\n" + "</ac:structured-macro>\n" ); node.PrependChild(newNode); if (lastCssNode == null) lastCssNode = newNode; } } } HtmlNode bodyNode = doc.DocumentNode.SelectNodes("//body")[0]; HtmlNode cssNode = doc.CreateTextNode("" + "<ac:structured-macro ac:name=\"style\">\n" + "<ac:plain-text-body>\n" + "<![CDATA[ " + " #title-text a\n" + " {\n" + " color: #41a940 !important;\n" + " }\n" + " \n" + " h4\n" + " {\n" + " color: #007F64 !important;\n" + " font-weight: normal;\n" + " }\n" + " \n" + " p\n" + " {\n" + " font-weight: normal;\n" + " }\n" + "]]>\n" + "</ac:plain-text-body>\n" + "</ac:structured-macro>\n" ); if (lastCssNode==null) lastCssNode = cssNode; bodyNode.PrependChild(cssNode); // Manage <a> links HtmlNodeCollection colHref = doc.DocumentNode.SelectNodes("//a[@href]"); if (colHref != null) { StringCollection arefs = new StringCollection(); foreach (HtmlNode link in colHref) { HtmlAttribute att = link.Attributes["href"]; string href = att.Value; // Remove the Wiki Index link and the following "&nbsp;|&nbsp;" text if relevant if (href.Contains("_index.html")) { if (att.OwnerNode.NextSibling.InnerText == "&nbsp;|&nbsp;") { att.OwnerNode.NextSibling.Remove(); } att.OwnerNode.Remove(); continue; } if (Regex.IsMatch(href, "^[0-9]*\\.htm[l]?$") || href.Contains("#teamwiki/")) { // Link to another page like // <a href="13468.html"> // <a href="https://open.sage.com/teams/view/4840/documentid:42939#teamwiki/12542" target="_blank"> string pageTitle = Regex.Replace(href, "^([0-9]*)\\.htm[l]?$", "$1"); if (href.Contains("#teamwiki/")) { pageTitle = href.Substring(href.LastIndexOf("/") + 1); } //att.Value = _baseUri + "display/" + ConfluenceSpace + "/" + pageTitle; HtmlNode newNode = doc.CreateTextNode("" + "<ac:link>" + "<ri:page ri:content-title=\""+ pageTitle + "\"/>" + "<ac:plain-text-link-body><![CDATA["+ ConfluenceApiHelper.specialEntityToChar(link.InnerText) + "]]>" + "</ac:plain-text-link-body>" + "</ac:link>"); HtmlNode parentNode = link.ParentNode; parentNode.AppendChild(newNode); link.Remove(); continue; } // kind of links managed: // <a href="https://open.sage.com/teams/view/4840/documentid:38688#documents"> // <a href="http://open.sage.com/documents/view/72851" target="_blank"> if (href.StartsWith("http") && !((href.StartsWith("http://open.sage.com") || href.StartsWith("https://open.sage.com")) && (href.Contains("/documents/") || href.Contains("/documentid:")))) continue; if (href.StartsWith("#")) continue; if (!(href.Contains(".pdf") || href.Contains(".ppt") || href.Contains(".pptx") || href.Contains(".doc") || href.Contains(".docx") || href.Contains(".wmv") || !href.Substring(href.LastIndexOf("/")+1).Contains(".")) || href.StartsWith("file:")) continue; if ((href.StartsWith("http://open.sage.com") || (href.StartsWith("https://open.sage.com")))) { // kind of links managed: // <a href="https://open.sage.com/teams/view/4840/documentid:38688#documents"> // <a href="http://open.sage.com/documents/view/72851" target="_blank"> href = href.Replace("%20", ""); href = href.Replace("/documentid:", "/"); if (href.Contains("#")) { href = href.Substring(0,href.LastIndexOf("#")); } //Search document using id string docId = href.Substring(href.LastIndexOf("/")+1); var fileEntries = Directory.GetFiles(baseDir.FullName + "\\..", "*.*", SearchOption.AllDirectories); foreach (string fileName in fileEntries) { if (fileName.Contains("("+docId+")")) { href = fileName.Substring(fileName.LastIndexOf("..")); href = href.Replace("\\", "/"); break; } } } MainForm.UpdateStatus("Start upload attachment : " + href); int pos1 = href.LastIndexOf("/"); string nameResource = href.Substring(pos1 + 1); string appType = "application/pdf"; if (href.Contains(".ppt")) appType = "application/vnd.ms-powerpoint"; if (href.Contains(".pptx")) appType = "application/vnd.openxmlformats-officedocument.presentationml.presentation"; if (href.Contains(".doc")) appType = "application/msword"; if (href.Contains(".docx")) appType = "application/vnd.openxmlformats-officedocument.wordprocessingml.document"; if (href.Contains(".wmv")) appType = "video/x-ms-wmv"; if (loadAttachment) if (!arefs.Contains(nameResource)) { UploadAttachment(id, nameResource, baseDir.FullName + "\\" + href, appType); arefs.Add(nameResource); MainForm.UpdateStatus("End upload attachment : " + href); } else { MainForm.UpdateStatus("Attachment already uploaded : " + href); } //att.Value = _baseUri + "/download/attachments/" + id + "/" + nameResource; HtmlNode attachmentNode = doc.CreateTextNode("" + "<ac:link>" + "<ri:attachment ri:filename=\"" + nameResource + "\"/>" + "<ac:plain-text-link-body><![CDATA[" + ConfluenceApiHelper.specialEntityToChar(link.InnerText) + "]]>" + "</ac:plain-text-link-body>" + "</ac:link>"); HtmlNode pNode = link.ParentNode; pNode.AppendChild(attachmentNode); link.Remove(); // Uncomment to change links by macros //HtmlNode pdfNode = doc.CreateTextNode("" // + "<ac:structured-macro ac:macro-id=\"3bab546e-999a-456f-a874-5c3106c9a863\" ac:name=\"view-file\" ac:schema-version=\"1\">\n" // + " <ac:parameter ac:name=\"name\">\n" // + " <ri:attachment ri:filename=\"" + nameResource + "\" />\n" // + " </ac:parameter>\n" // + "<ac:parameter ac:name=\"height\">250</ac:parameter>\n" // + "</ac:structured-macro>\n"); //link.ParentNode.RemoveChild(link); //bodyNode.InsertAfter(pdfNode, lastCssNode); } } HtmlNode headTitle = doc.DocumentNode.SelectSingleNode("//title"); if (headTitle != null) { title = headTitle.InnerText; } string newName = fullPath.Replace(".html", ".fix"); doc.Save(newName, Encoding.UTF8); string html = ""; using (StreamReader readerIn = new StreamReader(newName, true)) { html = readerIn.ReadToEnd(); // Remove <!DOCTYPE> nodes html = Regex.Replace(html, "<!DOCTYPE.*>", ""); // Change "&" by "&amp;", except for "&nbsp;" and "&amp;" strings html = Regex.Replace(html, regExAmp, "&amp;$1"); // Change "&amp;" by "&" in <CDATA html = Regex.Replace(html, "(<\\!\\[CDATA\\[[^<]*)&amp;(.*\\]\\]>)", "$1&$2"); // Change "&nbsp;" by " " in <CDATA html = Regex.Replace(html, "(<\\!\\[CDATA\\[[^<]*)&nbsp;(.*\\]\\]>)", "$1 $2"); // Remove <blockquote> html = Regex.Replace(html, "<[/]?blockquote.*>", ""); } return html; } public string ImporHtml(string fullPath, string parent) { FileInfo fi = new FileInfo(fullPath); string name = fi.Name; int p1 = name.LastIndexOf("."); name = name.Substring(0, p1); MainForm.UpdateStatus("Start upload document: " + fullPath + " parent: " + parent); string id = CreateNewEmptyDocument(parent, name); if (id == null) { MainForm.UpdateStatus("Error during document creation. Page may already exist (" + fullPath + ")"); return id; } string title = ""; string html = LoadHtml(id, fullPath, true, ref title); string url = _uri + "/content/" + id + "?expand=body.storage,version"; dynamic dynObj = GetExistingResource(id); int currentVersion = dynObj.version.number; dynObj.version.number = currentVersion + 1; dynObj.body.storage.value = html; string json = JsonConvert.SerializeObject(dynObj); System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding(); byte[] arr = encoding.GetBytes(json); HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url); _addAuth(request); _setProxy(request); request.ContentType = "application/json"; request.Method = "PUT"; request.ContentLength = arr.Length; Stream dataStream = request.GetRequestStream(); dataStream.Write(arr, 0, arr.Length); dataStream.Close(); string sResponse = ""; try { using (HttpWebResponse response = (HttpWebResponse)request.GetResponse()) { using (StreamReader reader = new StreamReader(response.GetResponseStream())) { sResponse = reader.ReadToEnd(); } } MainForm.UpdateStatus("End upload document : " + fullPath); } catch (Exception ex) { MessageBox.Show(ex.Message); MainForm.UpdateStatus("Failed upload document : " + fullPath); Instance.DeleteDoc(id); } return id; } public void BulkImporHtml(MainForm mainForm, string folderPath, string parent) { var fileEntries = Directory.GetFiles(folderPath,"*.html", SearchOption.TopDirectoryOnly); mainForm.initProgressBar(0, fileEntries.Count()); foreach (string fileName in fileEntries) { mainForm.performStep(); ImporHtml(fileName, parent); } mainForm.closeProgressBar(); } public void BulkImporIndex(MainForm mainForm, string fullPath, string parent) { HtmlAgilityPack.HtmlDocument _index = new HtmlAgilityPack.HtmlDocument(); _index.OptionWriteEmptyNodes = true; _index.OptionFixNestedTags = true; _index.Load(fullPath); HtmlNodeCollection aHref = _index.DocumentNode.SelectNodes("//a[@href]"); if (aHref != null) { mainForm.initProgressBar(0, aHref.Count); } else { mainForm.initProgressBar(0, 0); } HtmlNodeCollection nodes = _index.DocumentNode.ChildNodes; foreach (HtmlNode node in nodes) { string empty = ""; processNode(mainForm, fullPath.Substring(0,fullPath.LastIndexOf("\\")+1), node, parent, ref empty); } mainForm.closeProgressBar(); } public void BulkUpdateTitles(MainForm mainForm, string fullPath, string parent) { StringCollection coltitles = new StringCollection(); HtmlAgilityPack.HtmlDocument _index = new HtmlAgilityPack.HtmlDocument(); _index.OptionWriteEmptyNodes = true; _index.OptionFixNestedTags = true; _index.Load(fullPath, true); HtmlNodeCollection aHrefs = _index.DocumentNode.SelectNodes("//a[@href]"); if (aHrefs != null) { mainForm.initProgressBar(0, aHrefs.Count); } else { mainForm.initProgressBar(0, 0); } foreach (HtmlNode aHref in aHrefs) { HtmlAttribute att = aHref.Attributes["href"]; string newTitle = aHref.InnerText; newTitle = newTitle.Replace("\"", ""); int seq = 0; while (coltitles.Contains(newTitle.ToLower())) { seq += 1; newTitle = aHref.InnerText+"("+seq+")"; } coltitles.Add(newTitle.ToLower()); updateTitle(att.Value.Substring(0, att.Value.LastIndexOf(".")), newTitle); mainForm.performStep(); } mainForm.closeProgressBar(); } private void processNode(MainForm mainForm, string path, HtmlNode node, string parent, ref string aParent) { switch (node.Name) { case "ul": break; case "li": break; case "a": string href = node.Attributes["href"].Value; mainForm.performStep(); aParent = ImporHtml(path+href, parent); break; } HtmlNodeCollection childNodes = node.ChildNodes; if (childNodes != null) { foreach (HtmlNode childNode in childNodes) { processNode(mainForm, path, childNode, parent, ref aParent); if (childNode.Name == "a") { parent = aParent; } } } } private void UploadAttachment(string id, string src, string fileName, string contentType) { // Check the file exists if (!File.Exists(fileName)) { MainForm.UpdateStatus("Failed attachment does not exist : " + fileName); return; } byte[] boundarybytes = System.Text.Encoding.ASCII.GetBytes("\r\n--" + _boundary + "\r\n"); string url = _uri + "/content/" + id + "/child/attachment"; HttpWebRequest wr = (HttpWebRequest)WebRequest.Create(url); wr.ContentType = "multipart/form-data; boundary=" + _boundary; wr.Method = "POST"; wr.KeepAlive = true; wr.Headers.Add("X-Atlassian-Token", "no-check"); _addAuth(wr); _setProxy(wr); Stream rs = wr.GetRequestStream(); string formdataTemplate = "Content-Disposition: form-data; name=\"{0}\"\r\n\r\n{1}"; rs.Write(boundarybytes, 0, boundarybytes.Length); string formitem = string.Format(formdataTemplate, "id", src); byte[] formitembytes = System.Text.Encoding.UTF8.GetBytes(formitem); rs.Write(formitembytes, 0, formitembytes.Length); rs.Write(boundarybytes, 0, boundarybytes.Length); string headerTemplate = "Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\nContent-Type: {2}\r\n\r\n"; string header = string.Format(headerTemplate, "file", src, contentType); byte[] headerbytes = System.Text.Encoding.UTF8.GetBytes(header); rs.Write(headerbytes, 0, headerbytes.Length); FileStream fileStream; try { fileStream = new FileStream(fileName, FileMode.Open, FileAccess.Read); } catch (Exception ex) { MainForm.UpdateStatus("Failed open attachment : " + fileName); MainForm.addMsg(ex.Message); return; } byte[] buffer = new byte[4096]; int bytesRead = 0; while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0) { rs.Write(buffer, 0, bytesRead); } fileStream.Close(); byte[] trailer = System.Text.Encoding.ASCII.GetBytes("\r\n--" + _boundary + "--\r\n"); rs.Write(trailer, 0, trailer.Length); rs.Close(); try { using (WebResponse wresp = wr.GetResponse()) { using (StreamReader reader = new StreamReader(wresp.GetResponseStream())) { MainForm.UpdateStatus(string.Format("File uploaded, {0}", fileName)); } } } catch (Exception ex) { MainForm.UpdateStatus("Failed upload attachment : " + src); MainForm.addMsg(ex.Message); } } public void updateTitle(string oldTitle, string newTitle) { if ((oldTitle == "") || (newTitle == "")) { return; } MainForm.UpdateStatus("Start update title : " + newTitle + "(" + oldTitle + ")"); string id = findTitle(_pages, oldTitle); if (id == "") { MainForm.UpdateStatus("Failed finding id : " + newTitle + "(" + oldTitle + ")"); return; } string url = _uri + "/content/" + id + "?expand=body.storage,version"; dynamic dynObj = GetExistingResource(id); string json = "{ \"version\": { \"number\": " + (dynObj.version.number + 1) + " }, \"title\": \"" + newTitle + "\", \"type\" : \"page\" }"; System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding(); byte[] arr = encoding.GetBytes(json); HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url); _addAuth(request); _setProxy(request); request.ContentType = "application/json"; request.Method = "PUT"; request.ContentLength = arr.Length; Stream dataStream = request.GetRequestStream(); dataStream.Write(arr, 0, arr.Length); dataStream.Close(); string sResponse = ""; try { using (HttpWebResponse response = (HttpWebResponse)request.GetResponse()) { using (StreamReader reader = new StreamReader(response.GetResponseStream())) { sResponse = reader.ReadToEnd(); } } MainForm.UpdateStatus("End update title : " + newTitle + "(" + oldTitle + ")"); } catch (Exception ex) { MessageBox.Show(ex.Message); MainForm.UpdateStatus("Failed update title : " + newTitle + "(" + oldTitle + ")"); } } private string findTitle(ArrayList pages, string title) { string id = ""; foreach (ConfluencePages page in pages) { if (page.Title == title) { id = page.Id; break; } } return id; } } }
using System; using System.Collections.Generic; using System.Linq; /* * tags: sort, 3-way partition, index sort * Given an unsorted array nums, reorder it such that nums[0] < nums[1] > nums[2] < nums[3].... */ namespace leetcode { public class Lc324_Wiggle_Sort_II { /* * Time(nlogn), Space(n) */ public void WiggleSort(int[] nums) { var ns = nums.ToArray(); Array.Sort(ns); for (int i = 0, j = ns.Length / 2, k = ns.Length - 1; k >= 0; k--) { nums[k] = ns[k % 2 == 0 ? i++ : j++]; } } /* * 3-way partition, index sort * Time(n), Space(1) */ public void WiggleSort2(int[] nums) { int n = nums.Length; int mid = GetKthSmallest(nums, n / 2); for (int lo = 0, hi = n - 1, i = 0; i <= hi;) { if (nums[Remap(n, i)] > mid) Swap(nums, Remap(n, i++), Remap(n, lo++)); else if (nums[Remap(n, i)] < mid) Swap(nums, Remap(n, i), Remap(n, hi--)); else i++; } } int GetKthSmallest(int[] nums, int k) { Array.Sort(nums); return nums[k]; } // map index from 0,1,2,..mid to 1,3,5..., and from mid+1,mid+2... to 0,2,4... int Remap(int n, int i) { return (1 + 2 * i) % (n | 1); } void Swap(int[] nums, int i, int j) { int t = nums[i]; nums[i] = nums[j]; nums[j] = t; } // expected: nums[0] < nums[1] > nums[2] < nums[3].... bool IsExpected(int[] nums) { for (int i = 0; i < nums.Length; i += 2) { if (i > 0 && nums[i - 1] <= nums[i]) return false; if (i < nums.Length - 1 && nums[i] >= nums[i + 1]) return false; } return true; } public void Test() { var nums = new int[] { 1, 5, 1, 1, 6, 4 }; var nums2 = nums.ToArray(); WiggleSort(nums); Console.WriteLine(IsExpected(nums)); WiggleSort2(nums2); Console.WriteLine(IsExpected(nums2)); nums = new int[] { 1, 3, 2, 2, 3, 1 }; nums2 = nums.ToArray(); WiggleSort(nums); Console.WriteLine(IsExpected(nums)); WiggleSort2(nums2); Console.WriteLine(IsExpected(nums2)); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; public partial class Forgot : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { } protected void Button1_Click(object sender, EventArgs e) { String email = txtemail.Text; String phone = txtphone.Text; ConnectionClass obj = new ConnectionClass(); String qry = "select Id from Admin where email='" + email + "' and phone='" + phone + "'"; String id = obj.getSingleData(qry); String qry1 = "select count(*) from Admin where email='" + email + "' and phone='" + phone + "'"; String count = obj.getSingleData(qry1); if (count == "0") { String a = "Email and Mobile Number not Matching"; Response.Write("<script>alert('" + a + "')</script>"); } else { Session["id"] = id; Session["e"] = email; Session["p"] = phone; Response.Redirect("Resetpassword.aspx"); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace Ults { namespace Windows.Forms { public class MainFormBase : System.Windows.Forms.Form { private static readonly string _myEntryAssemblyVersionText = null; static MainFormBase() { var entryAsm = System.Reflection.Assembly.GetEntryAssembly(); if(entryAsm != null) { var location = entryAsm.Location; if(location != null) { _myEntryAssemblyVersionText = System.Diagnostics.FileVersionInfo.GetVersionInfo(location).FileVersion.ToString(); } } } private string _text; public new System.Windows.Forms.FormStartPosition StartPosition { get; } = System.Windows.Forms.FormStartPosition.CenterScreen; public new string Text { get { return _text; } set { _text = value; base.Text = _text + ((_myEntryAssemblyVersionText == null) ? string.Empty : (" version " + _myEntryAssemblyVersionText)); } } public MainFormBase() : base() { base.StartPosition = this.StartPosition; } } public class SplitContainerEx : System.Windows.Forms.SplitContainer { protected override void OnPaint(PaintEventArgs e) { base.OnPaint(e); var rect = this.SplitterRectangle; rect.Inflate(1, -2); e.Graphics.FillRectangle(System.Drawing.SystemBrushes.GrayText, rect); } } public class TextBoxEx : System.Windows.Forms.TextBox { protected override void OnKeyDown(KeyEventArgs e) { base.OnKeyDown(e); if(e.Control && e.KeyCode.Equals(Keys.A)) { this.SelectAll(); e.Handled = true; e.SuppressKeyPress = true; return; } } protected override void OnGotFocus(EventArgs e) { base.OnGotFocus(e); this.SelectAll(); } protected override void OnPaint(PaintEventArgs e) { base.OnPaint(e); } } } }
using Projectmanagement.Models; using System; using System.Data.Entity; using System.Linq; using System.Net; using System.Web.Mvc; namespace Projectmanagement.Controllers { [Authorize] public class EmployeesController : Controller { private FirmaEntities db = new FirmaEntities(); // GET: Employees public ActionResult Index(string sortOrder) { var employees = from e in db.Employees select e; employees.Include(e => e.Department); ViewBag.NameSortParam = String.IsNullOrEmpty(sortOrder) ? "name_desc" : ""; ViewBag.FirstNameSortParam = sortOrder == "FirstName" ? "firstName_desc" : "FirstName"; ViewBag.PhoneNumberSortParam = sortOrder == "PhoneNumber" ? "phoneNumber_desc" : "PhoneNumber"; ViewBag.EmailSortParam = sortOrder == "Email" ? "email_desc" : "Email"; ViewBag.SalarySortParam = sortOrder == "Salary" ? "salary_desc" : "Salary"; ViewBag.PositionSortParam = sortOrder == "Position" ? "position_desc" : "Position"; ViewBag.DepartmentSortParam = sortOrder == "Department" ? "department_desc" : "Department"; switch (sortOrder) { case "name_desc": employees = employees.OrderByDescending(e => e.name); break; case "firstName_desc": employees = employees.OrderByDescending(e => e.firstname); break; case "FirstName": employees = employees.OrderBy(e => e.firstname); break; case "phoneNumber_desc": employees = employees.OrderByDescending(e => e.tel); break; case "PhoneNumber": employees = employees.OrderBy(e => e.tel); break; case "email_desc": employees = employees.OrderByDescending(e => e.email); break; case "Email": employees = employees.OrderBy(e => e.email); break; case "salary_desc": employees = employees.OrderByDescending(e => e.salary); break; case "Salary": employees = employees.OrderBy(e => e.salary); break; case "position_desc": employees = employees.OrderByDescending(e => e.position); break; case "Position": employees = employees.OrderBy(e => e.position); break; case "department_desc": employees = employees.OrderByDescending(e => e.Department.designation); break; case "Department": employees = employees.OrderBy(e => e.Department.designation); break; default: employees = employees.OrderBy(e => e.name); break; } return View(employees.ToList()); } // GET: Employees/Details/5 public ActionResult Details(int? id) { if (id == null) { return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } Employee employee = db.Employees.Find(id); if (employee == null) { return HttpNotFound(); } return View(employee); } // GET: Employees/Create public ActionResult Create() { ViewBag.fk_department_id = new SelectList(db.Departments, "ID", "designation"); return View(); } // POST: Employees/Create // To protect from overposting attacks, please enable the specific properties you want to bind to, for // more details see http://go.microsoft.com/fwlink/?LinkId=317598. [HttpPost] [ValidateAntiForgeryToken] public ActionResult Create([Bind(Include = "ID,name,firstname,tel,email,salary,position,fk_department_id")] Employee employee) { if (ModelState.IsValid) { db.Employees.Add(employee); db.SaveChanges(); return RedirectToAction("Index"); } ViewBag.fk_department_id = new SelectList(db.Departments, "ID", "designation", employee.fk_department_id); return View(employee); } // GET: Employees/Edit/5 public ActionResult Edit(int? id) { if (id == null) { return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } Employee employee = db.Employees.Find(id); if (employee == null) { return HttpNotFound(); } ViewBag.fk_department_id = new SelectList(db.Departments, "ID", "designation", employee.fk_department_id); return View(employee); } // POST: Employees/Edit/5 // To protect from overposting attacks, please enable the specific properties you want to bind to, for // more details see http://go.microsoft.com/fwlink/?LinkId=317598. [HttpPost] [ValidateAntiForgeryToken] public ActionResult Edit([Bind(Include = "ID,name,firstname,tel,email,salary,position,fk_department_id")] Employee employee) { if (ModelState.IsValid) { db.Entry(employee).State = EntityState.Modified; db.SaveChanges(); return RedirectToAction("Index"); } ViewBag.fk_department_id = new SelectList(db.Departments, "ID", "designation", employee.fk_department_id); return View(employee); } // GET: Employees/Delete/5 public ActionResult Delete(int? id) { if (id == null) { return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } Employee employee = db.Employees.Find(id); if (employee == null) { return HttpNotFound(); } return View(employee); } // POST: Employees/Delete/5 [HttpPost, ActionName("Delete")] [ValidateAntiForgeryToken] public ActionResult DeleteConfirmed(int id) { Employee employee = db.Employees.Find(id); db.Employees.Remove(employee); db.SaveChanges(); return RedirectToAction("Index"); } protected override void Dispose(bool disposing) { if (disposing) { db.Dispose(); } base.Dispose(disposing); } } }
using UnityEngine; /// <summary> /// Simple flying camera the behaves much like the editor camera. /// </summary> public class FlyingCamera : MonoBehaviour{ [SerializeField] private float speed = 60f; private Vector3 moveVector = Vector3.zero; [SerializeField] private float lookSpeed = 8f; [SerializeField] private bool invertLook = false; private Vector3 lookRotation = Vector3.zero; void Start(){ lookRotation = transform.eulerAngles; } void Update(){ if (Input.GetMouseButton(1)) { lookRotation.y += Input.GetAxis("Mouse X") * lookSpeed; lookRotation.x += (invertLook ? 1 : -1) * Input.GetAxis("Mouse Y") * lookSpeed; } if (lookRotation.y > 360) { lookRotation.y = 0; } if (lookRotation.y < 0) { lookRotation.y = 360; } if (lookRotation.x > 360) { lookRotation.x = 0; } if (lookRotation.x < 0) { lookRotation.x = 360; } transform.rotation = Quaternion.Euler(lookRotation); moveVector.z = Input.GetAxis("Vertical"); moveVector.x = Input.GetAxis("Horizontal"); transform.Translate(moveVector * (speed * (Input.GetKey(KeyCode.LeftShift) ? 2 : 1)) * Time.deltaTime, Space.Self); } }
using System; using System.Collections.Generic; using System.Reflection; using Atc.XUnit.Internal; namespace Atc.XUnit { /// <summary> /// CodeComplianceNamingHelper. /// </summary> public static class CodeComplianceHelper { /// <summary> /// Asserts the exported types with wrong definitions. /// </summary> /// <param name="type">The type.</param> /// <param name="useFullName">if set to <c>true</c> [use full name].</param> public static void AssertExportedTypesWithWrongDefinitions( Type type, bool useFullName = false) { throw new NotImplementedException(); } /// <summary> /// Asserts the exported types with wrong definitions. /// </summary> /// <param name="assembly">The assembly.</param> /// <param name="excludeTypes">The exclude types.</param> /// <param name="useFullName">if set to <c>true</c> [use full name].</param> public static void AssertExportedTypesWithWrongDefinitions( Assembly assembly, List<Type>? excludeTypes = null, bool useFullName = false) { if (assembly == null) { throw new ArgumentNullException(nameof(assembly)); } var methodsWithWrongNaming = AssemblyAnalyzerHelper.CollectExportedMethodsWithWrongNaming( assembly, excludeTypes); TestResultHelper.AssertOnTestResultsFromMethodsWithWrongDefinitions( assembly.GetName().Name, methodsWithWrongNaming, useFullName); } } }
using UnityEngine; using System.Collections; using System.Collections.Generic; public class MechStationAndAttitudeControl : MonoBehaviour { //The square the of max magnitude the velocity should be private float maxSpeed; private float maxSpeedSqr; //The max accelration private float accelerationRate; private float breakSmooth; //should be in local coordinates private Vector3 accelVector; protected override void DoStart () { //If this is the server if ( Network.isServer || Network.peerType == NetworkPeerType.Disconnected ) { accelVector = Vector3.zero; Stats stats = shipRigidbody.gameObject.GetComponent<Stats>(); maxSpeed = stats.maxSpeed; maxSpeedSqr = maxSpeed * maxSpeed; accelerationRate = stats.acceleration; //DEBUG breakSmooth = stats.breakSmooth; } } void FixedUpdate () { //TODO Check if we're the server (which means we get to move stuff), then check which player is controlling it and apply the correct controls //whether that is coming from the network or on the local machine. Then either send it off if we're a client, or process it if we're the server #region Applying Velocity Debug.DrawRay( shipRigidbody.position, shipRigidbody.velocity * 10 ); //TODO Think of some way to still accelerate towards the keyed vectors while breaking the others //IF player wants to use the break, scale back the velocity if ( Input.GetKey ( keys ["break"] ) ) { //If the velocity is not already zero if( velocityVector != Vector3.zero ){ velocityVector = Vector3.MoveTowards( velocityVector, Vector3.zero, accelerationRate * Time.deltaTime ); } } else { //OTHERWISE accelerate towards a vector //Now using Unity's input manager //Final acceleration vector accelVector = new Vector3 (Input.GetAxis( "Thrust X"), Input.GetAxis( "Thrust Y"), Input.GetAxis( "Thrust Z" ) ).normalized * accelerationRate * Time.deltaTime; //TODO Do some math magic here and fix the velocity vector to align to a proper axis when it is being clamped //Finding the movement offset, then clamping the speed velocityVector = Vector3.ClampMagnitude (velocityVector + transform.TransformDirection (accelVector), maxSpeed * Time.deltaTime); } //Moving the rigid-body shipRigidbody.MovePosition (shipRigidbody.position + velocityVector); //TODO Maybe deal with this if I ever want to implement Warp //If drifting faster than max velocity, set back to max velocity if( shipRigidbody.velocity.sqrMagnitude > maxSpeedSqr ){ shipRigidbody.velocity *= 0.99f; } Debug.Log( shipRigidbody.velocity.magnitude ); //TODO Change this away from the input manager if ( Input.GetAxis( "Break" ) > 0 ) { //MAYBE!! TODO Think of some way to still accelerate towards the keyed vectors while breaking the others //TODO Fine, use Hyper Thrust meter to emergency break //IF player wants to use the break, scale back the velocity shipRigidbody.velocity = Vector3.MoveTowards( shipRigidbody.velocity, Vector3.zero, breakSmooth * Time.deltaTime ); } else { //OTHERWISE accelerate towards a vector //TODO Implement Hyper Thursting if double tap //If the speed isn't already at max if( shipRigidbody.velocity.sqrMagnitude < maxSpeedSqr ){ accelVector.x = Input.GetAxis( "Thrust X" ); accelVector.y = Input.GetAxis( "Thrust Y" ); accelVector.z = Input.GetAxis( "Thrust Z" ); accelVector = accelVector.normalized * Time.deltaTime * accelerationRate; shipRigidbody.AddRelativeForce( accelVector ); } } #endregion #region Applying Attitude Control //TODO This is pretty basic. Do some fancy attitude controls later. if( Screen.lockCursor ){ shipRigidbody.rotation = shipRigidbody.rotation * Quaternion.Euler( Input.GetAxis( "Pitch" ), Input.GetAxis( "Yaw" ), Input.GetAxis( "Roll" ) ); } #endregion } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class BallSpawnerTesting : MonoBehaviour { int numBalls=0; public GameObject ballPrefab; public bool ON; public int totballs; public Rigidbody2D[] ballsRigid; // Start is called before the first frame update void Start() { ballsRigid=new Rigidbody2D[totballs]; for(int i=0;i<totballs;i++){ GameObject ball=Instantiate(ballPrefab,this.transform.position,this.transform.rotation); ballsRigid[i]=ball.GetComponent<Rigidbody2D>(); } } // Update is called once per frame void FixedUpdate() { if(ON){ Vector2 force= new Vector2(Random.value,Random.value); ballsRigid[numBalls].AddForce(force,ForceMode2D.Impulse); ballsRigid[numBalls].gameObject.SetActive(true); ballsRigid[numBalls].transform.position=Vector3.zero; print(++numBalls); } } }
using System.Linq; using System.Collections.Generic; using Newtonsoft.Json; using JobKey = System.Tuple<int, string>; namespace WorldDominationCrawler { internal class ReportData { private CrawlJob _RootJob; private Dictionary<JobKey, CrawlJob> _Jobs; public ReportData(CrawlJob rootJob) { _RootJob = rootJob; _Jobs = new Dictionary<JobKey, CrawlJob>(); } public void TrackJob(CrawlJob job) { var key = job.GetJobKey(); if (_Jobs.ContainsKey(key)) return; _Jobs.Add(job.GetJobKey(), job); } private object _BuildJobToTree(CrawlJob job) { return new { url = job.Url, title = job.PageTitle, children = job.PageHrefs .Select((url) => new JobKey(job.Depth+1, url)) .Where((key) => _Jobs.ContainsKey(key)) .Select((key) => _Jobs[key]) .Select((childJob) => this._BuildJobToTree(childJob)), }; } public string ToJson() { var tree = this._BuildJobToTree(_RootJob); return JsonConvert.SerializeObject(tree, Formatting.Indented); } public void Reset() { _Jobs.Clear(); } } }
using UnityEngine; using System.Collections; using Action; public class Move : MonoBehaviour { public GameObject target; // Use this for initialization void Start () { ActionManager.Instance.Add( this.gameObject, ActionMove.Create( this.target, 2f, Vector3.zero, new Vector3(10f, 0f, 0f) ) ); } }
using MediatR; using System; using System.Collections.Generic; using System.Text; namespace Projeto.Application.Commands.Turmas { public class DeleteTurmaCommand : IRequest { public string Id { get; set; } } }
using System.Collections.Generic; using System.Linq; using System.Windows; using System.Windows.Controls; using System.Windows.Media; using System.Windows.Media.Media3D; using XamlCSS.Dom; namespace XamlCSS.WPF.Dom { public class TreeNodeProvider : TreeNodeProviderBase<DependencyObject, Style, DependencyProperty> { private ApplicationDependencyObject applicationDependencyObject; public TreeNodeProvider(IDependencyPropertyService<DependencyObject, Style, DependencyProperty> dependencyPropertyService) : base(dependencyPropertyService) { this.applicationDependencyObject = new ApplicationDependencyObject(Application.Current); } public override IDomElement<DependencyObject, DependencyProperty> CreateTreeNode(DependencyObject dependencyObject) { return new DomElement(dependencyObject, GetDomElement(GetParent(dependencyObject, SelectorType.VisualTree)), GetDomElement(GetParent(dependencyObject, SelectorType.LogicalTree)), this); } public override IEnumerable<DependencyObject> GetChildren(DependencyObject element, SelectorType type) { var list = new List<DependencyObject>(); if (element == null) { return list; } if (element == applicationDependencyObject) { return Application.Current.Windows.Cast<Window>().ToList(); } if (type == SelectorType.VisualTree) { try { list.AddRange(GetVisualChildren(element)); } catch { } } else { list = GetLogicalChildren(element).ToList(); } return list; } public IEnumerable<DependencyObject> GetLogicalChildren(DependencyObject element) { if (element == null) { return new List<DependencyObject>(); } if (element is ItemsControl ic) { var list = new List<DependencyObject>(); for (int i = 0; i < ic.Items.Count; i++) { var uiElement = ic.ItemContainerGenerator.ContainerFromIndex(i); if (uiElement != null) { var found = GetLogicalChildren(uiElement).FirstOrDefault(); if (found == null) list.Add(uiElement); else { list.Add(found); } } } return list; } if (element is ItemsPresenter itemsPresenter) { var itemshost = itemsPresenter != null ? VisualTreeHelper.GetChild(itemsPresenter, 0) as Panel : null; if (itemshost == null) { return new DependencyObject[0] { }; } var p = GetVisualChildren(itemshost).FirstOrDefault(); if (p != null) return GetLogicalChildren(p); return new DependencyObject[0]; } else if (element is ContentPresenter c) { return GetChildrenOfLogicalParent(element, GetVisualChildren(element)); } else if (element is Frame frame) { var content = frame.Content as DependencyObject; if (content != null) { return new[] { content }; } return new DependencyObject[0]; } var children = LogicalTreeHelper.GetChildren(element) .Cast<object>() .OfType<DependencyObject>() .ToList(); return children; } private List<DependencyObject> GetChildrenOfLogicalParent(DependencyObject searchParent, IEnumerable<DependencyObject> elements) { var list = new List<DependencyObject>(); foreach (var element in elements) { var found = false; if (element is FrameworkElement f) { if (f.Parent == searchParent || f.TemplatedParent == searchParent) { list.Add(f); found = true; } } else if (element is FrameworkContentElement fc) { if (fc.Parent == searchParent || fc.TemplatedParent == searchParent) { list.Add(fc); found = true; } } if (!found) { list.AddRange(GetChildrenOfLogicalParent(searchParent, GetVisualChildren(element))); } } return list; } public IEnumerable<DependencyObject> GetVisualChildren(DependencyObject element) { var list = new List<DependencyObject>(); if (element == null) { return list; } try { if (element is Visual || element is Visual3D) { for (int i = 0; i < VisualTreeHelper.GetChildrenCount(element); i++) { var child = VisualTreeHelper.GetChild(element, i) as DependencyObject; if (child != null) { list.Add(child); } } } } catch { } return list; } public override bool IsInTree(DependencyObject element, SelectorType type) { if (type == SelectorType.LogicalTree) { return IsInLogicalTree(element); } return IsInVisualTree(element); } private bool IsInVisualTree(DependencyObject element) { var p = GetVisualParent(element); if (p == null) return element is Window || element == applicationDependencyObject;// LogicalTreeHelper.GetParent(element) != null; return GetChildren(p, SelectorType.VisualTree).Contains(element); } private bool IsInLogicalTree(DependencyObject dependencyObject) { var p = GetLogicalParent(dependencyObject); if (p == null) return dependencyObject is Window || dependencyObject == applicationDependencyObject; return GetChildren(p, SelectorType.LogicalTree).Contains(dependencyObject); } public override DependencyObject GetParent(DependencyObject element, SelectorType type) { if (element == null) { return null; } if (element is Window) { return applicationDependencyObject; } if (type == SelectorType.VisualTree) { if (element is Visual || element is Visual3D) { return GetVisualParent(element); } else if (element is FrameworkContentElement) { return GetLogicalParent(element); } } else { return GetLogicalParent(element); } return null; } private DependencyObject GetVisualParent(DependencyObject element) { if (element == null) { return null; } if (element is Visual || element is Visual3D) { return VisualTreeHelper.GetParent(element); } // LoadedDetection: would insert into Logical Dom Tree return null;// LogicalTreeHelper.GetParent(element); } private DependencyObject GetLogicalParent(DependencyObject element) { if (element == null) { return null; } var p = LogicalTreeHelper.GetParent(element); if (p == null) // templated? { if (element is FrameworkElement f) { p = f.TemplatedParent; } else if (element is FrameworkContentElement fc) { p = fc.TemplatedParent; } if (p == null) { if (element is ContentControl cc) { p = cc.TemplatedParent ?? GetVisualParent(cc); } } if (p == null) { p = GetVisualParent(element); } if (p is ContentPresenter cp) { p = cp.TemplatedParent ?? GetVisualParent(cp); } if (p is Frame frame) { } if (p is Panel panel) { if (panel.IsItemsHost) { p = panel.TemplatedParent ?? GetVisualParent(panel); } } if (p is ItemsPresenter ip) { p = ip.TemplatedParent; } } return p; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Rendering; using Microsoft.EntityFrameworkCore; using AMS.Models; using AMS.Models.ViewModels; namespace AMS.Controllers { public class FeesController : Controller { private readonly OurEduAMSDbContext _context; public FeesController(OurEduAMSDbContext context) { _context = context; } // GET: Fees public async Task<IActionResult> Index() { var ourEduAMSDbContext = _context.Fees.Include(f => f.Class).Include(f => f.FeesType); return View(await ourEduAMSDbContext.ToListAsync()); } //public async Task<IActionResult> Index(string selectedClass) //{ // // Use LINQ to get list of genres. // IQueryable<long> feesQuery = from f in _context.Fees // orderby f.ClassId // select f.ClassId; // var fees = from f in _context.Fees // select f; // if (!string.IsNullOrEmpty(selectedClass)) // { // fees = fees.Where(f => f.ClassId == Convert.ToInt32(selectedClass)); // } // var FeesViewModel = new FeesViewModel // { // SelectedClass = new SelectList(await feesQuery.Distinct().ToListAsync()), // Fees = await Fees.ToListAsync() // }; // return View(FeesViewModel); //} public async Task<IActionResult> IndexAP() { var ourEduAMSDbContext = _context.Fees.Include(f => f.Class).Include(f => f.FeesType); return View(await ourEduAMSDbContext.ToListAsync()); } // GET: Fees/Details/5 public async Task<IActionResult> Details(long? id) { if (id == null) { return NotFound(); } var fees = await _context.Fees .Include(f => f.Class) .Include(f => f.FeesType) .FirstOrDefaultAsync(m => m.Id == id); if (fees == null) { return NotFound(); } return View(fees); } public async Task<IActionResult> DetailsAP(long? id) { if (id == null) { return NotFound(); } var fees = await _context.Fees .Include(f => f.Class) .Include(f => f.FeesType) .FirstOrDefaultAsync(m => m.Id == id); if (fees == null) { return NotFound(); } return View(fees); } // GET: Fees/Create public IActionResult Create() { ViewData["ClassId"] = new SelectList(_context.Classes, "Id", "Name"); ViewData["FeesTypeId"] = new SelectList(_context.FeesTypes, "Id", "Name"); return View(); } // POST: Fees/Create // To protect from overposting attacks, please enable the specific properties you want to bind to, for // more details see http://go.microsoft.com/fwlink/?LinkId=317598. [HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> Create([Bind("Id,ClassId,FeesTypeId,Name,Amount,DueDate")] Fees fees) { if (ModelState.IsValid) { _context.Add(fees); await _context.SaveChangesAsync(); return RedirectToAction(nameof(Index)); } ViewData["ClassId"] = new SelectList(_context.Classes, "Id", "Name", fees.ClassId); ViewData["FeesTypeId"] = new SelectList(_context.FeesTypes, "Id", "Id", fees.FeesTypeId); return View(fees); } // GET: Fees/Edit/5 public async Task<IActionResult> Edit(long? id) { if (id == null) { return NotFound(); } var fees = await _context.Fees.FindAsync(id); if (fees == null) { return NotFound(); } ViewData["ClassId"] = new SelectList(_context.Classes, "Id", "Name", fees.ClassId); ViewData["FeesTypeId"] = new SelectList(_context.FeesTypes, "Id", "Name", fees.FeesTypeId); return View(fees); } // POST: Fees/Edit/5 // To protect from overposting attacks, please enable the specific properties you want to bind to, for // more details see http://go.microsoft.com/fwlink/?LinkId=317598. [HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> Edit(long id, [Bind("Id,ClassId,FeesTypeId,Name,Amount,DueDate")] Fees fees) { if (id != fees.Id) { return NotFound(); } if (ModelState.IsValid) { try { _context.Update(fees); await _context.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!FeesExists(fees.Id)) { return NotFound(); } else { throw; } } return RedirectToAction(nameof(Index)); } ViewData["ClassId"] = new SelectList(_context.Classes, "Id", "Name", fees.ClassId); ViewData["FeesTypeId"] = new SelectList(_context.FeesTypes, "Id", "Id", fees.FeesTypeId); return View(fees); } // GET: Fees/Delete/5 public async Task<IActionResult> Delete(long? id) { if (id == null) { return NotFound(); } var fees = await _context.Fees .Include(f => f.Class) .Include(f => f.FeesType) .FirstOrDefaultAsync(m => m.Id == id); if (fees == null) { return NotFound(); } return View(fees); } // POST: Fees/Delete/5 [HttpPost, ActionName("Delete")] [ValidateAntiForgeryToken] public async Task<IActionResult> DeleteConfirmed(long id) { var fees = await _context.Fees.FindAsync(id); _context.Fees.Remove(fees); await _context.SaveChangesAsync(); return RedirectToAction(nameof(Index)); } private bool FeesExists(long id) { return _context.Fees.Any(e => e.Id == id); } } }
/* 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 frmMovies : Form { #region Public Static Variables public static bool ADD_NEW = false; public static string key = string.Empty; #endregion #region Private Variables string sql_stmt = string.Empty; double rental_price = 0; #endregion #region Private Methods private void display_record() { sql_stmt = "SELECT * FROM movies WHERE MovieCode = '" + key + "';"; DataTable dtCustomer = clsPublicMethods.DBUtilies.get_data_table(sql_stmt); if (dtCustomer.Rows.Count > 0) { foreach (DataRow dr in dtCustomer.Rows) { txtMovieCode.Text = dr["MovieCode"].ToString(); txtMovieTitle.Text = dr["MovieTitle"].ToString(); cboCategory.Text = dr["Category"].ToString(); txtRentalPrice.Text = dr["RentalPrice"].ToString(); txtYear.Text = dr["YearReleased"].ToString(); txtMovieDirector.Text = dr["Director"].ToString(); } } } #endregion #region Form Init Method and Control Events public frmMovies() { InitializeComponent(); } private void frmMovies_Load(object sender, EventArgs e) { if (ADD_NEW == false) { txtMovieCode.Enabled = false; display_record(); txtMovieTitle.Focus(); } } private void txtMovieCode_Leave(object sender, EventArgs e) { if (txtMovieCode.Text != string.Empty) { sql_stmt = "SELECT * FROM movies WHERE MovieCode = '" + txtMovieCode.Text + "';"; if (clsPublicMethods.record_exists(sql_stmt) == true) { clsPublicMethods.duplicate_msg("Movie Code"); } } } private void btnSave_Click(object sender, EventArgs e) { if (txtMovieCode.Text == string.Empty) { clsPublicMethods.required_field_msg("Movie Code"); txtMovieCode.Focus(); return; } if (txtMovieTitle.Text == string.Empty) { clsPublicMethods.required_field_msg("Movie Title"); txtMovieTitle.Focus(); return; } if (clsPublicMethods.confirm_save_update() == DialogResult.Yes) { if (ADD_NEW == true) { sql_stmt = "INSERT INTO movies (MovieCode, MovieTitle, Category, RentalPrice, Director,YearReleased) "; sql_stmt += "VALUES ('" + txtMovieCode.Text + "','" + txtMovieTitle.Text + "','" + cboCategory.Text + "'," + rental_price + ",'" + txtMovieDirector.Text + "','" + txtYear.Text + "');"; } else { sql_stmt = "UPDATE movies SET MovieTitle = '" + txtMovieTitle.Text + "',Category = '" + cboCategory.Text + "', RentalPrice = " + rental_price + ", Director = '" + txtMovieDirector.Text + "', YearReleased = '" + txtYear.Text + "' WHERE MovieCode = '" + txtMovieCode.Text + "';"; } clsPublicMethods.DBUtilies.execute_sql_statement(sql_stmt); ADD_NEW = false; txtMovieCode.Enabled = false; clsPublicMethods.saved_updated_msg(); } } private void btnClose_Click(object sender, EventArgs e) { Close(); } private void txtRentalPrice_TextChanged(object sender, EventArgs e) { if (txtRentalPrice.Text != string.Empty) { try { rental_price = double.Parse(txtRentalPrice.Text); } catch (Exception ex) { MessageBox.Show("We have detected a non numeric character. please check the value you entered.", "Non-numeric character", MessageBoxButtons.OK, MessageBoxIcon.Warning); } } } #endregion } }
using System; using MinistryPlatform.Translation.Models.DTO; using MinistryPlatform.Translation.Repositories.Interfaces; using Moq; using NUnit.Framework; using SignInCheckIn.Services; namespace SignInCheckIn.Tests.Services { public class KioskServiceTest { private Mock<IKioskRepository> _kioskRepository; private KioskService _fixture; [SetUp] public void SetUp() { AutoMapperConfig.RegisterMappings(); _kioskRepository = new Mock<IKioskRepository>(); _fixture = new KioskService(_kioskRepository.Object); } [Test] public void TestGetKioskConfig() { var testGuid = Guid.Parse("9c01a404-3ba8-4f4a-b7b1-2183e30addd1"); var e = new MpKioskConfigDto { KioskIdentifier = testGuid }; _kioskRepository.Setup(mocked => mocked.GetMpKioskConfigByIdentifier(It.IsAny<Guid>())).Returns(e); var result = _fixture.GetKioskConfigByIdentifier(testGuid); _kioskRepository.VerifyAll(); Assert.AreEqual(e.KioskIdentifier, result.KioskIdentifier); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Xml; using IRAP.Global; namespace IRAP.Entities.MES { public class BatchProductInfo { public BatchProductInfo() { BatchStartDate = DateTime.Now; } /// <summary> /// 热定型容次号 /// </summary> public string BatchNumber { get; set; } /// <summary> /// 操作工工号 /// </summary> public string OperatorCode { get; set; } /// <summary> /// 操作工姓名 /// </summary> public string OperatorName { get; set; } /// <summary> /// 生产开始时间 /// </summary> public DateTime BatchStartDate { get; set; } /// <summary> /// 结束时间 /// </summary> public string BatchEndDate { get; set; } /// <summary> /// 班次代码 /// </summary> public string T126Code { get; set; } /// <summary> /// 班次信息 /// </summary> public string T126Name { get; set; } /// <summary> /// 环别叶标识 /// </summary> public int T131LeafID { get; set; } /// <summary> /// 环别代码 /// </summary> public string T131Code { get; set; } /// <summary> /// 环别名称 /// </summary> public string T131Name { get; set; } /// <summary> /// 正在生产的工单信息 /// [MethodItem] /// [Row FactID="" PWONo="" T102LeafID="" T102Code="" /// T102Name="" WIPCode="" LotNumber="" SerialNumber="" /// AltWIPCode="" Texture="" BatchLot="" Qty=""/] /// [/MethodItem] /// </summary> public string BatchDataXML { get; set; } /// <summary> /// 待检验的检验标准信息列表 --暂时从前台调用其他接口获取 /// </summary> public string MethodDataXML { get; set; } /// <summary> /// 是否正在生产 /// </summary> public int InProduction { get; set; } public BatchProductInfo Clone() { return MemberwiseClone() as BatchProductInfo; } public List<EntityBatchPWO> GetPWOsFromXML() { List<EntityBatchPWO> rlt = new List<EntityBatchPWO>(); XmlDocument doc = new XmlDocument(); try { doc.LoadXml(BatchDataXML); foreach (XmlNode node in doc.SelectNodes("MethodItem/Row")) { EntityBatchPWO pwo = new EntityBatchPWO(); if (node.Attributes["FactID"] != null) pwo.FactID = Tools.ConvertToInt64(node.Attributes["FactID"].Value); if (node.Attributes["PWONo"] != null) pwo.PWONo = node.Attributes["PWONo"].Value; if (node.Attributes["T102LeafID"] != null) pwo.T102LeafID = Tools.ConvertToInt32(node.Attributes["T102LeafID"].Value); if (node.Attributes["T102Code"] != null) pwo.T102Code = node.Attributes["T102Code"].Value; if (node.Attributes["T102Name"] != null) pwo.T102Name = node.Attributes["T102Name"].Value; if (node.Attributes["WIPCode"] != null) pwo.WIPCode = node.Attributes["WIPCode"].Value; if (node.Attributes["LotNumber"] != null) pwo.LotNumber = node.Attributes["LotNumber"].Value; if (node.Attributes["SerialNumber"] != null) pwo.SerialNumber = node.Attributes["SerialNumber"].Value; if (node.Attributes["AltWIPCode"] != null) pwo.AltWIPCode = node.Attributes["AltWIPCode"].Value; if (node.Attributes["Texture"] != null) pwo.Texture = node.Attributes["Texture"].Value; if (node.Attributes["BatchLot"] != null) pwo.BatchLot = node.Attributes["BatchLot"].Value; if (node.Attributes["Qty"] != null) pwo.Quantity = Tools.ConvertToInt64(node.Attributes["Qty"].Value); if (node.Attributes["Remark"] != null) pwo.Remark = node.Attributes["Remark"].Value; rlt.Add(pwo); } } catch { rlt.Clear(); } return rlt; } } }
using MongoDB.Bson; using MongoDB.Bson.Serialization.Attributes; using System; using System.Collections.Generic; using System.Text; namespace TimeTableApi.Core.Entities { public class User : Generic { [BsonId] [BsonRepresentation(BsonType.ObjectId)] public string Id { get; set; } [BsonElement("firstName")] public string FirstName { get; set; } [BsonElement("lastName")] public string LastName { get; set; } [BsonElement("email")] public string Email { get; set; } [BsonElement("phoneNumber")] public string PhoneNumber { get; set; } [BsonElement("password")] public string Password { get; set; } [BsonElement("dateOfBirth")] public DateTime DateOfBirth { get; set; } [BsonRepresentation(BsonType.ObjectId)] [BsonElement("roleId")] public string RoleId { get; set; } } }
using ApiTemplate.Core.Entities.Weathers; using ApiTemplate.Data.Repositories.Base; namespace ApiTemplate.Data.Repositories.Weathers { public interface IWeatherRepository :IRepository<Weather> { } }
using Effigy.Entity.DBContext; using System; using System.Data; using System.Data.SqlClient; namespace Effigy.DataObject.UnitOfWork { public class CLSDALPayment : ClsBaseDAL { private GenericRepository<tblMstUserDetail> _userDetail = null; public CLSDALPayment() { _userDetail = new GenericRepository<tblMstUserDetail>(_context); } public int SavePaymentDetail(PaymentDetails _objVal) { int Result = 0; try { SqlParameter[] sqlParam = { new SqlParameter("@TransitionID",_objVal.TransitionID), new SqlParameter("@UserID",_objVal.UserID), new SqlParameter("@PaidAmount",_objVal.PaidAmount), new SqlParameter("@IsGstInvoice",_objVal.IsGstInvoice), new SqlParameter("@GstNumber",_objVal.GstNumber), new SqlParameter("@GstHolderName",_objVal.GstHolderName), new SqlParameter("@GstHolderAddress",_objVal.GstHolderAddress), }; Result = _objSql.ExecuteNonQuery(CommandType.StoredProcedure, "InsertUserPaymentDetails", sqlParam); return Result; } catch (Exception) { throw; } finally { Dispose(); } } public void UpdateUserAfterPayment(int userId, DateTime? paymentDate) { try { var userDetail = _userDetail.GetSingle(o => o.UserId == userId); if (userDetail != null) { userDetail.IsMemberShipExpired = false; userDetail.IsMemberShipTaken = true; userDetail.LastPaymentDate = paymentDate; _context.SaveChanges(); } } catch (Exception) { throw; } } } }
/* * @Author: Atilla Tanrikulu * @Date: 2018-04-16 10:10:45 * @Last Modified by: Atilla Tanrikulu * @Last Modified time: 2018-04-16 10:10:45 */ using Microsoft.AspNetCore.Builder; using Microsoft.Extensions.DependencyInjection; namespace JavaScriptClient { public class Startup { public void ConfigureServices(IServiceCollection services) { } public void Configure(IApplicationBuilder app) { app.UseDefaultFiles(); app.UseStaticFiles(); } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Net; using System.Text; using System.Text.RegularExpressions; using System.Threading.Tasks; using System.Windows.Forms; using System.Xml; using OfficeOpenXml; namespace FindPostalAndPhone { public partial class Form1 : Form { private ICollection<WebsiteWithPostal> sites; BackgroundWorker worker = new BackgroundWorker(); public Form1() { InitializeComponent(); sites = new List<WebsiteWithPostal>(); worker.RunWorkerCompleted += Worker_RunWorkerCompleted; worker.DoWork += Worker_DoWork; worker.WorkerSupportsCancellation = true; } private void Worker_DoWork(object sender, DoWorkEventArgs e) { SetButtonsVisibilityDelegate sbvd = new SetButtonsVisibilityDelegate(SetButtonsVisibility); Invoke(sbvd, true); ReadExcel(); } private void Worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) { btnRun.Visible = true; btnStop.Visible = false; txtFilePath.ReadOnly = false; btnFindFile.Enabled = true; } private void btnFindFile_Click(object sender, EventArgs e) { ofdExcelFile.ShowDialog(); if (ofdExcelFile.CheckFileExists) txtFilePath.Text = ofdExcelFile.FileName; } private void btnRun_Click(object sender, EventArgs e) => worker.RunWorkerAsync(); private void btnStop_Click(object sender, EventArgs e) => worker.CancelAsync(); private delegate void SetButtonsVisibilityDelegate(bool running); private void SetButtonsVisibility(bool running) { btnRun.Visible = !running; btnStop.Visible = running; txtFilePath.ReadOnly = running; btnFindFile.Enabled = !running; } private void ReadExcel() { try { System.IO.FileInfo file = new System.IO.FileInfo(txtFilePath.Text); if (file.Exists) { var package = new ExcelPackage(file); ExcelWorksheet ws = package.Workbook.Worksheets[1]; var endRow = ws.Dimension.End.Row; var lastRow = 0; for (int i = 1; i <= endRow; i++) { if (worker.CancellationPending) break; SetMessage($"Kører række {i} af {endRow}"); string link = ws.Cells[i, 1].Text.Trim(); if (link != "") { string address = ws.Cells[i, 1].Address; WebsiteWithPostal web = new WebsiteWithPostal { URL = link, Address = address }; sites.Add(web); getPostalCodeAndPhone(web); ws.Cells[i, 2].Value = web.PostalCode; ws.Cells[i, 3].Value = web.Phone; } if (i % 10 == 0) package.Save(); lastRow = i; } package.Save(); SetMessage($"{lastRow} rækker kørt og gemt!"); } else throw new ArgumentException(); } catch (ArgumentException) { MessageBox.Show("Kunne ikke finde filen"); } catch (System.IO.IOException e) { MessageBox.Show(e.Message); } finally { btnRun.Enabled = true; } } private void SetMessage(string message) => tssLeft.Text = message; private void getPostalCodeAndPhone(WebsiteWithPostal web) { try { WebClient client = new WebClient(); HtmlAgilityPack.HtmlDocument document = new HtmlAgilityPack.HtmlDocument(); string downloadString = client.DownloadString(web.URL); document.LoadHtml(downloadString.ToLower()); var select = document.DocumentNode.SelectNodes("//meta[@http-equiv='refresh' and contains(@content, 'url')]"); if (select != null) { web.URL = select[0].Attributes["content"].Value.Split('=')[1]; downloadString = client.DownloadString(web.URL); document.LoadHtml(downloadString); } HtmlAgilityPack.HtmlNodeCollection bodyNodes = document.DocumentNode.SelectNodes("//body"); if (bodyNodes == null) web.PostalCode = "Ingen <body> på siden."; else { string innerText = document.DocumentNode.SelectNodes("//body")[0].InnerText; web.PostalCode = getPostal(innerText); web.Phone = getPhone(innerText); if (web.Phone == "" || web.PostalCode == "") { web.getSubSites(); foreach (String sub in web.subsites) { downloadString = client.DownloadString(web.URL.TrimEnd('/') + sub); document.LoadHtml(downloadString); innerText = document.DocumentNode.SelectNodes("//body")[0].InnerText; if (web.Phone == "") web.Phone = getPhone(innerText); if (web.PostalCode == "") web.PostalCode = getPostal(innerText); if (web.PostalCode != "" && web.Phone != "") break; } } if (web.Phone == "") web.Phone = "Intet fundet!"; if (web.PostalCode == "") web.PostalCode = "Intet fundet!"; } } catch (WebException) { web.PostalCode = "Kunne ikke finde siden"; } catch (Exception e) { web.PostalCode = e.Message; } } public string getPostal(string innerText) { Regex f = new Regex(@"(?:(?:\w(?: |&nbsp;))(\d{4}))|(?:(\d{4})(?: |&nbsp;)\w)"); string result = ""; foreach (Match m in f.Matches(innerText)) { string value = m.Groups[1].Value; if (value == "" && m.Groups.Count > 2) value = m.Groups[2].Value; if (postalCodes.Contains(value)) { result = value; break; } } return result; } private string getPhone(string innerText) { string result = ""; Regex t = new Regex(@"(?:Tlf|Telefon)[\.\:]\s*(?:\+45)?((?: ?\d){8})"); Regex t2 = new Regex(@"(?:\+45 ?)?(\d(?: ?\d){7})"); MatchCollection mc = t.Matches(innerText); if (mc.Count > 0) result = mc[0].Groups[0].Value; else { mc = t2.Matches(innerText); foreach (Match m in mc) { string value = m.Groups[0].Value; if (value.Contains(" ")) result = value; } } return result; } #region Postalcodes private string postalCodes = @"1000,1001,1002,1003,1004,1005,1006,1007,1008,1009,1010,1011,1012,1013,1014,1015,1016,1017,1018,1019,1020,1021,1022,1023,1024, 1025,1026,1045,1050,1051,1052,1053,1054,1055,1055,1056,1057,1058,1059,1060,1061,1062,1063,1064,1065,1066,1067,1068,1069,1070,1071,1072,1073,1074,1092, 1093,1095,1098,1100,1101,1102,1103,1104,1105,1106,1107,1110,1111,1112,1113,1114,1115,1116,1117,1118,1119,1120,1121,1122,1123,1124,1125,1126,1127,1128, 1129,1130,1131,1140,1147,1148,1150,1151,1152,1153,1154,1155,1156,1157,1158,1159,1160,1161,1162,1163,1164,1165,1165,1166,1167,1168,1169,1170,1171,1172, 1173,1174,1175,1200,1201,1202,1203,1204,1205,1206,1207,1208,1209,1210,1211,1212,1213,1214,1215,1216,1217,1218,1218,1218,1218,1218,1218,1219,1220,1221, 1240,1250,1251,1253,1254,1255,1256,1257,1259,1259,1260,1261,1263,1263,1264,1265,1266,1267,1268,1270,1271,1300,1301,1302,1303,1304,1306,1307,1307,1308, 1309,1310,1311,1312,1313,1314,1315,1316,1317,1318,1319,1320,1321,1322,1323,1324,1325,1326,1327,1328,1329,1350,1352,1353,1354,1355,1356,1357,1358,1359, 1359,1360,1361,1361,1362,1363,1364,1365,1366,1367,1368,1369,1370,1371,1400,1400,1401,1402,1402,1402,1402,1402,1403,1404,1406,1407,1408,1409,1410,1411, 1411,1412,1413,1414,1415,1416,1417,1418,1419,1420,1421,1422,1423,1424,1425,1426,1427,1428,1429,1430,1431,1432,1432,1432,1433,1433,1433,1433,1433,1433, 1433,1434,1435,1436,1436,1436,1436,1436,1436,1436,1437,1437,1437,1437,1437,1437,1437,1437,1437,1437,1437,1437,1438,1438,1438,1438,1438,1439,1439,1439, 1439,1439,1439,1439,1439,1439,1439,1439,1439,1439,1439,1439,1440,1440,1440,1440,1440,1440,1440,1440,1440,1440,1440,1441,1441,1441,1448,1450,1451,1452, 1453,1454,1455,1456,1457,1458,1459,1460,1461,1462,1463,1464,1465,1466,1467,1468,1470,1471,1472,1473,1500,1501,1502,1503,1504,1505,1506,1507,1508,1509, 1510,1512,1513,1532,1533,1550,1550,1551,1552,1553,1553,1554,1555,1556,1557,1558,1559,1560,1561,1561,1562,1563,1564,1566,1567,1568,1569,1570,1570,1571, 1572,1573,1574,1575,1576,1577,1577,1577,1592,1599,1600,1601,1602,1603,1604,1605,1606,1607,1608,1609,1610,1611,1612,1613,1614,1615,1616,1617,1618,1619, 1620,1620,1621,1622,1623,1624,1630,1631,1632,1633,1634,1635,1650,1651,1652,1653,1654,1655,1656,1657,1658,1659,1660,1660,1661,1662,1663,1664,1665,1666, 1667,1668,1669,1670,1671,1672,1673,1674,1675,1676,1677,1699,1700,1701,1702,1703,1704,1705,1706,1707,1708,1709,1710,1711,1711,1712,1713,1714,1715,1716, 1717,1718,1719,1720,1721,1722,1723,1724,1725,1726,1727,1728,1729,1730,1731,1732,1733,1734,1735,1736,1737,1738,1739,1749,1750,1751,1752,1753,1754,1755, 1756,1757,1758,1759,1760,1761,1762,1763,1764,1765,1766,1770,1771,1772,1773,1774,1775,1777,1780,1782,1785,1786,1787,1790,1799,1799,1799,1799,1799,1799, 1799,1799,1799,1799,1799,1799,1799,1800,1801,1802,1803,1804,1805,1806,1807,1808,1809,1810,1811,1812,1813,1814,1815,1816,1817,1818,1819,1820,1822,1823, 1824,1825,1826,1827,1828,1829,1835,1850,1851,1852,1853,1854,1855,1856,1857,1860,1861,1862,1863,1864,1865,1866,1867,1868,1870,1871,1872,1873,1874,1875, 1876,1877,1878,1879,1900,1901,1902,1903,1904,1905,1906,1908,1909,1910,1911,1912,1913,1914,1915,1916,1917,1920,1921,1922,1923,1924,1925,1926,1927,1928, 1931,1950,1951,1952,1953,1954,1955,1956,1957,1958,1959,1960,1961,1962,1963,1964,1965,1966,1967,1970,1971,1972,1973,1974,2000,2100,2150,2200,2300,2400, 2450,2500,2600,2605,2610,2620,2625,2630,2635,2640,2650,2660,2665,2670,2680,2690,2700,2720,2730,2740,2750,2760,2765,2770,2791,2800,2820,2830,2840,2850, 2860,2870,2880,2900,2920,2930,2942,2950,2960,2970,2980,2990,3000,3050,3060,3070,3080,3100,3120,3140,3150,3200,3210,3220,3230,3250,3300,3310,3320,3330, 3360,3370,3390,3400,3450,3460,3480,3490,3500,3520,3540,3550,3600,3630,3650,3660,3670,3700,3720,3730,3740,3751,3760,3770,3782,3790,4000,4030,4040,4050, 4060,4070,4100,4129,4130,4140,4160,4171,4173,4174,4180,4190,4200,4220,4230,4241,4242,4243,4244,4245,4250,4261,4262,4270,4281,4291,4293,4295,4296,4300, 4305,4320,4330,4340,4350,4360,4370,4390,4400,4420,4440,4450,4460,4470,4480,4490,4500,4520,4532,4534,4540,4550,4560,4571,4572,4573,4581,4583,4591,4592, 4593,4600,4621,4622,4623,4632,4640,4652,4653,4654,4660,4671,4672,4673,4681,4682,4683,4684,4690,4700,4720,4733,4735,4736,4750,4760,4771,4772,4773,4780, 4791,4792,4793,4800,4840,4850,4862,4863,4871,4872,4873,4874,4880,4891,4892,4894,4895,4900,4912,4913,4920,4930,4941,4942,4943,4944,4945,4951,4952,4953, 4960,4970,4983,4990,4992,5000,5029,5100,5200,5210,5220,5230,5240,5250,5260,5270,5290,5300,5320,5330,5350,5370,5380,5390,5400,5450,5462,5463,5464,5466, 5471,5474,5485,5491,5492,5500,5540,5550,5560,5580,5591,5592,5600,5602,5603,5610,5620,5631,5642,5672,5683,5690,5700,5750,5762,5771,5772,5792,5800,5853, 5854,5856,5863,5871,5874,5881,5882,5883,5884,5892,5900,5932,5935,5943,5953,5960,5965,5970,5985,6000,6040,6051,6052,6064,6070,6091,6092,6093,6094,6100, 6200,6210,6230,6240,6261,6270,6280,6300,6310,6320,6330,6340,6360,6372,6392,6400,6430,6440,6470,6500,6510,6520,6534,6535,6541,6560,6580,6600,6621,6622, 6623,6630,6640,6650,6660,6670,6682,6683,6690,6700,6701,6705,6710,6715,6720,6731,6740,6752,6753,6760,6771,6780,6792,6800,6818,6823,6830,6840,6851,6852, 6853,6854,6855,6857,6862,6870,6880,6893,6900,6920,6933,6940,6950,6960,6971,6973,6980,6990,7000,7007,7017,7018,7029,7080,7100,7120,7130,7140,7150,7160, 7171,7173,7182,7183,7184,7190,7200,7250,7260,7270,7280,7300,7321,7323,7330,7361,7362,7400,7429,7430,7441,7442,7451,7470,7480,7490,7500,7540,7550,7560, 7570,7600,7620,7650,7660,7673,7680,7700,7730,7741,7742,7752,7755,7760,7770,7790,7800,7830,7840,7850,7860,7870,7884,7900,7950,7960,7970,7980,7990,7992, 7993,7996,7997,7998,7999,8000,8100,8200,8210,8220,8229,8230,8240,8245,8250,8260,8270,8300,8305,8310,8320,8330,8340,8350,8355,8361,8362,8370,8380,8381, 8382,8400,8410,8420,8444,8450,8462,8464,8471,8472,8500,8520,8530,8541,8543,8544,8550,8560,8570,8581,8585,8586,8592,8600,8620,8632,8641,8643,8653,8654, 8660,8670,8680,8700,8721,8722,8723,8732,8740,8751,8752,8762,8763,8765,8766,8781,8783,8789,8799,8800,8830,8831,8832,8840,8850,8860,8870,8881,8882,8883, 8900,8920,8930,8940,8950,8960,8961,8963,8970,8981,8983,8990,9000,9029,9100,9200,9210,9220,9230,9240,9260,9270,9280,9293,9300,9310,9320,9330,9340,9352, 9362,9370,9380,9381,9382,9400,9430,9440,9460,9480,9490,9492,9493,9500,9510,9520,9530,9541,9550,9560,9574,9575,9600,9610,9620,9631,9632,9640,9670,9681, 9690,9700,9740,9750,9760,9800,9830,9850,9870,9881,9900,9940,9970,9981,9982,9990,9992,9993,9996,9997,9998,2412,3900,3905,3910,3911,3912,3913,3915,3919, 3920,3921,3922,3923,3924,3930,3932,3940,3950,3951,3952,3953,3955,3961,3962,3964,3970,3971,3972,3980,3982,3984,3985,3992"; #endregion } public class WebsiteWithPostal { public List<String> subsites; public string URL { get; set; } public string Address { get; set; } public WebsiteWithPostal() => subsites = new List<String>(); public string PostalCode { get; set; } public string Phone { get; set; } public void getSubSites(bool checkAllSubs = false) { try { WebClient client = new WebClient(); HtmlAgilityPack.HtmlDocument document = new HtmlAgilityPack.HtmlDocument(); string downloadString = client.DownloadString(URL); document.LoadHtml(downloadString); HtmlAgilityPack.HtmlNodeCollection aNodes = document.DocumentNode.SelectNodes("//a"); foreach (HtmlAgilityPack.HtmlNode a in aNodes) { string href = a.Attributes["href"]?.Value; if (href != null && href.StartsWith("/") && href.Length > 1 && !subsites.Contains(href) && (checkAllSubs || (href.ToLower().Contains("contact") || href.ToLower().Contains("kontakt")))) subsites.Add(href); } if (!checkAllSubs && subsites.Count == 0) getSubSites(true); } catch (Exception) { PostalCode = "Kunne ikke finde undersider"; } } } }
using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using Alabo.Domains.Entities; using Alabo.Domains.Repositories.Mongo.Extension; using Alabo.Industry.Shop.Orders.Domain.Enums; using MongoDB.Bson; using MongoDB.Bson.Serialization.Attributes; using Newtonsoft.Json; namespace Alabo.Industry.Shop.AfterSales.Domain.Entities { /// <summary> /// 评价 /// </summary> [BsonIgnoreExtraElements] [Table("AfterSale_Evaluate")] public class Evaluate : AggregateMongodbUserRoot<Evaluate> { /// <summary> /// 商品ID /// </summary> [Required] public long ProductId { get; set; } /// <summary> /// 店铺ID,该字段为冗余字段,方便以后查询 /// </summary> [Required] [JsonConverter(typeof(ObjectIdConverter))] public ObjectId StoreId { get; set; } /// <summary> /// 订单ID /// </summary> [Required] public long OrderId { get; set; } /// <summary> /// 评价内容 /// </summary> [Required] public string Content { get; set; } /// <summary> /// 评价方式,好评中评,差评 /// </summary> public ReviewType ReviewType { get; set; } /// <summary> /// 商品评分,描述相符 /// 最终的商品评分需更新到Product表中 /// </summary> [Required] [Range(0, 5)] public long ProductScore { get; set; } /// <summary> /// 物流速度 物流评分 /// </summary> [Required] [Range(0, 5)] public long LogisticsScore { get; set; } /// <summary> /// 服务评分 /// </summary> [Required] [Range(0, 5)] public long ServiceScore { get; set; } /// <summary> /// 图片 逗号隔开(路径),最多五个 /// </summary> public List<string> Images { get; set; } } }
using System; using System.Collections; using System.Collections.Generic; using System.Data.Entity; using System.Linq; using System.Security; using System.Security.Cryptography.X509Certificates; using System.Threading.Tasks; using ApartmentApps.Api.BindingModels; using ApartmentApps.Api.Modules; using ApartmentApps.Api.ViewModels; using ApartmentApps.Data; using ApartmentApps.Data.Repository; using ApartmentApps.Data.Utils; using ApartmentApps.Forms; using ApartmentApps.Modules.Payments.Data; using ApartmentApps.Modules.Payments.Services; using ApartmentApps.Payments.Forte; using ApartmentApps.Payments.Forte.Forte.Client; using ApartmentApps.Payments.Forte.Forte.Merchant; using ApartmentApps.Payments.Forte.Forte.Transaction; using ApartmentApps.Payments.Forte.PaymentGateway; using ApartmentApps.Portal.Controllers; using IniParser.Model; using IniParser.Model.Configuration; using IniParser.Parser; using Ninject; using Ninject.Planning.Bindings; using Authentication = ApartmentApps.Payments.Forte.Forte.Client.Authentication; using ExecuteSocketQueryParams = ApartmentApps.Payments.Forte.PaymentGateway.ExecuteSocketQueryParams; namespace ApartmentApps.Api.Modules { public class PaymentsModule : Module<PaymentsConfig>, IMenuItemProvider, IAdminConfigurable, IPaymentsService, IFillActions, IWebJob { private readonly IRepository<UserLeaseInfo> _leaseRepository; private readonly IRepository<Invoice> _invoiceRepository; private readonly IRepository<InvoiceTransaction> _transactionRepository; private LeaseInfoManagementService _leaseService; private IRepository<TransactionHistoryItem> _transactionHistory; public PropertyContext Context { get; set; } public PaymentsModule(IRepository<UserLeaseInfo> leaseRepository, IRepository<Invoice> invoiceRepository, IRepository<InvoiceTransaction> transactionRepository, PropertyContext context, IRepository<PaymentsConfig> configRepo, IUserContext userContext, IKernel kernel, LeaseInfoManagementService leaseService, IRepository<TransactionHistoryItem> transactionHistory) : base(kernel, configRepo, userContext) { _leaseRepository = leaseRepository; _invoiceRepository = invoiceRepository; _transactionRepository = transactionRepository; Context = context; _leaseService = leaseService; _transactionHistory = transactionHistory; } public void FillActions(List<ActionLinkModel> actions, object viewModel) { var user = viewModel as UserBindingModel; var paymentRequest = viewModel as UserLeaseInfoBindingModel; if (user != null && !Config.UseUrl) { //paymentsHome.Children.Add(new MenuItemViewModel("Overview", "fa-shopping-cart", "UserPaymentsOverview", "Payments",new {id = UserContext.CurrentUser.Id})); actions.Add(new ActionLinkModel("Payments Overview", "UserPaymentsOverview", "Payments", new { id = user.Id }) { Icon = "fa-credit-card", Group = "Payments" }); actions.Add(new ActionLinkModel("Quick Add Rent", "QuickAddRent", "PaymentRequests", new { userId = user.Id }) { Icon = "fa-credit-card", Group = "Payments", IsDialog = true }); } else if ( paymentRequest != null ) { actions.Add(new ActionLinkModel("Edit Request","Entry","PaymentRequests",new {id = paymentRequest.Id}) { Icon = "fa-edit", Group = "Manage", IsDialog = true }); actions.Add(new ActionLinkModel("Cancel Request","","",new {id = paymentRequest.Id}) { Icon = "fa-remove", Group = "Manage" }); } } public void PopulateMenuItems(List<MenuItemViewModel> menuItems) { if (!UserContext.IsInRole("Admin") && !UserContext.IsInRole("PropertyAdmin") && !UserContext.IsInRole("Resident")) return; var paymentsHome = new MenuItemViewModel("Payments", "fa-money", "Index", "Payments"); if (!Config.UseUrl) { if (UserContext.IsInRole("Admin") || UserContext.IsInRole("PropertyAdmin")) { paymentsHome.Children.Add(new MenuItemViewModel("Create Payment Request", "fa-plus", "CreateUserLeaseInfoFor", "Payments")); paymentsHome.Children.Add(new MenuItemViewModel("Payment Requests", "fa-list-alt", "Index", "PaymentRequests")); // paymentsHome.Children.Add(new MenuItemViewModel("Payment Options", "fa-list-alt", "Index", "PaymentOptions")); // paymentsHome.Children.Add(new MenuItemViewModel("Users", "fa-shopping-cart", "PaymentsUsers", "Payments")); } if (Config.Enabled && UserContext.IsInRole("Resident")) { paymentsHome.Children.Add(new MenuItemViewModel("Overview", "fa-shopping-cart", "UserPaymentsOverview", "Payments", new {id = UserContext.CurrentUser.Id})); } menuItems.Add(paymentsHome); } else if (!string.IsNullOrEmpty(Config.Url)) { paymentsHome.Children.Add(new MenuItemViewModel(Config.Url) {Label = "Pay Rent", Icon = "fa-credit-card" }); menuItems.Add(paymentsHome); } } public string SettingsController => "PaymentsConfig"; public string MerchantPassword => Config.MerchantPassword; //IRepository<Property> propertyRepo, public int MerchantId => string.IsNullOrEmpty(Config.MerchantId) ? 0 : Convert.ToInt32(Config.MerchantId); public string ApiLoginId => Config.ApiLoginId; public string Key => Config.SecureTransactionKey; //Includes fee public async Task<PaymentListBindingModel> GetPaymentSummaryFor(string userId, string paymentOptionId) { var user = Context.Users.Find(userId); if (user == null) throw new KeyNotFoundException("User Not Found"); var paymentOption = Context.PaymentOptions.Find(paymentOptionId); if (paymentOption == null) throw new KeyNotFoundException("Payment Option Not Found"); var dateTime = user.Property.TimeZone.Now(); var invoices = _invoiceRepository.GetAvailableBy(dateTime, userId).ToArray(); var subtotal = invoices.Sum(s => s.Amount); var confFeefunction = GetConvenienceFeeForPaymentOption(Convert.ToInt32(paymentOptionId), userId); decimal convFee = confFeefunction(subtotal); return new PaymentListBindingModel() { Items = invoices.Concat(new[] { new Invoice() { Amount = convFee, Title = "Convenience Fee" } }).ToLines() }; } public async Task<PaymentListBindingModel> GetRentSummaryFor(string userId) { var user = Context.Users.Find(userId); if (user == null) throw new KeyNotFoundException("User Not Found"); var dateTime = user.Property.TimeZone.Now(); var invoices = _invoiceRepository.GetAvailableBy(dateTime, userId).ToArray(); return new PaymentListBindingModel() { Items = invoices.ToLines() }; } public IEnumerable<TransactionHistoryItemBindingModel> GetOpenTransactions() { var openedTransactions = _transactionHistory.Where(s => s.State == TransactionState.Open).ToArray(); //var cl = new TransactionServiceClient("BasicHttpBinding_ITransactionService"); //var auth = Authenticate.GetTransactionAuthTicket(ApiLoginId, Key); foreach (var tr in openedTransactions) { // var state = cl.getTransaction(auth, MerchantId, tr.Trace); //ForteTransactionStateCode fState; //Enum.TryParse(state.Response.Status,out fState); yield return tr.ToBindingModel(); } } public async Task<AddCreditCardResult> AddCreditCard(AddCreditCardBindingModel addCreditCard) { var auth = Authenticate.GetClientAuthTicket(ApiLoginId, Key); var userId = addCreditCard.UserId ?? UserContext.UserId; int clientId = await EnsureClientId(auth, userId); PaymentMethod payment = new PaymentMethod(); payment.AcctHolderName = addCreditCard.AccountHolderName; payment.CcCardNumber = addCreditCard.CardNumber; payment.CcExpirationDate = addCreditCard.ExpirationDate; payment.CcCardType = (CcCardType)Enum.Parse(typeof(CcCardType), addCreditCard.CardType.ToString()); payment.Note = addCreditCard.FriendlyName; payment.ClientID = clientId; payment.MerchantID = MerchantId; using (var client = new ClientServiceClient("WSHttpBinding_IClientService")) { try { var result = await client.createPaymentMethodAsync(auth, payment); var paymentMethodId = result.Body.createPaymentMethodResult; var userPaymentOption = new UserPaymentOption() { UserId = userId, FriendlyName = addCreditCard.FriendlyName, TokenId = paymentMethodId.ToString() }; switch (addCreditCard.CardType) { case CardType.VISA: userPaymentOption.Type = PaymentOptionType.VisaCard; break; case CardType.MAST: userPaymentOption.Type = PaymentOptionType.MasterCard; break; case CardType.DISC: userPaymentOption.Type = PaymentOptionType.DiscoveryCard; break; case CardType.AMER: userPaymentOption.Type = PaymentOptionType.AmericanExpressCard; break; case CardType.DINE: throw new NotImplementedException(); break; case CardType.JCB: throw new NotImplementedException(); break; default: throw new ArgumentOutOfRangeException(); } Context.PaymentOptions.Add(userPaymentOption); Context.SaveChanges(); return new AddCreditCardResult() {PaymentOptionId = userPaymentOption.Id}; } catch (Exception ex) { return new AddCreditCardResult() {ErrorMessage = ex.Message}; } } } public async Task<AddBankAccountResult> AddBankAccount(AddBankAccountBindingModel addCreditCard) { var auth = Authenticate.GetClientAuthTicket(ApiLoginId, Key); var userId = addCreditCard.UserId ?? UserContext.UserId; int clientId = await EnsureClientId(auth, userId); PaymentMethod payment = new PaymentMethod(); payment.AcctHolderName = addCreditCard.AccountHolderName; payment.EcAccountNumber = addCreditCard.AccountNumber; payment.EcAccountTRN = addCreditCard.RoutingNumber; payment.EcAccountType = addCreditCard.IsSavings ? EcAccountType.SAVINGS : EcAccountType.CHECKING; payment.Note = addCreditCard.FriendlyName; payment.ClientID = clientId; payment.MerchantID = MerchantId; using (var client = new ClientServiceClient("WSHttpBinding_IClientService")) { try { var result = await client.createPaymentMethodAsync(auth, payment); var paymentMethodId = result.Body.createPaymentMethodResult; var userPaymentOption = new UserPaymentOption() { UserId = userId, Type = addCreditCard.IsSavings ? PaymentOptionType.Savings : PaymentOptionType.Checking, FriendlyName = addCreditCard.FriendlyName, TokenId = paymentMethodId.ToString() }; Context.PaymentOptions.Add(userPaymentOption); Context.SaveChanges(); return new AddBankAccountResult() {PaymentOptionId = userPaymentOption.Id}; } catch (Exception ex) { return new AddBankAccountResult() {ErrorMessage = ex.Message}; } } } public IEnumerable<PaymentOptionBindingModel> GetPaymentOptions() { return Context.PaymentOptions.Where(p => p.UserId == UserContext.UserId).Select(x => new PaymentOptionBindingModel() { FriendlyName = x.FriendlyName, Type = x.Type, Id = x.Id.ToString(), }); } public IEnumerable<PaymentOptionBindingModel> GetPaymentOptionsFor(string userId) { return Context.PaymentOptions.Where(p => p.UserId == userId).Select(x => new PaymentOptionBindingModel() { FriendlyName = x.FriendlyName, Type = x.Type, Id = x.Id.ToString(), }); } public IEnumerable<UserInvoiceHistoryBindingModel> GetPaymentHistory() { //return Context.UserTransactions. yield break; } public Func<decimal, decimal> GetConvenienceFeeForPaymentOption(int paymentOptionId, string userId) { var paymentOption = Context.PaymentOptions.FirstOrDefault(p => p.UserId == userId && p.Id == paymentOptionId); if (paymentOption == null) { throw new KeyNotFoundException("Payment Option Not Found"); } switch (paymentOption.Type) { case PaymentOptionType.VisaCard: return cash => (cash/100)*Config.VisaConvenienceFee; case PaymentOptionType.AmericanExpressCard: return cash => (cash/100)*Config.AmericanExpressConvenienceFee; case PaymentOptionType.DiscoveryCard: return cash => (cash/100)*Config.DiscoverConvenienceFee; case PaymentOptionType.MasterCard: return cash => (cash/100)*Config.MastercardConvenienceFee; case PaymentOptionType.Checking: return cash => Config.BankAccountCheckingConvenienceFee; case PaymentOptionType.Savings: return cash => Config.BankAccountSavingsConvenienceFee; default: return cash => 0m; } } public async Task<bool> ForceRejectTransaction(int transactionId) { var transaction = _transactionHistory.Where(s => s.Id == transactionId).Include(s => s.Invoices).FirstOrDefault(); return await ForceRejectTransaction(transaction); } public async Task<bool> ForceCompleteTransaction(int transactionId) { var transaction = _transactionHistory.Where(s => s.Id == transactionId).Include(s => s.Invoices).FirstOrDefault(); return await ForceCompleteTransaction(transaction); } public async Task<bool> ForceRejectTransaction(TransactionHistoryItem transaction) { RejectForteTransaction(transaction, "Force Reject by " + UserContext.Email, ForteTransactionStateCode.SystemForceRejected); return false; } public async Task<bool> ForceCompleteTransaction(TransactionHistoryItem transaction) { CompleteForteTransaction(transaction, "Force Complete by " + UserContext.Email, ForteTransactionStateCode.SystemForceComplete); return false; } public async Task<MakePaymentResult> MakePayment(MakePaymentBindingModel makePaymentBindingModel) { var auth = Authenticate.GetClientAuthTicket(ApiLoginId, Key); var userId = makePaymentBindingModel.UserId ?? UserContext.UserId; int clientId = await EnsureClientId(auth, userId); var paymentOptionId = Convert.ToInt32(makePaymentBindingModel.PaymentOptionId); var paymentOption = Context.PaymentOptions.FirstOrDefault(p => p.UserId == userId && p.Id == paymentOptionId); if (paymentOption == null) { return new MakePaymentResult() {ErrorMessage = "Payment Option Not Found."}; } var user = Context.Users.Find(userId); var by = user.Property.TimeZone.Now(); //TODO: change later to get UserId from parameter var invoices = _invoiceRepository.GetAvailableBy(by, userId).ToArray(); var subtotal = invoices.Sum(s => s.Amount); var convFeeFunction = GetConvenienceFeeForPaymentOption(paymentOptionId, userId); var convFee = convFeeFunction(subtotal); var total = subtotal + convFee; PaymentGatewaySoapClient transactionClient = null; try { transactionClient = new Payments.Forte.PaymentGateway.PaymentGatewaySoapClient("PaymentGatewaySoap"); } catch (Exception ex) { throw; } var pgTotalAmount = $"{total.ToString("0.00")}"; var response = transactionClient.ExecuteSocketQuery(new ExecuteSocketQueryParams() { PgMerchantId = MerchantId.ToString(), PgClientId = clientId.ToString(), PgPaymentMethodId = paymentOption.TokenId, PgPassword = MerchantPassword, //"LEpLqvx7Y5L200" PgTotalAmount = pgTotalAmount, PgTransactionType = "10", //sale }); ForteMakePaymentResponse typedResponse = null; try { typedResponse = ForteMakePaymentResponse.FromIniString(response); } catch (Exception ex) { return new MakePaymentResult() { ErrorMessage = "Please, contact our support." }; } _leaseService.CreateTransaction(typedResponse.TraceNumber, userId, UserContext.UserId, total, convFee, invoices, "Transaction Opened.", DateTime.Now); return new MakePaymentResult() { }; } private async Task<int> EnsureClientId(Authentication auth, string userId) { var user = UserContext.CurrentUser; if (!string.IsNullOrEmpty(userId)) { user = Context.Users.Find(userId); } var clientId = user.ForteClientId ?? 0; var client = new ClientServiceClient("WSHttpBinding_IClientService"); // If the user doesnt have a client account with forte try { if (clientId == 0) { var result = await client.createClientAsync(auth, new ClientRecord() { MerchantID = MerchantId, FirstName = user.FirstName, LastName = user.LastName, Status = ClientStatus.Active }); user.ForteClientId = clientId = result.Body.createClientResult; Context.SaveChanges(); } } catch (Exception ex) { throw; } return clientId; } public void UpdateOpenForteTransactions() { // get payments module var openedTransactions = _transactionHistory.Where(s => s.State == TransactionState.Open).Include(s => s.Invoices).ToArray(); var cl = new TransactionServiceClient("BasicHttpBinding_ITransactionService"); var auth = Authenticate.GetTransactionAuthTicket(ApiLoginId, Key); foreach (var tr in openedTransactions) { var state = cl.getTransaction(auth, MerchantId, tr.Trace); UpdateForteTransaction(tr, state); } } public void UpdateForteTransaction(TransactionHistoryItem transaction, Transaction forteTransaction) { var forteState = ForteTransactioNStateCodeMapping.FromString(forteTransaction.Response.Status); switch (forteState) { case ForteTransactionStateCode.Complete: // eCheck verification was performed and the results were positive (POS) or unknown (UNK). case ForteTransactionStateCode.Authorized: // The customer's payment was authorized. To complete the sale, the item must be captured from the transaction's detail page. case ForteTransactionStateCode.Review: // Transaction was unable to be settled due to a merchant configuration issue. Please contact Customer Service to resolve (1-469-675-9920 x1). case ForteTransactionStateCode.Ready: // Transaction was received and is awaiting origination (echeck) or settlement (credit card). case ForteTransactionStateCode.Settling: // eCheck item has been originated and Forte is awaiting the settlement results. UpdateForteTransaction(transaction, forteTransaction.Response.ResponseDescription, forteState); break; case ForteTransactionStateCode.Funded: // eCheck item was funded to or from the merchant's bank account. case ForteTransactionStateCode.Settled: // Credit Card itme has been funded to the merchant's bank account. CompleteForteTransaction(transaction, forteTransaction.Response.ResponseDescription, forteState); break; case ForteTransactionStateCode.Declined: // Transaction was declined for reasons detailed in Response Code and Response Description. case ForteTransactionStateCode.Failed: // eCheck verification was performed and the results were negative (NEG) or the transaction failed for reasons detailed in the Response Code and Response Description. case ForteTransactionStateCode.Rejected: // eCheck item has been rejected or returned by the client's financial institution. Merchant will not be funded for the item case ForteTransactionStateCode.Unfunded: // Previously funded eCheck itme has been returned and funding was reversed. case ForteTransactionStateCode.Voided: // Transaction was voided and item will not be originated or settled. RejectForteTransaction(transaction, forteTransaction.Response.ResponseDescription, forteState); break; default: throw new ArgumentOutOfRangeException(); } _transactionHistory.Save(); } public void UpdateForteTransaction(TransactionHistoryItem target, string message, ForteTransactionStateCode state) { target.StateMessage = message; target.ForteState = state; } public void CompleteForteTransaction(TransactionHistoryItem target, string message, ForteTransactionStateCode state) { target.StateMessage = message; target.ForteState = state; _leaseService.OnTransactionComplete(target, message, target.User.Property.TimeZone.Now()); } public PaymentHistoryIndexBindingModel GetPaymentHistoryFor(string userId) { var tranascations = _transactionHistory.GetAll().Where(s => s.UserId == userId); return new PaymentHistoryIndexBindingModel() { UserId = userId, History = tranascations.Select(s => new PaymentHistoryIndexItemBindingModel() { }).ToList() }; } public TransactionHistoryItemBindingModel GetPaymentHistoryItemFor(string transactionId) { var tranascation = _transactionHistory.Find(transactionId); return tranascation.ToBindingModel(); } public void RejectForteTransaction(TransactionHistoryItem target, string message, ForteTransactionStateCode state) { target.StateMessage = message; target.ForteState = state; _leaseService.OnTransactionError(target, message, target.User.Property.TimeZone.Now()); } public void MarkAsPaid(int id, string s) { var invoice = _invoiceRepository.Find(id); if (invoice == null) throw new KeyNotFoundException(); var user = invoice.UserLeaseInfo.User; if (user == null) throw new KeyNotFoundException(); var opId = Guid.NewGuid().ToString(); //_leaseService.˘CreateTransaction(opId, user.Id, new[] {invoice}, "", DateTime.Now); //var transaction = _transactionRepository.Find(opId); //_leaseService.OnTransactionComplete(transaction,s,user.Property.TimeZone.Now()); //_transactionRepository.Save(); } public TimeSpan Frequency => new TimeSpan(5, 0, 0); public int JobStartHour => 0; public int JobStartMinute => 0; public void Execute(ILogger logger) { if (string.IsNullOrEmpty(ApiLoginId)) return; if (MerchantId < 1) return; if (string.IsNullOrEmpty(Key)) return; UpdateOpenForteTransactions(); logger.Info("Open transactions updated from forte."); } } } public class PaymentHistoryIndexBindingModel { public string UserId { get; set; } public List<PaymentHistoryIndexItemBindingModel> History { get; set; } } public class PaymentHistoryIndexItemBindingModel { public string UserId { get; set; } public string Id { get; set; } public TransactionState State { get; set; } public DateTime OpenDate { get; set; } public DateTime? CloseDate { get; set; } public decimal Amount { get; set; } } public class ForteMakePaymentResponse { /* pg_response_type=A pg_response_code=A01 pg_response_description=TEST APPROVAL pg_authorization_code=123456 pg_trace_number=796B02B2-35DB-4987-BD62-15F5DD1EDF25 pg_avs_code=Y pg_cvv_code=M pg_merchant_id=187762 pg_transaction_type=10 pg_total_amount=1215.0 pg_client_id=2077254 pg_payment_method_id=2358399 endofdata */ public string TraceNumber { get { return _traceNumber; } set { _traceNumber = value; } } public string ResponseCodeString { get { return _responseCodeString; } set { _responseCodeString = value; } } public ForteTransactionResultCode ResponseCode { get; set; } private static IniDataParser Parser = new IniDataParser(new IniParserConfiguration() { SkipInvalidLines = true }); private string _traceNumber; private string _responseCodeString; public static ForteMakePaymentResponse FromIniString(string ini) { var res = new ForteMakePaymentResponse(); res.ReadFromIni(Parser.Parse(ini)); return res; } public void ReadFromIni(IniData data) { string respCode = null; if (data.TryGetKey("pg_response_code", out _responseCodeString)) { ResponseCode = ForteTransactionResultCodeMapping.Codes[_responseCodeString]; } data.TryGetKey("pg_trace_number", out _traceNumber); } } public static class PaymentsListExtensions { public static List<PaymentLineBindingModel> ToLines(this IEnumerable<Invoice> invoices) { var list = new List<PaymentLineBindingModel>(); decimal total = 0; foreach (var inv in invoices) { var line = new PaymentLineBindingModel() { Format = PaymentSummaryFormat.Default, Price = $"{inv.Amount:$#,##0.00;($#,##0.00);Zero}", Title = inv.Title }; total += inv.Amount; list.Add(line); } list.Add(new PaymentLineBindingModel() { Format = PaymentSummaryFormat.Total, Price = $"{total:$#,##0.00;($#,##0.00);Zero}", Title = "Total" }); return list; } }
using Alabo.Framework.Core.Reflections.Interfaces; using Alabo.Helpers; using Alabo.Industry.Cms.Articles.Domain.Services; namespace Alabo.Industry.Cms.Articles { public class ArticleDefaultInit : IDefaultInit { public bool IsTenant => false; public void Init() { //频道数据初始化 Ioc.Resolve<IChannelService>().InitialData(); //关于我们 Ioc.Resolve<IAboutService>().InitialData(); } } }
using ISE.Framework.Common.CommonBase; using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ISE.SM.Common.DTO { public partial class RoleToRoleConstraintDto:BaseDto { public RoleToRoleConstraintDto() { this.PrimaryKeyName = "RrConstraintId"; } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class BaseAttackAudio { public AudioClip SE; public int frame; }
using System; using System.Linq; namespace Calculator.Logic.Operations { public abstract class BasicOperation { public string Tag { get; set; } public string StringToFile { get; set; } protected Operation OperationClass; public BasicOperation(IOperation operationClass) { OperationClass = operationClass as Operation; } public virtual void Run() { } public virtual void AddToList() { } public virtual void DeleteSingleOperation() { if (OperationClass.OperationList.Count > 0) { var item = OperationClass.OperationList.Last(); if (item is SingleOperation) OperationClass.OperationList.RemoveAt(OperationClass.OperationList.Count - 1); } } protected void RefreashProperty(string n) { double result; Double.TryParse(n, out result); OperationClass.ActualNumber = result; OperationClass.BottomNumber = OperationClass.ActualNumber.ToString(); OperationClass.TopNumber = String.Join(" ", OperationClass.OperationList.Select(x => x.Tag).ToArray()); } } }
using EBS.Query.DTO; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace EBS.Query { public interface IAdjustStorePriceQuery { IEnumerable<AdjustStorePriceDto> GetPageList(Pager page, SearchAdjustStorePrice condition); IEnumerable<AdjustStorePriceListDto> QueryFinish(Pager page, SearchAdjustStorePrice condition); IEnumerable<AdjustStorePriceItemDto> GetAdjustStorePriceItems(int AdjustStorePriceId); IEnumerable<AdjustStorePriceItemDto> GetItems(int AdjustStorePriceId); AdjustStorePriceItemDto GetAdjustStorePriceItem(int storeId,string productCodeOrBarCode); IEnumerable<AdjustStorePriceItemDto> GetAdjustStorePriceList(int storeId, string inputProducts); AdjustStorePriceDto GetById(int id); Dictionary<int, string> GetAdjustStorePriceStatus(); } }
using gView.Framework.Data; using gView.Framework.Symbology; using gView.Framework.Symbology.UI; using gView.Win.Carto.Rendering.UI.Framework.Carto.Rendering.Extensions; using System; using System.Drawing; using System.Windows.Forms; namespace gView.Framework.Carto.Rendering.UI { public partial class PropertyForm_DimensionRenderer : Form, IPropertyPanel { private DimensionRenderer _renderer = null; private IFeatureClass _featureClass = null; public PropertyForm_DimensionRenderer() { //InitializeComponent(); } #region IPropertyPanel Member public object PropertyPanel(IFeatureRenderer renderer, IFeatureLayer layer) { _renderer = renderer as DimensionRenderer; if (layer != null) { _featureClass = layer.FeatureClass; } InitializeComponent(); foreach (object e in Enum.GetValues(typeof(DimensionRenderer.lineCapType))) { cmbLineCap.Items.Add(e); } if (_renderer != null) { cmbLineCap.SelectedItem = _renderer.LineCapType; txtFormat.Text = _renderer.LabelFormat; } else { if (cmbLineCap.Items.Count > 0) { cmbLineCap.SelectedIndex = 0; } } return panel1; } #endregion #region Symbology Events private void btnLineSymbol_Paint(object sender, PaintEventArgs e) { if (_renderer == null) { return; } e.Graphics.DrawSymbol(((DimensionRenderer)_renderer).LineSymbol, new Rectangle(5, 5, btnLineSymbol.Width - 10, btnLineSymbol.Height - 10)); } private void btnTextSymbol_Paint(object sender, PaintEventArgs e) { if (_renderer == null) { return; } e.Graphics.DrawSymbol(((DimensionRenderer)_renderer).TextSymbol, new Rectangle(5, 5, btnTextSymbol.Width - 10, btnTextSymbol.Height - 10)); } private void btnLineSymbol_Click(object sender, EventArgs e) { if (_renderer == null) { return; } FormSymbol dlg = new FormSymbol(((DimensionRenderer)_renderer).LineSymbol); if (dlg.ShowDialog() == DialogResult.OK && dlg.Symbol is ILineSymbol) { ((DimensionRenderer)_renderer).LineSymbol = (ILineSymbol)dlg.Symbol; } } private void btnTextSymbol_Click(object sender, EventArgs e) { if (_renderer == null) { return; } FormSymbol dlg = new FormSymbol(((DimensionRenderer)_renderer).TextSymbol); if (dlg.ShowDialog() == DialogResult.OK && dlg.Symbol is ITextSymbol) { ((DimensionRenderer)_renderer).TextSymbol = (ITextSymbol)dlg.Symbol; } } #endregion #region Design Events private void cmbLineCap_DrawItem(object sender, DrawItemEventArgs e) { if (e.Index == -1) { return; } if ((e.State & DrawItemState.Focus) == DrawItemState.Focus) { e.Graphics.FillRectangle(Brushes.LightBlue, e.Bounds); } else { e.Graphics.FillRectangle(Brushes.White, e.Bounds); } DimensionRenderer.lineCapType type = (DimensionRenderer.lineCapType)cmbLineCap.Items[e.Index]; switch (type) { case DimensionRenderer.lineCapType.Arrow: DrawArrow(e.Graphics, e.Bounds, true); break; case DimensionRenderer.lineCapType.ArrowLine: DrawArrowLine(e.Graphics, e.Bounds, true); break; case DimensionRenderer.lineCapType.Line: DrawLine(e.Graphics, e.Bounds, true); break; case DimensionRenderer.lineCapType.Circle: DrawCircle(e.Graphics, e.Bounds, true); break; } } private void cmbLineCap_SelectedIndexChanged(object sender, EventArgs e) { if (_renderer != null) { _renderer.LineCapType = (DimensionRenderer.lineCapType)cmbLineCap.SelectedItem; } } private void txtFormat_TextChanged(object sender, EventArgs e) { if (_renderer != null) { _renderer.LabelFormat = txtFormat.Text; } } #endregion #region Drawing private void DrawArrow(System.Drawing.Graphics g, Rectangle bounds, bool left) { int x1 = (left ? 10 : bounds.Right - 10); int y1 = bounds.Top + bounds.Height / 2; int x2 = (left ? bounds.Right - 10 : 10); int y2 = y1; g.DrawLine(Pens.Black, x1, y1, x2, y2); if (left) { g.DrawLine(Pens.Black, x1, y1, x1 + 7, y1 + 7); g.DrawLine(Pens.Black, x1, y1, x1 + 7, y1 - 7); } else { g.DrawLine(Pens.Black, x1, y1, x1 - 7, y1 + 7); g.DrawLine(Pens.Black, x1, y1, x1 - 7, y1 - 7); } } private void DrawArrowLine(System.Drawing.Graphics g, Rectangle bounds, bool left) { int x1 = (left ? 10 : bounds.Right - 10); int y1 = bounds.Top + bounds.Height / 2; int x2 = (left ? bounds.Right - 10 : 10); int y2 = y1; DrawArrow(g, bounds, left); if (left) { g.DrawLine(Pens.Black, x1, y1 - 7, x1, y1 + 7); } else { g.DrawLine(Pens.Black, x2, y2 - 7, x2, y2 + 7); } } private void DrawLine(System.Drawing.Graphics g, Rectangle bounds, bool left) { int x1 = (left ? 10 : bounds.Right - 10); int y1 = bounds.Top + bounds.Height / 2; int x2 = (left ? bounds.Right - 10 : 10); int y2 = y1; g.DrawLine(Pens.Black, x1, y1, x2, y2); if (left) { g.DrawLine(Pens.Black, x1, y1 - 7, x1, y1 + 7); g.DrawLine(Pens.Black, x1 - 5, y1 + 5, x1 + 5, y1 - 5); } else { g.DrawLine(Pens.Black, x2, y2 - 7, x2, y2 + 7); g.DrawLine(Pens.Black, x2 - 5, y2 + 5, x2 + 5, y2 - 5); } } private void DrawCircle(System.Drawing.Graphics g, Rectangle bounds, bool left) { int x1 = (left ? 10 : bounds.Right - 10); int y1 = bounds.Top + bounds.Height / 2; int x2 = (left ? bounds.Right - 10 : 10); int y2 = y1; g.DrawLine(Pens.Black, x1, y1, x2, y2); if (left) { g.DrawEllipse(Pens.Black, x1 - 5, y1 - 5, 10, 10); g.DrawLine(Pens.Black, x1, y1 - 7, x1, y1 + 7); } else { g.DrawEllipse(Pens.Black, x2 - 5, y2 - 5, 10, 10); g.DrawLine(Pens.Black, x2, y2 - 7, x2, y2 + 7); } } #endregion } }
 namespace WorkScheduleManagement.Application.Models.Requests { public class ReqeustTableModel { public string Id { get; set; } public string Creator { get; set; } public string RequestType { get; set; } public string RequestStatus { get; set; } public string SelectedDates { get; set; } public int CountOfVacationDays { get; set; } } }
// <copyright file="ObjectMatcher.cs" company="Firoozeh Technology LTD"> // Copyright (C) 2020 Firoozeh Technology LTD. All Rights Reserved. // // 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. // </copyright> using System; using System.Collections.Generic; using FiroozehGameService.Models.Enums; using FiroozehGameService.Models.Enums.DBaaS; using FiroozehGameService.Utils; /** * @author Alireza Ghodrati */ namespace FiroozehGameService.Models.BasicApi.DBaaS.Matcher { /// <summary> /// Represents ObjectMatcher Model In Game Service Basic API /// </summary> [Serializable] public class ObjectMatcher : MatcherCore { private string _name; private ObjectMatcherTypes _type; private object _value; /// <summary> /// the ObjectMatcher Aggregation /// </summary> /// <param name="name">the name of Element you want to Match it</param> /// <param name="value">the value of Element you want to Match it</param> /// <param name="matcherType">The Type of Object Match</param> public ObjectMatcher(string name, object value, ObjectMatcherTypes matcherType) { _name = string.IsNullOrEmpty(name) ? throw new GameServiceException("Name Cant Be EmptyOrNull").LogException<ObjectMatcher>( DebugLocation.Internal, "Constructor") : _name = name; _value = value == null ? throw new GameServiceException("Value Cant Be Null").LogException<ObjectMatcher>( DebugLocation.Internal, "Constructor") : _value = value; _type = matcherType; } internal override Dictionary<string, List<object>> GetMatcher() { return new Dictionary<string, List<object>> {{_type.ToStringType(), new List<object> {_name, _value}}}; } } }
using System.Threading; using System.Threading.Tasks; namespace DDMedi { public interface IDecorator { } public interface IAsyncDecorator<TInputs, TOutput> : IDecorator where TInputs : IInputs<TOutput> { Task<TOutput> ProcessAsync(IAsyncDecoratorContext<TInputs, TOutput> context, CancellationToken token = default); } public interface IAsyncDecorator<TInputs> : IDecorator where TInputs : IInputs { Task ProcessAsync(IAsyncDecoratorContext<TInputs> context, CancellationToken token = default); } public interface IDecorator<TInputs, TOutput> : IDecorator where TInputs : IInputs<TOutput> { TOutput Process(IDecoratorContext<TInputs, TOutput> context); } public interface IDecorator<TInputs> : IDecorator where TInputs : IInputs { void Process(IDecoratorContext<TInputs> context); } public interface IEDecorator<TEInputs> : IDecorator where TEInputs : IEInputs { Task ProcessAsync(IEDecoratorContext<TEInputs> context, CancellationToken token = default); } }
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 System.Data.SqlClient; namespace Otel_1 { public partial class new_klient : Form { public new_klient() { InitializeComponent(); button1.Enabled = false; } private void button1_Click(object sender, EventArgs e) // Добавить нового клиента { new_klients(); } string connectionString = @"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\otel.mdf;Integrated Security=True;Connect Timeout=30"; private void new_klients() // Добавить нового клиента { try { string family = Convert.ToString(this.family.Text); // Инициализируем переменные из texbox_сов. string name = Convert.ToString(this.name.Text); string surname = Convert.ToString(this.surname.Text); string city = Convert.ToString(this.city.Text); long passport = long.Parse(this.passport.Text); string date = Convert.ToString(this.date.Text); int number = int.Parse(this.number.Text); double oplata = double.Parse(this.oplata.Text); int id_klients = int.Parse(this.id_klients.Text); double oplata_2 = 0.00; // Переменная для записи в БД начальной суммы, которую оплатил клиент, она равна нулю SqlConnection conn = new SqlConnection(connectionString); SqlCommand myCommand = conn.CreateCommand(); myCommand.Parameters.Add("@family", SqlDbType.NVarChar).Value = family; // создаем параметры myCommand.Parameters.Add("@name", SqlDbType.NVarChar).Value = name; myCommand.Parameters.Add("@surname", SqlDbType.NVarChar).Value = surname; myCommand.Parameters.Add("@city", SqlDbType.NVarChar, 50).Value = city; myCommand.Parameters.Add("@passport", SqlDbType.BigInt, 10).Value = passport; myCommand.Parameters.Add("@date", SqlDbType.Date).Value = date; myCommand.Parameters.Add("@number", SqlDbType.Int).Value = number; myCommand.Parameters.Add("@oplata", SqlDbType.Money).Value = oplata; myCommand.Parameters.Add("@oplata_2", SqlDbType.Decimal).Value = oplata_2; myCommand.Parameters.Add("@id_klients", SqlDbType.Int, 4).Value = id_klients; SqlCommand command_2 = conn.CreateCommand(); // Создадим новую команду command_2.CommandText = "SELECT Свободен_Занят FROM Номера_гостиницы WHERE id_номера = " + number; conn.Open(); int chislo = Convert.ToInt32(command_2.ExecuteScalar()); conn.Close(); switch (chislo) // Пояснение конструкции: БД в разделе "Свободен_Занят" спроектирована в виде чисел, первая цифра в числе обозначает количество комнат в номере, вторая цифра в числе обозначает количество человек, живущих в номере поэтому { // создаем переменную chislo, в которую записываем то, что было в БД на текущий момент // Далее изменяем переменную chislo в зависимости от того, скольки комнатный номер и сколько человек уже живет в нем case 10: // 10 - Свободен chislo = 11; // 11 - Занят break; case 20: // 20 - Свободен chislo = 21; // 21 - Свободно_1_место break; case 21: // 21 - Свободно_1_место chislo = 22; // 22 - Занят break; case 30: //30 - Свободен chislo = 31; // 31 - Свободно_2_места break; case 31: // 31 - Свободно_2_места chislo = 32; // 32 - Свободно_1_место break; case 32: // 32 - Свободно_1_место chislo = 33; // 33 - Занят break; default: chislo = 0; break; } if (chislo != 0) // Проверка на состояние гостиничноо номера, которое нас устраивает { conn.Open(); myCommand.Transaction = conn.BeginTransaction(System.Data.IsolationLevel.Serializable); // Создаем транзакцию myCommand.CommandText = "INSERT INTO Клиенты (id_клиента, Фамилия, Имя, Отчество, id_номера) VALUES (@id_klients, @family, @name, @surname, @number)"; myCommand.ExecuteNonQuery(); myCommand.CommandText = "UPDATE Номера_гостиницы SET Свободен_Занят = " + chislo + " WHERE id_номера = " + number; myCommand.ExecuteNonQuery(); myCommand.CommandText = "INSERT INTO Клиенты_информация (id_клиента, Серия_номер_паспорта, Откуда_приехал, Дата_заселения, Необходимая_оплата, Оплатил) VALUES (@id_klients, @passport, @city, @date, @oplata, @oplata_2)"; myCommand.ExecuteNonQuery(); myCommand.Transaction.Commit(); // Завершаем тразакцию conn.Close(); MessageBox.Show("Изменения успешно внесены!"); Close(); } else { MessageBox.Show("К сожалению, данный номер имеет максимальное количество проживающих!"); } } catch { MessageBox.Show("Скорее всего Вы ввели что-то не так, не вводите цифры вместо букв и наоборот, проверьте формат даты. Также все поля должны быть заполнены!"); method_clear(); } } private void button2_Click(object sender, EventArgs e) // Стоимость номера в сутки заполняется автоматически после нажатия кнопки { data_set(); } private void data_set() { try { double a = Convert.ToDouble(number.Text); if (a > 50) { MessageBox.Show("Такого номера в гостинице нет", "Ошибка"); oplata.Text = "Такого номера нет"; button1.Enabled = false; } else { SqlConnection conn = new SqlConnection(connectionString); SqlCommand command = conn.CreateCommand(); command.CommandText = "SELECT Цена_номера_в_сутки FROM Номера_гостиницы WHERE id_номера = " + a; conn.Open(); a = Convert.ToDouble(command.ExecuteScalar()); oplata.Text = a.ToString(); conn.Close(); comparison_id(); // если проверка номера прошла успешно, запускаем метод проверки валидности id_клиента } } catch { MessageBox.Show("Необходимо ввести номер комнаты", "Ошибка"); } } private void comparison_id() // Метод для проверки валидности id { try { SqlConnection conn = new SqlConnection(connectionString); SqlCommand command = conn.CreateCommand(); command.CommandText = "SELECT id_клиента FROM Клиенты WHERE id_клиента = " + Convert.ToInt32(id_klients.Text); conn.Open(); int a = Convert.ToInt32(command.ExecuteScalar()); conn.Close(); if (a == 0) button1.Enabled = true; else MessageBox.Show("Клиент с таким id уже существует, необходимо указать другой id", "Ошибка"); } catch { MessageBox.Show("Необходимо заполнить поле id_клиента", "Ошибка"); } } private void number_TextChanged(object sender, EventArgs e) // метод для блокировки кнопки в случае смены значений комнаты и id_клиента { button1.Enabled = false; } private void method_clear() // Метод очистки данных { family.Clear(); name.Clear(); surname.Clear(); passport.Clear(); city.Clear(); date.Clear(); number.Clear(); id_klients.Clear(); button1.Enabled = false; } } }
using System.Collections.Generic; namespace WebShop.API.Models { public class CategoryDto { public int Id { get; set; } public string Title { get; set; } public string Description { get; set; } public int SortOrder { get; set; } public int? ParentId { get; set; } public int? RedirectToId { get; set; } public bool Active { get; set; } public List<CategoryDto> SubCategories { get; set; } } }
namespace Cs_Notas.Infra.Data.Migrations { using System; using System.Data.Entity.Migrations; public partial class Complemento2 : DbMigration { public override void Up() { AddColumn("dbo.Complementos", "Enviado", c => c.String(maxLength: 1, unicode: false)); } public override void Down() { DropColumn("dbo.Complementos", "Enviado"); } } }
using FluentValidation; using MediatR; using Projeto.Application.Commands.Alunos; using Projeto.Application.Interfaces; using Projeto.Domain.DTOs; using Projeto.Domain.Interfaces.Caching; using Projeto.Domain.Interfaces.IServices; using Projeto.Domain.Models; using Projeto.Domain.Validations; using System; using System.Collections.Generic; using System.Text; using System.Threading.Tasks; namespace Projeto.Application.Services { public class AlunoApplicationService : IAlunoApplicationService { //atributos private readonly IMediator mediator; private readonly IAlunoCaching _alunoCaching; //construtor para injecao de dependencia public AlunoApplicationService(IMediator mediator, IAlunoCaching alunoCaching) { this.mediator = mediator; _alunoCaching = alunoCaching; } public async Task Add(CreateAlunoCommand command) { await mediator.Send(command); } public async Task Update(UpdateAlunoCommand command) { await mediator.Send(command); } public async Task Remove(DeleteAlunoCommand command) { await mediator.Send(command); } public List<AlunoDTO> GetAll() { return _alunoCaching.GetAll(); } public AlunoDTO GetById(string id) { return _alunoCaching.GetById(Guid.Parse(id)); } public void Dispose() { throw new NotImplementedException(); } } }
using capacited_facility_location_problem.model; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace capacited_facility_location_problem.optimizer { class ConstraintsNames { internal static string CustomerIsSuppliedConstraintNameForCustomer(Customer customer) { return String.Format("constraint_customer_{0}_is_supplied", customer.CustomerNumber); } internal static string FacilityCantExceedCapacityConstraintNameForFacility(Facility facility) { return String.Format("facility_{0}_cant_exceed_capacity", facility.FacilityNumber); } internal static string FacilityCantSupplyCustomerIfItsClosedConstraintNameForFacilityAndCustomer(Facility facility, Customer customer) { return String.Format("constraint_facility_{0}_cant_supply_customer_{1}_if_it_is_not_open", facility.FacilityNumber, customer.CustomerNumber); } } }
using System.Collections.Generic; using System.Diagnostics; using System.Linq; using Microsoft.AspNetCore.Mvc; using Tndm_ArtShop.Models; namespace Tndm_ArtShop.Controllers { public class HomeController : Controller { private readonly ProdavnicaContext db; public HomeController(ProdavnicaContext _db) { db = _db; } public IActionResult Index(int id = 0) { ViewBag.id = id; ViewBag.Kategorije = db.Kategorija.ToList(); IEnumerable<Proizvod> listaProizvoda = db.Proizvod; if (id != 0) { listaProizvoda = listaProizvoda.Where(p => p.KategorijaId == id); } return View(listaProizvoda); } // filtriranje public PartialViewResult _FiltrirajPoNaslovu(string deoNaslova, int id) { ViewBag.id = 0; ViewBag.Kategorije = db.Proizvod.ToList(); IEnumerable<Proizvod> listaProizvoda = db.Proizvod; if (id != 0) { Proizvod k1 = db.Proizvod.Find(id); if (k1 != null) { ViewBag.Kategorija = k1.Naziv; listaProizvoda = listaProizvoda .Where(p => p.KategorijaId == id); } else { ViewBag.Kategorija = ""; return PartialView(); } } else { ViewBag.Kategorija = "Sve kategorije"; } if (!string.IsNullOrWhiteSpace(deoNaslova)) { listaProizvoda = listaProizvoda .Where(p => p.Naziv.ToLower().Contains(deoNaslova.ToLower())); } return PartialView(listaProizvoda.ToList()); } public PartialViewResult _FiltrirajPoOpisu(string deoOpisa, int id) { ViewBag.id = 0; ViewBag.Kategorije = db.Proizvod.ToList(); IEnumerable<Proizvod> listaProizvoda = db.Proizvod; if (id != 0) { Proizvod k1 = db.Proizvod.Find(id); if (k1 != null) { ViewBag.Kategorija = k1.Opis; listaProizvoda = listaProizvoda .Where(p => p.KategorijaId == id); } else { ViewBag.Kategorija = ""; return PartialView(); } } else { ViewBag.Kategorija = "Sve kategorije"; } if (!string.IsNullOrWhiteSpace(deoOpisa)) { listaProizvoda = listaProizvoda .Where(p => p.Opis.ToLower().Contains(deoOpisa.ToLower())); } return PartialView(listaProizvoda.ToList()); } public PartialViewResult _FiltrirajPoCeni(decimal? min, decimal? max, int KategorijaId = 0) { IEnumerable<Proizvod> listaProizvoda = db.Proizvod; if (KategorijaId != 0) { Kategorija k1 = db.Kategorija.Find(KategorijaId); if (k1 != null) { ViewBag.Kategorija = k1.Naziv; listaProizvoda = listaProizvoda.Where(p => p.KategorijaId == KategorijaId); } else { ViewBag.Kategorija = ""; return PartialView(); } } else { ViewBag.Kategorija = "Svi proizvodi"; } if (min == null) { min = listaProizvoda.Min(p => p.Cena); } if (max == null) { max = listaProizvoda.Max(p => p.Cena); } listaProizvoda = listaProizvoda.Where(p => p.Cena >= min && p.Cena <= max); return PartialView(listaProizvoda); } [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)] public IActionResult Error() { return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier }); } } }
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 ArtificialArt.Audio.Midi.Generator; namespace WaveBuilder { /// <summary> /// Interaction logic for TrackViewer.xaml /// </summary> public partial class TrackViewer : UserControl, IEnumerable<CheckBox> { #region Constants private const int maxBarCount = 64; #endregion #region Events public event EventHandler OnClickCheckBox; public event EventHandler OnMetaRiffPackNameChanged; #endregion #region Fields private List<CheckBox> internalList = new List<CheckBox>(); #endregion #region Constructors public TrackViewer(IEnumerable<string> listValues) : this(listValues,0) { } public TrackViewer(IEnumerable<string> listValues, int barCountAtStart) { InitializeComponent(); metaRiffPackNameListBox.Items.Add(""); foreach (string value in listValues) metaRiffPackNameListBox.Items.Add(value); metaRiffPackNameListBox.SelectedItem = ""; for (int index = 0; index < barCountAtStart; index++) this[index].IsChecked = false; } #endregion #region Public Methods public void RefreshControls(PredefinedGeneratorTrack track, int barCount) { metaRiffPackNameListBox.SelectedItem = track.MetaRiffPackName; for (int index = 0; index<barCount;index++) { this[index].IsChecked = track[index]; } if (internalList.Count > barCount) { int currentIndex = 0; foreach (CheckBox checkBox in new List<CheckBox>(this)) { if (currentIndex >= barCount) Remove(checkBox); currentIndex++; } } } #endregion #region Properties public CheckBox this[int index] { get { while (internalList.Count - 1 < index) { CheckBox checkBox = new CheckBox(); checkBox.Width = 48; checkBox.Tag = internalList.Count; checkBox.Click += new RoutedEventHandler(CheckBoxClickHandler); internalList.Add(checkBox); stackPanelTrack.Children.Add(checkBox); } return internalList[index]; } } #endregion #region Handlers private void CheckBoxClickHandler(object sender, RoutedEventArgs e) { CheckBox checkBox = (CheckBox)sender; e.Source = checkBox; if (OnClickCheckBox != null) OnClickCheckBox(this, e); } private void MetaRiffPackNameChangedHandler(object sender, RoutedEventArgs e) { if (OnMetaRiffPackNameChanged != null) { ComboBox comboBox = (ComboBox)sender; e.Source = comboBox; OnMetaRiffPackNameChanged(this, e); } } #endregion #region Collection Members private void Remove(CheckBox checkBox) { internalList.Remove(checkBox); stackPanelTrack.Children.Remove(checkBox); } public IEnumerator<CheckBox> GetEnumerator() { return internalList.GetEnumerator(); } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return internalList.GetEnumerator(); } #endregion } }
using System; using System.Collections.Generic; using System.Linq; namespace FeriaVirtual.Infrastructure.SeedWork.Events { public class DomainEventSubscribersInformation { private readonly Dictionary<Type, DomainEventSubscriberInformation> _information; public DomainEventSubscribersInformation(Dictionary<Type, DomainEventSubscriberInformation> information) => _information = information; public Dictionary<Type, DomainEventSubscriberInformation>.ValueCollection All() => _information.Values; } }
using System; using System.Collections.Generic; using DFC.ServiceTaxonomy.GraphSync.Extensions; using DFC.ServiceTaxonomy.GraphSync.Interfaces; using DFC.ServiceTaxonomy.GraphSync.Models; namespace DFC.ServiceTaxonomy.GraphSync.CosmosDb.Queries { public class CosmosDbMatchSynonymsQuery : IQuery<IRecord> { private string FirstNodeLabel { get; } private string SecondNodeLabel { get; } private string PropertyValue { get; } private string[] RelationshipTypes { get; } public CosmosDbMatchSynonymsQuery(string firstNodeLabel, string secondNodeLabel, string propertyValue, params string[] relationshipTypes) { FirstNodeLabel = firstNodeLabel; SecondNodeLabel = secondNodeLabel; PropertyValue = propertyValue; RelationshipTypes = relationshipTypes; } public List<string> ValidationErrors() { var validationErrors = new List<string>(); if(RelationshipTypes.Length == 0) { validationErrors.Add("At least one RelationshipType must be provided."); } return validationErrors; } public Query Query { get { this.CheckIsValid(); throw new NotSupportedException("Synonyms functionality is no longer used, so hasn't been ported into Cosmos Db."); } } public IRecord ProcessRecord(IRecord record) { return record; } } }
using CC.Web.Dao.Core; using CC.Web.Model; using CC.Web.Model.Core; using CC.Web.Model.System; using System; using System.Collections.Generic; using System.Linq; namespace CC.Web.Service.Core { public class BaseService<T> : IBaseService<T> where T : class, IEntity { public IBaseDao<T> CurDao { get; set; } public IWorkContext WorkContext { get; set; } public void Delete(Guid Id) { CurDao.Delete(Id); } public void Delete(IEnumerable<Guid> Ids) { CurDao.Delete(Ids); } public T Find(Guid Id, bool includeDel = false) { return CurDao.Find(Id,includeDel); } public IQueryable<T> Find(IEnumerable<Guid> Ids, bool includeDel = false) { return CurDao.Find(Ids, includeDel); } public Guid Insert(T entity) { return CurDao.Insert(entity); } public IEnumerable<Guid> Insert(IEnumerable<T> entities) { return CurDao.Insert(entities); } public void Remove(Guid Id) { CurDao.Remove(Id); } public void Remove(IEnumerable<Guid> Ids) { CurDao.Remove(Ids); } public void Update(T entity) { CurDao.Update(entity); } public void Update(IEnumerable<T> entity) { CurDao.Update(entity); } } }
using UnityEngine; using System.Collections; public class RunningPlayer : MonoBehaviour { [SerializeField] private GameObject arm; private bool armDropped = false; private GameObject bear; void OnCollisionEnter (Collision collision) { if (!armDropped && collision.collider.name == "Bear") GameManager.instance.SwitchScene ("Bear"); else if (collision.collider.name == "NewLevelTrigger") GameManager.instance.SwitchScene ("Cliff"); } void DropArm() { GameObject arm_dropped = Instantiate (arm, transform.position, Quaternion.identity) as GameObject; bear = GameObject.Find ("Bear"); BearStop bs = bear.GetComponent<BearStop> (); bs.ReTarget (arm_dropped.transform); armDropped = true; GameManager.instance.feedBear (); } void Update() { if (Input.GetKeyDown ("l") && GameManager.instance.getLimbs() > 0) DropArm (); } }
using System; using System.Text; class CodePage437 { public static void Main(string[] args) { // Set the window size and title Console.Title = "Code Page windows-1251: MS-DOS ASCII Characters"; Console.Write("Decimal".PadRight(10)); Console.Write("ASCII".PadRight(10)); Console.WriteLine(); for (byte b = 0; b < byte.MaxValue; b++) { //Console.OutputEncoding = System.Text.Encoding.Unicode; char c = Encoding.GetEncoding(1251).GetChars(new byte[] { b })[0]; string display = string.Empty; if (char.IsWhiteSpace(c)) { display = c.ToString(); switch (c) { case '\t': display = "\\t"; break; case ' ': display = "space"; break; case '\n': display = "\\n"; break; case '\r': display = "\\r"; break; case '\v': display = "\\v"; break; case '\f': display = "\\f"; break; } } else if (char.IsControl(c)) { display = "control"; } else { display = c.ToString(); } Console.Write(b.ToString().PadRight(10)); Console.Write(display.PadRight(10)); Console.WriteLine(); } Console.WriteLine(); } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.SceneManagement; public class PausePopup : MonoBehaviour { private void OnEnable() { Time.timeScale = 0f; } private void OnDisable() { Time.timeScale = 1.0f; } public void MenuButtonClick() { SceneManager.LoadSceneAsync((int)SceneName.LobbyScene); SoundManager.Instance.PlaySoundEffect("Button"); } public void ResumeButtonClick() { this.gameObject.SetActive(false); SoundManager.Instance.PlaySoundEffect("Button"); } public void RetryButtonClick() { SceneManager.LoadSceneAsync((int)SceneName.GameScene); SoundManager.Instance.PlaySoundEffect("Button"); } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class timescaleScript : MonoBehaviour { public float Timescale = 1f; void Start() { Time.timeScale = Timescale; } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace FiiiCoin.Models { public class ListLockUnspent : BaseModel { private string txid { get; set; } public string TxId { get { return txid; } set { txid = value; OnChanged("TxId"); } } private int vout { get; set; } public int Vout { get { return vout; } set { vout = value; OnChanged("Vout"); } } } }
/* * Created by SharpDevelop. * User: admin * Date: 8/8/2016 * Time: 10:03 PM * * To change this template use Tools | Options | Coding | Edit Standard Headers. */ using System; using System.Xml.Serialization; using System.IO; using System.Windows.Forms; namespace Robot { /// <summary> /// Description of IngredientsBD. /// </summary> public class RecipesDB : IDisposable { private GroupsList _recipes = new GroupsList(); readonly string _ingredientFileName; readonly string _directoryPath; public RecipesDB() { //string _directoryPath = Path.GetDirectoryName(Application.ExecutablePath); _directoryPath = @"c:\RobotData"; _ingredientFileName = Path.Combine(_directoryPath, "Ingredients.xml"); ReadFile(); } public void Dispose() { //TODO } private void ReadFile() { try { using(TextReader reader = new StreamReader(_ingredientFileName)) { XmlSerializer deserializer = new XmlSerializer(typeof(GroupsList)); object obj = deserializer.Deserialize(reader); _recipes = (GroupsList)obj;; } } catch { bool exists = System.IO.Directory.Exists(_directoryPath); if(!exists) System.IO.Directory.CreateDirectory(_directoryPath); if(File.Exists(_ingredientFileName)) { File.Delete(_ingredientFileName); } CreateFile(); } } public void SaveFile() { Serialize(); } private void CreateFile() { _recipes = new GroupsList(); for(int i = 1; i <= GV.NB_GROUPS; i++) { Group gp = new Group(); gp._groupID = i; _recipes._groupsList.Add(gp); for(int x = 1; x <= GV.NB_INGREDIENTS; x++) { Ingredient ing = new Ingredient(); ing._ingredientID = x; gp._ingredientList.Add(ing); } } Serialize(); } private void Serialize() { XmlSerializer serializer = new XmlSerializer(typeof(GroupsList)); using ( TextWriter writer = new StreamWriter(_ingredientFileName)) { serializer.Serialize(writer, _recipes); } } public WeightValue GetWeightValue(int groupID, int ingredientID) { var groupItem = _recipes._groupsList.Find(x => x._groupID.Equals(groupID)); var ingredientItem = groupItem._ingredientList.Find(x => x._ingredientID.Equals(ingredientID)); return ingredientItem._weightValue; } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class FPSCounter : MonoBehaviour { public Player player; Text text; void Start () { text = GetComponent<Text>(); } void FixedUpdate () { //text.text = "IVP : " + player.itemGrabInfoRight.itemVelocityPercentage; } }
using DemoS3.Models; using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace DemoS3.Controllers { public class ClienteController : Controller { public static List<Cliente> empList = new List<Cliente> { new Cliente { ID = 1, nombre = "Renato", fechaRegistro= DateTime.Parse(DateTime.Today.ToString()), edad = 30 }, new Cliente { ID = 2, nombre = "Patricio", fechaRegistro= DateTime.Parse(DateTime.Today.ToString()), edad = 32 }, }; // GET: Cliente private EmpDbContext db = new EmpDbContext(); public ActionResult Index() { var Clientes = from e in db.Cliente orderby e.ID select e; return View(Clientes); } // GET: Cliente/Details/5 public ActionResult Details(int id) { return View(); } // GET: Cliente/Create public ActionResult Create() { return View(); } // POST: Cliente/Create [HttpPost] public ActionResult Create(Cliente emp) { try { db.Cliente.Add(emp); db.SaveChanges(); return RedirectToAction("Index"); } catch { return View(); } } // GET: Cliente/Edit/5 public ActionResult Edit(int id) { var Clientes = db.Cliente.Single(m => m.ID == id); return View(Clientes); } // POST: Cliente/Edit/5 [HttpPost] public ActionResult Edit(int id, FormCollection collection) { try { // TODO: Add update logic here var Cliente = db.Cliente.Single(m => m.ID == id); if (TryUpdateModel(Cliente)) { db.SaveChanges(); return RedirectToAction("Index"); } return View(Cliente); } catch { return View(); } } // GET: Cliente/Delete/5 public ActionResult Delete(int id) { return View(); } // POST: Cliente/Delete/5 [HttpPost] public ActionResult Delete(int id, FormCollection collection) { try { // TODO: Add delete logic here return RedirectToAction("Index"); } catch { return View(); } } [NonAction] public List<Cliente> TodosLosClientes() { return new List<Cliente> { new Cliente { ID = 1, nombre = "Renato", fechaRegistro= DateTime.Parse(DateTime.Today.ToString()), edad = 30 }, new Cliente { ID = 2, nombre = "Patricio", fechaRegistro= DateTime.Parse(DateTime.Today.ToString()), edad = 32 } }; } } }
using System.Diagnostics; using Microsoft.AspNetCore.Mvc; using SnakeMultiplayer.Models; namespace SnakeMultiplayer.Controllers; public class HomeController : Controller { public IActionResult Index() => View(); [HttpPost] public IActionResult Error(string errorMessage = "An error has occured.\n We are already taking action to prevent this error from happening.") { ViewData["ErrorMessage"] = errorMessage; return View("Views/Home/Index.cshtml"); } public IActionResult About() { ViewData["Message"] = "Your application description page."; return View(); } [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)] public IActionResult Error() => View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier }); }
 namespace WarMachines.Machines { using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using WarMachines.Interfaces; public class Tank : Machine, ITank { public bool DefenseMode { get { return defenseMode; } set { this.defenseMode = value; } } public void ToggleDefenseMode() { if (this.DefenseMode == true) { this.DefensePoints += 30; this.AttackPoints -= 40; } else { this.DefenseMode = false; this.DefensePoints -= 30; this.AttackPoints += 40; } } public Tank() { this.HealthPoints = 100; this.DefenseMode = true; this.DefensePoints += 30; this.AttackPoints -= 40; } public Tank(string name, double attackPoints, double defensePoints) { this.HealthPoints = 100; this.DefenseMode = true; this.DefensePoints += 30; this.AttackPoints -= 40; } public override string ToString() { string defMode = "ON"; if (this.DefenseMode == true) { defMode = "OFF"; } if (Targets.Count == 0) { return String.Format("- {0} {1} *Type: Tank {2} *Health: {3} {4} *Attack: {5} *Defense: {6} {7} *Targets: None {8} *Defense: {9} {10}", this.Name, Environment.NewLine, Environment.NewLine, this.HealthPoints, Environment.NewLine, this.AttackPoints, Environment.NewLine, this.DefensePoints, Environment.NewLine, Environment.NewLine, defMode, Environment.NewLine ); } else { return String.Format("- {0} {1} *Type: Tank {2} *Health: {3} {4} *Attack: {5} *Defense: {6} {7} *Targets: {8} {9} *Defense: {10} {11}", this.Name, Environment.NewLine, Environment.NewLine, this.HealthPoints, Environment.NewLine, this.AttackPoints, Environment.NewLine, this.DefensePoints, Environment.NewLine, this.Targets.First(), Environment.NewLine, defMode, Environment.NewLine ); } } public bool defenseMode { get; set; } } }
using System; using System.Drawing; using CoreFoundation; using IdeasLibrary; using UIKit; using Foundation; namespace Playground.iOS { //[Register("UniversalView")] [Register("IdeaPagerViewController")] public class IdeaPagerViewController : UIViewController { private UIPageViewController pageViewController; private IdeaManager ideaManager; private string _categoryTitle; public IdeaPagerViewController(string categoryTitle) { _categoryTitle = categoryTitle; } public override void DidReceiveMemoryWarning() { // Releases the view if it doesn't have a superview. base.DidReceiveMemoryWarning(); // Release any cached data, images, etc that aren't in use. } public override void ViewDidLoad() { base.ViewDidLoad(); // Perform any additional setup after loading the view pageViewController = new UIPageViewController( UIPageViewControllerTransitionStyle.PageCurl, UIPageViewControllerNavigationOrientation.Horizontal, UIPageViewControllerSpineLocation.Min); pageViewController.View.Frame = View.Bounds; View.AddSubview(pageViewController.View); ideaManager = new IdeaManager(_categoryTitle); ideaManager.MoveFirst(); var dataSource = new IdeaPagerViewControllerDataSource(ideaManager); pageViewController.DataSource = dataSource; var firstViewController = dataSource.GetFirstViewController(); pageViewController.SetViewControllers( new UIViewController[] { firstViewController }, UIPageViewControllerNavigationDirection.Forward, false, null); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace WebQLKhoaHoc.Models { public class topicChartViewModel { public List<object> Headers {get;set;} public List<object> Rows { get; set; } public topicChartViewModel() { } } }