text
stringlengths
13
6.01M
using System; namespace Fbtc.Domain.Entities { public class CartaoAssociado { public int CartaoAssociadoId { get; set; } public int AssociadoId { get; set; } public DateTime DtEmissao { get; set; } } }
using Infrastructure.Data.Shared; using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Text; using System.Text.Json.Serialization; namespace Infrastructure.Data.Entities { public class Clinic : ResponseModel { public int Id { get; set; } public string Name { get; set; } [JsonIgnore] public DateTime CreationDate { get; set; } = DateTime.UtcNow; [JsonIgnore] public DateTime? ModificationDate { get; set; } [JsonIgnore] public ICollection<Equipment> Equipments { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading; namespace ConsoleApp21 { class Vehicle { public string Type { get; set; } public int Speed { get; set; } public int Wheels { get; set; } public string Color { get; set; } public bool IsBroken { get; set; } public int Distance { get; set; } public Vehicle(string type = "car", int speed = 60, int wheels = 4, string color = "white", bool isBroken = false, int distance = 0) { Type = type; Speed = speed; Wheels = wheels; Color = color; IsBroken = isBroken; Distance = distance; } public string Condition() { return IsBroken ? "This vehicle is Broken." : "It's not broken for now"; } public void PrintInfo() { Console.WriteLine("Type : {0}\nColor : {1}\nWheels : {2}\nSpeed : {3}\nDistance : {4}\n{5}\n", Type, Color, Wheels, Speed, Distance, Condition()); } public void Ride(Vehicle vehicle) { if (vehicle.IsBroken) { Console.WriteLine("This Vehicle is broken, repair it first"); Console.ReadKey(); return; } Random rand = new Random(); Console.WriteLine("Riding for 1 hour..."); Thread.Sleep(1000); vehicle.Distance += vehicle.Speed; int chance = rand.Next(1, 4); vehicle.IsBroken = chance == 2 ? true : false; if (vehicle.IsBroken) { Console.Clear(); Console.WriteLine("Your vehicle was broken."); Console.ReadKey(); } } public void Repair(Vehicle vehicle) { Console.WriteLine("Oh, look at what you've done... Okay give me some time. I'll try to repair this junk"); vehicle.IsBroken = false; Console.ReadKey(); } } static class Assist { static public void NumberCheck(string str, out int number) { if (int.TryParse(str, out number)) return; Console.WriteLine("Invalid number will be replaced with 0"); } static public bool DefineBool(string word) { word.ToLower(); while (true) { switch (word) { case "1": case "da": case "да": case "yes": case "yeah": case "yup": return true; case "0": case "net": case "now": case "no": case "nope": return false; default: Console.WriteLine("Incorrect input will be replaced with false"); return false; } } } } class MainClass { static void AllVehicleInfo(List<Vehicle> garage) { foreach (Vehicle vehicle in garage) { vehicle.PrintInfo(); } } static void VehicleChoice(List<Vehicle> garage, out int index) { int size = garage.Count(); do { Console.WriteLine("Choose the vehicle by its id (from 0 to {0})", size); Assist.NumberCheck(Console.ReadLine(), out index); } while (index >= size); } static public void InfoCorrect(Vehicle vehicle) { Console.WriteLine("What exactly do you want to correct : \n1 - Type\n2 - Color\n3 - Wheels\n4 - Speed\n5 - Distance\n6 - Condtition\n7 - Exit"); switch (Console.ReadKey(false).Key) { case ConsoleKey.D1: Console.WriteLine("Correct type is : "); vehicle.Type = Console.ReadLine(); Console.Clear(); break; case ConsoleKey.D2: Console.WriteLine("Correct color is : "); vehicle.Color = Console.ReadLine(); Console.Clear(); break; case ConsoleKey.D3: Console.WriteLine("Correct amount of wheels is : "); vehicle.Wheels = int.Parse(Console.ReadLine()); Console.Clear(); break; case ConsoleKey.D4: Console.WriteLine("Correct speed is : "); vehicle.Speed = int.Parse(Console.ReadLine()); Console.Clear(); break; case ConsoleKey.D5: Console.WriteLine("Correct distance is : "); vehicle.Distance = int.Parse(Console.ReadLine()); Console.Clear(); break; case ConsoleKey.D6: Console.WriteLine("Correct condition is : "); vehicle.IsBroken = bool.Parse(Console.ReadLine()); Console.Clear(); break; default: return; } } static public Vehicle AddNewVehicle() { Console.WriteLine("Type : "); string type = Console.ReadLine(); Console.WriteLine("Color : "); string color = Console.ReadLine(); Console.WriteLine("Wheels : "); int wheels; Assist.NumberCheck(Console.ReadLine(), out wheels); Console.WriteLine("Speed : "); int speed; Assist.NumberCheck(Console.ReadLine(), out speed); Console.WriteLine("Distance : "); int distance; Assist.NumberCheck(Console.ReadLine(), out distance); Console.WriteLine("Broken : "); string isBroken = (Console.ReadLine()); bool izBroken = Assist.DefineBool(isBroken); return new Vehicle(type, speed, wheels, color, izBroken, distance); } static void Main(string[] args) { Vehicle car = new Vehicle(); List<Vehicle> garage = new List<Vehicle>(); garage.Add(car); int index; do { Console.WriteLine("Your garage : \n1 - Add\n2 - Info about my vehicles\n3 - Throw Vehicle Away\n4 - Correct info\n5 - Test Drive\n6 - Repair\n7 - Exit"); switch (Console.ReadKey(false).Key) { case ConsoleKey.D1: Console.Clear(); garage.Add(AddNewVehicle()); Console.Clear(); break; case ConsoleKey.D2: Console.Clear(); AllVehicleInfo(garage); Console.ReadKey(); Console.Clear(); break; case ConsoleKey.D3: Console.Clear(); VehicleChoice(garage, out index); garage.Remove(garage[index]); Console.Clear(); break; case ConsoleKey.D4: Console.Clear(); VehicleChoice(garage, out index); garage[index].PrintInfo(); InfoCorrect(garage[index]); Console.Clear(); break; case ConsoleKey.D5: Console.Clear(); VehicleChoice(garage, out index); garage[index].Ride(garage[index]); Console.Clear(); break; case ConsoleKey.D6: Console.Clear(); VehicleChoice(garage, out index); garage[index].Repair(garage[index]); Console.Clear(); break; case ConsoleKey.D7: return; default: Console.Clear(); break; } } while (true); } } }
using KingNetwork.Shared.Interfaces; namespace KingNetwork.Server.Interfaces { /// <summary> /// This interface is responsible for represents the server packet handler. /// </summary> internal interface IPacketHandler { /// <summary> /// This method is responsible for receive the message from server packet handler. /// </summary> /// <param name="client">The connected client.</param> /// <param name="reader">The king buffer reader received from message.</param> void HandleMessageData(IClientConnection client, IKingBufferReader reader); } }
using System.Collections.Generic; using System.Text; namespace Algorithms.LeetCode { public class GenerateParenthesisTask { public IList<string> GenerateParenthesis(int n) { var results = new List<string>(); Generate(n, n, new StringBuilder(), results); return results; } private void Generate(int lNum, int rNum, StringBuilder str, IList<string> results) { if (lNum == 0 && rNum == 0) results.Add(str.ToString()); if (rNum > lNum) { var copy = new StringBuilder(str.ToString()); copy.Append(')'); Generate(lNum, rNum - 1, copy, results); } if (lNum > 0) { var copy = new StringBuilder( str.ToString()); copy.Append('('); Generate(lNum - 1, rNum, copy, results); } } } }
using Microsoft.EntityFrameworkCore; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using static WebApp1.Models.ContactModel; namespace WebApp1.Data { public class ContactContext : DbContext { public DbSet<Contacts> Contact { get; set; } protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { optionsBuilder.UseMySQL("server=ec2-18-221-1-66.us-east-2.compute.amazonaws.com;database=contacts;user=myuser;password=mypass"); } protected override void OnModelCreating(ModelBuilder modelBuilder) { base.OnModelCreating(modelBuilder); modelBuilder.Entity<Contacts>(entity => { entity.HasKey(e => e.FirstName); entity.Property(e => e.LastName).IsRequired(); }); } } }
using Alabo.Domains.Entities; using Alabo.Domains.Services; using Alabo.Tables.Domain.Entities; using MongoDB.Bson; using System.Collections.Generic; namespace Alabo.Tables.Domain.Services { /// <summary> /// 表结构相关服务 /// </summary> public interface ITableService : IService<Table, ObjectId> { /// <summary> /// 初始化所有的表 /// </summary> void Init(); List<KeyValue> MongodbCatalogEntityKeyValues(); List<KeyValue> SqlServcieCatalogEntityKeyValues(); List<KeyValue> CatalogEntityKeyValues(); } }
using UnityEngine; using System.Collections; /* The CameraWallCollider class allows the player to see the Player when the Player is backed against a wall. The Wall is made transparent to achieve this. */ public class CameraWallCollider : MonoBehaviour { Shader shader1; //oldShader Shader shader2; //new Shader Color color1; //old Color Color color2; //new Color /* The Start function instantiates the new Shader and Color. */ void Start() { shader2 = Shader.Find("Transparent/VertexLit"); color2 = Color.clear; } /* The OnTriggerEnter function makes transparent the wall. */ void OnTriggerEnter(Collider other) { shader1 = other.gameObject.GetComponent<Renderer>().material.shader; color1 = other.gameObject.GetComponent<Renderer>().material.color; other.gameObject.GetComponent<Renderer>().material.shader = shader2; other.gameObject.GetComponent<Renderer>().material.color = color2; } /* The OnTriggerExit function makes the wall opaque again. */ void OnTriggerExit(Collider other) { other.gameObject.GetComponent<Renderer>().material.shader = shader1; other.gameObject.GetComponent<Renderer>().material.color = color1; } }
using System; namespace Algorithms.LeetCode { public class KthSmallestElementInSortedMatrix { public int KthSmallest(int[][] matrix, int k) { var n = matrix.Length; var heap = new MinHeap(n); for (int i = 0; i < n; ++i) { heap.Add((0, i, matrix[0][i])); } for (int i = 0; i < k - 1; ++i) { var value = heap.ExtractMin(); if (value.x == n - 1) continue; heap.Add((value.x + 1, value.y, matrix[value.x + 1][value.y])); } return heap.GetMin().value; } #region MinHeap private class MinHeap { private (int x, int y, int value)[] _elements; private int _size; private int _capacity; public MinHeap(int size) { _elements = new (int x, int y, int value)[size]; _capacity = size; _size = 0; } // return the min value -> O(1) public (int x, int y, int value) GetMin() => _elements[0]; // O(logN) public (int x, int y, int value) ExtractMin() { if (_size == 0) throw new InvalidOperationException(); if (_size == 1) { _size = 0; return _elements[0]; } var result = GetMin(); _elements[0] = _elements[_size - 1]; _size--; Heapify(0); return result; } public void Add((int x, int y, int value) data) { if (_size == _capacity || data.value.Equals(int.MinValue)) throw new ArgumentOutOfRangeException(); _elements[_size] = data; var parentIndex = GetParent(_size); var childIndex = _size; while (parentIndex >= 0 && _elements[parentIndex].value > _elements[childIndex].value) { Swap(ref _elements[parentIndex], ref _elements[childIndex]); childIndex = parentIndex; parentIndex = GetParent(childIndex); } ++_size; } private int GetParent(int index) => (index - 1) / 2; private int GetFirstChild(int index) => 2 * index + 1; private int GetSecondChild(int index) => 2 * index + 2; private void Heapify(int index) { var left = GetFirstChild(index); var right = GetSecondChild(index); var min = index; if (left < _size && _elements[left].value < _elements[min].value) min = left; if (right < _size && _elements[right].value < _elements[min].value) min = right; if (_elements[index].value > _elements[min].value) { Swap(ref _elements[index], ref _elements[min]); Heapify(min); } } private static void Swap(ref (int x, int y, int value) first, ref (int x, int y, int value) second) { var temp = first; first = second; second = temp; } } #endregion } }
namespace E10 { public class Exalumnos { int cantidadDeIdiomasQueHabla; public int CantidadDeIdiomasQueHabla { get => cantidadDeIdiomasQueHabla; } int cuantoGana; public int CuantoGana { get => cuantoGana; } int cantidadDePaisesVisitados; public int CantidadDePaisesVisitados { get => cantidadDePaisesVisitados; } public Exalumnos(int cantidadDeIdiomasQueHabla, int cuantoGana, int cantidadDePaisesVisitados) { this.cantidadDeIdiomasQueHabla = cantidadDeIdiomasQueHabla; this.cuantoGana = cuantoGana; this.cantidadDePaisesVisitados = cantidadDePaisesVisitados; } } }
using System; using System.Collections.Generic; using System.Text; namespace DataStructurePrograms.DoublyLinekdList { class DoublyLinekdList { DNode head; DNode tail; int length; public DoublyLinekdList() { this.length = 0; } public bool isEmpty() { return length == 0; } public int Length() { return length; } public void InsertAtBegingin(object data) { DNode newNode = new DNode(data); if (head == null) { tail = newNode; } else { newNode.next = head; head.previous = newNode; } head = newNode; } public void displayBackWord() { DNode current = tail; while (current != null) { Console.Write(current.data +" ---> "); current = current.previous; } } /*public void createList() { DNode head = new DNode(20); DNode second = new DNode(30); DNode third = new DNode(40); head.next = second; second.previous = head; second.next = third; third.previous = second; third.next=null; } */ public void deleteAtLast() { DNode current = head; DNode currenttolast = null; while (current.next != null) { currenttolast = current; current = current.next; }currenttolast.next = null; current.previous = null; } public void deleteAt(int position) { DNode current = head; DNode currenttoPrevious = null; int count = 1; if (position == 1) { deleteFrist(); } else { while (count <= position - 1) { currenttoPrevious = current; current = current.next; count++; } DNode temp = current.next; temp.previous = currenttoPrevious; currenttoPrevious.next = temp; current.next = null; current.previous = null; } } public void deleteFrist() { DNode temp = head; head = head.next; head.previous = null; temp.next = null; } public void InsertAtLast(object data) { DNode NewNode = new DNode(data); DNode current = head; while (current.next != null) { current = current.next; } current.next = NewNode; NewNode.previous = current; } public void insertAt(int position,object data) { int count = 1; DNode newNode = new DNode(data); DNode current = head; while (count < position - 1) { current = current.next; count++; } DNode temp = current.next; newNode.next = temp; temp.previous = newNode; newNode.previous = current; current.next = newNode; } public void DisplayFoward() { DNode current = head; while (current != null) { Console.Write(current.data); if (current.next!= null) { Console.Write(" ----> "); } current = current.next; } Console.WriteLine("\n"); } } }
namespace TaxiService.CarCatalog.Models { public class Car { public int CarId { get; set; } public string Model { get; set; } public Category Category { get; set; } public string ImageName { get; set; } } }
using BLL; using DTO; using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace PL { public partial class FrmProdutoCadastrar : Form { public Produto produto = new Produto(); public FrmProdutoCadastrar(Acao acao) { InitializeComponent(); if (acao == Acao.Inserir) { this.Text = "Cadastrar Produto"; } else if (acao == Acao.Alterar) { this.Text = "Alterar Produto"; } } public FrmProdutoCadastrar(int CodigoProduto) { InitializeComponent(); if (CodigoProduto != 0) { this.Text = "Alterar Produto"; produto = PizzariaBLL.BuscarProdutoBLL(CodigoProduto); txtNome.Text = produto.DescricaoProduto; txtPreco.Text = produto.Preco; cboCategoria.Text = produto.Categoria; } } private void btnSalvar_Click(object sender, EventArgs e) { if (produto == null) produto = new Produto(); produto.DescricaoProduto = txtNome.Text; produto.Preco = txtPreco.Text; produto.Categoria = cboCategoria.Text; if (produto.CodProduto == 0) produto.CodProduto = PizzariaBLL.InserirProdutoBLL(produto); else PizzariaBLL.AtualizarProdutoBLL(produto); DialogResult = DialogResult.OK; } private void btnCancelar_Click(object sender, EventArgs e) { Close(); } } }
using System; using System.Collections.Generic; using System.Text; using System.Xml.Linq; namespace SlackTemplate.Core { public class StrongRenderer : IInlineRenderer { public string Render(XElement element) { return $"*{element.Value}*"; } } public abstract class ImageBlockRenderer<T> : ElementRenderer<T> where T : class { public class ImageBlock { public string ImageUrl { get; set; } public string AltText { get; set; } public string Title { get; set; } public string BlockId { get; set; } } protected ImageBlock ParseElement(XElement element) { return new ImageBlock() { ImageUrl = element.Attribute("image_url")?.Value ?? element.Attribute("src")?.Value, AltText = element.Attribute("alt_text")?.Value ?? element.Attribute("alt")?.Value, Title = element.Attribute("title")?.Value, BlockId = element.Attribute("block_id")?.Value }; } } }
using Infrostructure.Exeption; namespace DomainModel.Entity.ProductParts { /// <summary> /// ابعاد /// </summary> public class Size { private const decimal MinValue = 0m; public decimal Value { get; private set; } public Size(decimal value) { ValidateSizeValue(value); Value = value; } private void ValidateSizeValue(decimal value) { if (value < MinValue) throw new InvalidSizeMeasureValueException(value.ToString()); } } }
namespace KK.AspNetCore.EasyAuthAuthentication.Services { using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Security.Claims; using System.Threading.Tasks; using KK.AspNetCore.EasyAuthAuthentication.Models; using Microsoft.AspNetCore.Authentication; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.Logging; using Newtonsoft.Json; using Newtonsoft.Json.Linq; internal class LocalAuthMeService { public LocalAuthMeService( ILogger logger, string httpSchema, string host, IRequestCookieCollection cookies, IHeaderDictionary headers) { this.HttpSchema = httpSchema; this.Host = host; this.Cookies = cookies; this.Headers = headers; this.Logger = logger; } private readonly LocalProviderOption defaultOptions = new LocalProviderOption(".auth/me.json", ClaimTypes.Name, ClaimTypes.Role); private string Host { get; } private IRequestCookieCollection Cookies { get; } private IHeaderDictionary Headers { get; } private ILogger Logger { get; } private string HttpSchema { get; } /// <summary> /// Use this method to authenticate a user with easy auth. /// This will set the `context.User` of your HttpContext. /// </summary> /// <param name="logger">An instance of <see cref="ILogger"/>.</param> /// <param name="context">The http context with the missing user claim.</param> /// <param name="options">The <c>EasyAuthAuthenticationOptions</c> to use.</param> /// <returns>An <see cref="AuthenticateResult" />.</returns> public async Task<AuthenticateResult> AuthUser(HttpContext context, LocalProviderOption? options) { this.defaultOptions.ChangeModel(options); if (context.Request.Path.ToString() == this.defaultOptions.AuthEndpoint || context.Request.Path.ToString() == $"/{this.defaultOptions.AuthEndpoint}") { return AuthenticateResult.Fail($"The path {this.defaultOptions.AuthEndpoint} doesn't exsists or don't contain a valid auth json."); } try { var ticket = await this.CreateUserTicket(); this.Logger.LogInformation("Set identity to user context object."); context.User = ticket.Principal; this.Logger.LogInformation("identity build was a success, returning ticket"); return AuthenticateResult.Success(ticket); } catch (Exception ex) { return AuthenticateResult.Fail(ex.Message); } } private async Task<AuthenticationTicket> CreateUserTicket() { var cookieContainer = new CookieContainer(); var handler = this.CreateHandler(ref cookieContainer); var httpRequest = this.CreateAuthRequest(ref cookieContainer); var payload = await this.GetAuthMe(handler, httpRequest); // build up identity from json... var ticket = this.BuildIdentityFromEasyAuthMeJson((JObject)payload[0]); this.Logger.LogInformation("Set identity to user context object."); return ticket; } private AuthenticationTicket BuildIdentityFromEasyAuthMeJson(JObject payload) { var providerName = payload["provider_name"].Value<string>(); this.Logger.LogDebug($"payload was fetched from easyauth me json, provider: {providerName}"); this.Logger.LogInformation("building claims from payload..."); var ticket = AuthenticationTicketBuilder.Build( JsonConvert.DeserializeObject<IEnumerable<AADClaimsModel>>(payload["user_claims"].ToString()), providerName, this.defaultOptions.GetProviderOptions() ); var name = ticket.Principal.Claims?.FirstOrDefault(c => c.Type == ClaimTypes.Name)?.Value ?? string.Empty; var roles = ticket.Principal.Claims?.Where(c => c.Type == ClaimTypes.Role); var rolesString = string.Join(", ", roles?.Select(r => r.Value)) ?? string.Empty; this.Logger.LogInformation($"identity name: '{ name }' with roles: [{ rolesString }]"); return ticket; } private async Task<JArray> GetAuthMe(HttpClientHandler handler, HttpRequestMessage httpRequest) { JArray? payload = null; using (var client = new HttpClient(handler)) { HttpResponseMessage? response; try { response = await client.SendAsync(httpRequest); } catch (Exception ex) { throw ex; } if (!response.IsSuccessStatusCode) { this.Logger.LogDebug("auth endpoint was not successful. Status code: {0}, reason {1}", response.StatusCode, response.ReasonPhrase); response.Dispose(); throw new WebException("Unable to fetch user information from auth endpoint."); } var content = await response.Content.ReadAsStringAsync(); response.Dispose(); try { payload = JArray.Parse(content); } catch (Exception) { throw new JsonSerializationException("Could not retrieve json from /me endpoint."); } } return payload; } private HttpRequestMessage CreateAuthRequest(ref CookieContainer cookieContainer) { this.Logger.LogInformation($"identity not found, attempting to fetch from auth endpoint '/{this.defaultOptions.AuthEndpoint}'"); var uriString = $"{this.HttpSchema}://{this.Host}"; this.Logger.LogDebug("host uri: {0}", uriString); foreach (var c in this.Cookies) { cookieContainer.Add(new Uri(uriString), new Cookie(c.Key, c.Value)); } this.Logger.LogDebug("found {0} cookies in request", cookieContainer.Count); foreach (var cookie in this.Cookies) { this.Logger.LogDebug(cookie.Key); } // fetch value from endpoint string authMeEndpoint; if (this.defaultOptions.AuthEndpoint.StartsWith("http")) { authMeEndpoint = this.defaultOptions.AuthEndpoint; // enable pulling from places like storage account private blob container } else { authMeEndpoint = $"{uriString}/{this.defaultOptions.AuthEndpoint}"; // localhost relative path, e.g. wwwroot/.auth/me.json } var request = new HttpRequestMessage(HttpMethod.Get, authMeEndpoint); foreach (var header in this.Headers) { if (header.Key.StartsWith("X-ZUMO-")) { request.Headers.Add(header.Key, header.Value[0]); } } return request; } private HttpClientHandler CreateHandler(ref CookieContainer cookieContainer) { var handler = new HttpClientHandler() { CookieContainer = cookieContainer }; return handler; } } }
using EmirateHMBot.Models; using EmirateHMBot.Services; using IronPdf; using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Diagnostics; using System.Drawing.Printing; using System.IO; using System.Reflection; using System.Text; using System.Windows.Forms; using TheArtOfDev.HtmlRenderer.PdfSharp; using TuesPechkin; namespace EmirateHMBot { public partial class CredentialForm : Form { string userName = "bilel"; string passWord = "2305"; public CredentialForm() { InitializeComponent(); } private async void CredentialForm_Load(object sender, EventArgs e) { var employees = JsonConvert.DeserializeObject<List<Employee>>(File.ReadAllText("employes.txt")); var companyInfo = new CompanyInfo() { CompanyCategory = "D", CompanyCode= "352128", CompanyName= "الامارات للرخام", DateOfImprimate= "00:31:28 02/02/202", NbrOfEmployees= "292" }; EservicesMohreService.SaveBrutHtml(employees, companyInfo); } private void ScrapePermitB_Click(object sender, EventArgs e) { if (UsernameT.Text == "" || PasswordT.Text == "") { MessageBox.Show("username and/or password is missed"); return; } if (UsernameT.Text != userName || PasswordT.Text != passWord) { MessageBox.Show("username or passsword is not valide"); return; } else { Hide(); MainForm mainfrom = new MainForm(); mainfrom.Show(); } } private void CredentialForm_FormClosing(object sender, FormClosingEventArgs e) { Application.Exit(); } } }
using Common.Models; using NHibernate; using NHibernate.Criterion; using System; using System.Collections.Generic; namespace Common.Services { public class KursleiterService : BaseService { public KursleiterService(Func<ISession> session) : base(session) { } public IList<Kursleiter> Get() { return CurrentSession.CreateCriteria(typeof(Kursleiter)).List<Kursleiter>(); } public Kursleiter Get(int id) { return CurrentSession.Get<Kursleiter>(id); } public Kursleiter Add(Kursleiter kursleiter) { using (var tran = CurrentSession.BeginTransaction()) { try { if (kursleiter.KursleiterID > 0) { throw new Exception(String.Format("A Kursleiter with Bid {0} already exists. To update please use PUT.",kursleiter.KursleiterID)); } CurrentSession.Save(kursleiter); tran.Commit(); return kursleiter; } catch (Exception ex) { tran.Rollback(); throw ex; } } } public Kursleiter Update(Kursleiter kursleiter) { using (var tran = CurrentSession.BeginTransaction()) { try { if (kursleiter.KursleiterID == 0) { throw new Exception("For creating a Kursleiter please use POST"); } CurrentSession.Update(kursleiter); tran.Commit(); return kursleiter; } catch (Exception ex) { tran.Rollback(); throw ex; } } } public bool Delete(int id) { using (var tran = CurrentSession.BeginTransaction()) { try { var kursleiter = Get(id); if (kursleiter != null) { CurrentSession.Delete(kursleiter); tran.Commit(); } return true; } catch (Exception ex) { tran.Rollback(); throw ex; } } } } }
using System.Collections; using System.Collections.Generic; using System.Xml.Serialization; using System.IO; using System.Xml; using System; [XmlRoot("Empire")] public class Empire { [XmlElement] public int id; [XmlElement] public string name; [XmlElement] public string description; [XmlArray("populationTypes")] [XmlArrayItem("populationType")] public List<Population> population; [XmlElement] public Government government; public Empire() { id = 0; name = "none"; } public static void SaveXML(Empire empire,string empireName) { XMLUtility.SaveUserXML<Empire>(Path.Combine(XMLUtility.userGalaxyXMLPath, empireName), empire); } public static Empire LoadXML(string empireName) { return XMLUtility.LoadUserXML<Empire>(Path.Combine(XMLUtility.userGalaxyXMLPath, empireName)); } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net.WebSockets; using System.Text; using System.Threading; using System.Threading.Tasks; using WebCore.Extension; namespace WebCore.Internal { internal class ChatRoom : IChatRoom { private ChatRoom() { } private static ChatRoom _chatRoom { get; set; } = new ChatRoom(); public static ChatRoom GetInstance() => _chatRoom; Dictionary<string, WebSocket> _dic = new Dictionary<string, WebSocket>();//临时客户端存储 public void Add(string key, WebSocket webSocket) { if (!_dic.ContainsKey(key)) { _dic.Add(key, webSocket); } } public bool Remove(string key) { return _dic.ContainsKey(key) ? _dic.Remove(key) : _dic.ContainsKey(key); } public async void RaiseMsg(string msg) { foreach (var client in _dic) { await client.Value.SendStringAsync(msg, CancellationToken.None); } } } public interface IChatRoom { void Add(string key, WebSocket webSocket); bool Remove(string key); void RaiseMsg(string msg); } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; namespace ConsoleApp1.Domain.Dishes { public class Teaspoon : Cutlery { private static SemaphoreSlim nbrItemAvailable = new SemaphoreSlim(0, 150); public static int getnbrItemAvailable() { return nbrItemAvailable.CurrentCount; } public static void getVaiselle() { nbrItemAvailable.Wait(); } public void releaseVaiselle() { nbrItemAvailable.Release(); } } }
using System; using System.Collections; using PlayerController; using UnityEngine; using Zenject; using Random = UnityEngine.Random; namespace Obstacles { public class Wall : MonoBehaviour, ICollision { [SerializeField] private int _minimumStrength; [SerializeField] private int _maximumStrength; public event Action OnStrengthChanged; private int _strength; private Rigidbody _rigidbody; private MeshRenderer _meshRenderer; private PlayerState _playerState; public int Strength => _strength; [Inject] private void Construct(Rigidbody rigidbody,MeshRenderer meshRenderer, PlayerState playerState) { _rigidbody = rigidbody; _meshRenderer = meshRenderer; _playerState = playerState; ; } private void Awake() { _strength = Random.Range(_minimumStrength, _maximumStrength); } private IEnumerator LoseWallStrength() { while (_strength > 0) { _strength--; OnStrengthChanged?.Invoke(); _rigidbody.velocity = _playerState.transform.forward * 2f; yield return new WaitForSeconds(0.1f); } StartCoroutine(ChangeWallTransparency()); GetComponent<BoxCollider>().isTrigger = true; _playerState.State = State.RUN; } private IEnumerator ChangeWallTransparency() { var wallColor = _meshRenderer.material.color; wallColor.a = 0f; while (_meshRenderer.material.color.a >= 0) { _meshRenderer.material.color = Color.Lerp(_meshRenderer.material.color, wallColor, 2f * Time.deltaTime); yield return null; } } public void Collide() { _playerState.State = State.PUSH; StartCoroutine(LoseWallStrength()); } } }
using System; using System.Collections.Generic; using Autofac; using Framework.Core.Common; using NUnit.Framework; using Tests.Data.Van; using Tests.Data.Van.Input; using Tests.Data.Van.Input.Filters; using Tests.Pages.Van.LogIn; using Tests.Pages.Van.Main.Common.DefaultPage; using Tests.Pages.Van.Main.Turf; using Tests.Pages.Van.Main.VoterBatchPages; namespace Tests.Projects.Van.TurfManagementTests.BulkActionsTests { public class ExportBulkAction : BaseTest { #region Test Pages private Driver Driver { get { return Scope.Resolve<Driver>(); } } private LoginPage LogInPage { get { return Scope.Resolve<LoginPage>(); } } private VoterDefaultPage HomePage { get { return Scope.Resolve<VoterDefaultPage>(); } } private TurfListPage TurfListPage { get { return Scope.Resolve<TurfListPage>(); } } private ExportListPage ExportListPage { get { return Scope.Resolve<ExportListPage>(); } } #endregion #region Test Case Data #region TestCase: Export Single Turfs from Different Map Regions private static readonly VanTestUser User1 = new VanTestUser { UserName = "TurfTester11", Password = "@uT0Te$t11InG", Site = "featureturfmanagement.dev.local" }; private static readonly TurfListPageFilter Filter1 = new TurfListPageFilter { Name = "Turf 01" }; private static readonly ScriptSortOptionsForm SsoForm1 = new ScriptSortOptionsForm { UseDefaultOptions = true, ReportFormat = "Calling List New!", Script = "DM_Test_Script", ContactedHow = "Walk" }; private static readonly List<string> TurfsToSelectList1 = new List<string> { "Test_Region1 Turf 01", "Test_Region2 Turf 01", "Test_Region3 Turf 01" }; #endregion private static readonly object[] TestData = { new object[] { User1, Filter1, SsoForm1, TurfsToSelectList1 } }; #endregion /// <summary> /// Tests the functionality of the Export feature for multiple Turfs. /// Exports multiple Turfs. /// </summary> [Test, TestCaseSource("TestData")] [Ignore] // Incomplete test [Category("van"), Category("van_turfmanagement")] public void ExportBulkActionTest( VanTestUser user, TurfListPageFilter filter, ScriptSortOptionsForm ssoForm, List<string> turfsToSelectList) { LogInPage.Login(user); HomePage.ClickMyTurfsLink(); TurfListPage.ApplyFilter(filter); TurfListPage.SelectTurfsOrRegionsForBulkAction(turfsToSelectList, "Turf", "Export"); foreach (var turf in turfsToSelectList) { ExportListPage.ClickMostRecentDownloadLink(); Assert.That(Driver.UrlContains("FileExportHandler.ashx"), Is.True, String.Format("URL for Turf: {0} does not contain the proper page for PDF viewing", turf)); Driver.GoToPreviousPage(); } } } }
using System; namespace Agency Profit { class Program { static void Main(string[] args) { string nameOfCompany = Console.ReadLine(); int ticketsAdults = int.Parse(Console.ReadLine()); int ticketsChildren = int.Parse(Console.ReadLine()); double netoPriceAdult = double.Parse(Console.ReadLine()); double taksaPrice = double.Parse(Console.ReadLine()); double netoPriceChildren = netoPriceAdult - (0.7 * netoPriceAdult); double PriceAdult = netoPriceAdult + taksaPrice; double priceChildren = netoPriceChildren + taksaPrice; double priceOfAll = (PriceAdult * ticketsAdults) + (priceChildren * ticketsChildren); Console.WriteLine($"The profit of your agency from {nameOfCompany} tickets is {(priceOfAll * 0.2):f2} lv."); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using System; public static class GameMath { public static int DamageToShow(int realDamage) { int res = 0; //достать текущее здоровье игрока //определить на основании этого соотношение, по которому будет отниматься визуальное здоровье //изменить реальное здоровье игрока и визуальное return res; } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using System.IO; [DisallowMultipleComponent] public class MakeATexture : MonoBehaviour { //public RenderTexture m_InputTexture; void SaveRenderTexture() { int width = 2; int height = 2; Texture2D texture = new Texture2D(width, height, TextureFormat.RGBAFloat, false); texture.SetPixel(0, 0, Color.red); texture.SetPixel(0, 1, Color.green); texture.SetPixel(1, 0, Color.blue); texture.SetPixel(1, 0, Color.white); texture.Apply(); byte[] bytes = texture.EncodeToEXR(Texture2D.EXRFlags.CompressZIP); //byte[] bytes = texture.EncodeToPNG(); File.WriteAllBytes(Application.dataPath + "/Test.exr", bytes); Debug.Log(Application.dataPath); Object.DestroyImmediate(texture); } private void Start() { Debug.Log("...."); SaveRenderTexture(); } }
using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Security.Claims; using System.Text; using System.Threading.Tasks; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Options; using Microsoft.Extensions.Primitives; using Newtonsoft.Json; using MeeToo.Api.Models; using MeeToo.Api.Options; using MeeToo.Security; using MeeToo.Security.Identity; using MeeToo.Services.MessageSending.Email; namespace MeeToo.Api.Controllers { [Route("api/v1.1/auth")] public class AuthenticationController : Controller { private readonly IOptions<WebsiteCookiesOptions> cookiesOptions; private readonly UserManager<MeeTooUser> userManager; private readonly IEmailSender emailSender; private readonly IEmailTemplateSource emailTemplateSource; private WebsiteCookiesOptions WebsiteCookiesOptions => cookiesOptions.Value; public AuthenticationController(IOptions<WebsiteCookiesOptions> cookiesOptions, UserManager<MeeTooUser> userManager, IEmailSender emailSender, IEmailTemplateSource emailTemplateSource) { this.cookiesOptions = cookiesOptions; this.userManager = userManager; this.emailSender = emailSender; this.emailTemplateSource = emailTemplateSource; } [HttpPost] [Route("signin")] [AllowAnonymous] public async Task<IActionResult> SignIn([FromBody] SignInModel signInModel) { var claims = new List<Claim> {new Claim(ClaimTypes.Email, signInModel.Email)}; var principal = new ClaimsPrincipal(new ClaimsIdentity(claims)); var user = await userManager.GetUserAsync(principal); if (user == null || !await userManager.CheckPasswordAsync(user, signInModel.Password)) { return Unauthorized(); } claims.AddRange(await userManager.GetClaimsAsync(user)); claims.AddRange((await userManager.GetRolesAsync(user)).Select(role => new Claim(ClaimTypes.Role, role))); var identity = new ClaimsIdentity(claims, "MeeToo.api"); await HttpContext.Authentication.SignInAsync("api", new ClaimsPrincipal(identity)); HttpClient httpClient = new HttpClient(); var jsonClaims = JsonConvert.SerializeObject(claims); var requestContent = new StringContent(jsonClaims, Encoding.UTF8, "application/json"); var response = await httpClient.PostAsync(WebsiteCookiesOptions.WebsiteCookieEndpoint, requestContent); var enumerable = response.Headers.GetValues("Set-Cookie"); StringValues values; if (Response.Headers.TryGetValue("Set-Cookie", out values)) { Response.Headers["Set-Cookie"] = new StringValues(values.Concat(enumerable).ToArray()); } else { Response.Headers.Add("Set-Cookie", new StringValues(enumerable.ToArray())); } return Ok(); } [HttpPost] [Route("register")] [AllowAnonymous] public async Task<IActionResult> Register([FromBody]UserRegistrationModel regModel) { var claims = new List<Claim> {new Claim(ClaimTypes.Email, regModel.Email)}; var principal = new ClaimsPrincipal(new ClaimsIdentity(claims)); var user = await userManager.GetUserAsync(principal); if (user != null) { return new StatusCodeResult((int) HttpStatusCode.Conflict); } var newUser = new MeeTooUser(regModel.Email); try { await userManager.CreateAsync(newUser); await userManager.AddPasswordAsync(newUser, regModel.Password); await userManager.AddToRoleAsync(newUser, Roles.Student); var emailConfirmToken = await userManager.GenerateEmailConfirmationTokenAsync(newUser); await SetEmailConfirmationCookieAsync(newUser.Id); var templateModel = new { Link = $"http://google.com/{emailConfirmToken}" }; await emailSender.To(newUser.Email) .AddSubject("MeeToo - Email Підтвердження") .SetTemplate(emailTemplateSource, "emailConfirmation.html", templateModel) .SendAsync(); } catch (Exception) { await userManager.DeleteAsync(newUser); throw; } return Ok(); } [HttpPost] [Route("verifyEmail")] [Authorize(ActiveAuthenticationSchemes = "emailConfirmation")] public async Task<IActionResult> VerifyEmail(string token) { var user = await userManager.GetUserAsync(User); var identityResult = await userManager.ConfirmEmailAsync(user, token); if (identityResult.Succeeded) { return Ok(); } return Unauthorized(); } private async Task SetEmailConfirmationCookieAsync(string userId) { var identity = new ClaimsIdentity("emailConfirmation"); identity.AddClaim(new Claim(ClaimTypes.Email, userId)); await HttpContext.Authentication.SignInAsync("emailConfirmation", new ClaimsPrincipal(identity)); } } }
using Microsoft.AspNetCore.Routing.Constraints; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DonLEonFilms.Utils { public class WebFileStorage { public static String SaveFile(String rootPath, String fileName, Stream stream ) { String storage_full = FileNameToFileNameStorage( fileName ); String os_full = rootPath + "\\" + storage_full; var folder = Path.GetDirectoryName( os_full ); if( false == Directory.Exists( folder ) ) { System.IO.Directory.CreateDirectory( folder ); } using( var file_stream = new FileStream( os_full, FileMode.Create, FileAccess.Write ) ) { stream.Seek( 0, SeekOrigin.Begin ); stream.CopyTo( file_stream ); } return storage_full; } /// <summary> /// /// </summary> /// <param name="fileName"></param> /// <returns></returns> public static String FileNameToFileNameStorage( String fileName ) { String md5 = FileToMD4( fileName ); String file_name = Md5ToPath( md5 ); String extension = Path.GetExtension( fileName ); return file_name + "." + extension; } /// <summary> /// /// </summary> /// <param name="md5String"></param> /// <returns></returns> private static String Md5ToPath( String md5String ) { String path_l1 = md5String.Substring( 0, 2 ); String path_l2 = md5String.Substring( 2, 2 ); String file_name = md5String.Substring( 4 ); String result = path_l1 + "\\" + path_l2 + "\\" + file_name; return result; } /// <summary> /// /// </summary> /// <param name="fileName"></param> /// <returns></returns> private static String FileToMD4( String fileName) { fileName += DateTime.Now.Ticks.ToString(); // так то лучше считать не из имени а из данных using( System.Security.Cryptography.MD5 md5 = System.Security.Cryptography.MD5.Create() ) { byte[] inputBytes = System.Text.Encoding.ASCII.GetBytes( fileName ); byte[] hashBytes = md5.ComputeHash( inputBytes ); StringBuilder sb = new StringBuilder(); for( int i = 0; i < hashBytes.Length; i++ ) { sb.Append( hashBytes[i].ToString( "X2" ) ); } return sb.ToString(); } } } }
using System; using System.Collections.Generic; using System.Text; namespace SomeTechie.RoundRobinScheduleGenerator { public class CourtRound : Round { public bool IsActive { get { if(IsCompleted)return false; bool isActive=true; List<CourtRound> courtRounds = Controller.GetController().Tournament.CourtRounds; int thisIndex = courtRounds.IndexOf(this); if(thisIndex<0)return false; for (int i = 0; i < thisIndex; i++) { if (!courtRounds[i].IsCompleted) { isActive = false; break; } } return isActive; } } public CourtRound(List<Game> games, int roundNumber) : base(games, roundNumber) { } protected CourtRound() : base() { } public static string CourtNumToCourtName(int courtNum) { return String.Format("Court {0}", CourtNumToCourtLetter(courtNum)); } public static string CourtNumToCourtLetter(int courtNum) { char courtLetter = Convert.ToChar((courtNum - 1) + 65); return courtLetter.ToString(); } public override string ToString() { string value = ""; for (int i = 0; i < numGames; i++) { if(i>0){ value+="\n"; } string courtName = CourtNumToCourtName(i + 1); value += String.Format("{0}: {1}", courtName, Games[i]); } return value; } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class Tkm1_Gm3_Phone : MonoBehaviour { public Animator PhoneAnim; void Start () { PhoneAnim = GameObject.Find("GameObject_Phone").GetComponent <Animator> (); } public void OnClickSmallPhone() { //BigPhone.SetActive (true); PhoneAnim.Play("3test_Phone_ZoomAnim"); PhoneAnim.SetBool ("Phone", true); } }
using WebsiteManagerPanel.Data.Entities.Base; namespace WebsiteManagerPanel.Data.Entities { //Sayfa üzerindeki, her bir Action’a karşılık gelen yetki tablosudur.Burada dikkat edilmesi gereken bir husus da, RoleID alanının “bigint” olmasıdır.Bu kısım makalenin devamında detaylıca anlatılacaktır. public partial class Role:Entity { public long? RoleId { get; set; } public string RoleName { get; set; } public bool IsActive { get; set; } public virtual RoleGroup ?Group { get; set; } } }
using System; using Microsoft.AspNetCore.Mvc; using thedailypost.Service.Interfaces; using thedailypost.Service.Models; namespace thedailypost.Api.Controllers { [Route("api/[controller]")] public class UserSubredditController : Controller { private readonly IAuthenticationService _authService; private readonly IUserSubredditService _userSubredditService; public UserSubredditController(IAuthenticationService authService, IUserSubredditService userSubredditService) { _authService = authService; _userSubredditService = userSubredditService; } // GET: UserSubreddit [HttpGet("{userId}")] public ActionResult GetUserSubreddit(int userId) { try { var results = _userSubredditService.GetUserSubreddit(userId); return Ok(results); } catch(Exception) { return BadRequest(); } } [HttpPost] public ActionResult AddNewUserSubreddit([FromBody] UserSubredditModel userSub) { try { var results = _userSubredditService.AddNewUserSubreddit(userSub); return Created("", results); } catch (Exception) { return BadRequest(); } } [HttpDelete] public ActionResult DeleteUserSubreddit([FromBody] UserSubredditModel userSub) { try { _userSubredditService.DeleteUserSubreddit(userSub); return NoContent(); } catch (ArgumentNullException) { return NotFound(); } } } }
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Threading.Tasks; namespace NgNetCore.Models { public class Arriendo { public Arriendo() { } public Arriendo(Cliente cliente, Inmueble inmueble, int mes) { Cliente = cliente; Inmueble = inmueble; Mes = mes; } [Required] public int Id { get; set; } [Required] public Cliente Cliente { get; set; } [Required] public Inmueble Inmueble { get; set; } [Required] public int Mes { get; set; } [Required] public decimal ValorContrato { get=>Inmueble.Valor*Mes; set { } } } }
using Microsoft.Win32; using Spire.Barcode; using System; using System.Drawing; using System.Drawing.Imaging; using System.IO; using System.Windows; using System.Windows.Media; using System.Windows.Media.Imaging; using Visitors.DAO; using Visitors.DAOImpl; using Visitors.entity; namespace Visitors.View { /// <summary> /// Interaction logic for QrCodeGeneration.xaml /// </summary> public partial class QrCodeGeneration : Window { public QrCodeGeneration() { InitializeComponent(); } private void qrBtn_Click(object sender, RoutedEventArgs e) { BarcodeSettings.ApplyKey("your key");//you need a key from e-iceblue, otherwise the watermark 'E-iceblue' will be shown in barcode BarcodeSettings settings = new BarcodeSettings(); settings.Type = BarCodeType.QRCode; settings.Unit = GraphicsUnit.Pixel; settings.ShowText = false; settings.ResolutionType = ResolutionType.UseDpi; //input data UserMaster u = new UserMaster(); UserMasterDAO usrDAO = new UserMasterDAOImpl(); u = usrDAO.findbyprimaryKey(6); string data = "UserName :" + u.username + "\n Password : " + u.pwd + "\nMobileNo : " + u.mobileNo + "\ngender : " + u.gender; Console.WriteLine("Usren mae:{0} password:{1} Mobile No={2} gender={3}", u.username, u.pwd, u.mobileNo, u.gender); settings.Data = data; string foreColor = "Black"; string backColor = "White"; settings.ForeColor = System.Drawing.Color.FromName(foreColor); settings.BackColor = System.Drawing.Color.FromName(backColor); settings.X = Convert.ToInt16(30); short leftMargin = 1; settings.LeftMargin = leftMargin; short rightMargin = 1; settings.RightMargin = rightMargin; short topMargin = 1; settings.TopMargin = topMargin; short bottomMargin = 1; settings.BottomMargin = bottomMargin; settings.QRCodeECL = QRCodeECL.L; BarCodeGenerator generator = new BarCodeGenerator(settings); Image QRbarcode = generator.GenerateImage(); image1.Source = BitmapToImageSource(QRbarcode); } private ImageSource BitmapToImageSource(Image bitmap) { //throw new NotImplementedException(); using (MemoryStream memory = new MemoryStream()) { bitmap.Save(memory, ImageFormat.Bmp); memory.Position = 0; BitmapImage bitmapimage = new BitmapImage(); bitmapimage.BeginInit(); bitmapimage.StreamSource = memory; bitmapimage.CacheOption = BitmapCacheOption.OnLoad; bitmapimage.EndInit(); return bitmapimage; } } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using Microsoft.Kinect; public class motionController : MonoBehaviour { //we are going to create a custome gesture using the kinect ! //the GETJOINTPOSITIONDEMO.cs was a real help // Use this for initialization private KinectInterop.JointType head = KinectInterop.JointType.SpineShoulder; private KinectInterop.JointType hip = KinectInterop.JointType.SpineBase; private KinectInterop.JointType leftKnee = KinectInterop.JointType.KneeLeft; private KinectInterop.JointType rightKnee = KinectInterop.JointType.KneeRight; private KinectInterop.JointType leftShoulder = KinectInterop.JointType.ShoulderLeft; private KinectInterop.JointType rightShoulder = KinectInterop.JointType.ShoulderRight; public Vector3 headJointPosition; public Vector3 hipJointPosition; public Vector3 leftKneeJointPosition; public Vector3 rightKneeJointPosition; public Vector3 leftShoulderJointPosition; public Vector3 rightShoulderJointPosition; private long trackedUsersId; public float moveSpeed = 2.5f; public float turnSpeed = 12.5f; void Start () { } void checkPosture() { KinectManager manager = KinectManager.Instance; trackedUsersId = manager.GetPrimaryUserID(); if (manager.IsUserDetected() && manager.IsUserTracked(trackedUsersId)) { print("user detected"); if (manager.IsJointTracked(trackedUsersId, (int)head) && manager.IsJointTracked(trackedUsersId, (int)hip) && manager.IsJointTracked(trackedUsersId, (int)leftKnee) && manager.IsJointTracked(trackedUsersId, (int)rightKnee) && manager.IsJointTracked(trackedUsersId, (int)rightShoulder) && manager.IsJointTracked(trackedUsersId, (int)leftShoulder)) { print("got the joints .. of the body"); headJointPosition = manager.GetJointPosition(trackedUsersId, (int)head); hipJointPosition = manager.GetJointPosition(trackedUsersId, (int)hip); leftKneeJointPosition = manager.GetJointPosition(trackedUsersId, (int)leftKnee); rightKneeJointPosition = manager.GetJointPosition(trackedUsersId, (int)rightKnee); leftShoulderJointPosition = manager.GetJointPosition(trackedUsersId, (int)leftShoulder); rightShoulderJointPosition = manager.GetJointPosition(trackedUsersId, (int)rightShoulder); if ((headJointPosition.z - hipJointPosition.z) < -0.05 ) { gameObject.transform.Translate(0, 0, (moveSpeed * Time.deltaTime)); print("lean forward"+ (headJointPosition.y - hipJointPosition.y)); print("going forward"); } else if(leftKneeJointPosition.y > 0.65 || rightKneeJointPosition.y > 0.65) { gameObject.transform.Translate(0, 0, (moveSpeed * 4 * Time.deltaTime)); print("left knee" + leftKneeJointPosition.y); print("right knee" + rightKneeJointPosition.y); print("going forward"); } else { gameObject.transform.Translate(0, 0, 0); print(headJointPosition.y - hipJointPosition.y); print("not moving"); } //rotation if ((leftShoulderJointPosition.z - rightShoulderJointPosition.z) > 0.05) { gameObject.transform.Rotate(Vector3.up, (-turnSpeed * Time.deltaTime)); print(leftShoulderJointPosition.z - rightShoulderJointPosition.z); print("rotating left"); } else if ((leftShoulderJointPosition.z - rightShoulderJointPosition.z) < -0.05) { gameObject.transform.Rotate(Vector3.up, (turnSpeed * Time.deltaTime)); print(leftShoulderJointPosition.z - rightShoulderJointPosition.z); print("rotating right"); } }//if the joint is tracked ny this user.. }//if the kinect senses atleast a user and if the user is the primary user id, or the first sensed user } // Update is called once per frame void Update () { checkPosture(); } }
using UnityEngine; public class BallBouncer : MonoBehaviour { [SerializeField] private Vector3 m_initialVelocity; [SerializeField] private float m_minVelocity = 10f; private Vector3 lastFrameVelocity; private Rigidbody2D m_rigidBody2D; private void Start() { m_rigidBody2D = this.GetComponent<Rigidbody2D>(); m_rigidBody2D.velocity = m_initialVelocity; } private void Update() { lastFrameVelocity = m_rigidBody2D.velocity; } private void OnCollisionEnter2D(Collision2D collision) { Bounce(collision.contacts[0].normal); } private void Bounce(Vector3 collisionNormal) { var speed = lastFrameVelocity.magnitude; var direction = Vector3.Reflect(lastFrameVelocity.normalized, collisionNormal); m_rigidBody2D.velocity = direction * Mathf.Max(speed, m_minVelocity); } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace project09 { class Bowlers { private const int MAX_SIZE = 10; private string[] plyrNames; private int[] plyrScores; private int arrCount; private double sum, average; // Constructor Bowlers() // Initialize data public Bowlers() { plyrNames = new string[MAX_SIZE]; plyrScores = new int[MAX_SIZE]; arrCount = 0; sum = 0.0; average = 0.0; } // SplitEm method // Purpose: splits user's name and score input and store in string arrays // Parameters: user's name and score input // Returns: none public void SplitEm(string input) { int score = 0; string name = ""; string[] wook = input.Split(); name = wook[0]; score = int.Parse(wook[1]); plyrScores[arrCount] = score; plyrNames[arrCount] = name; arrCount++; } // SplitEm method // Purpose: splits user's name and score input and store in string arrays // Parameters: user's name and score input // Returns: none public void SortEm() { for (int i = 0; i < arrCount - 1; i++) { for (int j = 0; j < arrCount - 1; j++) { if (plyrScores[j] < plyrScores[j + 1]) { int temp = plyrScores[j]; // Sort the player scores plyrScores[j] = plyrScores[j + 1]; plyrScores[j + 1] = temp; string tempName = plyrNames[j]; // Sort the player names at the same time plyrNames[j] = plyrNames[j + 1]; plyrNames[j + 1] = tempName; } } } } // GetNames method // Purpose: return player's name for the index number // Parameters: i for index number of the string array // Returns: player's name for the index number public string GetNames(int i) { return plyrNames[i]; } // GetScores method // Purpose: return player's score for the index number // Parameters: i for index number of the int array // Returns: player's score for the index number public int GetScores(int i) { return plyrScores[i]; } // CalcAverage method // Purpose: calculates the average of all bowler's scores // Parameters: i for index number of the string array // Returns: player's name for the index number public void CalcAverage() { for (int i = 0; i < arrCount; i++) sum += plyrScores[i]; average = sum / arrCount; } // GetAverage method // Purpose: return average score of bowler's scores // Parameters: none // Returns: average score of bowler's scores public double GetAverage( ) { return average; } }// end class Bowlers }
using System; using System.Text; namespace String_Manipulator___Group_2 { class Program { static void Main(string[] args) { var myString = new StringBuilder(Console.ReadLine()); var command = Console.ReadLine(); while (command!="Done") { var tokens = command.Split(" ", StringSplitOptions.RemoveEmptyEntries); if (tokens[0] == "Change") { var symbol = tokens[1]; var replacement = tokens[2]; myString = myString.Replace(symbol, replacement); Console.WriteLine(myString); } else if (tokens[0] == "Includes") { var substring = tokens[1]; Console.WriteLine(myString.ToString().Contains(substring)); } else if (tokens[0] == "End") { var substring = tokens[1]; Console.WriteLine(myString.ToString().EndsWith(substring)); } else if (tokens[0] == "Uppercase") { myString = new StringBuilder(myString.ToString().ToUpper()); Console.WriteLine(myString); } else if (tokens[0] == "FindIndex") { var symbol = tokens[1]; Console.WriteLine(myString.ToString().IndexOf(symbol)); } else if (tokens[0] == "Cut") { var startIndex = int.Parse(tokens[1]); var length = int.Parse(tokens[2]); myString =new StringBuilder(myString.ToString().Substring(startIndex, length)); Console.WriteLine(myString); } command = Console.ReadLine(); } } } }
using System.Net; using System.Net.Http.Headers; using System.Threading.Tasks; using Justa.Job.Backend.Api.Application.Services.DataValidation.Models; using Newtonsoft.Json; using Xunit; namespace Justa.Job.Backend.Test { public class DataValidationTest : JustaJobBackendTestBase { [Theory] [InlineData("00000000000", false)] [InlineData("93124123", false)] [InlineData("99672059035", true)] [InlineData("87827655025", true)] public async Task ValidateCpfTheory(string cpf, bool isValid) { var jwt = await GetJwt(); _httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", jwt.AccessToken); using (var httpResponse = await _httpClient.GetAsync($"/validate/cpf/{cpf}")) { Assert.True(httpResponse.StatusCode == HttpStatusCode.OK); var httpContent = await httpResponse.Content.ReadAsStringAsync(); var response = JsonConvert.DeserializeAnonymousType(httpContent, new { type = string.Empty, isValid = false, value = string.Empty, formated = string.Empty }); Assert.Equal(cpf, response.value); Assert.Equal(isValid, response.isValid); } } [Theory] [InlineData("11111111111111", false)] [InlineData("93124123314124", false)] [InlineData("62735445000177", true)] [InlineData("50205502000127", true)] public async Task ValidateCnpjTheory(string cnpj, bool isValid) { var jwt = await GetJwt(); _httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", jwt.AccessToken); using (var httpResponse = await _httpClient.GetAsync($"/validate/cnpj/{cnpj}")) { Assert.True(httpResponse.StatusCode == HttpStatusCode.OK); var httpContent = await httpResponse.Content.ReadAsStringAsync(); var response = JsonConvert.DeserializeAnonymousType(httpContent, new { type = string.Empty, isValid = false, value = string.Empty, formated = string.Empty }); Assert.Equal(cnpj, response.value); Assert.Equal(isValid, response.isValid); } } [Theory] [InlineData("9sahrawia_15_207a@grandw88.info", true)] [InlineData("fulano.gmail", false)] public async Task ValidateEmail(string email, bool isValid) { var jwt = await GetJwt(); _httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", jwt.AccessToken); using (var httpResponse = await _httpClient.GetAsync($"/validate/email/{email}")) { Assert.True(httpResponse.StatusCode == HttpStatusCode.OK); var httpContent = await httpResponse.Content.ReadAsStringAsync(); var response = JsonConvert.DeserializeObject<EmialValidatorResponse>(httpContent); Assert.Equal(email, response.Email); Assert.Equal(isValid, response.FormatValid); } } [Theory] [InlineData("14158586273", true)] public async Task ValidatePhoneNumber(string number, bool isValid) { var jwt = await GetJwt(); _httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", jwt.AccessToken); using (var httpResponse = await _httpClient.GetAsync($"/validate/phone-number/{number}")) { Assert.True(httpResponse.StatusCode == HttpStatusCode.OK); var httpContent = await httpResponse.Content.ReadAsStringAsync(); var response = JsonConvert.DeserializeObject<PhoneNumberValidatorResponse>(httpContent); Assert.Equal(number, response.Number); Assert.Equal(isValid, response.Valid); } } } }
using NeuroLinker.Enumerations; using NeuroLinker.Interfaces.Configuration; using System.Net.Http; using VaraniumSharp.Attributes; using VaraniumSharp.Enumerations; using VaraniumSharp.Extensions; namespace NeuroLinker.Configuration { /// <summary> /// Configuration for <see cref="HttpClient"/> /// </summary> [AutomaticContainerRegistration(typeof(IHttpClientConfiguration), ServiceReuse.Singleton)] public sealed class HttpClientConfiguration : IHttpClientConfiguration { #region Properties /// <summary> /// The UserAgent string that should be used by the HttpClient when contacting the MAL API /// </summary> public string UserAgent => ConfigurationKeys.UserAgent.GetConfigurationValue<string>(); #endregion } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using TRPO_labe_2.Interfaces; namespace TRPO_labe_2.Models { abstract class PossessionBase : IPossession { public string Name => GetType().Name; public abstract string Info(); public int CountOfClerks { get; } = new Random().Next(5,30); } }
 namespace ServiceCenter.Helpers { interface ICallbackAddToList { void AddToList(object o); } }
using System.ComponentModel.DataAnnotations; using Alabo.Web.Mvc.Attributes; namespace Alabo.Industry.Cms.Articles.Domain.Enums { [ClassProperty(Name = "文章显示动作类型")] public enum ArticleState { [LabelCssClass(BadgeColorCalss.Success)] [Display(Name = "置顶")] Top = 0, [LabelCssClass(BadgeColorCalss.Success)] [Display(Name = "推荐")] Recommend = 1, [LabelCssClass(BadgeColorCalss.Success)] [Display(Name = "热门")] Hot = 2, [LabelCssClass(BadgeColorCalss.Success)] [Display(Name = "跳转")] Jump = 3, [LabelCssClass(BadgeColorCalss.Success)] [Display(Name = "幻灯片")] Slide = 4 } }
using System; using FluentAssertions; using NUnit.Framework; namespace Hatchet.Tests.HatchetConvertTests.DeserializeTests { [TestFixture] public class SingleValueTests { [Test] public void Deserialize_ANonQuotedDateTime_ShouldReturnADateTime() { // Arrange var date = DateTime.Parse("2013-01-02"); var input = date.ToString("yyyy-MM-dd"); // Act var result = HatchetConvert.Deserialize<DateTime>(input); // Assert result.Should().Be(date); } [Test] public void Deserialize_AQuotedDateTime_ShouldReturnADateTime() { // Arrange var date = DateTime.Parse("2014-10-01 07:20:00"); var input = "'" + date.ToString("O") + "'"; // Act var result = HatchetConvert.Deserialize<DateTime>(input); // Assert result.Should().Be(date); } [Test] public void Deserialize_AByte_ShouldReturnAByte() { // Arrange var input = "14"; // Act var result = HatchetConvert.Deserialize<byte>(input); // Assert result.Should().Be(14); } [Test] public void Deserialize_AChar_ShouldReturnAChar() { // Arrange var input = "a"; // Act var result = HatchetConvert.Deserialize<char>(input); // Assert result.Should().Be('a'); } [Test] public void Deserialize_AGuid_ShouldReturnAGuid() { // Arrange var input = new Guid("{879FC5CF-74EE-4525-A457-C1CD2F5C451E}"); // Act var result = HatchetConvert.Deserialize<Guid>(input.ToString()); // Assert result.Should().Be(input); } [Test] public void Deserialize_AnSbyte_ShouldReturnAnSbyte() { // Arrange var input = "-8"; // Act var result = HatchetConvert.Deserialize<sbyte>(input); // Assert result.Should().Be(-8); } [Test] public void Deserialize_AShort_ShouldReturnAShort() { // Arrange var input = "-372"; // Act var result = HatchetConvert.Deserialize<short>(input); // Assert result.Should().Be(-372); } [Test] public void Deserialize_AUshort_ShouldReturnAUshort() { // Arrange var input = "8192"; // Act var result = HatchetConvert.Deserialize<ushort>(input); // Assert result.Should().Be(8192); } [Test] public void Deserialize_ADecimal_ShouldReturnADecimal() { // Arrange var input = "4377.89"; // Act var result = HatchetConvert.Deserialize<decimal>(input); // Assert result.Should().Be(4377.89m); } [Test] public void Deserialize_AUint_ShouldReturnAUint() { // Arrange var input = "487182"; // Act var result = HatchetConvert.Deserialize<uint>(input); // Assert result.Should().Be(487182); } [Test] public void Deserialize_AUlong_ShouldReturnAUlong() { // Arrange var input = "1818118181"; // Act var result = HatchetConvert.Deserialize<ulong>(input); // Assert result.Should().Be(1818118181L); } [Test] public void Deserialize_ALong_ShouldReturnALong() { // Arrange var input = "123105051"; // Act var result = HatchetConvert.Deserialize<long>(input); // Assert result.Should().Be(123105051L); } [Test] public void Deserialize_AString_ShouldReturnAString() { // Arrange var input = "'Hello World'"; // Act var result = HatchetConvert.Deserialize<string>(input); // Assert result.Should().Be("Hello World"); } [Test] public void Deserialize_AnInteger_ShouldReturnAnInteger() { // Arrange var input = "1234"; // Act var result = HatchetConvert.Deserialize<int>(input); // Assert result.Should().Be(1234); } [Test] public void Deserialize_AFloat_ShouldReturnAFloat() { // Arrange var input = "12.34"; // Act var result = HatchetConvert.Deserialize<float>(input); // Assert result.Should().BeApproximately(12.34f, 0.0001f); } [Test] public void Deserialize_ABoolean_ShouldReturnABoolean() { // Arrange var input = "true"; // Act var result = HatchetConvert.Deserialize<bool>(input); // Assert result.Should().Be(true); } [TestCase("true", true)] [TestCase("false", false)] [TestCase("null", null)] public void Deserialize_ANullableBoolean_ShouldReturnABoolean(string input, bool? expected) { // Act var result = HatchetConvert.Deserialize<bool?>(input); // Assert result.Should().Be(expected); } [TestCase("1", 1)] [TestCase("null", null)] public void Deserialize_ANullableInt_ShouldReturnAnInt(string input, int? expected) { // Act var result = HatchetConvert.Deserialize<int?>(input); // Assert result.Should().Be(expected); } } }
using System.Collections.Generic; namespace Amf.Ultima.Api.Models { public class PanierUltima { public int Id { get; set; } public string Nom { get; set; } public List<string> Erreurs { get; set; } } }
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="ConfigureServiceApiBlock.cs" company="Sitecore Corporation"> // Copyright (c) Sitecore Corporation 1999-2017 // </copyright> // -------------------------------------------------------------------------------------------------------------------- namespace Sitecore.Commerce.Plugin.Sample { using System.Threading.Tasks; using global::Commerce.Plugin.Asset.Entities; using Microsoft.AspNetCore.OData.Builder; using Sitecore.Commerce.Core; using Sitecore.Commerce.Core.Commands; using Sitecore.Framework.Conditions; using Sitecore.Framework.Pipelines; /// <summary> /// Defines a block which configures the OData model /// </summary> /// <seealso> /// <cref> /// Sitecore.Framework.Pipelines.PipelineBlock{Microsoft.AspNetCore.OData.Builder.ODataConventionModelBuilder, /// Microsoft.AspNetCore.OData.Builder.ODataConventionModelBuilder, /// Sitecore.Commerce.Core.CommercePipelineExecutionContext} /// </cref> /// </seealso> [PipelineDisplayName("SamplePluginConfigureServiceApiBlock")] public class ConfigureServiceApiBlock : PipelineBlock<ODataConventionModelBuilder, ODataConventionModelBuilder, CommercePipelineExecutionContext> { /// <summary> /// The execute. /// </summary> /// <param name="modelBuilder"> /// The argument. /// </param> /// <param name="context"> /// The context. /// </param> /// <returns> /// The <see cref="ODataConventionModelBuilder"/>. /// </returns> public override Task<ODataConventionModelBuilder> Run(ODataConventionModelBuilder modelBuilder, CommercePipelineExecutionContext context) { Condition.Requires(modelBuilder).IsNotNull($"{this.Name}: The argument cannot be null."); // Add the entities modelBuilder.AddEntityType(typeof(Asset)); // Add the entity sets //modelBuilder.EntitySet<Asset>("Assets"); // Add complex types // Add unbound functions // Add unbound actions var createAssetConfiguration = modelBuilder.Action("CreateAsset"); createAssetConfiguration.Parameter<string>("id"); createAssetConfiguration.Parameter<string>("name"); createAssetConfiguration.Parameter<string>("displayname"); createAssetConfiguration.ReturnsFromEntitySet<CommerceCommand>("Commands"); var associateAssetToParent = modelBuilder.Action("AssociateAssetToParent"); associateAssetToParent.Parameter<string>("catalogid"); associateAssetToParent.Parameter<string>("parentid"); associateAssetToParent.Parameter<string>("referenceid"); associateAssetToParent.ReturnsFromEntitySet<CommerceCommand>("Commands"); return Task.FromResult(modelBuilder); } } }
using System; using System.Collections; using CarouselView.FormsPlugin.Abstractions; using Plugin.Swank.Panorama.ImageSources; using Swank.FormsPlugin; using Xamarin.Forms; namespace Plugin.Swank { public class Viewer : CarouselViewControl { private Gallery Gallery => Parent?.Parent as Gallery; public new IEnumerable ItemsSource { get => (IEnumerable)GetValue(ItemsSourceProperty); set => SetValue(ItemsSourceProperty, value); } public Viewer() { HorizontalOptions = LayoutOptions.FillAndExpand; VerticalOptions = LayoutOptions.FillAndExpand; Orientation = CarouselViewOrientation.Horizontal; BackgroundColor = Color.Black; ShowIndicators = true; ItemTemplate = new DataTemplate(typeof(ViewerImageTemplate)); } public void ToggleIsSwipeEnabled(string filePath) { IsSwipeEnabled = !IsSwipeEnabled; Gallery?.TogglePanoramaVisibility(); if (!string.IsNullOrEmpty(filePath)) { var image = filePath.Contains("http") ? new PanoramaUriImageSource(new Uri(filePath)) : (PanoramaImageSource)new PanoramaFileSystemImageSource(filePath); Gallery?.SetPanoramaImage(image); } } } }
using Infrastructure.Data.Entities; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Metadata.Builders; using System; using System.Collections.Generic; using System.Text; namespace Infrastructure.Data.Config { public class EquipmentConfiguration { public void Configure(EntityTypeBuilder<Equipment> builder) { builder.HasKey(e => e.Id); builder.Property(e => e.Id) .ValueGeneratedOnAdd() .IsRequired(); builder.Property(e => e.Quantity) .IsRequired(); builder.Property(e => e.UnitPrice) .HasPrecision(18, 2) .IsRequired(); builder.Property(e => e.UtilizationRatio) .HasPrecision(4, 1) .IsRequired(); builder.Property(e => e.CreationDate) .ValueGeneratedOnAdd() .IsRequired(); } } }
using System; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; namespace HeBoGuoShi.DBModels { [Table("OwnerProductImages")] public class OwnerProductImage { [Key] [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)] public Guid Id { get; set; } public Guid ProductId { get; set; } public string Name { get; set; } public string Path { get; set; } [ForeignKey("ProductId")] public virtual OwnerProduct OwnProduct { get; set; } } }
using Abp.Configuration.Startup; using Abp.Localization.Dictionaries; using Abp.Localization.Dictionaries.Xml; using Abp.Reflection.Extensions; namespace DgKMS.Cube.Localization { public static class CubeLocalizationConfigurer { public static void Configure(ILocalizationConfiguration localizationConfiguration) { localizationConfiguration.Sources.Add( new DictionaryBasedLocalizationSource(CubeConsts.LocalizationSourceName, new XmlEmbeddedFileLocalizationDictionaryProvider( typeof(CubeLocalizationConfigurer).GetAssembly(), "DgKMS.Cube.Localization.SourceFiles" ) ) ); } } }
// <copyright file="LookupTable.cs" company="WaterTrans"> // © 2020 WaterTrans // </copyright> using System.Collections.Generic; using WaterTrans.GlyphLoader.Internal.OpenType.GPOS; using WaterTrans.GlyphLoader.Internal.OpenType.GSUB; namespace WaterTrans.GlyphLoader.Internal.OpenType { /// <summary> /// The OpenType lookup table. /// </summary> internal sealed class LookupTable { /// <summary> /// Initializes a new instance of the <see cref="LookupTable"/> class. /// </summary> /// <param name="reader">The <see cref="TypefaceReader"/>.</param> internal LookupTable(TypefaceReader reader) { Offset = reader.ReadUInt16(); } /// <summary>Gets Offset.</summary> /// <remarks>Offset to Script table.- from beginning of ScriptList.</remarks> public ushort Offset { get; } /// <summary>Gets or sets LookupType.</summary> /// <remarks>Different enumerations for GSUB and GPOS.</remarks> public ushort LookupType { get; internal set; } /// <summary>Gets or sets LookupFlag.</summary> /// <remarks>Lookup qualifiers.</remarks> public ushort LookupFlag { get; internal set; } /// <summary>Gets or sets SubTableCount.</summary> /// <remarks>Number of SubTables for this lookup.</remarks> public ushort SubTableCount { get; internal set; } /// <summary>Gets array of offsets to SubTables.- from beginning of Lookup table.</summary> public List<ushort> SubTableList { get; } = new List<ushort>(); /// <summary>Gets list of SingleSubstitution.</summary> public List<SingleSubstitution> SingleSubstitutionList { get; } = new List<SingleSubstitution>(); /// <summary>Gets list of MultipleSubstitution.</summary> public List<MultipleSubstitution> MultipleSubstitutionList { get; } = new List<MultipleSubstitution>(); /// <summary>Gets list of AlternateSubstitution.</summary> public List<AlternateSubstitution> AlternateSubstitutionList { get; } = new List<AlternateSubstitution>(); /// <summary>Gets list of LigatureSubstitution.</summary> public List<LigatureSubstitution> LigatureSubstitutionList { get; } = new List<LigatureSubstitution>(); /// <summary>Gets list of SingleAdjustment.</summary> public List<SingleAdjustment> SingleAdjustmentList { get; } = new List<SingleAdjustment>(); /// <summary>Gets list of PairAdjustment.</summary> public List<PairAdjustment> PairAdjustmentList { get; } = new List<PairAdjustment>(); } }
using System; using System.Reflection; namespace LuckSkill { class Util { // http://stackoverflow.com/questions/3303126/how-to-get-the-value-of-private-field-in-c public static object GetInstanceField(Type type, object instance, string fieldName) { BindingFlags bindFlags = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static; FieldInfo field = type.GetField(fieldName, bindFlags); return field.GetValue(instance); } public static void CallInstanceMethod(Type type, object instance, string name, object[] args) { // TODO: Support method overloading BindingFlags bindFlags = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static; MethodInfo func = type.GetMethod(name, bindFlags); func.Invoke(instance, args); } public static void DecompileComment( string str ) { } } }
using UnityEngine; using System; using System.Collections; using TreeSharpPlus; public class B3BehaviorInformant : MonoBehaviour { public GameObject friend; public GameObject informant; private BehaviorAgent behaviorAgent; // Use this for initialization void Start () { behaviorAgent = new BehaviorAgent (this.BuildTreeRoot ()); BehaviorManager.Instance.Register (behaviorAgent); behaviorAgent.StartBehavior (); } // Update is called once per frame void Update () { } protected RunStatus beginStory() { print ("phase changed"); BehaviorManager.Instance.changeBeginning (); return RunStatus.Success; } protected Node ST_ApproachAndWait(Transform target) { Val<Vector3> position = Val.V (() => new Vector3(target.position.x-1, 0, target.position.z)); return new Sequence( informant.GetComponent<BehaviorMecanim>().Node_GoTo(position), new LeafWait(1000)); } protected Node BuildTreeRoot() { Val<bool> status = Val.V (() => BehaviorManager.Instance.beginning); Func<bool> act = () => (status.Value == false); Node phaseNode = new DecoratorLoop(new LeafAssert (act)); Node wonderful = new Sequence (informant.GetComponent<BehaviorMecanim> ().Node_HandAnimation ("WONDERFUL", true), new LeafWait (2000),informant.GetComponent<BehaviorMecanim> ().Node_HandAnimation ("WONDERFUL", false)); Func<RunStatus> beginStory = () => (this.beginStory()); Node begin = new LeafInvoke (beginStory); Node firstPhase = new Sequence (this.ST_ApproachAndWait (friend.transform),wonderful, begin); Node root = new DecoratorLoop (new DecoratorForceStatus(RunStatus.Success, new SequenceParallel (phaseNode, firstPhase))); return root; } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using VRTK; public class Haptics : MonoBehaviour { public static Haptics Instance { get; private set; } void Awake() { Instance = this; } /// <summary> /// <paramref name="whichController"/> is what controller you want the haptics to happen. /// <paramref name="strength"/> is the strength of the vibration, its clamped between 0 and 1. /// <paramref name="duration"/> is how many seconds the vibration will play. /// <paramref name="pulseInterval"/> puts pauses during the the play time. /// </summary> public void StartHaptics (GameObject whichController, float strength, float duration, float pulseInterval) { GameObject controller = whichController.GetComponent<VRTK_InteractableObject>().GetGrabbingObject(); VRTK_ControllerHaptics.TriggerHapticPulse(VRTK_ControllerReference.GetControllerReference(controller), strength, duration, pulseInterval); } }
using GDS.Entity; using SqlSugar; using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Text; using System.Threading.Tasks; namespace GDS.Dal { public interface IDaoBase<T> where T : class { object Insert<TReturn>(TReturn entity, bool isIdentity = true) where TReturn : class, new(); List<TReturn> GetListByIds<TReturn>(string ids) where TReturn : class, new(); TReturn GetDataById<TReturn>(int Id) where TReturn : class, new(); TReturn GetViewDataById<TReturn>(int Id) where TReturn : class, new(); List<TReturn> GetDataAll<TReturn>() where TReturn : class, new(); List<TReturn> GetViewDataAll<TReturn>() where TReturn : class, new(); List<TReturn> GetDataByPage<TReturn>(PageRequest pr) where TReturn : class, new(); bool DeleteDataById<TReturn>(int Id) where TReturn : class, new(); bool DeleteDataByIds<TReturn>(int[] Ids) where TReturn : class, new(); bool FalseDeleteDataByIds<TReturn>(int[] Ids) where TReturn : class, new(); bool Update<TReturn>(TReturn rowObj) where TReturn : class, new(); bool Update<TReturn>(object rowObj, Expression<Func<TReturn, bool>> expression) where TReturn : class, new(); bool Update<TReturn>(string setValues, Expression<Func<TReturn, bool>> expression, object whereObj = null) where TReturn : class, new(); } }
using System.Collections; using System.Collections.Generic; using UnityEngine; // We ask some Data to get the script working [RequireComponent (typeof(Rigidbody))] [RequireComponent (typeof(CapsuleCollider))] [RequireComponent (typeof(Animator))] public class HeroController : MonoBehaviour { // Data get from the asset on the scene Rigidbody m_Rigidbody; // We get the rigid body use to move the Hero Animator m_Animator; // The animator to tell witch animation must run CapsuleCollider m_Capsule; // The capsule collider used to get the hitbox (if the hero hit the ground) // Private data // Here were goin to get Ethan to walk on left or right ///////////////////////// // Movement private bool isMovingLeft = false; private bool isMovingRight = false; // A serializeField is an writable flied from the inspector view [SerializeField] int velocityX = 10; ///////////////////////// // Use this for initialization void Start () { // Get value from autolink m_Animator = GetComponent<Animator>(); m_Rigidbody = GetComponent<Rigidbody>(); m_Capsule = GetComponent<CapsuleCollider>(); // Init RigidBody this.m_Rigidbody.velocity = new Vector3 (0, 0, 0); // Idle // Can only move X, no rotation XYZ no movement YZ m_Rigidbody.constraints = RigidbodyConstraints.FreezeRotationX | RigidbodyConstraints.FreezeRotationY | RigidbodyConstraints.FreezeRotationZ | RigidbodyConstraints.FreezePositionY | RigidbodyConstraints.FreezePositionZ; // Animator this.m_Animator.speed = 1; this.m_Animator.Play ("Grounded"); } // Update is called once per frame void Update () { this.isMovingLeft = Input.GetKey (KeyCode.LeftArrow); this.isMovingRight = Input.GetKey (KeyCode.RightArrow); ProcessMovement (); } void ProcessMovement () { if (this.isMovingLeft == this.isMovingRight) { // Both are true or both are false this.m_Rigidbody.velocity = new Vector3 (0, m_Rigidbody.velocity.y, m_Rigidbody.velocity.z); // We stop return; } if (this.isMovingLeft) { this.m_Rigidbody.velocity = new Vector3 (-velocityX, m_Rigidbody.velocity.y, m_Rigidbody.velocity.z); } else { this.m_Rigidbody.velocity = new Vector3 (velocityX, m_Rigidbody.velocity.y, m_Rigidbody.velocity.z); } } }
using System.Text.Json; namespace WitsmlExplorer.Api.Middleware { public class ErrorDetails { public int StatusCode { get; set; } public string Message { get; set; } public override string ToString() { return JsonSerializer.Serialize(this, new JsonSerializerOptions {PropertyNamingPolicy = JsonNamingPolicy.CamelCase}); } } }
namespace Application.Controllers { using System.Collections.Generic; using Data; using Data.Interfaces; using Data.Services; using Models.BindingModels; using Models.ViewModels; using SimpleHttpServer.Models; using SimpleMVC.Attributes.Methods; using SimpleMVC.Controllers; using SimpleMVC.Interfaces.Generic; using Utilities; public class AdminController : Controller { private readonly IDataProvidable data; private readonly AdminService adminService; public AdminController(IDataProvidable data) { this.data = data; this.adminService = new AdminService(this.data); } public AdminController() : this(new SoftUniData(new SoftUniStoreContext())) { } [HttpGet] public IActionResult<AddGameViewModel> Add(HttpSession session, HttpResponse response) { var isAuthenticated = session.IsUserAuthenticated(this.data); var user = this.adminService.FindUserBySession(session); bool isUserInAdmin = false; if (user != null) { isUserInAdmin = this.adminService.IsUserInAdminRole(user); } if (!isAuthenticated || !isUserInAdmin) { this.Redirect(response, "/"); return null; } this.SetupNavAndHome(true); this.adminService.SetupNavbar(user); return this.View(this.adminService.GetAddGame()); } [HttpPost] public void Add(HttpSession session, HttpResponse response, AddGameBindingModel agbm) { var isAuthenticated = session.IsUserAuthenticated(this.data); var user = this.adminService.FindUserBySession(session); bool isUserInAdmin = false; if (user != null) { isUserInAdmin = this.adminService.IsUserInAdminRole(user); } if (!isAuthenticated || !isUserInAdmin) { this.Redirect(response, "/"); } this.SetupNavAndHome(true); this.adminService.AddGame(agbm); this.Redirect(response, "/admin/games"); } [HttpGet] public IActionResult<IEnumerable<AdminGamesViewModel>> Games( HttpSession session, HttpResponse response) { var isAuthenticated = session.IsUserAuthenticated(this.data); var user = this.adminService.FindUserBySession(session); bool isUserInAdmin = false; if (user != null) { isUserInAdmin = this.adminService.IsUserInAdminRole(user); } if (!isAuthenticated || !isUserInAdmin) { this.Redirect(response, "/"); return null; } this.SetupNavAndHome(true); this.adminService.SetupNavbar(user); return this.View(this.adminService.GetGames()); } [HttpGet] public IActionResult<EditGameViewModel> Edit(HttpSession session, HttpResponse response, int id) { var isAuthenticated = session.IsUserAuthenticated(this.data); var user = this.adminService.FindUserBySession(session); bool isUserInAdmin = false; if (user != null) { isUserInAdmin = this.adminService.IsUserInAdminRole(user); } if (!isAuthenticated || !isUserInAdmin) { this.Redirect(response, "/"); return null; } this.SetupNavAndHome(true); this.adminService.SetupNavbar(user); return this.View(this.adminService.GetEditGame(id)); } [HttpPost] public void Edit(HttpResponse response, HttpSession session, EditGameBindingModel egbm) { var isAuthenticated = session.IsUserAuthenticated(this.data); var user = this.adminService.FindUserBySession(session); bool isUserInAdmin = false; if (user != null) { isUserInAdmin = this.adminService.IsUserInAdminRole(user); } if (!isAuthenticated || !isUserInAdmin) { this.Redirect(response, "/"); } this.SetupNavAndHome(true); this.adminService.EditGame(egbm); this.Redirect(response, "/admin/games"); } [HttpGet] public IActionResult<DeleteGameViewModel> Delete(HttpSession session, HttpResponse response, int id) { var isAuthenticated = session.IsUserAuthenticated(this.data); var user = this.adminService.FindUserBySession(session); bool isUserInAdmin = false; if (user != null) { isUserInAdmin = this.adminService.IsUserInAdminRole(user); } if (!isAuthenticated || !isUserInAdmin) { this.Redirect(response, "/"); return null; } this.SetupNavAndHome(true); this.adminService.SetupNavbar(user); return this.View(this.adminService.GetDeleteGame(id)); } [HttpPost] public void Delete(HttpResponse response, HttpSession session, int id) { var isAuthenticated = session.IsUserAuthenticated(this.data); var user = this.adminService.FindUserBySession(session); bool isUserInAdmin = false; if (user != null) { isUserInAdmin = this.adminService.IsUserInAdminRole(user); } if (!isAuthenticated || !isUserInAdmin) { this.Redirect(response, "/"); } this.SetupNavAndHome(true); this.adminService.SetupNavbar(user); this.adminService.DeleteGame(id); this.Redirect(response, "/admin/games"); } } }
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; using System.Data.SqlClient; namespace GestorDeFlotasDesktop.AbmChofer { public partial class addEditChofer : Form { public long dniChofer { get; set; } public string modoAbm { get; set; } public string tituloPantalla { get; set; } private static addEditChofer unicaInst = null; public static addEditChofer Instance() { if (unicaInst == null) { unicaInst = new addEditChofer(); } return unicaInst; } private addEditChofer() { InitializeComponent(); } private void addEditChofer_Load(object sender, EventArgs e) { inicializarFormulario(); } private void inicializarFormulario() { txtDniChofer.Text = ""; txtNombre.Text = ""; txtApellido.Text = ""; txtDireccion.Text = ""; txtTelefono.Text = ""; txtEmail.Text = ""; dtpNacimiento.Value = DateTime.Today; lblTitulo.Text = tituloPantalla; this.Text = tituloPantalla; if (modoAbm == "Editar") { getDatosRegistro(dniChofer); txtDniChofer.ReadOnly = true; } } private void getDatosRegistro(long dniChofer) { DataTable dtValores = new DataTable(); dtValores = GestorDeFlotasDesktop.BD.GD1C2012.executeSqlQuery("Select dniChofer, nombre, apellido, direccion, telefono, email, fechaNacimiento, anulado from femig.choferes where dniChofer = " + dniChofer); txtDniChofer.Text = dtValores.Rows[0]["dniChofer"].ToString(); txtNombre.Text = dtValores.Rows[0]["nombre"].ToString(); txtApellido.Text = dtValores.Rows[0]["apellido"].ToString(); txtDireccion.Text = dtValores.Rows[0]["direccion"].ToString(); txtTelefono.Text = dtValores.Rows[0]["telefono"].ToString(); txtEmail.Text = dtValores.Rows[0]["email"].ToString(); dtpNacimiento.Value = (DateTime)dtValores.Rows[0]["fechaNacimiento"]; if (dtValores.Rows[0]["anulado"].ToString() == "True") chkDeshabilitado.Checked = true; else chkDeshabilitado.Checked = false; } private bool validaCamposRequeridos() { if (txtDniChofer.Text.Trim() == string.Empty | txtNombre.Text.Trim() == string.Empty | txtApellido.Text.Trim() == string.Empty | txtDireccion.Text.Trim() == string.Empty | txtTelefono.Text.Trim() == string.Empty | txtEmail.Text.Trim() == string.Empty | dtpNacimiento.Value>=DateTime.Today) return false; else return true; } private void btnAceptar_Click(object sender, EventArgs e) { try { if (!validaCamposRequeridos()) { GestorDeFlotasDesktop.ListaErrores.ListaErrores frmErrores = new GestorDeFlotasDesktop.ListaErrores.ListaErrores(); frmErrores.setTitulo("Ocurrieron algunos errores al intentar crear el nuevo Chofer."); if (string.IsNullOrEmpty(txtDniChofer.Text)) frmErrores.agregarError("Debe completar el DNI del chofer."); if (string.IsNullOrEmpty(txtNombre.Text)) frmErrores.agregarError("Debe completar el Nombre."); if (string.IsNullOrEmpty(txtApellido.Text)) frmErrores.agregarError("Debe completar el apellido."); if (string.IsNullOrEmpty(txtDireccion.Text)) frmErrores.agregarError("Debe completar la dirección."); if (string.IsNullOrEmpty(txtTelefono.Text)) frmErrores.agregarError("Debe completar el teléfono."); if (string.IsNullOrEmpty(txtEmail.Text)) frmErrores.agregarError("Debe completar el Email."); if (dtpNacimiento.Value>=DateTime.Today) frmErrores.agregarError("La fecha de nacimiento debe ser menor a hoy."); frmErrores.ShowDialog(); frmErrores.Dispose(); return; } string retCatchError = string.Empty; SqlParameter pDniChofer = new SqlParameter("@pDniChofer", SqlDbType.BigInt); pDniChofer.Value = txtDniChofer.Text; SqlParameter pNombre = new SqlParameter("@pNombre", SqlDbType.VarChar, 255); pNombre.Value = txtNombre.Text; SqlParameter pApellido = new SqlParameter("@pApellido", SqlDbType.VarChar, 255); pApellido.Value = txtApellido.Text; SqlParameter pDireccion = new SqlParameter("@pDireccion", SqlDbType.VarChar, 255); pDireccion.Value = txtDireccion.Text; SqlParameter pTelefono = new SqlParameter("@pTelefono", SqlDbType.BigInt); pTelefono.Value = txtTelefono.Text; SqlParameter pEmail = new SqlParameter("@pEmail", SqlDbType.VarChar,50); pEmail.Value = txtEmail.Text; SqlParameter pFechaNacimiento = new SqlParameter("@pFechaNacimiento", SqlDbType.DateTime); pFechaNacimiento.Value = dtpNacimiento.Value; SqlParameter pAnulado = new SqlParameter("@pAnulado", SqlDbType.Bit); if (chkDeshabilitado.Checked) pAnulado.Value = 1; else pAnulado.Value = 0; SqlParameter pRetCatchError = new SqlParameter("@pRetCatchError", SqlDbType.VarChar, 1000); pRetCatchError.Direction = ParameterDirection.Output; SqlParameter[] parametros = { pDniChofer,pNombre,pApellido,pDireccion,pTelefono,pEmail,pFechaNacimiento,pAnulado,pRetCatchError }; if (modoAbm == "Nuevo") { if (GestorDeFlotasDesktop.BD.GD1C2012.ejecutarSP("FEMIG.crearChofer", parametros)) { if (string.IsNullOrEmpty(pRetCatchError.Value.ToString())) { MessageBox.Show("El chofer con dni: " + txtDniChofer.Text + " fue dato de alta exitosamente.", "Alta exitosa", MessageBoxButtons.OK, MessageBoxIcon.Information); this.DialogResult = DialogResult.OK; } else MessageBox.Show(pRetCatchError.Value.ToString(), "Aviso", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); } } else { if (GestorDeFlotasDesktop.BD.GD1C2012.ejecutarSP("FEMIG.editarChofer", parametros)) { if (string.IsNullOrEmpty(pRetCatchError.Value.ToString())) { MessageBox.Show("El chofer con dni: " + txtDniChofer.Text + " fue editado exitosamente.", "Edición exitosa", MessageBoxButtons.OK, MessageBoxIcon.Information); this.DialogResult = DialogResult.OK; } else MessageBox.Show(pRetCatchError.Value.ToString(), "Aviso", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); } } } catch (Exception ex) { MessageBox.Show(ex.ToString(), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } } private void btnCancelar_Click(object sender, EventArgs e) { this.DialogResult = DialogResult.Cancel; } private void btnLimpiar_Click(object sender, EventArgs e) { if (modoAbm == "Nuevo") txtDniChofer.Text = ""; txtNombre.Text = ""; txtApellido.Text = ""; txtDireccion.Text = ""; txtTelefono.Text = ""; txtEmail.Text = ""; chkDeshabilitado.Checked = false; } private void txtDniChofer_KeyPress(object sender, KeyPressEventArgs e) { e.Handled = !char.IsDigit(e.KeyChar) && !char.IsControl(e.KeyChar); } private void txtTelefono_KeyPress(object sender, KeyPressEventArgs e) { e.Handled = !char.IsDigit(e.KeyChar) && !char.IsControl(e.KeyChar); } } }
using Microsoft.VisualStudio.TestTools.UnitTesting; using ModelTransformationComponent; using ModelTransformationComponent.SystemRules; namespace TransformationComponentUnitTest { public partial class TransformUnitTest { public partial class TransformToRules { public partial class OnlyBase { [TestClass] public class Params { [TestMethod] [TestCategory("TransformToRules")] public void ToRulesTypeEmptyParamsEmpty() { //arrange var name = "a"; var rules = "Some strange comment-like text\n" + "with some new lines and //////star\n" + "but eventually /start\n" + "/type " + name + "\n" + "/params_start\n" + "/params_end\n" + "/end\n" + "Some more comments"; var component = new TransformationComponent(); //act var actual = component.TransformToRules(rules); //assert Assert.AreEqual(actual.Languages.Count, 0); var resultRules = actual.GetBaseRules; Assert.AreEqual(1, resultRules.Count); Assert.IsTrue(resultRules.ContainsKey(name)); var resultTypeRule = resultRules[name] as TypeRule; TestUtil.AssertBNF(resultTypeRule, name, new BasicBNFRule[0]); } [TestMethod] [TestCategory("TransformToRules")] public void ToRulesTypeParamsEmpty() { //arrange var name = "a"; var bnf = "a/child"; var rules = "Some strange comment-like text\n" + "with some new lines and //////star\n" + "but eventually /start\n" + "/type " + name + " ::= " + bnf + "\n" + "/params_start\n" + "/params_end\n" + "/end\n" + "Some more comments"; var component = new TransformationComponent(); //act var actual = component.TransformToRules(rules); //assert Assert.AreEqual(actual.Languages.Count, 0); var resultRules = actual.GetBaseRules; Assert.AreEqual(1, resultRules.Count); Assert.IsTrue(resultRules.ContainsKey(name)); var resultTypeRule = resultRules[name] as TypeRule; var basicBNFRule = new BasicBNFRule(); basicBNFRule.Add(new BNFString("a" )); basicBNFRule.Add(new BNFSystemRef(new Child() )); TestUtil.AssertBNF(resultTypeRule, name, new BasicBNFRule[] { basicBNFRule }); } [TestMethod] [TestCategory("TransformToRules")] public void ToRulesTypeOneParamNoBody() { //arrange var name = "a"; var param_name = "b"; var bnf = "<" + param_name + ">/child"; var rules = "Some strange comment-like text\n" + "with some new lines and //////star\n" + "but eventually /start\n" + "/type " + name + " ::= " + bnf + "\n" + "/params_start\n" + param_name + "\n" + "/params_end\n" + "/end\n" + "Some more comments"; var component = new TransformationComponent(); //act var actual = component.TransformToRules(rules); //assert Assert.AreEqual(actual.Languages.Count, 0); var resultRules = actual.GetBaseRules; Assert.AreEqual(2, resultRules.Count); Assert.IsTrue(resultRules.ContainsKey(name)); var resultTypeRule = resultRules[name] as TypeRule; var basicBNFRule = new BasicBNFRule(); basicBNFRule.Add(new BNFReference("a.b" )); basicBNFRule.Add(new BNFSystemRef(new Child() )); TestUtil.AssertBNF(resultTypeRule, name, new BasicBNFRule[] { basicBNFRule }); var full_par_n = name + "." + param_name; var resultBNFRule = resultRules[full_par_n] as BNFRule; TestUtil.AssertBNF(resultBNFRule, full_par_n, new BasicBNFRule[0]); } [TestMethod] [TestCategory("TransformToRules")] public void ToRulesTypeOneParam() { //arrange var n1 = "c"; var name = "a"; var param_name = "b"; var param_body = "<" + n1 + ">"; var bnf = "<" + param_name + ">/child"; var rules = "Some strange comment-like text\n" + "with some new lines and //////star\n" + "but eventually /start\n" + n1 + "\n" + "/type " + name + " ::= " + bnf + "\n" + "/params_start\n" + param_name + " ::= " + param_body + "\n" + "/params_end\n" + "/end\n" + "Some more comments"; var component = new TransformationComponent(); //act var actual = component.TransformToRules(rules); //assert Assert.AreEqual(actual.Languages.Count, 0); var resultRules = actual.GetBaseRules; Assert.AreEqual(3, resultRules.Count); CollectionAssert.Contains(resultRules.Keys, n1); TestUtil.AssertBNF((BNFRule)resultRules[n1], n1, new BasicBNFRule[0]); Assert.IsTrue(resultRules.ContainsKey(name)); var resultTypeRule = resultRules[name] as TypeRule; var basicBNFRule = new BasicBNFRule(); basicBNFRule.Add(new BNFReference("a.b" )); basicBNFRule.Add(new BNFSystemRef(new Child() )); TestUtil.AssertBNF(resultTypeRule, name, new BasicBNFRule[] { basicBNFRule }); var full_par_n = name + "." + param_name; var resultBNFRule = resultRules[full_par_n] as BNFRule; basicBNFRule = new BasicBNFRule(); basicBNFRule.Add(new BNFReference(n1 )); TestUtil.AssertBNF(resultBNFRule, full_par_n, new BasicBNFRule[] { basicBNFRule }); } [TestMethod] [TestCategory("TransformToRules")] public void ToRulesTypeTwoParams() { //arrange var n1 = "c"; var n2 = "d"; var name = "a"; var param_name = "b"; var param_name_2 = "b2"; var param_body = "<" + n1 + ">"; var param_body_2 = "<" + n2 + ">"; var bnf = "<" + param_name + ">/child"; var rules = "Some strange comment-like text\n" + "with some new lines and //////star\n" + "but eventually /start\n" + n1 + "\n" + n2 + "\n" + "/type " + name + " ::= " + bnf + "\n" + "/params_start\n" + param_name + " ::= " + param_body + "\n" + param_name_2 + " ::= " + param_body_2 + "\n" + "/params_end\n" + "/end\n" + "Some more comments"; var component = new TransformationComponent(); //act var actual = component.TransformToRules(rules); //assert Assert.AreEqual(actual.Languages.Count, 0); var resultRules = actual.GetBaseRules; Assert.AreEqual(5, resultRules.Count); CollectionAssert.Contains(resultRules.Keys, n1); TestUtil.AssertBNF((BNFRule)resultRules[n1], n1, new BasicBNFRule[0]); CollectionAssert.Contains(resultRules.Keys, n2); TestUtil.AssertBNF((BNFRule)resultRules[n2], n2, new BasicBNFRule[0]); Assert.IsTrue(resultRules.ContainsKey(name)); var resultTypeRule = resultRules[name] as TypeRule; var basicBNFRule = new BasicBNFRule(); basicBNFRule.Add(new BNFReference("a.b" )); basicBNFRule.Add(new BNFSystemRef(new Child() )); TestUtil.AssertBNF(resultTypeRule, name, new BasicBNFRule[] { basicBNFRule }); var full_par_n = name + "." + param_name; var resultBNFRule = resultRules[full_par_n] as BNFRule; basicBNFRule = new BasicBNFRule(); basicBNFRule.Add(new BNFReference(n1 )); TestUtil.AssertBNF(resultBNFRule, full_par_n, new BasicBNFRule[] { basicBNFRule }); var full_par_n_2 = name + "." + param_name_2; resultBNFRule = resultRules[full_par_n_2] as BNFRule; basicBNFRule = new BasicBNFRule(); basicBNFRule.Add(new BNFReference(n2 )); TestUtil.AssertBNF(resultBNFRule, full_par_n_2, new BasicBNFRule[] { basicBNFRule }); } [TestMethod] [TestCategory("TransformToRules")] public void ToRulesBNFEmptyParamsEmpty() { //arrange var name = "a"; var rules = "Some strange comment-like text\n" + "with some new lines and //////star\n" + "but eventually /start\n" + name + "\n" + "/params_start\n" + "/params_end\n" + "/end\n" + "Some more comments"; var component = new TransformationComponent(); //act var actual = component.TransformToRules(rules); //assert Assert.AreEqual(actual.Languages.Count, 0); var resultRules = actual.GetBaseRules; Assert.AreEqual(1, resultRules.Count); Assert.IsTrue(resultRules.ContainsKey(name)); var resultTypeRule = resultRules[name] as BNFRule; TestUtil.AssertBNF(resultTypeRule, name, new BasicBNFRule[0]); } [TestMethod] [TestCategory("TransformToRules")] public void ToRulesBNFParamsEmpty() { //arrange var name = "a"; var bnf = "a"; var rules = "Some strange comment-like text\n" + "with some new lines and //////star\n" + "but eventually /start\n" + name + " ::= " + bnf + "\n" + "/params_start\n" + "/params_end\n" + "/end\n" + "Some more comments"; var component = new TransformationComponent(); //act var actual = component.TransformToRules(rules); //assert Assert.AreEqual(actual.Languages.Count, 0); var resultRules = actual.GetBaseRules; Assert.AreEqual(1, resultRules.Count); Assert.IsTrue(resultRules.ContainsKey(name)); var resultTypeRule = resultRules[name] as BNFRule; var basicBNFRule = new BasicBNFRule(); basicBNFRule.Add(new BNFString("a" )); TestUtil.AssertBNF(resultTypeRule, name, new BasicBNFRule[] { basicBNFRule }); } [TestMethod] [TestCategory("TransformToRules")] public void ToRulesBNFOneParamNoBody() { //arrange var name = "a"; var param_name = "b"; var bnf = "<" + param_name + ">"; var rules = "Some strange comment-like text\n" + "with some new lines and //////star\n" + "but eventually /start\n" + name + " ::= " + bnf + "\n" + "/params_start\n" + param_name + "\n" + "/params_end\n" + "/end\n" + "Some more comments"; var component = new TransformationComponent(); //act var actual = component.TransformToRules(rules); //assert Assert.AreEqual(actual.Languages.Count, 0); var resultRules = actual.GetBaseRules; Assert.AreEqual(2, resultRules.Count); Assert.IsTrue(resultRules.ContainsKey(name)); var resultTypeRule = resultRules[name] as BNFRule; var basicBNFRule = new BasicBNFRule(); basicBNFRule.Add(new BNFReference("a.b" )); TestUtil.AssertBNF(resultTypeRule, name, new BasicBNFRule[] { basicBNFRule }); var full_par_n = name + "." + param_name; var resultBNFRule = resultRules[full_par_n] as BNFRule; TestUtil.AssertBNF(resultBNFRule, full_par_n, new BasicBNFRule[0]); } [TestMethod] [TestCategory("TransformToRules")] public void ToRulesBNFOneParam() { //arrange var n1 = "c"; var name = "a"; var param_name = "b"; var param_body = "<" + n1 + ">"; var bnf = "<" + param_name + ">"; var rules = "Some strange comment-like text\n" + "with some new lines and //////star\n" + "but eventually /start\n" + n1 + "\n" + name + " ::= " + bnf + "\n" + "/params_start\n" + param_name + " ::= " + param_body + "\n" + "/params_end\n" + "/end\n" + "Some more comments"; var component = new TransformationComponent(); //act var actual = component.TransformToRules(rules); //assert Assert.AreEqual(actual.Languages.Count, 0); var resultRules = actual.GetBaseRules; Assert.AreEqual(3, resultRules.Count); CollectionAssert.Contains(resultRules.Keys, n1); TestUtil.AssertBNF((BNFRule)resultRules[n1], n1, new BasicBNFRule[0]); Assert.IsTrue(resultRules.ContainsKey(name)); var resultTypeRule = resultRules[name] as BNFRule; var basicBNFRule = new BasicBNFRule(); basicBNFRule.Add(new BNFReference("a.b" )); TestUtil.AssertBNF(resultTypeRule, name, new BasicBNFRule[] { basicBNFRule }); var full_par_n = name + "." + param_name; var resultBNFRule = resultRules[full_par_n] as BNFRule; basicBNFRule = new BasicBNFRule(); basicBNFRule.Add(new BNFReference(n1)); TestUtil.AssertBNF(resultBNFRule, full_par_n, new BasicBNFRule[] { basicBNFRule }); } [TestMethod] [TestCategory("TransformToRules")] public void ToRulesBNFTwoParams() { //arrange var n1 = "c"; var n2 = "d"; var name = "a"; var param_name = "b"; var param_name_2 = "b2"; var param_body = "<" + n1 + ">"; var param_body_2 = "<" + n2 + ">"; var bnf = "<" + param_name + ">"; var rules = "Some strange comment-like text\n" + "with some new lines and //////star\n" + "but eventually /start\n" + n1 + "\n" + n2 + "\n" + name + " ::= " + bnf + "\n" + "/params_start\n" + param_name + " ::= " + param_body + "\n" + param_name_2 + " ::= " + param_body_2 + "\n" + "/params_end\n" + "/end\n" + "Some more comments"; var component = new TransformationComponent(); //act var actual = component.TransformToRules(rules); //assert Assert.AreEqual(actual.Languages.Count, 0); var resultRules = actual.GetBaseRules; Assert.AreEqual(5, resultRules.Count); CollectionAssert.Contains(resultRules.Keys, n1); TestUtil.AssertBNF((BNFRule)resultRules[n1], n1, new BasicBNFRule[0]); CollectionAssert.Contains(resultRules.Keys, n2); TestUtil.AssertBNF((BNFRule)resultRules[n2], n2, new BasicBNFRule[0]); Assert.IsTrue(resultRules.ContainsKey(name)); var resultTypeRule = resultRules[name] as BNFRule; var basicBNFRule = new BasicBNFRule(); basicBNFRule.Add(new BNFReference( "a.b" )); TestUtil.AssertBNF(resultTypeRule, name, new BasicBNFRule[] { basicBNFRule }); var full_par_n = name + "." + param_name; var resultBNFRule = resultRules[full_par_n] as BNFRule; basicBNFRule = new BasicBNFRule { new BNFReference(n1) }; TestUtil.AssertBNF(resultBNFRule, full_par_n, new BasicBNFRule[] { basicBNFRule }); var full_par_n_2 = name + "." + param_name_2; resultBNFRule = resultRules[full_par_n_2] as BNFRule; basicBNFRule = new BasicBNFRule { new BNFReference(n2) }; TestUtil.AssertBNF(resultBNFRule, full_par_n_2, new BasicBNFRule[] { basicBNFRule }); } } } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace Kendo_UI_Bootstrap_Integration.Models { public class DonutChartViewModel { public DonutChartViewModel(string series, string category, double value) { Series = series; Category = category; Value = value; } public string Series { get; set; } public string Category { get; set; } public double Value { get; set; } } }
using System; using Utilities; namespace EddiEvents { [PublicAPI] public class SystemScanComplete : Event { public const string NAME = "System scan complete"; public const string DESCRIPTION = "Triggered after having identified all bodies in the system"; public const string SAMPLE = @"{""timestamp"":""2019-03-10T16:09:36Z"", ""event"":""FSSAllBodiesFound"", ""SystemName"":""Dumbae DN-I d10-6057"", ""SystemAddress"":208127228285531, ""Count"":19 }"; [PublicAPI("The name of the scanned system")] public string systemname { get; private set; } [PublicAPI("The count of bodies from the scanned system")] public int count { get; private set; } // Not intended to be user facing public long systemAddress { get; private set; } public SystemScanComplete(DateTime timestamp, string systemname, long systemAddress, int count) : base(timestamp, NAME) { this.systemname = systemname; this.systemAddress = systemAddress; this.count = count; } } }
namespace Sentry.Internal.JsonConverters; internal class IntPtrJsonConverter : JsonConverter<IntPtr> { public override IntPtr Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { return new IntPtr(reader.GetInt64()); } public override void Write(Utf8JsonWriter writer, IntPtr value, JsonSerializerOptions options) { writer.WriteNumberValue(value.ToInt64()); } }
using Microsoft.AspNetCore.Authentication; using Microsoft.AspNetCore.Identity; using System.Collections.Generic; using System.ComponentModel; using System.ComponentModel.DataAnnotations; namespace IdSP.Core.Models { public class LogoutInputModel { public string LogoutId { get; set; } } public class LogoutViewModel : LogoutInputModel { public bool ShowLogoutPrompt { get; set; } } public class AccountOptions { public static bool ShowLogoutPrompt = false; public static bool AutomaticRedirectAfterSignOut = true; } public class LoggedOutViewModel { public string PostLogoutRedirectUri { get; set; } public string ClientName { get; set; } public string SignOutIframeUrl { get; set; } public bool AutomaticRedirectAfterSignOut { get; set; } public string LogoutId { get; set; } public bool TriggerExternalSignout => ExternalAuthenticationScheme != null; public string ExternalAuthenticationScheme { get; set; } } public class LoginViewModel { [Required] [EmailAddress] public string Email { get; set; } [Required] [DataType(DataType.Password)] public string Password { get; set; } [Display(Name = "Remember me?")] public bool RememberMe { get; set; } } public class LoginWith2faViewModel { [Required] [StringLength(7, ErrorMessage = "The {0} must be at least {2} and at max {1} characters long.", MinimumLength = 6)] [DataType(DataType.Text)] [Display(Name = "Authenticator code")] public string TwoFactorCode { get; set; } [Display(Name = "Remember this machine")] public bool RememberMachine { get; set; } public bool RememberMe { get; set; } } public class LoginWithRecoveryCodeViewModel { [Required] [DataType(DataType.Text)] [Display(Name = "Recovery Code")] public string RecoveryCode { get; set; } } public class RegisterViewModel { [Required] [EmailAddress] [Display(Name = "Email")] public string Email { get; set; } [Required] [Phone] [Display(Name = "Cell Phone")] public string Phone { get; set; } [Required] [StringLength(100, ErrorMessage = "The {0} must be at least {2} and at max {1} characters long.", MinimumLength = 6)] [DataType(DataType.Password)] [Display(Name = "Password")] public string Password { get; set; } [DataType(DataType.Password)] [Display(Name = "Confirm password")] [Compare("Password", ErrorMessage = "The password and confirmation password do not match.")] public string ConfirmPassword { get; set; } } public class ExternalLoginViewModel { [Required] [EmailAddress] public string Email { get; set; } } public class ForgotPasswordViewModel { [Required] [EmailAddress] public string Email { get; set; } } public class ResetPasswordViewModel { [Required] [EmailAddress] public string Email { get; set; } [Required] [StringLength(100, ErrorMessage = "The {0} must be at least {2} and at max {1} characters long.", MinimumLength = 6)] [DataType(DataType.Password)] public string Password { get; set; } [DataType(DataType.Password)] [Display(Name = "Confirm password")] [Compare("Password", ErrorMessage = "The password and confirmation password do not match.")] public string ConfirmPassword { get; set; } public string Code { get; set; } } public class IndexViewModel { public string Username { get; set; } public bool IsEmailConfirmed { get; set; } [Required] [EmailAddress] public string Email { get; set; } [Phone] [Display(Name = "Phone number")] public string PhoneNumber { get; set; } public string StatusMessage { get; set; } } public class ChangePasswordViewModel { [Required] [DataType(DataType.Password)] [Display(Name = "Current password")] public string OldPassword { get; set; } [Required] [StringLength(100, ErrorMessage = "The {0} must be at least {2} and at max {1} characters long.", MinimumLength = 6)] [DataType(DataType.Password)] [Display(Name = "New password")] public string NewPassword { get; set; } [DataType(DataType.Password)] [Display(Name = "Confirm new password")] [Compare("NewPassword", ErrorMessage = "The new password and confirmation password do not match.")] public string ConfirmPassword { get; set; } public string StatusMessage { get; set; } } public class SetPasswordViewModel { [Required] [StringLength(100, ErrorMessage = "The {0} must be at least {2} and at max {1} characters long.", MinimumLength = 6)] [DataType(DataType.Password)] [Display(Name = "New password")] public string NewPassword { get; set; } [DataType(DataType.Password)] [Display(Name = "Confirm new password")] [Compare("NewPassword", ErrorMessage = "The new password and confirmation password do not match.")] public string ConfirmPassword { get; set; } public string StatusMessage { get; set; } } public class ExternalLoginsViewModel { public IList<UserLoginInfo> CurrentLogins { get; set; } public IList<AuthenticationScheme> OtherLogins { get; set; } public bool ShowRemoveButton { get; set; } public string StatusMessage { get; set; } } public class RemoveLoginViewModel { public string LoginProvider { get; set; } public string ProviderKey { get; set; } } public class TwoFactorAuthenticationViewModel { public bool HasAuthenticator { get; set; } public int RecoveryCodesLeft { get; set; } public bool Is2faEnabled { get; set; } } public class EnableAuthenticatorViewModel { [Required] [StringLength(7, ErrorMessage = "The {0} must be at least {2} and at max {1} characters long.", MinimumLength = 6)] [DataType(DataType.Text)] [Display(Name = "Verification Code")] public string Code { get; set; } [ReadOnly(true)] public string SharedKey { get; set; } public string AuthenticatorUri { get; set; } } public class GenerateRecoveryCodesViewModel { public string[] RecoveryCodes { get; set; } } }
using System; using ToDoManager.Views; using ToDoManager.ViewModels; using Prism.Services; using Prism.DryIoc; using Xamarin.Forms; using Prism; using Prism.Ioc; using Prism.Plugin.Popups; using Xamarin.Forms.Xaml; using Plugin.Settings; using CustomXamarinControls; [assembly: XamlCompilation(XamlCompilationOptions.Compile)] namespace ToDoManager { public partial class App : PrismApplication { public App (IPlatformInitializer initializer = null) : base(initializer) { } protected override void OnInitialized() { InitializeComponent(); App.Current.Resources["Primary"] = Color.FromHex(CrossSettings.Current.GetValueOrDefault("Primary", ((Color)App.Current.Resources["Primary"]).ToHex())); MessagingCenter.Send(typeof(ThemeColorPickerViewModel), "UpdateStatusbar"); App.Current.Resources["Accent"] = Color.FromHex(CrossSettings.Current.GetValueOrDefault("Accent", ((Color)App.Current.Resources["Accent"]).ToHex())); NavigationService.NavigateAsync("MainPage/NavigationPage/Tasks"); } protected override void RegisterTypes(IContainerRegistry containerRegistry) { containerRegistry.RegisterPopupNavigationService(); containerRegistry.RegisterForNavigation<NavigationPage>(); containerRegistry.RegisterForNavigation<MainPage>(); containerRegistry.RegisterForNavigation<Tasks>(); containerRegistry.RegisterForNavigation<Subtasks>(); containerRegistry.RegisterForNavigation<Settings>(); containerRegistry.RegisterForNavigation<ThemeColorPicker>(); } } }
using System; namespace ScratchTutorial { class RegistrationException : Exception { public RegistrationException(string message) : base(message) { } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace AbstractsInterfaces { internal abstract class BaseExc04 { protected int Number01, Number02; public abstract int this [int k] { get; } } interface IMyInterfaceExc04 { int Method(int n); } internal class MyClassExc04: BaseExc04, IMyInterfaceExc04 { public MyClassExc04(int n,int m) { Number01 = n; Number02 = m; } public override int this [int k] { get { if (k % 2 == 0) { return Number01; } else return Number02; } } public int Method(int n) { return ((Number01 + Number02) * n); } } internal class Exc04 { public static void Main04() { MyClassExc04 A = new MyClassExc04(4, 13); Console.WriteLine(A.Method(2)); Console.WriteLine(A[84]); Console.WriteLine(A[59]); } } }
using Reactive.Flowable; using Reactive.Flowable.Subscriber; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; namespace Reactive.Flowable.Flowable { public class FlowableMerge<TReturn> : FlowableMergeBase<TReturn, Maybe<TReturn>> { public FlowableMerge(IEnumerable<IFlowable<TReturn>> flow, Action<Maybe<TReturn>, ISubscriber<TReturn>> filter = null) : base(flow) { } public FlowableMerge(IFlowable<TReturn> flow1, IFlowable<TReturn> flow2, Action<Maybe<TReturn>, ISubscriber<TReturn>> filter = null) : base(flow1, flow2) { } protected override void ContinueWhen(ISubscriber<Maybe<TReturn>> x, ISubscriber<TReturn> s) { if (x is Maybe<TReturn>.Some some) { s.OnNext(some.Value); } } protected override void MergeFilter(Maybe<TReturn> inValue, ISubscriber<TReturn> outSubscriber) { if (inValue is Maybe<TReturn>.Some some) { outSubscriber.OnNext(some.Value); } } protected override Maybe<TReturn> Tointernal(IFlowable<TReturn> f, TReturn v) { return Maybe<TReturn>.AsSome(v, f.GetHashCode()); } } public abstract class FlowableMergeBase<TReturn, Tinternal> : IFlowable<TReturn> { private List<IFlowable<Tinternal>> Upstream = new List<IFlowable<Tinternal>>(); public FlowableMergeBase(IFlowable<TReturn> flow1, IFlowable<TReturn> flow2) : this(new List<IFlowable<TReturn>>() { flow1, flow2 }) { } public FlowableMergeBase(IEnumerable<IFlowable<TReturn>> flow) { Upstream.AddRange(flow.Select(f => f.Select(v => Tointernal(f, v)))); } public IDisposable Subscribe(ISubscriber<TReturn> subscriber) { int cancelations = 0; int cancelCount = Upstream.Count(); Action complete = () => { if (Interlocked.Increment(ref cancelations) >= cancelCount) { subscriber.OnComplete(); } }; var flowN = Upstream .Select(x => SubscriberToFlow(subscriber, x, complete)) .AsRoundRobbin() .AsFlowable() .Where( x=> x.State == SubscriberState.Subscribed); ////x.State != SubscriberState.Canceled //// && x.State != SubscriberState.Disposed //// && x.State != SubscriberState.Completed IFlowable<TReturn> fl = new FlowableWithUpstream<ISubscriber<Tinternal>, TReturn>( flowN, (x, s) => { ContinueWhen(x, s); }, onRequestFilter: (r, s) => { s.Request(r); }); fl.Subscribe(subscriber); return subscriber; } protected abstract void ContinueWhen(ISubscriber<Tinternal> x, ISubscriber<TReturn> s); protected abstract Tinternal Tointernal(IFlowable<TReturn> f, TReturn v); protected abstract void MergeFilter(Tinternal inValue, ISubscriber<TReturn> outSubscriber); protected Action<Tinternal> FilterComposer(ISubscriber<TReturn> subscriber, Action<Tinternal, ISubscriber<TReturn>> filter) { return x => filter(x, subscriber); } private ProxySubscriber<Tinternal> SubscriberToFlow(ISubscriber<TReturn> subscriber, IFlowable<Tinternal> flow, Action onComplete) { var composed = FilterComposer(subscriber, (a,b) => MergeFilter(a, b)); var sourceSubscriber = new ProxySubscriber<Tinternal>( new LambdaSubscriber<Tinternal>( onNext: (x,c) => { composed(x); c(); }, onRequest: (r, s) => { s.Request(r); }, onComplete: onComplete)); flow.Subscribe(sourceSubscriber); return sourceSubscriber; } } public abstract class Maybe<T> { private readonly int tag; public Maybe(int tag) { this.tag = tag; } public abstract bool IsSome { get; } public int Tag => tag; public static Maybe<T> AsSome(T value, int tag) { return new Some(value, tag); } public static Maybe<T> AsNone(T value, int tag) { return new None(tag); } public class Some : Maybe<T> { public Some(T value, int tag) : base(tag) { Value = value; } public T Value { get; } public override bool IsSome => true; } public class None : Maybe<T> { public None(int tag) : base(tag) { } public override bool IsSome => false; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using Welic.Dominio.Models.Users.Enums; namespace WebApi.Models { public class GroupUserDto { public int Id { get; set; } public string Description { get; set; } public int Nivel { get; set; } //public List<GroupUser> ListaGroupUser() //{ // return new List<GroupUser> // { // new GroupUser(GroupUserEnum.None), // new GroupUser(GroupUserEnum.Teacher), // new GroupUser(GroupUserEnum.Student), // new GroupUser(GroupUserEnum.TeacherStudent), // }; //} } }
using System; using System.Collections.Generic; using System.Linq; using RRExpress.AppCommon; using RRExpress.AppCommon.Attributes; namespace RRExpress.Store { [Regist(InstanceMode.Singleton)] public class TestViewModel : StoreBaseVM { public override char Icon { get { return (char)0xf015; } } public override string Title { get { return "商城"; } } public List<string> Datas { get; } = System.Linq.Enumerable.Range(0, 100).Select(i => i.ToString()).ToList(); } }
using System; using System.Collections.Generic; using System.Data; using System.Linq; using System.Text; using System.Threading.Tasks; using Microsoft.Practices.Unity; using OrgMan.Data.UnitOfWork; using OrgMan.Domain.Handler.HandlerBase; using OrgMan.DomainContracts.Membership; namespace OrgMan.Domain.Handler.Membership { public class DeleteMembershipQueryHandler : QueryHandlerBase { private DeleteMembershipQuery _query; public DeleteMembershipQueryHandler(DeleteMembershipQuery query, IUnityContainer unityContainer) : base(unityContainer) { _query = query; } public void Handle() { OrgManUnitOfWork uow = new OrgManUnitOfWork(); try { var membership = uow.MembershipRepository.Get(_query.MandatorUIDs, _query.MembershipUID); if (membership == null) { throw new DataException("No Entity found to UID : " + _query.MembershipUID); } if (_query.MandatorUIDs.Intersect(membership.MandatorUIDs).Any()) { if (membership.MemberInformationToMemberships != null && membership.MemberInformationToMemberships.Any()) { throw new DataException( string.Format( "Could not remove Membership, because it is beeing used by {0} MemberInformationToMemberships", membership.MemberInformationToMemberships.Count)); } uow.MembershipRepository.Delete(_query.MandatorUIDs, _query.MembershipUID); } else { throw new UnauthorizedAccessException("Membership from another Mandator"); } } catch (DataException e) { throw new DataException("Internal Server Error during deleting Membership", e); } catch (UnauthorizedAccessException e) { throw new DataException("Internal Server Error during deleting Membership", e); } catch (Exception) { throw new Exception("Internal Server Error during deleting Membership"); } try { uow.Commit(); } catch (DataException e) { throw new Exception("Internal Server Error during Saving changes", e); } catch (Exception) { throw new Exception("Internal Server Error during Saving changes"); } } } }
using UnityEngine; using System.Collections; public class CBahram_STT_First : IState,IMessageObsever { #region Private Fields private CiaObject _owner; private CMessageManager.MessageDelegate messageHandler; #endregion #region Constructors public CBahram_STT_First(){ _owner = null; } public CBahram_STT_First(CiaObject owner){ _owner = owner; } #endregion #region Ineteractive Object's Events public IEnumerator OnBegin(){ messageHandler = OnMessage; CMessageManager.MessageEvent += OnMessage; Debug.Log("\"CBahram_STT_First\" OnBegin called."); yield return true; } public void OnUpdate(){ // Debug.Log("\"CBahram_STT_First\" Update is called."); } public IEnumerator OnExit() { CMessageManager.MessageEvent -= messageHandler; Debug.Log("\"CBahram_STT_First\" OnExit is called."); yield return true; } public IEnumerator OnEnd() { yield return true; } #endregion #region Additional Events public void OnMessage(CMessages.eMessages m,object data) { if (m == CMessages.eMessages.ActionPressed ) { Debug.Log("\"CBahram_STT_First\" state receive Action pressed message."); } } #endregion }
using UnityEngine; using System; using System.Collections; namespace BanSupport { [AttributeUsage(AttributeTargets.Field | AttributeTargets.Property | AttributeTargets.Class | AttributeTargets.Struct, Inherited = true)] public class IntConditionAttribute : PropertyAttribute { public string intField = ""; public int expertValue; public IntConditionAttribute(string intField,int expectValue) { this.intField = intField; this.expertValue = expectValue; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace SocketServer { public class Location { public double Langtitude { get; set; } public double Longtitude { get; set; } public Location(double la, double lo) { Langtitude = la; Longtitude = lo; } public override string ToString() { return Langtitude + "; " + Longtitude; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace gMediaTools.Models.MediaAnalyze { public class MediaAnalyzeFileRequest : MediaAnalyzeRequest { public string MediaFile { get; set; } public MediaAnalyzeFileRequest() { } public MediaAnalyzeFileRequest(string mediaFilename, MediaAnalyzeRequest baseRequest) { MediaFile = mediaFilename; BitratePercentageThreshold = baseRequest.BitratePercentageThreshold; GainPercentageThreshold = baseRequest.GainPercentageThreshold; MaxAllowedWidth = baseRequest.MaxAllowedWidth; MaxAllowedHeight = baseRequest.MaxAllowedHeight; MinAllowedBitrate = baseRequest.MinAllowedBitrate; } } }
using System; using System.IO; using System.Windows; using System.Windows.Controls; using System.Windows.Media.Imaging; using MahApps.Metro.Controls; namespace ScratchTutorial.Gui { /// <summary> /// Interaction logic for LessonViewer.xaml /// </summary> public partial class LessonViewer : MetroWindow { private Lesson lesson; public LessonViewer(Lesson lesson) { InitializeComponent(); this.lesson = lesson; LoadPage(); } private void LoadPage() { this.lessonView.Children.Clear(); var page = this.lesson.CurrentPage; foreach (var paragraph in this.lesson.CurrentPage) { this.lessonView.Children.Add(new TextBlock { TextWrapping = TextWrapping.Wrap, Text = paragraph.Text, FontSize = 14 }); if (paragraph.Image != null) { var image = new BitmapImage(new Uri(paragraph.Image)); this.lessonView.Children.Add(new Image { Source = image, MaxWidth = image.PixelWidth, MaxHeight = image.PixelHeight }); } } if (this.lesson.CurrentHint != null) { AddHintButton(this.lessonView, Path.GetFullPath(this.lesson.CurrentHint)); } // TODO: counts percents and write to statistic this.btnBack.IsEnabled = !this.lesson.IsFirst; this.btnForward.IsEnabled = !this.lesson.IsLast; } private void NextPage(object sender, RoutedEventArgs e) { this.lesson.ToNext(); LoadPage(); } private void btnBack_Click(object sender, RoutedEventArgs e) { this.lesson.ToPrevious(); LoadPage(); } private static void AddHintButton(StackPanel panel, string path) { var hintButton = new Button { Height = 28, Width = 90, Opacity = 0.5, HorizontalAlignment = HorizontalAlignment.Left, Content = Properties.Resources.HintButton }; hintButton.Click += (_, __) => { new HintWindow(path).ShowDialog(); }; panel.Children.Add(hintButton); } } }
#if DEMO namespace System.Collections.Generic { public class List<T> : IList<T>, IList, IReadOnlyList<T> { public void Add(T item) { /* ... */ } public void Clear() { /* ... */ } public void ForEach(Action<T> action) { /* ... */ } public void Insert(int index, T item) { /* ... */ } public void RemoveAt(int index) { /* ... */ } public void Reverse() { /* ... */ } // Other members. } } #endif namespace Tutorial.Functional { using System; using System.Collections.Generic; internal class FluentList<T> : List<T> { internal new FluentList<T> Add(T item) { base.Add(item); return this; } internal new FluentList<T> Clear() { base.Clear(); return this; } internal new FluentList<T> ForEach(Action<T> action) { base.ForEach(action); return this; } internal new FluentList<T> Insert(int index, T item) { base.Insert(index, item); return this; } internal new FluentList<T> RemoveAt(int index) { base.RemoveAt(index); return this; } internal new FluentList<T> Reverse() { base.Reverse(); return this; } } internal static class ListExtensions { internal static List<T> FluentAdd<T>(this List<T> list, T item) { list.Add(item); return list; } internal static List<T> FluentClear<T>(this List<T> list) { list.Clear(); return list; } internal static List<T> FluentForEach<T>(this List<T> list, Action<T> action) { list.ForEach(action); return list; } internal static List<T> FluentInsert<T>(this List<T> list, int index, T item) { list.Insert(index, item); return list; } internal static List<T> FluentRemoveAt<T>(this List<T> list, int index) { list.RemoveAt(index); return list; } internal static List<T> FluentReverse<T>(this List<T> list) { list.Reverse(); return list; } } internal static partial class Fluent { internal static void List() { List<int> list = new List<int>() { 1, 2, 3, 4, 5 }; list.Add(1); list.Insert(0, 0); list.RemoveAt(1); list.Reverse(); list.ForEach(value => value.WriteLine()); list.Clear(); } internal static void FluentList() { FluentList<int> fluentlist = new FluentList<int>() { 1, 2, 3, 4, 5 } .Add(1) .Insert(0, 0) .RemoveAt(1) .Reverse() .ForEach(value => value.WriteLine()) .Clear(); } internal static void String() { string source = "..."; string result = source .Trim() .Replace('a', 'b') .Substring(1) .Remove(2) .Insert(0, "c") .ToUpperInvariant(); } internal static void ListFluentExtensions() { List<int> list = new List<int>() { 1, 2, 3, 4, 5 } .FluentAdd(1) .FluentInsert(0, 0) .FluentRemoveAt(1) .FluentReverse() .FluentForEach(value => value.WriteLine()) .FluentClear(); } internal static void CompiledListExtensions() { List<int> list = ListExtensions.FluentClear( ListExtensions.FluentForEach( ListExtensions.FluentReverse( ListExtensions.FluentRemoveAt( ListExtensions.FluentInsert( ListExtensions.FluentAdd( new List<int>() { 1, 2, 3, 4, 5 }, 1), 0, 0), 1) ), value => value.WriteLine()) ); } } } #if DEMO namespace System.Collections { public interface IEnumerable { IEnumerator GetEnumerator(); } } namespace System.Collections.Generic { public interface IEnumerable<out T> : IEnumerable { IEnumerator<T> GetEnumerator(); } } namespace System.Linq { using System.Collections.Generic; public static class Enumerable { public static IEnumerable<TSource> Where<TSource>( this IEnumerable<TSource> source, Func<TSource, bool> predicate); public static IEnumerable<TResult> Select<TSource, TResult>( this IEnumerable<TSource> source, Func<TSource, TResult> selector); public static IEnumerable<TSource> Concat<TSource>( this IEnumerable<TSource> first, IEnumerable<TSource> second); // Other members. } } namespace System.Linq { using System.Collections.Generic; public static class Enumerable { public static TSource First<TSource>(this IEnumerable<TSource> source); public static TSource Last<TSource>(this IEnumerable<TSource> source); } } namespace System.Linq { using System.Collections.Generic; public static class Enumerable { public static IOrderedEnumerable<TSource> OrderBy<TSource, TKey>( this IEnumerable<TSource> source, Func<TSource, TKey> keySelector); public static IOrderedEnumerable<TSource> OrderByDescending<TSource, TKey>( this IEnumerable<TSource> source, Func<TSource, TKey> keySelector); public static IOrderedEnumerable<TSource> ThenBy<TSource, TKey>( this IOrderedEnumerable<TSource> source, Func<TSource, TKey> keySelector); public static IOrderedEnumerable<TSource> ThenByDescending<TSource, TKey>( this IOrderedEnumerable<TSource> source, Func<TSource, TKey> keySelector); } } namespace System.Linq { using System.Collections; using System.Collections.Generic; public interface IOrderedEnumerable<TElement> : IEnumerable<TElement>, IEnumerable { IOrderedEnumerable<TElement> CreateOrderedEnumerable<TKey>( Func<TElement, TKey> keySelector, IComparer<TKey> comparer, bool descending); } } #endif
using Galeri.Entities.Concrete; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Galeri.DataAccess.Abstract { public interface IModelDal:IEntityRepository<Model>,IFilterMethods<Model> { } }
/* * Company: * Motto: Talk more to loved ones! * Assignment: A book shelf application * Deadline: 2012-01-02 * Programmer: Baran Topal * Solution name: .BookShelfWeb * Folder name: .ConstantsAndDefs * Project name: .BookShelfWeb.Definitions * File name: Enums.cs * Status: Ongoing - Future use */ using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace BookShelfWeb.Definitions { /// <summary> /// Enumerators for the whole application /// </summary> public enum Language { #region enums /// <summary> /// None /// </summary> None = -1, /// <summary> /// English /// </summary> English = 0, /// <summary> /// Swedish /// </summary> Swedish = 1 #endregion enums } }
using UnityEngine; using System.Collections; public class PlatformFall : MonoBehaviour { public float fallDelay = 1f; public float DisableColliderDelay = 3f; private Rigidbody2D rb2d; private Collider2D col2d; private Vector2 originalPosition; [SerializeField] float _timeToReset; [SerializeField] AudioClip crackSound; GameObject ball; AudioSource audioS; void Awake() { rb2d = GetComponent<Rigidbody2D>(); col2d = GetComponent<Collider2D>(); originalPosition = this.transform.position; audioS = GetComponent<AudioSource>(); } void OnCollisionEnter2D(Collision2D other) { if (other.gameObject.CompareTag("Ball")) { audioS.PlayOneShot(crackSound, 1F); Invoke("Fall", fallDelay); } } void Fall() { if(ball) ball.transform.parent = null; rb2d.bodyType = RigidbodyType2D.Dynamic; this.gameObject.GetComponent<Collider2D>().enabled = false; this.transform.Find("FallChild").gameObject.GetComponent<Collider2D>().enabled = false; this.gameObject.GetComponent<SpriteRenderer>().enabled = false; StartCoroutine(ExecuteAfterTime(_timeToReset)); } public void ResetPosition() { CancelInvoke(); this.gameObject.GetComponent<Collider2D>().enabled = true; this.transform.Find("FallChild").gameObject.GetComponent<Collider2D>().enabled = true; this.gameObject.GetComponent<SpriteRenderer>().enabled = true; rb2d.velocity = Vector2.zero; rb2d.bodyType = RigidbodyType2D.Kinematic; this.transform.position = originalPosition; } IEnumerator ExecuteAfterTime(float time) { yield return new WaitForSeconds(time); // Code to execute after the delay ResetPosition(); } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using QTouristik.Interface.Search; using QTouristik.PlugIn.OVH_V3.Search.LM; using QTouristik.PlugIn.OVH_V10.Search.DP; namespace QTouristik.PlugIn.OVH_V10.Search { public class SearchManager : ISearchManager, ISearchBulkCopyManager { public void DeleteOfferForAngebotId(int id) { using (var context = new OHV_V3_SearchEntities()) { context.SEH_FeWoPreiseSet.RemoveRange(context.SEH_FeWoPreiseSet.Where(m => m.Angebot_Id == id)); context.SaveChanges(); } } public void TruncateSearchItems(string dbName) { using (var context = new OHV_V3_SearchEntities()) { context.Database.ExecuteSqlCommand("TRUNCATE TABLE [" + dbName + "]"); } } public List<ObjektSearchResultEntity> GetBestPriceList(ObjektSearchArgs param, int page, ref int count) { if (param.ReisedauerMin > param.ReisedauerMax) param.ReisedauerMax = param.ReisedauerMin; if (param.FruehesteAnreise > param.SpaetesteRueckreise) param.SpaetesteRueckreise = param.FruehesteAnreise.AddDays(param.ReisedauerMax); DateTime lastAnreise = param.SpaetesteRueckreise.AddDays(-param.ReisedauerMin); int reisende = param.ReisendeErwachsener + param.ReisendeKinder; int erwachsene = param.ReisendeErwachsener; using (var context = new OHV_V3_SearchEntities()) { var result = from unit in context.SEH_UnitInfo join r in context.SEH_FeWoPreiseSet on unit.suUnitId equals r.Angebot_Id join ob in context.SEH_ObjektInfo on unit.suObjektId equals ob.soObjektId join rg in context.SEH_RegionInfoSet on ob.soRegion equals rg.Id join ort in context.SEH_PlaceInfoSet on ob.soOrtId equals ort.Id join portal in context.SEH_PortalSet on unit.suTourOperator equals portal.TourOperator where r.Anreise >= param.FruehesteAnreise && r.Anreise <= lastAnreise && r.Reisedauer >= param.ReisedauerMin && r.Reisedauer <= param.ReisedauerMax && unit.suMaxBelegung >= reisende && unit.suMaxErwachsener >= param.ReisendeErwachsener && r.MaxPersonen >= reisende select new { Region = ob.soRegion, RegionName = rg.RegionName, ObjektName = ob.soKurzBeschreibung, ObjektImage = ob.soImageLocation, ObjektRoute = ob.soRouteObjektId, OrtId = ob.soOrtId, OrtName = ort.PlaceName, AnlageMitPool = ob.Pool, ObjektID = unit.suObjektId, Schlafzimmer = unit.suSchlafzimmer, MH_Grosse = unit.suMHGroße, Geschirrspüler = unit.suGeschirrspueler, Bettwaesche = unit.suBettwaesche, Hund = unit.suHund, UnitID = unit.suUnitId, r.Reisedauer, param.ReisedauerMin, LeistungBeschreibung = ob.soLangBeschreibung, TourOperator = unit.suTourOperator, resultPreis = r.EndPreis, PortalCode = portal.PortalCode.Trim(), r.Anreise }; if (param.PortalCode != string.Empty) result = result.Where(i => i.PortalCode == param.PortalCode); if (param.MH_Grosse > 0) result = result.Where(i => i.MH_Grosse >= param.MH_Grosse); if (param.Geschirrspüler) result = result.Where(i => i.Geschirrspüler == "y"); if (param.Bettwaesche) result = result.Where(i => i.Bettwaesche == "y"); if (param.AnlageMitPool) result = result.Where(i => i.AnlageMitPool == "y"); if (param.Hund > 0) result = result.Where(i => i.Hund >= param.Hund); if (param.Schlafzimmer > 0) result = result.Where(i => i.Schlafzimmer == param.Schlafzimmer); if (param.RegionId > 0) result = result.Where(i => i.Region == param.RegionId); //if (param.OrtId > 0) // result = result.Where(i => i.OrtId == param.OrtId); //else if (param.RegionId > 0) // result = result.Where(i => i.RegionId == param.RegionId); //if (param.Kategorie > 0) // result = result.Where(i => i.Sterne >= param.Kategorie); //if (param.Verflegung > 1) // result = result.Where(i => i.Verpflegung >= param.Verflegung); var result1 = from s in result group s by s.UnitID into grp select grp.OrderBy(g => g.resultPreis).FirstOrDefault(); var result2 = (from r in result1 join to in context.SD_PartnerSet on r.TourOperator equals to.Id orderby r.resultPreis select new { r.UnitID, r.ObjektID, r.ObjektName, r.resultPreis, r.OrtId, r.OrtName, r.Reisedauer, r.Anreise, r.TourOperator, TourOperatorCode = to.Code, r.RegionName, r.LeistungBeschreibung, r.ObjektImage, r.ObjektRoute, r.AnlageMitPool }).Skip((page - 1) * 10).OrderBy(o => o.resultPreis); count = result2.Count() + (page - 1) * 10; var resultEntityList = new List<ObjektSearchResultEntity>(); int counter = 0; foreach (var k in result2) { int ix = resultEntityList.FindIndex(i => i.ObjektId == k.ObjektID); if (ix == -1) { decimal preis = k.resultPreis; resultEntityList.Add(new ObjektSearchResultEntity { ObjektId = k.ObjektID, Preis = preis, GesamtPreis = k.resultPreis, Reisedauer = k.Reisedauer, Reisende = reisende, Name = k.ObjektName, LeistungBeschreibung = k.LeistungBeschreibung, TourOperator = k.TourOperator.ToString(), TourOperatorCode = k.TourOperatorCode, OrtId = k.OrtId, OrtName = k.OrtName, RegionName = k.RegionName, ImageUrl = k.ObjektImage, ObjektRoute = k.ObjektRoute }); counter++; if (counter == 50) break; } } return resultEntityList.OrderBy(o => o.Preis).ToList(); } } public List<UnitSearchResultEntity> GetBestPriceListForObjekt(UnitSearchArgs param) { if (param.ReisedauerMin > param.ReisedauerMax) param.ReisedauerMax = param.ReisedauerMin; if (param.FruehesteAnreise > param.SpaetesteRueckreise) param.SpaetesteRueckreise = param.FruehesteAnreise.AddDays(param.ReisedauerMax); DateTime lastAnreise = param.SpaetesteRueckreise.AddDays(-param.ReisedauerMin); int reisende = param.ReisendeErwachsener + param.ReisendeKinder; int erwachsene = param.ReisendeErwachsener; using (var context = new OHV_V3_SearchEntities()) { var result = from unit in context.SEH_UnitInfo join r in context.SEH_FeWoPreiseSet on unit.suUnitId equals r.Angebot_Id join ob in context.SEH_ObjektInfo on unit.suObjektId equals ob.soObjektId join rg in context.SEH_RegionInfoSet on ob.soRegion equals rg.Id join ort in context.SEH_PlaceInfoSet on ob.soOrtId equals ort.Id where unit.suUnitId == param.SD_UnitId && r.Anreise >= param.FruehesteAnreise && r.Anreise <= lastAnreise && r.Reisedauer >= param.ReisedauerMin && r.Reisedauer <= param.ReisedauerMax && r.MaxPersonen >= reisende && r.MinPersonen <= reisende && unit.suMaxErwachsener >= param.ReisendeErwachsener && r.MaxPersonen >= reisende select new { UnitId = unit.suUnitId, Schlafzimmer = unit.suSchlafzimmer, MH_Grosse = unit.suMHGroße, Geschirrspüler = unit.suGeschirrspueler, Bettwaesche = unit.suBettwaesche, Hund = unit.suHund, Anreise = r.Anreise, Reisedauer = r.Reisedauer, TourOperator = unit.suTourOperator, ob.soRegion, RegionName = rg.RegionName, ImageName = unit.suImageLocation, UnitRoute = unit.suRouteObjektId, UnitTypRoute = unit.suRouteObjektTyp, ObjektName = ob.soKurzBeschreibung, OrtId = ob.soOrtId, OrtName = ort.PlaceName, ListenPreis = r.ListenPreis, EndPreis = r.EndPreis, PVPreisId = r.counter, PVLeistungId = r.Angebot_Id, HtmlBeschreibungLang = unit.suLangBeschreibung, UnitName = unit.suKurzBeschreibung }; var resultAlle = new List<IgorResult>(); foreach (var k in result.OrderBy(m => m.EndPreis)) { string groupCode = k.TourOperator.ToString() + k.UnitId.ToString() + k.Reisedauer.ToString() + k.EndPreis.ToString(); resultAlle.Add(new IgorResult { Anreise = k.Anreise, GroupCode = groupCode, ListenPreis = k.ListenPreis, EndPreis = k.EndPreis, Reisedauer = k.Reisedauer, TourOperator = k.TourOperator.ToString(), UnitId = k.UnitId, PVPreisId = k.PVPreisId, PVLeistungId = k.PVLeistungId, ImageName = k.ImageName, HtmlBeschreibungLang = k.HtmlBeschreibungLang, UnitName = k.UnitName, UnitRoute = k.UnitRoute, UnitTypRoute = k.UnitTypRoute }); } var resultGruppe = from s in resultAlle group s by s.GroupCode into grp select grp.OrderBy(g => g.EndPreis); var resultEntityList = new List<UnitSearchResultEntity>(); int counter = 0; foreach (var k in resultGruppe) { var anreiseList = new List<PreisVergleichUnitInfo>(); int pVPreisId = 0; int pV_LeistungId = 0; int verpflegung = 0; decimal EndPreis = 0; decimal listenPreis = 0; int reisedauer = 0; string leistungBeschreibung = String.Empty; string tourOperator = String.Empty; int UnitId = 0; string imageName = String.Empty; string groupCode = String.Empty; string unitName = String.Empty; string unitRoute = String.Empty; string unitTypRoute = String.Empty; foreach (IgorResult x in k) { groupCode = x.GroupCode; UnitId = x.UnitId; var pvui = new PreisVergleichUnitInfo { PVLeistungId = x.PVLeistungId, PVPreisId = x.PVPreisId, AnreiseDatum = x.Anreise }; anreiseList.Add(pvui); EndPreis = x.EndPreis; listenPreis = x.ListenPreis; reisedauer = x.Reisedauer; leistungBeschreibung = x.HtmlBeschreibungLang; tourOperator = x.TourOperator; pVPreisId = x.PVPreisId; pV_LeistungId = x.PVLeistungId; verpflegung = x.Verpflegung; imageName = x.ImageName.Trim(); unitName = x.UnitName; unitRoute = x.UnitRoute; unitTypRoute = x.UnitTypRoute; } if (pVPreisId != 0) { var uvre = new UnitSearchResultEntity { AnreiseList = anreiseList, EndPreis = EndPreis, ListenPreis = listenPreis, Reisedauer = reisedauer, Reisende = reisende, LeistungBeschreibung = leistungBeschreibung, TourOperator = tourOperator, Verpflegung = verpflegung, TO_UnitId = UnitId.ToString(), ImageName = imageName, UnitName = unitName, GroupCode = groupCode, UnitRoute = unitRoute, UnitTypRoute = unitTypRoute, UnitId = UnitId }; uvre.AnreiseBuchungsTermin = anreiseList[0].AnreiseDatum; uvre.BuchungsLeistungId = anreiseList[0].PVLeistungId; uvre.BuchungPreisId = anreiseList[0].PVPreisId; uvre.Counter = counter; resultEntityList.Add(uvre); } if (counter == 10) break; } return resultEntityList.OrderBy(o => o.EndPreis).ToList(); } } public List<UnitSearchResultEntity> GetBestPriceListForObjekt(UnitSearchArgs param, int page, ref int count) { if (param.ReisedauerMin > param.ReisedauerMax) param.ReisedauerMax = param.ReisedauerMin; if (param.FruehesteAnreise > param.SpaetesteRueckreise) param.SpaetesteRueckreise = param.FruehesteAnreise.AddDays(param.ReisedauerMax); DateTime lastAnreise = param.SpaetesteRueckreise.AddDays(-param.ReisedauerMin); int reisende = param.ReisendeErwachsener + param.ReisendeKinder; int erwachsene = param.ReisendeErwachsener; using (var context = new OHV_V3_SearchEntities()) { var result = from unit in context.SEH_UnitInfo join r in context.SEH_FeWoPreiseSet on unit.suUnitId equals r.Angebot_Id join ob in context.SEH_ObjektInfo on unit.suObjektId equals ob.soObjektId //join o in context.dbGeoLocation //on ob.soObjektId equals o.geoID join rg in context.SEH_RegionInfoSet on ob.soRegion equals rg.Id join ort in context.SEH_PlaceInfoSet on ob.soOrtId equals ort.Id join portal in context.SEH_PortalSet on unit.suTourOperator equals portal.TourOperator where unit.suObjektId == param.SD_ObjektId && r.Anreise >= param.FruehesteAnreise && r.Anreise <= lastAnreise && r.Reisedauer >= param.ReisedauerMin && r.Reisedauer <= param.ReisedauerMax && r.MaxPersonen >= reisende && r.MinPersonen <= reisende && unit.suMaxErwachsener >= param.ReisendeErwachsener && r.MaxPersonen >= reisende select new { UnitId = unit.suUnitId, Schlafzimmer = unit.suSchlafzimmer, MH_Grosse = unit.suMHGroße, Geschirrspüler = unit.suGeschirrspueler, Bettwaesche = unit.suBettwaesche, Hund = unit.suHund, Anreise = r.Anreise, Reisedauer = r.Reisedauer, TourOperator = unit.suTourOperator, ob.soRegion, RegionName = rg.RegionName, ImageName = unit.suImageLocation, UnitRoute = unit.suRouteObjektId, UnitTypRoute = unit.suRouteObjektTyp, ObjektName = ob.soKurzBeschreibung, OrtId = ob.soOrtId, OrtName = ort.PlaceName, ListenPreis = r.ListenPreis, EndPreis = r.EndPreis, PVPreisId = r.counter, PVLeistungId = r.Angebot_Id, HtmlBeschreibungLang = unit.suLangBeschreibung, UnitName = unit.suKurzBeschreibung, PortalCode = portal.PortalCode.Trim() }; if (param.PortalCode != string.Empty) result = result.Where(i => i.PortalCode == param.PortalCode); if (param.SD_UnitId > 0) result = result.Where(i => i.UnitId == param.SD_UnitId); if (param.MobilhomeGrosse > 0) result = result.Where(i => i.MH_Grosse >= param.MobilhomeGrosse); if (param.Geschirrspüler) result = result.Where(i => i.Geschirrspüler == "y"); if (param.Bettwaesche) result = result.Where(i => i.Bettwaesche == "y"); if (param.Hund > 0) result = result.Where(i => i.Hund >= param.Hund); if (param.Schlafzimmer > 0) result = result.Where(i => i.Schlafzimmer == param.Schlafzimmer); var resultAlle = new List<IgorResult>(); foreach (var k in result.OrderBy(m => m.EndPreis)) { string groupCode = k.TourOperator.ToString() + k.UnitId.ToString() + k.Reisedauer.ToString() + k.EndPreis.ToString(); resultAlle.Add(new IgorResult { Anreise = k.Anreise, GroupCode = groupCode, ListenPreis = k.ListenPreis, EndPreis = k.EndPreis, Reisedauer = k.Reisedauer, TourOperator = k.TourOperator.ToString(), UnitId = k.UnitId, PVPreisId = k.PVPreisId, PVLeistungId = k.PVLeistungId, ImageName = k.ImageName, HtmlBeschreibungLang = k.HtmlBeschreibungLang, UnitName = k.UnitName, UnitRoute = k.UnitRoute, UnitTypRoute = k.UnitTypRoute }); } var resultGruppe = from s in resultAlle group s by s.GroupCode into grp select grp.OrderBy(g => g.EndPreis); var resultEntityList = new List<UnitSearchResultEntity>(); int skip = (page - 1) * 10; count = resultGruppe.Count(); int counter = 0; int skipCounter = 0; foreach (var k in resultGruppe) { if (skipCounter < skip) { ++skipCounter; continue; } var anreiseList = new List<PreisVergleichUnitInfo>(); int pVPreisId = 0; int pV_LeistungId = 0; int verpflegung = 0; decimal EndPreis = 0; decimal listenPreis = 0; int reisedauer = 0; string leistungBeschreibung = String.Empty; string tourOperator = String.Empty; int UnitId = 0; string imageName = String.Empty; string groupCode = String.Empty; string unitName = String.Empty; string unitRoute = String.Empty; string unitTypRoute = String.Empty; foreach (IgorResult x in k) { groupCode = x.GroupCode; UnitId = x.UnitId; var pvui = new PreisVergleichUnitInfo { PVLeistungId = x.PVLeistungId, PVPreisId = x.PVPreisId, AnreiseDatum = x.Anreise }; anreiseList.Add(pvui); EndPreis = x.EndPreis; listenPreis = x.ListenPreis; reisedauer = x.Reisedauer; leistungBeschreibung = x.HtmlBeschreibungLang; tourOperator = x.TourOperator; pVPreisId = x.PVPreisId; pV_LeistungId = x.PVLeistungId; verpflegung = x.Verpflegung; imageName = x.ImageName.Trim(); unitName = x.UnitName; unitRoute = x.UnitRoute; unitTypRoute = x.UnitTypRoute; } if (pVPreisId != 0) { var uvre = new UnitSearchResultEntity { AnreiseList = anreiseList, EndPreis = EndPreis, ListenPreis = listenPreis, Reisedauer = reisedauer, Reisende = reisende, LeistungBeschreibung = leistungBeschreibung, TourOperator = tourOperator, Verpflegung = verpflegung, TO_UnitId = UnitId.ToString(), ImageName = imageName, UnitName = unitName, GroupCode = groupCode, UnitRoute = unitRoute, UnitTypRoute = unitTypRoute, UnitId = UnitId }; uvre.AnreiseBuchungsTermin = anreiseList[0].AnreiseDatum; uvre.BuchungsLeistungId = anreiseList[0].PVLeistungId; uvre.BuchungPreisId = anreiseList[0].PVPreisId; uvre.Counter = counter; resultEntityList.Add(uvre); } if (counter == 10) break; } return resultEntityList.OrderBy(o => o.EndPreis).ToList(); } } public int GetNewAppKeyCode(string key) { var entity = DP_Search.KeyDatabase.GetFirstOrDefault(m => m.AppKeyCode == key); entity.KeyCounter++; DP_Search.KeyDatabase.UpdateEntity(entity); return entity.KeyCounter; } public int GetObjektIdForRoute(string route) { var obj = DP_Search.SEH_ObjektInfo.GetFirstOrDefault(m => m.soRouteObjektId.ToLower() == route.ToLower()); if (obj == null) return 0; return obj.soObjektId; } public SearchMasterDataUnitEntity GetSearchMasterDataUnitEntity(int id) { var ret = new SearchMasterDataUnitEntity(); using (var context = new OHV_V3_SearchEntities()) { var result = (from unit in context.SEH_UnitInfo where unit.suUnitId == id select unit).FirstOrDefault(); if (result == null) return null; ret.suUnitId = result.suUnitId; ret.SiteCode = result.suSiteCode.Trim(); ret.OfferCode = result.suOfferCode.Trim(); ret.TourOperatorId = result.suTourOperator; ret.TourOperatorCode = result.TourOperatorCode.Trim(); ret.ImagePath = "/thumbnail/" + result.suImageLocation.Trim(); ret.OfferName = result.suKurzBeschreibung.Trim(); ret.AnbieterHinweis = result.suAnbieterHinweis == null ? string.Empty : result.suAnbieterHinweis.Trim(); } return ret; } public IEnumerable<SearchMasterDataUnitEntity> GetSearchMasterDataUnitEntitys(string routeObjektId, string portalCode) { var list = new List<SearchMasterDataUnitEntity>(); using (var context = new OHV_V3_SearchEntities()) { var result = from unit in context.SEH_UnitInfo join portal in context.SEH_PortalSet on unit.suTourOperator equals portal.TourOperator where unit.suRouteObjektId.ToUpper() == routeObjektId.ToUpper() && portal.PortalCode.ToLower() == portalCode.ToLower() orderby unit.SuSort select new { unit.Id, SuUnitId = unit.suUnitId, TourOperator = unit.suTourOperator, SiteCode = unit.suSiteCode, OfferCode = unit.suOfferCode, OfferName = unit.suKurzBeschreibung, Description = unit.suLangBeschreibung, ImageName = unit.suImageLocation, RouteObjektType = unit.suRouteObjektTyp, IsActive = unit.suIsActive }; foreach (var item in result) { if (item.IsActive.Trim() == "y") { var smdue = new SearchMasterDataUnitEntity(); smdue.Id = item.Id; smdue.SiteCode = item.SiteCode.Trim(); smdue.OfferCode = item.OfferCode.Trim(); smdue.TourOperatorId = item.TourOperator; smdue.suUnitId = item.SuUnitId; smdue.OfferName = item.OfferName.Trim(); smdue.Description = item.Description.Trim(); smdue.ImagePath = item.ImageName.Trim(); smdue.RouteObjektTyp = item.RouteObjektType.Trim(); smdue.IsActiveUnit = item.IsActive.Trim(); list.Add(smdue); } } } return list; } public IEnumerable<SearchMasterDataUnitEntity> GetSearchMasterDataUnitEntitys(string routeObjektId) { var list = new List<SearchMasterDataUnitEntity>(); using (var context = new OHV_V3_SearchEntities()) { var result = from unit in context.SEH_UnitInfo where unit.suRouteObjektId.ToUpper() == routeObjektId.ToUpper() orderby unit.SuSort select new { unit.Id, SuUnitId = unit.suUnitId, TourOperator = unit.suTourOperator, SiteCode = unit.suSiteCode, OfferCode = unit.suOfferCode, OfferName = unit.suKurzBeschreibung, Description = unit.suLangBeschreibung, ImageName = unit.suImageLocation, RouteObjektType = unit.suRouteObjektTyp, IsActive = unit.suIsActive }; foreach (var item in result) { if (item.IsActive.Trim() == "y") { var smdue = new SearchMasterDataUnitEntity(); smdue.Id = item.Id; smdue.SiteCode = item.SiteCode.Trim(); smdue.OfferCode = item.OfferCode.Trim(); smdue.TourOperatorId = item.TourOperator; smdue.suUnitId = item.SuUnitId; smdue.OfferName = item.OfferName.Trim(); smdue.Description = item.Description.Trim(); smdue.ImagePath = item.ImageName.Trim(); smdue.RouteObjektTyp = item.RouteObjektType.Trim(); list.Add(smdue); } } } return list; } public IEnumerable<SearchMasterDataUnitEntity> GetSearchMasterDataUnitEntitys(int tourOperatorId) { var list = new List<SearchMasterDataUnitEntity>(); using (var context = new OHV_V3_SearchEntities()) { var result = from unit in context.SEH_UnitInfo where unit.suTourOperator == tourOperatorId select new { unit.Id, SuUnitId = unit.suUnitId, angebotVon = unit.suAngebotVon, angebotBis = unit.suAngebotBis, TourOperator = unit.suTourOperator, TourOperatorCode = unit.TourOperatorCode, SiteCode = unit.suSiteCode, OfferCode = unit.suOfferCode, OfferName = unit.suKurzBeschreibung, Description = unit.suLangBeschreibung, IsActive = unit.suIsActive }; foreach (var item in result) { if (item.IsActive.Trim() == "y") { var smdue = new SearchMasterDataUnitEntity(); smdue.Id = item.Id; smdue.SiteCode = item.SiteCode.Trim(); smdue.OfferName = item.OfferName.Trim(); smdue.OfferCode = item.OfferCode.Trim(); smdue.Description = item.Description.Trim(); smdue.AngebotVon = item.angebotVon; smdue.AngebotBis = item.angebotBis; smdue.TourOperatorId = item.TourOperator; smdue.TourOperatorCode = item.TourOperatorCode; smdue.suUnitId = item.SuUnitId; list.Add(smdue); } } } return list; } public List<TouristSiteItem> GetTouristSiteItems() { var retList = new List<TouristSiteItem>(); using (var context = new OHV_V3_SearchEntities()) { var result = from obj in context.SEH_ObjektInfo select obj; foreach (var item in result) { var siteItem = new TouristSiteItem(); siteItem.Description = item.soLangBeschreibung; siteItem.SiteName = item.soKurzBeschreibung; siteItem.ImageThumbnailsPath = item.soImageLocation; siteItem.SiteCode = item.soRouteObjektId; siteItem.RegionId = item.soRegion; siteItem.ImageThumbnailsPath = item.soImageLocation; siteItem.PlaceId = item.soObjektId; retList.Add(siteItem); } } return retList; } public void UpdateSearchUnit(SearchMasterDataUnitEntity unit) { SEH_UnitInfo entity = DP_Search.SEH_UnitInfo.GetFirstOrDefault(m => m.suSiteCode == unit.SiteCode && m.suOfferCode == unit.OfferCode); if (entity != null) { entity.suAngebotVon = unit.AngebotVon; entity.suAngebotBis = unit.AngebotBis; entity.suKurzBeschreibung = unit.OfferName; entity.suLangBeschreibung = unit.Description; entity.suAnbieterHinweis = unit.AnbieterHinweis; DP_Search.SEH_UnitInfo.AddEntity(entity); } } public void DeletePriceIndexForStopBooking(string touropetatorCode, string siteCode, string unitCode, DateTime von, DateTime bis) { var unit = DP_Search.SEH_UnitInfo.GetFirstOrDefault(m => m.TourOperatorCode == touropetatorCode && m.suSiteCode == siteCode ); DeletePriceIndexForStopBooking(unit.suUnitId, von, bis); } public void DeletePriceIndexForStopBooking(int unitId, DateTime von, DateTime bis) { var entities = new OHV_V3_SearchEntities(); DateTime abr = von.AddDays(-21); var v = from preis in entities.SEH_FeWoPreiseSet join unit in entities.SEH_UnitInfo on preis.Angebot_Id equals unit.suUnitId where unit.suUnitId == unitId && preis.Anreise >= abr && preis.Anreise <= bis select preis; foreach (SEH_FeWoPreiseSet fp in v) { DateTime anreise = fp.Anreise; DateTime abreise = fp.Anreise.AddDays(fp.Reisedauer); if (abreise > von && abreise < bis) entities.SEH_FeWoPreiseSet.Remove(fp); else if (anreise > von && anreise < bis) entities.SEH_FeWoPreiseSet.Remove(fp); else if (anreise < von && abreise > bis) entities.SEH_FeWoPreiseSet.Remove(fp); else if (anreise >= von && abreise <= bis) entities.SEH_FeWoPreiseSet.Remove(fp); else if (von >= anreise && von < abreise) entities.SEH_FeWoPreiseSet.Remove(fp); else if (bis > anreise && bis < abreise) entities.SEH_FeWoPreiseSet.Remove(fp); } entities.SaveChanges(); } public TouristSiteItem GetSiteEntity(string siteCode) { var ret = new TouristSiteItem(); using (var context = new OHV_V3_SearchEntities()) { var result = (from site in context.SEH_ObjektInfo where site.soRouteObjektId == siteCode select site).FirstOrDefault(); if (result == null) return null; ret.SiteCode = result.soRouteObjektId; ret.SiteName = result.soKurzBeschreibung.Trim(); ret.RegionId = result.soRegion; ret.Description = result.soLangBeschreibung; ret.PlaceId = result.soOrtId; } return ret; } public List<TerminAndPriceItem> GetTerminAndPriceList(int unitId) { var entities = new OHV_V3_SearchEntities(); var retList = new List<TerminAndPriceItem>(); var v = from preis in entities.SEH_FeWoPreiseSet where preis.Angebot_Id == unitId select preis; foreach (var item in v) retList.Add(new TerminAndPriceItem() { Anreise = item.Anreise, ReiseDauer = item.Reisedauer, VonPersonen = item.MinPersonen, BisPersonen = item.MaxPersonen, Preis = item.EndPreis }); return retList; } } public class IgorResult { public int PVLeistungId; public int PVPreisId; public string GroupCode; public int UnitId; public DateTime Anreise; public int Reisedauer; public decimal ListenPreis; public decimal EndPreis; public string HtmlBeschreibungLang; public string TourOperator; public int Verpflegung; public string ImageName; public string UnitName; public string UnitRoute; public string UnitTypRoute; } }
using System.Collections.Generic; namespace LaboDotNet.Models { public class Auto { private static IList<Auto> _autos; private int _id; private string _naam; public int id { get { return _id; } } public string naam { get { return _naam; } set { _naam = value; } } private Auto(int id, string naam) { this._id = id; this._naam = naam; } public static IList<Auto> Autos { get { if (_autos == null) { int i = 0; _autos = new List<Auto> { new Auto(i++,"Auto 1"), new Auto(i++,"Auto 2"), new Auto(i++,"Auto 3"), new Auto(i++,"Auto 4"), new Auto(i++,"Auto 5"), }; } return _autos; } } public static string getNameById(int i) { foreach (var item in Autos) { if (item.id == i) return item.naam; } return "--Kapot--"; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Polymorphism { class CheckingAccount: BankAccount { public double ServiceCharge { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Runtime.InteropServices; namespace Ginkgo { class ControlGPIO { // General Error Code public struct ERROR { public const Int32 SUCCESS = 0; // no Error public const Int32 PARAMETER_NULL = -1; // void pointer public const Int32 INPUT_DATA_TOO_MUCH = -2; // too many parameters public const Int32 INPUT_DATA_TOO_LESS = -3; // too few parameters public const Int32 INPUT_DATA_ILLEGALITY = -4; // illegal parameter public const Int32 USB_WRITE_DATA_ERROR = -5; // USB write data error public const Int32 USB_READ_DATA_ERROR = -6; // USB read data error public const Int32 READ_NO_DATA = -7; // no data return when request data public const Int32 OPEN_DEVICE_FAILD = -8; // failed to open device public const Int32 CLOSE_DEVICE_FAILD = -9; // failed to close device public const Int32 EXECUTE_CMD_FAILD = -10; // the command failed to execute public const Int32 SELECT_DEVICE_FAILD = -11; // failed to select device public const Int32 DEVICE_OPENED = -12; // device has open public const Int32 DEVICE_NOTOPEN = -13; // device not open public const Int32 BUFFER_OVERFLOW = -14; // buffer overflow public const Int32 DEVICE_NOTEXIST = -15; // device not exist public const Int32 LOAD_KERNELDLL = -16; // failed to load KernelDLL public const Int32 CMD_FAILED = -17; // failed to execute command public const Int32 BUFFER_CREATE = -18; // out of memory } //Define GPIO public struct GPIO_MASK { public const UInt16 VGI_GPIO_PIN0 = 1 << 0; //GPIO_0 public const UInt16 VGI_GPIO_PIN1 = 1 << 1; //GPIO_1 public const UInt16 VGI_GPIO_PIN2 = 1 << 2; //GPIO_2 public const UInt16 VGI_GPIO_PIN3 = 1 << 3; //GPIO_3 public const UInt16 VGI_GPIO_PIN4 = 1 << 4; //GPIO_4 public const UInt16 VGI_GPIO_PIN5 = 1 << 5; //GPIO_5 public const UInt16 VGI_GPIO_PIN6 = 1 << 6; //GPIO_6 public const UInt16 VGI_GPIO_PIN7 = 1 << 7; //GPIO_7 public const UInt16 VGI_GPIO_PIN8 = 1 << 8; //GPIO_8 public const UInt16 VGI_GPIO_PIN9 = 1 << 9; //GPIO_9 public const UInt16 VGI_GPIO_PIN10 = 1 << 10; //GPIO_10 public const UInt16 VGI_GPIO_PIN11 = 1 << 11; //GPIO_11 public const UInt16 VGI_GPIO_PIN12 = 1 << 12; //GPIO_12 public const UInt16 VGI_GPIO_PIN13 = 1 << 13; //GPIO_13 public const UInt16 VGI_GPIO_PIN14 = 1 << 14; //GPIO_14 public const UInt16 VGI_GPIO_PIN15 = 1 << 15; //GPIO_15 public const UInt16 VGI_GPIO_PIN_ALL = 0xFFFF; //GPIO_ALL } // Device type public const Int32 VGI_USBGPIO = 1; // Device dll [DllImport("Ginkgo_Driver.dll")] // Scan device public static extern int VGI_ScanDevice(Byte NeedInit = 1); [DllImport("Ginkgo_Driver.dll")] // Open device public static extern int VGI_OpenDevice(Int32 DevType, Int32 DevIndex, Int32 Reserved); [DllImport("Ginkgo_Driver.dll")] // Close device public static extern int VGI_CloseDevice(Int32 DevType, Int32 DevIndex); [DllImport("Ginkgo_Driver.dll")] // Set specified pin to input public static extern int VGI_SetInput(Int32 DevType, Int32 DevIndex, UInt16 Pins); [DllImport("Ginkgo_Driver.dll")] // Set specified pin to output public static extern int VGI_SetOutput(Int32 DevType, Int32 DevIndex, UInt16 Pins); [DllImport("Ginkgo_Driver.dll")] // Set specified pin to output(Bi-directional, need pull-up resistor) public static extern int VGI_SetOpenDrain(Int32 DevType, Int32 DevIndex, UInt16 Pins); [DllImport("Ginkgo_Driver.dll")] // Set specified pin to high level public static extern int VGI_SetPins(Int32 DevType, Int32 DevIndex, UInt16 Pins); [DllImport("Ginkgo_Driver.dll")] // Set specified pin to low level public static extern int VGI_ResetPins(Int32 DevType, Int32 DevIndex, UInt16 Pins); [DllImport("Ginkgo_Driver.dll")] // Get specified pin value public static extern int VGI_ReadDatas(Int32 DevType, Int32 DevIndex, UInt16 PinMask, ref UInt16 pData); } }
using Microsoft.AspNetCore.Identity; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace ManhaleAspNetCore.ModelView.Account { public class CustomerIdentityRole:IdentityRole { public int PowerOfRole { get; set; } } }
 using Ecommerce_Framework.Api.Data; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using System; using System.Diagnostics.CodeAnalysis; namespace Ecommerce_Framework.Api.Configuration { [ExcludeFromCodeCoverage] public static class DataBaseConfig { public static void DataBaseRegister(this IServiceCollection services, IConfiguration configuration) { IServiceProvider serviceProvider = services.BuildServiceProvider(); IWebHostEnvironment env = serviceProvider.GetService<IWebHostEnvironment>(); services.AddDbContext<EcommerceFrameworkContext>(options => options.UseNpgsql(configuration.GetConnectionString("DefaultConnection"), b => b.MigrationsAssembly("Ecommerce-Framework.Api"))); } public static void DataBaseRegister(this IApplicationBuilder app, IWebHostEnvironment env) { using var serviceScope = app.ApplicationServices.GetService<IServiceScopeFactory>().CreateScope(); var ioasysFilmeContext = serviceScope.ServiceProvider.GetRequiredService<EcommerceFrameworkContext>(); ioasysFilmeContext.Database.Migrate(); } } }
using ClaimDi.DataAccess; using ClaimDi.DataAccess.Entity; using ClaimDi.DataAccess.Object.API; using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ClaimDi.Business.Master { public class MasterDataLogic { MyContext _context = null; public MasterDataLogic() { _context = new MyContext(); //_context.Configuration.LazyLoadingEnabled = false; //_context.Configuration.ProxyCreationEnabled = false; } private List<SyncGender> GetGenders(string language) { List<SyncGender> genders = new List<SyncGender>(); genders.Add(new SyncGender { GenderId = "none", GenderName = (language.ToUpper() == "TH" ? "ไม่ระบุ" : "Prefer not to disclose"), Sort = 100, IsActive = true }); genders.Add(new SyncGender { GenderId = "male", GenderName = (language.ToUpper() == "TH" ? "ชาย" : "Male"), Sort = 99, IsActive = true }); genders.Add(new SyncGender { GenderId = "female", GenderName = (language.ToUpper() == "TH" ? "หญิง" : "Female"), Sort = 99, IsActive = true }); return genders; } private List<SyncLanguage> GetLanguage(string language) { List<SyncLanguage> languages = new List<SyncLanguage>(); languages.Add(new SyncLanguage { LanguageId = "TH", LanguageName = (language.ToUpper() == "TH" ? "ไทย" : "Thai"), Sort = 99, IsActive = true }); languages.Add(new SyncLanguage { LanguageId = "EN", LanguageName = (language.ToUpper() == "TH" ? "อังกฤษ" : "English"), Sort = 99, IsActive = true }); return languages; } public SyncMasterDataResponse GetMasterData(SyncMasterDataRequest request) { string language = "TH"; if (!string.IsNullOrEmpty(request.Language)) { language = request.Language; } DateTime? lastSyncedDateTime = null; var dtValue = new DateTime(); var default_com_id = new Guid("13b00d32-d761-4eaa-9bb5-e6fe4905d04c"); // default claimdi app if (request != null) { if (DateTime.TryParseExact(request.Criteria, Constant.Format.ApiDateFormat, System.Globalization.CultureInfo.InvariantCulture, DateTimeStyles.None, out dtValue)) { lastSyncedDateTime = dtValue; } if (request.comid != null) { default_com_id = new Guid(request.comid); } } SyncMasterDataResponse dto = new SyncMasterDataResponse(); var carBrandLogic = new CarBrandLogic(_context); var carModelLogic = new CarModelLogic(_context); var carTypeLogic = new CarTypeLogic(_context); var causeOfLossLogic = new CauseOfLossLogic(_context, language); var insurerLogic = new InsurerLogic(_context, language); var provinceLogic = new ProvinceLogic(_context); var taskLogic = new TaskConsumerLogic(_context); var partyAtFault = new PartyAtFaultLogic(_context); dto.CarBrands = carBrandLogic.GetCarBrands(lastSyncedDateTime); dto.CarModels = carModelLogic.GetCarModels(lastSyncedDateTime); dto.CarTypes = carTypeLogic.GetCarTypes(lastSyncedDateTime); dto.CauseOfLosses = causeOfLossLogic.GetCauseOfLosses(lastSyncedDateTime); dto.Insurers = insurerLogic.GetInsurers(lastSyncedDateTime); dto.Provinces = provinceLogic.GetProvinces(language, lastSyncedDateTime); dto.PictureType = taskLogic.GetPictureTypes(language, lastSyncedDateTime); dto.PartyAtFault = partyAtFault.GetPartyAtFaults(language, lastSyncedDateTime); dto.Genders = this.GetGenders(language); dto.Languages = this.GetLanguage(language); dto.IsDisplayUberPromotionCode = false; dto.Criteria = DateTime.Now.ToString(Constant.Format.ApiDateFormat); return dto; } } }
using System; using System.Collections.Generic; using System.Collections.Specialized; using System.Net; using System.Text; namespace jaytwo.Common.Http { public partial class HttpClient { public HttpWebResponse SubmitGet(string url) { return Submit(url, HttpMethod.GET); } public HttpWebResponse SubmitGet(Uri uri) { return Submit(uri, HttpMethod.GET); } public HttpWebResponse SubmitGet(HttpWebRequest request) { return Submit(request, HttpMethod.GET); } } }
using Alabo.Domains.Entities; using Alabo.Domains.Services; using System; namespace Alabo.Framework.Core.WebUis.Services { /// <summary> /// 通用表单服务 /// </summary> public interface IAdminTableService : IService { /// <summary> /// 导出表格 /// </summary> /// <param name="key">导出表格key,通过key从缓存中读取用户的设置</param> /// <param name="service">获取数据的服务</param> /// <param name="method">获取数据的方法</param> /// <param name="query">Url参数,用户通过界面选择传递</param> Tuple<ServiceResult, string, string> ToExcel(string key, string service, string method, object query); Tuple<ServiceResult, string, string> ToExcel(string type, object query); /// <summary> /// 导出Excel /// </summary> /// <returns></returns> Tuple<ServiceResult, string, string> ToExcel(Type type, dynamic data); } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; using SimpleJSON; public class StageLevel : MonoBehaviour { public string GhostMap1, GhostMap2, GhostMap3; public string LevelName; public Button StartButton, LevelButton; public Text LevelNameText; public Text LevelText; public int StageChoosen; private int localStagenumber; private bool pressed; [HideInInspector] public Map Map; [HideInInspector] public MapListManager MapLM; [HideInInspector] public bool complete; public GameObject Panah; public GameObject CompleteText; JSONNode jsonString; // Use this for initialization void Start () { this.GetComponent<Button>().onClick.AddListener(OnClick); if(complete) { CompleteText.SetActive(true); } jsonString = JSON.Parse (PlayerPrefs.GetString(Link.StageData)); //LevelNameText = MapLM.LevelNameText; } // Update is called once per frame void Update () { } private void OnClick() { print(jsonString); int n; int mystage = int.Parse(PlayerPrefs.GetString(Link.Stage)); PlayerPrefs.SetString(Link.StageChoose, StageChoosen.ToString()); Map.R1.text=""; ShowDrop(StageChoosen); if (PlayerPrefs.GetString ("PLAY_TUTORIAL") == "TRUE") { if(StageChoosen==99) { StartButton.interactable = true; StartButton.onClick.AddListener(OnStart); } else { StartButton.interactable = false; } MapLM.GhostSelectedTarget[0].sprite = Resources.Load<Sprite> ("icon_char_Maps/" + GhostMap1); if(!string.IsNullOrEmpty(GhostMap2)) { MapLM.GhostSelectedTarget[1].sprite = Resources.Load<Sprite> ("icon_char_Maps/" + GhostMap2); } else { MapLM.GhostSelectedTarget[1].sprite = Map.DefaultSelectedGhostTarget; } if(!string.IsNullOrEmpty(GhostMap3)) { MapLM.GhostSelectedTarget[2].sprite = Resources.Load<Sprite> ("icon_char_Maps/" + GhostMap3); } else { MapLM.GhostSelectedTarget[2].sprite = Map.DefaultSelectedGhostTarget; } LevelNameText.text = LevelName; } else { if(mystage >= StageChoosen) { StartButton.interactable = true; StartButton.onClick.AddListener(OnStart); } else { StartButton.interactable = false; } MapLM.GhostSelectedTarget[0].sprite = Resources.Load<Sprite> ("icon_char_Maps/" + GhostMap1); if(!string.IsNullOrEmpty(GhostMap2)) { MapLM.GhostSelectedTarget[1].sprite = Resources.Load<Sprite> ("icon_char_Maps/" + GhostMap2); } else { MapLM.GhostSelectedTarget[1].sprite = Map.DefaultSelectedGhostTarget; } if(!string.IsNullOrEmpty(GhostMap3)) { MapLM.GhostSelectedTarget[2].sprite = Resources.Load<Sprite> ("icon_char_Maps/" + GhostMap3); } else { MapLM.GhostSelectedTarget[2].sprite = Map.DefaultSelectedGhostTarget; } LevelNameText.text= LevelName; } } private void ShowDrop(int stageChoosen) { // if(stageChoosen==0||stageChoosen==6){ // n=0; // for(int i=0;i<3;i++) // { // Map.R1.text+=Map.dropItemQuantity[i]+" "+Map.dropItemName[i]+" Chance "+Map.dropItemRate[i]+"% \n"; // } // for(int z=0;z<3;z++) // { // PlayerPrefs.SetString("RewardItemFN"+z.ToString(),Map.dropItemFileName[n]); // PlayerPrefs.SetString("RewardItemName"+z.ToString(),Map.dropItemName[n]); // PlayerPrefs.SetString("RewardItemQuantity"+z.ToString(),Map.dropItemQuantity[n]); // PlayerPrefs.SetString("RewardItemType"+z.ToString(),Map.dropItemType[n]); // PlayerPrefs.SetString("RewardItemRate"+z.ToString(),Map.dropItemRate[n]); // n++; // } if(stageChoosen>=6) { float hasilbagi = stageChoosen/6; stageChoosen-=(int) hasilbagi*6; localStagenumber=stageChoosen; } print(stageChoosen); SetGhost(); var choose=0; var n=0; n = stageChoosen*3; if(stageChoosen==0) { choose = stageChoosen+3; } else { choose = stageChoosen+1*3; } for(int i=stageChoosen;i<choose;i++) { Map.R1.text+=Map.dropItemQuantity[i]+" "+Map.dropItemName[i]+" Chance "+Map.dropItemRate[i]+"% \n"; } for(int z=0;z<3;z++) { PlayerPrefs.SetString("RewardItemFN"+z.ToString(),Map.dropItemFileName[n]); PlayerPrefs.SetString("RewardItemName"+z.ToString(),Map.dropItemName[n]); PlayerPrefs.SetString("RewardItemQuantity"+z.ToString(),Map.dropItemQuantity[n]); PlayerPrefs.SetString("RewardItemType"+z.ToString(),Map.dropItemType[n]); PlayerPrefs.SetString("RewardItemRate"+z.ToString(),Map.dropItemRate[n]); n++; } } // else if(stageChoosen==1||stageChoosen==7){ // n=3; // for(int i=3;i<6;i++) // { // Map.R1.text+=Map.dropItemQuantity[i]+" "+Map.dropItemName[i]+" Chance "+Map.dropItemRate[i]+"% \n"; // } // for(int z=0;z<3;z++) // { // PlayerPrefs.SetString("RewardItemFN"+z.ToString(),Map.dropItemFileName[n]); // PlayerPrefs.SetString("RewardItemName"+z.ToString(),Map.dropItemName[n]); // PlayerPrefs.SetString("RewardItemQuantity"+z.ToString(),Map.dropItemQuantity[n]); // PlayerPrefs.SetString("RewardItemType"+z.ToString(),Map.dropItemType[n]); // PlayerPrefs.SetString("RewardItemRate"+z.ToString(),Map.dropItemRate[n]); // n++; // } private void OnStart() { Map.On_Start(); } void SetGhost() { if (PlayerPrefs.GetString ("PLAY_TUTORIAL") == "TRUE") { //print (jsonString[]) PlayerPrefs.SetString(Link.POS_1_CHAR_1_FILE, jsonString [6]["HantuId1".ToString()]["name_file"]); PlayerPrefs.SetString(Link.POS_1_CHAR_1_ELEMENT, jsonString [6]["HantuId1".ToString()]["type"]); PlayerPrefs.SetString(Link.POS_1_CHAR_1_MODE, jsonString [6]["HantuId1".ToString()]["element"]); PlayerPrefs.SetString(Link.POS_1_CHAR_1_GRADE, jsonString [6]["HantuId1".ToString()]["grade"]); PlayerPrefs.SetString(Link.POS_1_CHAR_1_ATTACK, jsonString [6]["HantuId1".ToString()]["ATTACK"]); PlayerPrefs.SetString(Link.POS_1_CHAR_1_DEFENSE, jsonString [6]["HantuId1".ToString()]["DEFEND"]); PlayerPrefs.SetString(Link.POS_1_CHAR_1_HP, jsonString [6]["HantuId1".ToString()]["HP"]); print(PlayerPrefs.GetString("pos_1_char_1_file")); print("here"); } else { for(int i=1;i<4;i++) { PlayerPrefs.SetString("pos_1_char_"+i.ToString()+"_file", jsonString [localStagenumber]["HantuId"+i.ToString()]["name_file"]); PlayerPrefs.SetString("pos_1_char_"+i.ToString()+"_element", jsonString [localStagenumber]["HantuId"+i.ToString()]["type"]); PlayerPrefs.SetString("pos_1_char_"+i.ToString()+"_mode", jsonString [localStagenumber]["HantuId"+i.ToString()]["element"]); PlayerPrefs.SetString("pos_1_char_"+i.ToString()+"_grade", jsonString [localStagenumber]["HantuId"+i.ToString()]["grade"]); PlayerPrefs.SetString("pos_1_char_"+i.ToString()+"_attack", jsonString [localStagenumber]["HantuId"+i.ToString()]["ATTACK"]); PlayerPrefs.SetString("pos_1_char_"+i.ToString()+"_defense", jsonString [localStagenumber]["HantuId"+i.ToString()]["DEFEND"]); PlayerPrefs.SetString("pos_1_char_"+i.ToString()+"_hp", jsonString [localStagenumber]["HantuId"+i.ToString()]["HP"]); } // print(jsonString[0]); for(int i=1;i<4;i++) { print(PlayerPrefs.GetString("pos_1_char_"+i.ToString()+"_hp")); } } } }
using System.Threading.Tasks; using FluentAssertions; using NUnit.Framework; namespace Beeffective.Tests.Data.CellRepositoryTests { class RemoveAsync : TestFixture { public override void SetUp() { base.SetUp(); Sut.Add(CellEntity1); } [Test] public async Task DoesNotContain_RemovedCellEntity() { await Sut.RemoveAsync(CellEntity1); var cellEntities = await Sut.LoadAsync(); cellEntities.Should().NotContain(CellEntity1); } } }
using System; using System.Collections.Generic; using System.Data; using System.Data.Entity; using System.Data.Entity.Infrastructure; using System.Linq; using System.Net; using System.Net.Http; using System.Web.Http; using System.Web.Http.Description; using DemoWebAPIPrj.Models; namespace DemoWebAPIPrj.Controllers { public class MISROTsController : ApiController { private EntitiesModel db = new EntitiesModel(); // GET: api/MISROTs public IQueryable<MISROT> GetMISROT() { return db.MISROT; } // GET: api/MISROTs/5 [ResponseType(typeof(MISROT))] public IHttpActionResult GetMISROT(int id) { MISROT mISROT = db.MISROT.Find(id); if (mISROT == null) { return NotFound(); } return Ok(mISROT); } // PUT: api/MISROTs/5 [ResponseType(typeof(void))] public IHttpActionResult PutMISROT(int id, MISROT mISROT) { if (!ModelState.IsValid) { return BadRequest(ModelState); } if (id != mISROT.KOD_MISRA) { return BadRequest(); } db.Entry(mISROT).State = EntityState.Modified; try { db.SaveChanges(); } catch (DbUpdateConcurrencyException) { if (!MISROTExists(id)) { return NotFound(); } else { throw; } } return StatusCode(HttpStatusCode.NoContent); } // POST: api/MISROTs [ResponseType(typeof(MISROT))] public IHttpActionResult PostMISROT(MISROT mISROT) { if (!ModelState.IsValid) { return BadRequest(ModelState); } db.MISROT.Add(mISROT); try { db.SaveChanges(); } catch (DbUpdateException) { if (MISROTExists(mISROT.KOD_MISRA)) { return Conflict(); } else { throw; } } return CreatedAtRoute("DefaultApi", new { id = mISROT.KOD_MISRA }, mISROT); } // DELETE: api/MISROTs/5 [ResponseType(typeof(MISROT))] public IHttpActionResult DeleteMISROT(int id) { MISROT mISROT = db.MISROT.Find(id); if (mISROT == null) { return NotFound(); } db.MISROT.Remove(mISROT); db.SaveChanges(); return Ok(mISROT); } protected override void Dispose(bool disposing) { if (disposing) { db.Dispose(); } base.Dispose(disposing); } private bool MISROTExists(int id) { return db.MISROT.Count(e => e.KOD_MISRA == id) > 0; } } }
using System; using System.Data; using System.Globalization; using System.Linq; using System.Text; using System.Threading; using HTB.Database; using System.Collections; using HTB.Database.HTB.StoredProcs; using HTB.GeocodeService; using HTBAktLayer; using HTBExtras.KingBill; using HTBUtilities; using System.Net.Mail; using HTBReports; using System.IO; using HTB.Database.Views; using HTBExtras; using System.Diagnostics; using HTB.v2.intranetx.routeplanter; using System.Collections.Generic; using System.Net; using HTB.v2.intranetx.util; using Microsoft.VisualBasic; using HTBServices; using HTBServices.Mail; namespace HTBDailyKosten { internal class Program { private static tblControl control = HTBUtils.GetControlRecord(); private static void Main(string[] args) { // Thread.CurrentThread.CurrentUICulture = new CultureInfo("de-DE"); //TestSystem(); //TestNextStepManager(); //TestZinsen(); //TestWorkflow(); // TestOverdue(); //TestPayments(); //TestEmail(); //TestSystem(); // TestMahnung(); // TestMahnungPdf(); // TestAuftragReceipt(); //TestExtensionRequest(); // TestZwischenbericht(); //TestKlientbericht(); //TestUebergabeAkten(); // TestExcel(); // TestMissingBeleg(); // TestRV(); // TestRoutePlanner(); // Console.WriteLine("OUTPUT: " + HTBUtils.ReplaceStringBetween(HTBUtils.ReplaceStringBetween("Rennbahnstrasse 4 Top 10, 5020, Salzburg, Österreich", " top ", ",", ","), "/", ",", ",")); // TestSerilization(); // ProcessDir("C:\\NintendoDS"); // ProcessDir2("C:\\NintendoDS\\Unzip"); // TestFtp(); // FixAllAE(); // TestProtokol(); //TestWebServiceNewAkt_Debug(); // TestWebServiceNewAkt(); // TestWebServiceNewAktProduction(); // TestWebServiceAktStatus(); // TestWebServiceAktStatusProduction(); //TestFinancialPmt(); //TestFinanacial_NumberOfInstallments(); // ObjectiveCSql.GenerateSql(); // TestLogFileConverssion(); // TestErlagschein(); // TestSmallLinesOfCode(); // TestInterverntionAction(); //TestLawyerMahnung(); Console.WriteLine(Uri.EscapeUriString("BE Pröll.txt")); Console.Read(); } private static void TestSmallLinesOfCode() { var strEmails = "m.haendlhuber@geyrhofer.bmw.at xyz bledi1@yahoo.com bla test@tesrt.at"; var strEmails2 = "bledi1@gmail.com test@bla.test adf some thi things.@bla. things@t12.com"; string strEmails3 = null; Console.WriteLine(string.Format("testig: \t1. {0}\n\t\t2. {1}\n\t\t3. {2}\n\n", strEmails, strEmails2, strEmails3)); foreach (var valid in (HTBUtils.GetValidEmailAddressesFromStrings(new[] { strEmails, strEmails2, strEmails3 }))) { Console.WriteLine(string.Format("\t[{0}]", valid)); } Console.WriteLine("Done!"); } private static void TestSystem() { while (true) { TestNextStepManager(); TestZinsen(); TestWorkflow(); TestZinsen(); TestOverdue(); //TestPayments(); //TestMahnungPdf(); //TestEmail(); TestMahnung(); TestAuftragReceipt(); TestExtensionRequest(); Thread.Sleep(1000); } } private static void TestZinsen() { new HTBInvoiceManager.InvoiceManager().GenerateInterest(); } private static void TestWorkflow() { new KostenCalculator().CalculateKosten(); } private static void TestPayments() { for (int i = 0; i < 1; i++) TestPayment(19632, 500); //TestPayment(19625, 467.14); //TestPayment(19625, 500); return; } private static void TestPayment(int aktId, double amount) { //int aktId = 19625; //double amount = 7467.14; //double amount = 1000; var invMgr = new HTBInvoiceManager.InvoiceManager(); invMgr.CreateAndSavePayment(aktId, amount); ArrayList list = invMgr.GetOpenedPayments(aktId); foreach (tblCustInkAktInvoice inv in list) invMgr.ApplyPayment(inv.InvoiceID); } private static void TestOverdue() { var installMgr = new InstallmentManager(); installMgr.GenerateOverdueInvoices(); } private static void TestMahnungPdf() { new MahnungPdfReportGenerator("C:\\temp\\mahnung.xml"); } private static void TestAuftragReceipt() { string[] wtimeString = control.KlientReceiptTime.Split(':'); int wrunHour = Convert.ToInt16(wtimeString[0]); int wrunMin = Convert.ToInt16(wtimeString[1]); var wrunTime = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, wrunHour, wrunMin, 0); DateTime now = DateTime.Now; TimeSpan wrunSpan = now.Subtract(wrunTime); if (wrunSpan.TotalMinutes >= 1) { String klientQuery = "SELECT DISTINCT k.klientid AS [IntValue] FROM tblKlient k inner join tblCustInkAkt a " + " on k.KlientID = a.CustInkAktKlient " + " WHERE a.CustInkAktEnterDate BETWEEN '" + now.ToShortDateString() + " 00:00.000' AND '" + now.ToShortDateString() + " 23:59.999'"; ArrayList klientsList = HTBUtils.GetSqlRecords(klientQuery, typeof (SingleValue)); var email = ServiceFactory.Instance.GetService<IHTBEmail>(); foreach (SingleValue klientId in klientsList) { // make sure we have not already sent a receipt for this klient klientQuery = "SELECT * FROM tblCommunicationLog " + " WHERE ComLogKlientID = " + klientId.IntValue + " AND ComLogType = " + tblCommunicationLog.COMMUNICATION_TYPE_RECEIPT + " AND ComLogDate BETWEEN '" + now.ToShortDateString() + " 00:00.000' AND '" + now.ToShortDateString() + " 23:59.999'"; var receiptLog = (tblCommunicationLog) HTBUtils.GetSqlSingleRecord(klientQuery, typeof (tblCommunicationLog)); if (receiptLog == null) { using (var stream = new MemoryStream()) { var paramaters = new ReportParameters {StartKlient = klientId.IntValue, EndKlient = klientId.IntValue, StartDate = now, EndDate = now}; var receipt = new AuftragReceipt(); receipt.GenerateClientReceipt(paramaters, stream); var klient = (tblKlient) HTBUtils.GetSqlSingleRecord("SELECT * FROM tblKlient WHERE KlientId = " + klientId.IntValue, typeof (tblKlient)); if (klient != null) { var emailAddressList = new ArrayList(); String body = GetKlientReceiptBody(klient); if (body != null) { email.SendKlientReceipt(klient, null, body, HTBUtils.ReopenMemoryStream(stream)); SaveKlientAuftragReceipt(receipt.RecordsList, HTBUtils.ReopenMemoryStream(stream), klientId.IntValue); // insert log record so that we know when the receipt was sent RecordSet.Insert(new tblCommunicationLog {ComLogKlientID = klientId.IntValue, ComLogType = tblCommunicationLog.COMMUNICATION_TYPE_RECEIPT, ComLogDate = DateTime.Now}); } } } } } } } private static string GetKlientReceiptBody(tblKlient klient) { var sb = new StringBuilder(); if (klient != null) { var contact = (tblAnsprechpartner) HTBUtils.GetSqlSingleRecord("SELECT * FROM tblAnsprechpartner WHERE AnsprechKlient = " + klient.KlientID, typeof (tblAnsprechpartner)); StreamReader re = File.OpenText(HTBUtils.GetConfigValue("Klient_Receipt_Text")); string input = null; while ((input = re.ReadLine()) != null) { sb.Append(input); } re.Close(); re.Dispose(); if (contact != null) { if (contact.AnsprechTitel.Trim().ToUpper() == "HERR") { return sb.ToString().Replace("[name]", "r " + contact.AnsprechTitel + " " + contact.AnsprechNachname); } return sb.ToString().Replace("[name]", " " + contact.AnsprechTitel + " " + contact.AnsprechNachname); } return sb.ToString().Replace("[name]", " Damen und Herren"); } return null; } private static void SaveKlientAuftragReceipt(ArrayList recordsList, MemoryStream stream, int klientId) { string documentsFolder = HTBUtils.GetConfigValue("DocumentsFolder"); string filename = klientId + "_AB_" + HTBUtils.GetPathTimestamp() + ".pdf"; HTBUtils.SaveMemoryStream(stream, documentsFolder + filename); foreach (spAGReceipt rec in recordsList) { var doc = new tblDokument { // CollectionInvoice DokDokType = 25, DokCaption = "Auftragsbestätigung", DokInkAkt = rec.CustInkAktID, DokCreator = control.AutoUserId, DokAttachment = filename, DokCreationTimeStamp = DateTime.Now, DokChangeDate = DateTime.Now }; RecordSet.Insert(doc); doc = (tblDokument) HTBUtils.GetSqlSingleRecord("SELECT TOP 1 * FROM tblDokument ORDER BY DokID DESC", typeof (tblDokument)); if (doc != null) { RecordSet.Insert(new tblAktenDokumente {ADAkt = rec.CustInkAktID, ADDok = doc.DokID, ADAkttyp = 1}); } } } private static void TestMahnung() { new MahnungManager().GenerateMahnungen(control.AutoUserId); } private static void TestEmail() { try { tblServerSettings serverSettings = (tblServerSettings) HTBUtils.GetSqlSingleRecord("Select * from tblServerSettings", typeof (tblServerSettings)); // TODO: Add error handling for invalid arguments // To MailMessage mailMsg = new MailMessage(); mailMsg.To.Add("bledi1@yahoo.com"); // From MailAddress mailAddress = new MailAddress("E.C.P. Office " + serverSettings.ServerSystemMail); mailMsg.From = mailAddress; // Subject and Body mailMsg.Subject = "Ze Subject"; mailMsg.Body = "haha"; // Init SmtpClient and send SmtpClient smtpClient = new SmtpClient(serverSettings.ServerSMTP); System.Net.NetworkCredential credentials = new System.Net.NetworkCredential(serverSettings.ServerSMTPUser, serverSettings.ServerSMTPPW); smtpClient.Credentials = credentials; smtpClient.Send(mailMsg); } catch (Exception ex) { Console.WriteLine(ex.Message); } Console.Read(); } private static void TestFormPostFromEmail() { string htmlEmail = "<html>" + "<head>" + "<title>Test</title>" + "</head>" + "<body>" + " <a href=\"http://localhost/v2/intranetx/auftraggeber/AuftraggeberExtension.aspx?params=" + HTBUtils.EncodeTo64("AG=41,1234") + "\"> check params </a>" + "</body>" + "</html>"; IHTBEmail email = ServiceFactory.Instance.GetService<IHTBEmail>(); email.SendGenericEmail(HTBUtils.GetConfigValue("Default_EMail_Addr"), "test form data", htmlEmail); } private static void TestExtensionRequest() { string[] wtimeString = control.KlientNotificationTime.Split(':'); int wrunHour = Convert.ToInt16(wtimeString[0]); int wrunMin = Convert.ToInt16(wtimeString[1]); DateTime wrunTime = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, wrunHour, wrunMin, 0); DateTime now = DateTime.Now; TimeSpan wrunSpan = now.Subtract(wrunTime); if (wrunSpan.TotalMinutes >= 1) { string extCriteria = "AktIntExtIsRequestSent = 0 and AktIntExtApprovedDate = '01.01.1900' AND AktIntExtDeniedDate = '01.01.1900'"; String agQuery = "SELECT AuftraggeberId as[IntValue], AKTIntAGSB AS [StringValue] FROM qryAktenIntExtension WHERE " + extCriteria + " GROUP BY AuftraggeberId, AKTIntAGSB"; ArrayList agList = HTBUtils.GetSqlRecords(agQuery, typeof (SingleValue)); IHTBEmail email = ServiceFactory.Instance.GetService<IHTBEmail>(); RecordSet set = new RecordSet(); foreach (SingleValue agSB in agList) { if (agSB.StringValue.Trim() != string.Empty) { // make sure we have not already sent a request to this auftraggeber agQuery = "SELECT * FROM tblCommunicationLog " + " WHERE ComLogAuftraggeberID = " + agSB.IntValue + " AND ComLogAuftraggeberSB = '" + agSB.StringValue + "'" + " AND ComLogType = " + tblCommunicationLog.COMMUNICATION_TYPE_EXTENSION_REQUEST + " AND ComLogDate BETWEEN '" + now.ToShortDateString() + " 00:00.000' AND '" + now.ToShortDateString() + " 23:59.999'"; tblCommunicationLog receiptLog = (tblCommunicationLog) HTBUtils.GetSqlSingleRecord(agQuery, typeof (tblCommunicationLog)); if (receiptLog == null) { qryAktenIntExtension ext = (qryAktenIntExtension) HTBUtils.GetSqlSingleRecord("SELECT * FROM qryAktenIntExtension WHERE AuftraggeberID = " + agSB.IntValue + " AND AKTIntAGSB = '" + agSB.StringValue + "' AND " + extCriteria, typeof (qryAktenIntExtension)); if (ext != null) { ArrayList emailAddressList = new ArrayList(); String body = GetAGExtensionRequestBody(ext); if (body != null) { ArrayList toList = new ArrayList(); toList.Add(HTBUtils.GetConfigValue("Default_EMail_Addr")); body = "TO: [" + ext.AKTIntKSVEMail + "]<BR>" + body; string[] toAddress = new string[toList.Count]; for (int i = 0; i < toList.Count; i++) toAddress[i] = toList[i].ToString(); email.SendGenericEmail(toAddress, "Verlängerungsanfrage", body, true); // insert log record so that we know when the receipt was sent receiptLog = new tblCommunicationLog(); receiptLog.ComLogAuftraggeberID = ext.AuftraggeberID; receiptLog.ComLogAuftraggeberSB = ext.AKTIntAGSB; receiptLog.ComLogType = tblCommunicationLog.COMMUNICATION_TYPE_EXTENSION_REQUEST; receiptLog.ComLogDate = DateTime.Now; set.InsertRecord(receiptLog); string extReqUpdate = "UPDATE qryAktenIntExtension set AktIntExtIsRequestSent = 1 WHERE AuftraggeberID = " + agSB.IntValue + " AND AKTIntAGSB = '" + ext.AKTIntAGSB + "'"; set.ExecuteNonQuery(extReqUpdate); } } } } } } } private static string GetAGExtensionRequestBody(qryAktenIntExtension ext) { StringBuilder sb = new StringBuilder(); if (ext != null) { StreamReader re = File.OpenText(HTBUtils.GetConfigValue("AG_Extension_Req_Text")); string input = null; while ((input = re.ReadLine()) != null) { sb.Append(input); } re.Close(); re.Dispose(); return sb.ToString().Replace("[name]", ext.AKTIntAGSB).Replace("[AG_EXTENSION_HREF]", HTBUtils.GetConfigValue("URL_Extension_Req") + HTBUtils.EncodeTo64("AG=" + ext.AuftraggeberID + "&AGSB=" + ext.AKTIntAGSB)); } return null; } private static void TestNextStepManager() { var mgr = new NextStepManager(); mgr.GenerateIntNextStep(); mgr.GenerateMeldeNextStep(); } private static void TestZwischenbericht() { int aktId = 22127; qryCustInkAkt akt = (qryCustInkAkt) HTBUtils.GetSqlSingleRecord("SELECT * FROM qryCustInkAkt WHERE CustInkAktID = " + aktId, typeof (qryCustInkAkt)); if (akt != null) { ArrayList aktionsList = new ArrayList(); #region Load Records ArrayList interventionAktions = new ArrayList(); ArrayList invoiceList = HTBUtils.GetSqlRecords("SELECT * FROM tblCustInkAktInvoice WHERE InvoiceCustInkAktId = " + aktId, typeof (tblCustInkAktInvoice)); ArrayList inkassoAktions = HTBUtils.GetSqlRecords("SELECT * FROM qryCustInkAktAktionen WHERE CustInkAktAktionAktID = " + aktId + " ORDER BY CustInkAktAktionDate", typeof (qryCustInkAktAktionen)); tblAktenInt intAkt = (tblAktenInt) HTBUtils.GetSqlSingleRecord("SELECT * FROM tblAktenInt WHERE AktIntCustInkAktID = " + aktId + " ORDER BY AktIntID DESC", typeof (tblAktenInt)); if (intAkt != null) interventionAktions = HTBUtils.GetSqlRecords("SELECT * FROM qryInktAktAction WHERE AktIntActionAkt = " + intAkt.AktIntID + " ORDER BY AktIntActionDate DESC", typeof (qryInktAktAction)); #endregion #region CombineActions foreach (qryCustInkAktAktionen inkAction in inkassoAktions) aktionsList.Add(new InkassoActionRecord(inkAction, intAkt)); foreach (qryInktAktAction intAction in interventionAktions) aktionsList.Add(new InkassoActionRecord(intAction, intAkt)); aktionsList.Sort(new InkassoActionRecordComparer()); #endregion #region Send Zwischenbericht /* HTBReports.Zwischenbericht mahMgr = new HTBReports.Zwischenbericht(); using (MemoryMappedFile mmf = MemoryMappedFile.CreateNew("Zwischenbericht" + akt.CustInkAktID + ".pdf", 5000000)) { using (MemoryMappedViewStream stream = mmf.CreateViewStream()) { mahMgr.GenerateZwischenbericht(akt, aktionsList, "TEST text here", stream); HTBEmail email = new HTBEmail(); email.SendKlientReceipt(new string[]{"b.bitri@ecp.or.at"}, "here it is", mmf.CreateViewStream()); } } */ #endregion #region Save Zwischenbericht to file string fileName = "c:/temp/Zwischenbericht.pdf"; var mahMgr = new Zwischenbericht(); mahMgr.GenerateZwischenbericht(akt, aktionsList, "das ist ein test bericht... bla bla test hob i g'sogt!", new FileStream(fileName, FileMode.OpenOrCreate)); var proc = new Process(); proc.StartInfo.FileName = fileName; proc.Start(); #endregion } } private static void TestKlientbericht() { int klientId = 13439; ArrayList aktList = HTBUtils.GetSqlRecords("SELECT * FROM qryCustInkAkt WHERE KlientId = " + klientId, typeof (qryCustInkAkt)); string fileName = "c:/temp/Klientbericht.pdf"; var rpt = new Zwischenbericht(); rpt.Open(new FileStream(fileName, FileMode.OpenOrCreate)); bool firstAkt = true; foreach (qryCustInkAkt akt in aktList) { if (akt != null) { ArrayList aktionsList = new ArrayList(); #region Load Records ArrayList interventionAktions = new ArrayList(); ArrayList invoiceList = HTBUtils.GetSqlRecords("SELECT * FROM tblCustInkAktInvoice WHERE InvoiceCustInkAktId = " + akt.CustInkAktID, typeof (tblCustInkAktInvoice)); ArrayList inkassoAktions = HTBUtils.GetSqlRecords("SELECT * FROM qryCustInkAktAktionen WHERE CustInkAktAktionAktID = " + akt.CustInkAktID + " ORDER BY CustInkAktAktionDate", typeof (qryCustInkAktAktionen)); tblAktenInt intAkt = (tblAktenInt) HTBUtils.GetSqlSingleRecord("SELECT * FROM tblAktenInt WHERE AktIntCustInkAktID = " + akt.CustInkAktID + " ORDER BY AktIntID DESC", typeof (tblAktenInt)); if (intAkt != null) { interventionAktions = HTBUtils.GetSqlRecords("SELECT * FROM qryInktAktAction WHERE AktIntActionAkt = " + intAkt.AktIntID + " ORDER BY AktIntActionDate DESC", typeof (qryInktAktAction)); if (intAkt.AKTIntMemo.Trim() != string.Empty) { InkassoActionRecord action = new InkassoActionRecord(); action.ActionDate = DateTime.Now; action.ActionCaption = "Interventionsmemo:"; action.ActionMemo = intAkt.AKTIntMemo; action.IsOnlyMemo = true; aktionsList.Add(action); } } #endregion #region CombineActions foreach (qryCustInkAktAktionen inkAction in inkassoAktions) aktionsList.Add(new InkassoActionRecord(inkAction, intAkt)); foreach (qryInktAktAction intAction in interventionAktions) aktionsList.Add(new InkassoActionRecord(intAction, intAkt)); aktionsList.Sort(new InkassoActionRecordComparer()); #endregion #region Generate KLientbericht if (!firstAkt) { rpt.NewPage(); } else { firstAkt = false; } rpt.GenerateZwischenbericht(akt, aktionsList, "", null, false); #endregion } } rpt.PrintFooter(); rpt.CloseReport(); #region Show PDF File var proc = new Process(); proc.StartInfo.FileName = fileName; proc.Start(); #endregion } private static void TestUebergabeAkten() { ArrayList aktList = HTBUtils.GetSqlRecords("SELECT * FROM qryAkten ", typeof (qryAkten)); #region Save Uebergabeakten to file string fileName = "c:/temp/UebergabenAkten.pdf"; UebergabenAkten mahMgr = new UebergabenAkten(); mahMgr.GenerateUebergabenAktenPDF(aktList, new FileStream(fileName, FileMode.OpenOrCreate)); Process proc = new Process(); proc.StartInfo.FileName = fileName; proc.Start(); #endregion } private static void TestExcel() { new HTBAktLayer.AktUtils(22155).SendInkassoPackageToLawyer(new HTBEmailAttachment(ReportFactory.GetZwischenbericht(22155), "Zwischenbericht.pdf", "Application/pdf")); } private static void TestMissingBeleg() { var sqlWhere = "WHERE (KbMissReceivedDate IS NULL OR KbMissReceivedDate = '01.01.1900') "; var missingBelegUserList = HTBUtils.GetSqlRecords("SELECT distinct (KbMissUser) IntValue FROM tblKassaBlockMissingNr " + sqlWhere, typeof (SingleValue)); foreach (SingleValue missingUserIdRec in missingBelegUserList) { var missingRec = (tblKassaBlockMissingNr) HTBUtils.GetSqlSingleRecord("SELECT TOP 1 * FROM tblKassaBlockMissingNr " + sqlWhere + " AND KbMissUser = " + missingUserIdRec.IntValue + " ORDER BY KbMissDate DESC", typeof (tblKassaBlockMissingNr)); if ((DateTime.Now.Subtract(missingRec.KbMissDate)).Days >= 7) { var user = (tblUser) HTBUtils.GetSqlSingleRecord("SELECT * FROM tblUser WHERE UserID = " + missingRec.KbMissUser, typeof (tblUser)); user.UserStatus = 0; RecordSet.Update(user); ServiceFactory.Instance.GetService<IHTBEmail>().SendGenericEmail(new string[] {HTBUtils.GetConfigValue("Default_EMail_Addr"), "b.bitri@ecp.or.at"}, "Login gesperrt für Benutzer: " + user.UserVorname + " " + user.UserNachname, "Belege fehlen"); #region Notify when last beleg in block gets used #endregion } } } private static void TestRV() { var akt = (qryCustInkAkt) HTBUtils.GetSqlSingleRecord("SELECT * FROM qryCustInkAkt WHERE CustInkAktID = 22127", typeof (qryCustInkAkt)); var ms = new MemoryStream(); var rpt = new Ratenansuchen(); rpt.GenerateRatenansuchen(akt, ms, true); FileStream fs = File.OpenWrite("c:\\temp\\RV.pdf"); // ms.Seek(0, SeekOrigin.Begin); // ms.WriteTo(fs); fs.Write(ms.ToArray(), 0, ms.ToArray().Length); fs.Close(); fs.Dispose(); Process.Start("c:\\temp\\RV.pdf"); } #region RoutePlaner private static readonly RoutePlanerManager rpManager = new RoutePlanerManager(9999, true, "123"); private static void TestRoutePlanner() { rpManager.Clear(); string aktIdList = "146241,146240,146239,146238,146237,146236,146235,146234,146233,146232,146231,146230,146229,146228,146227,146226,146225,146221,146220,146219,146218,146217,146216,146215,146214,146213,146212,146205,146204,146203"; // string aktIdList = "146241,146240,146239,146238,146237,146236,146235,146234,146233,146232,146231,146230,146229"; if (aktIdList.Trim().Length > 0) { string qryAktCommand = "SELECT * FROM dbo.qryAktenInt WHERE AktIntID in (" + aktIdList + ")"; ArrayList aktenList = HTBUtils.GetSqlRecords(qryAktCommand, typeof (qryAktenInt)); LoadAddresses(aktenList); rpManager.CalculateBestRoute(); Console.WriteLine("LOCATIONS\n===========================\n"); foreach (City city in rpManager.Cities) { Console.WriteLine(city.Address.ID + "&nbsp;&nbsp;" + city.Address.Address + "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;LAT:" + city.Location.Locations[0].Latitude + "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;LGN:" + city.Location.Locations[0].Longitude + "<br>"); } Console.WriteLine("\nROADS\n===========================\n"); foreach (Road road in rpManager.Roads) { Console.WriteLine(road.From.Address.ID + "&nbsp;&nbsp;" + road.From.Address.Address + " =====> " + road.To.Address.ID + "&nbsp;&nbsp;" + road.To.Address + "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;" + road.Distance); } } } private static void LoadAddresses(ArrayList akten) { foreach (qryAktenInt akt in akten) { var address = new StringBuilder(HTBUtils.ReplaceStringAfter(HTBUtils.ReplaceStringAfter(akt.GegnerLastStrasse, " top ", ""), "/", "")); address.Append(","); address.Append(akt.GegnerLastZip); address.Append(","); address.Append(akt.GegnerLastOrt); address.Append(",österreich"); rpManager.AddAddress(new AddressWithID(akt.AktIntID, address.ToString())); } } #endregion private static void TestLawyerEmail() { } private static void TestSerilization() { var addr = new AddressWithID(100, "some street"); addr.SuggestedAddresses.Add(new AddressLocation(new AddressWithID(200, "bla bla"), new GeocodeLocation[] { new GeocodeLocation { Latitude = 0, Longitude = 1 } })); string str = HTBUtils.SerializeObject(addr, typeof (AddressWithID)); } public static void ProcessDir(string sourceDir) { // Process the list of files found in the directory. string[] fileEntries = Directory.GetFiles(sourceDir); foreach (string fileName in fileEntries) { if (sourceDir != "C:\\NintendoDS" && sourceDir != "C:\\NintendoDS\\AllFiles") { if (fileName.ToLower().EndsWith(".zip")) { try { File.Copy(fileName, "C:\\NintendoDS\\AllFiles\\" + sourceDir.Substring(sourceDir.LastIndexOf("\\")) + ".zip"); } catch (Exception e) { throw e; } Console.WriteLine(fileName.Substring(fileName.LastIndexOf("\\"))); } else if (fileName.ToLower().EndsWith(".rar")) { try { File.Copy(fileName, "C:\\NintendoDS\\AllFiles\\" + sourceDir.Substring(sourceDir.LastIndexOf("\\")) + ".rar"); } catch (Exception e) { throw e; } Console.WriteLine(fileName.Substring(fileName.LastIndexOf("\\"))); } else { for (int i = 0; i < 99; i++) { string ext = GetRarFileExtension(i); if (fileName.ToLower().EndsWith(ext)) { try { File.Copy(fileName, "C:\\NintendoDS\\AllFiles\\" + sourceDir.Substring(sourceDir.LastIndexOf("\\")) + "." + ext); } catch (Exception e) { throw e; } Console.WriteLine(fileName.Substring(fileName.LastIndexOf("\\"))); } } } } } // Recurse into subdirectories of this directory. string[] subdirEntries = Directory.GetDirectories(sourceDir); foreach (string subdir in subdirEntries) // Do not iterate through reparse points if ((File.GetAttributes(subdir) & FileAttributes.ReparsePoint) != FileAttributes.ReparsePoint) ProcessDir(subdir); } public static void ProcessDir2(string sourceDir) { // Process the list of files found in the directory. string[] fileEntries = Directory.GetFiles(sourceDir); foreach (string fileName in fileEntries) { if (sourceDir != "C:\\NintendoDS\\Unzip" && sourceDir != "C:\\NintendoDS\\Unzip\\Games") { if (fileName.ToLower().EndsWith(".nds")) { try { string fname = sourceDir.Substring(sourceDir.LastIndexOf("\\") + 1); fname = fname.Substring(fname.IndexOf("_") + 1); fname = fname.Substring(0, fname.LastIndexOf("_")); File.Copy(fileName, "C:\\NintendoDS\\Unzip\\Games\\" + fname + ".nds"); } catch (Exception) { //throw e; } Console.WriteLine(fileName.Substring(fileName.LastIndexOf("\\"))); } } } // Recurse into subdirectories of this directory. string[] subdirEntries = Directory.GetDirectories(sourceDir); foreach (string subdir in subdirEntries) // Do not iterate through reparse points if ((File.GetAttributes(subdir) & FileAttributes.ReparsePoint) != FileAttributes.ReparsePoint) ProcessDir2(subdir); } private static string GetRarFileExtension(int idx) { return (idx < 10) ? "r0" + idx : "r" + idx; } private static void TestFtp() { HTBSftp.SendFile("c:/temp/Mahnung.xml"); } private static void FixAllAE() { var list = new List<AeCountRecord>(); using (StreamWriter file = new System.IO.StreamWriter(@"C:\temp\AktivResults.txt")) { foreach (string f in Directory.GetFiles("C:\\temp\\bledi_aktiv\\test")) // foreach (string f in Directory.GetFiles("C:\\temp\\bledi_aktiv")) { if (f.EndsWith(".txt")) { Console.WriteLine(f); FixAE(file, list, f); } } foreach (var rec in list) { // file.Write(rec.dateList[0] + "\t" + rec.caption + "\t" + (rec.count - 1)); // for (int i = 0; i < rec.priceList.Count; i++ ) // { // if(i > 0) // file.Write("\t" + rec.dateList[i] + " "+rec.priceList[i]); // else // file.Write("\t" + rec.priceList[i]); // } // file.WriteLine(""); for (int i = 0; i < rec.priceList.Count; i++) { double price = 0; try { price = Convert.ToDouble(rec.priceList[i].Replace(",", ".")); } catch (Exception) { price = 0; } if (price > 0) file.WriteLine(rec.dateList[i] + "\t" + rec.caption + "\t" + (rec.count - 1) + "\t" + rec.priceList[i]); } } } } private static void FixAE(StreamWriter file, List<AeCountRecord> list, string fileName = null) { if (fileName == null) fileName = @"c:\temp\aeshit\2\aeshit.txt"; string text = HTBUtils.GetFileText(fileName); var sb = new StringBuilder(); string dateText = "Salzburg, am "; bool lookForAktivNumber = true; string startToken = "Unser AZ: "; string endToken = "Ihr AZ: "; if (lookForAktivNumber) { startToken = "Ihr AZ:"; endToken = "Anschrifterhebung:"; } string priceTextStart = "Kosten der Erhebung € "; string priceTextEnd = ","; int dateIdx = text.IndexOf(dateText); string dateString = text.Substring(dateIdx + dateText.Length, 10); int startIdx = text.IndexOf(startToken); startIdx += startToken.Length; int endIdx = text.IndexOf(endToken, startIdx); int startPriceIdx = text.IndexOf(priceTextStart, startIdx); startPriceIdx += priceTextStart.Length; int endPriceIdx = text.IndexOf(priceTextEnd, startPriceIdx) + 3; // cent ,00 // Console.WriteLine("Fixing AE"); Console.WriteLine("Text Length: " + text.Length); while (startIdx > 10 && endIdx > startIdx) { //Console.WriteLine("[ " + startIdx +" - " +(endIdx - startIdx)+" ]"); string token = text.Substring(startIdx, endIdx - startIdx - 1).Trim(); string price = text.Substring(startPriceIdx, endPriceIdx - startPriceIdx).Trim(); bool found = false; AeCountRecord aeRec = null; foreach (var rec in list) { if (rec.caption.Equals(token)) { aeRec = rec; } } if (aeRec == null) list.Add(new AeCountRecord(token, price, dateString)); else aeRec.Increment(price, dateString); startIdx = text.IndexOf(startToken, endIdx); startIdx += startToken.Length; endIdx = text.IndexOf(endToken, startIdx); startPriceIdx = text.IndexOf(priceTextStart, endPriceIdx); startPriceIdx += priceTextStart.Length; endPriceIdx = text.IndexOf(priceTextEnd, startPriceIdx) + 3; } //Console.WriteLine(sb.ToString()); Console.WriteLine("DONE!"); } private static void TestProtokol() { // ProtocolId Reposession (mercedes): 2237 // ProtocolId Reposession: 2244 // ProtocolId Collection: 2245 //var protocol = (tblProtokol) HTBUtils.GetSqlSingleRecord("SELECT TOP 1 * FROM tblProtokol where protokolid = 2244 order by ProtokolID DESC", typeof (tblProtokol)); //var protocol = (tblProtokol) HTBUtils.GetSqlSingleRecord("SELECT TOP 1 * FROM tblProtokol where aktintid = 221508 order by ProtokolID DESC", typeof (tblProtokol)); var protocol = (tblProtokol)HTBUtils.GetSqlSingleRecord("SELECT TOP 1 * FROM tblProtokol order by ProtokolID DESC", typeof(tblProtokol)); //protocol.ProtokolAkt = 221504; // test var akt = (qryAktenInt) HTBUtils.GetSqlSingleRecord("SELECT * FROM qryAktenInt WHERE AktIntID = " + protocol.ProtokolAkt, typeof (qryAktenInt)); var action = (qryAktenIntActionWithType) HTBUtils.GetSqlSingleRecord("SELECT * FROM qryAktenIntActionWithType WHERE AktIntActionAkt = " + akt.AktIntID + " and AktIntActionIsInternal = 0 ORDER BY AktIntActionTime DESC", typeof (qryAktenIntActionWithType)); var protokolUbername = (tblProtokolUbername)HTBUtils.GetSqlSingleRecord($"SELECT * FROM tblProtokolUbername WHERE UbernameAktIntID = { protocol.ProtokolAkt } ORDER BY UbernameDatum DESC", typeof(tblProtokolUbername)); ArrayList docsList = HTBUtils.GetSqlRecords("SELECT * FROM qryDoksIntAkten WHERE AktIntID = " + akt.AktIntID, typeof(qryDoksIntAkten)); var fileName = "Protocol_" + protocol.ProtokolAkt + ".pdf"; string filepath = HTBUtils.GetConfigValue("DocumentsFolder") + fileName; FileStream ms = null; ms = File.Exists(filepath) ? new FileStream(filepath, FileMode.Truncate) : new FileStream(filepath, FileMode.Create); var rpt = new ProtokolTablet(); var emailAddresses = new List<string>(); emailAddresses.AddRange(HTBUtils.GetConfigValue("Office_Email").Split(' ')); emailAddresses.AddRange(akt.AuftraggeberEMail.Split(' ')); emailAddresses.AddRange(protocol.HandlerEMail.Split(' ')); ///* rpt.GenerateProtokol(akt, protocol, protokolUbername, action, ms, GlobalUtilArea.GetVisitedDates(akt.AktIntID), GlobalUtilArea.GetPosList(akt.AktIntID), docsList.Cast<Record>().ToList(), emailAddresses); //*/ //rpt.GenerateDealerProtokol(akt, protocol, ms, emailAddresses); ms.Close(); ms.Dispose(); Thread.Sleep(100); Process.Start(HTBUtils.GetConfigValue("DocumentsFolder").Replace("/", "\\") + fileName); } private static void TestWebServiceNewAkt_Debug() { var newAktService = new WsInkassoDebug.WsNewInkassoSoapClient(); var akt = new InkassoAkt { RechnungDatum = new DateTime(2013, 10, 18), RechnungNummer = "Rechnung Nr. 2013-224", RechnungReferencenummer = "", RechnungForderungOffen = 132, RechnungMahnKosten = 0, RechnungMemo = "", KlientAnrede = "Herr", KlientTitel = "", KlientVorname = "Anton Kraushofer", KlientNachname = "", KlientGeschlecht = 2, KlientStrasse = "Neugebäudeplatz 10", KlientPLZ = "3100", KlientOrt = "St. Pölten", KlientLKZ = "A", // KlientTelefonVorwahlLand = "43", // KlientTelefonVorwahl = "660", KlientTelefonNummer = "027422 7 65", KlientEMail = "office@fire-control.at", KlientBank = "Volksbank NÖ-Mitte", KlientKontonummer = "VBOEATWWNOM", KlientBLZ = "47150", KlientFirmenbuchnummer = "", // KlientVersicherungnummer = "Versicherung: 121241343434", // KlientPolizzennummer = "12 12 -21012091290", KlientAnschprechPartnerAnrede = "Frau", KlientAnschprechPartnerVorname = "Maria", KlientAnschprechPartnerNachname = "Mayr", KlientAnschprechPartnerGeburtsdatum = new DateTime(1990, 5, 6), KlientAnschprechPartnerTelefonNummer = "43 662 445566", KlientAnschprechPartnerEMail = "m.mayr@klientssite.at", // KlientMemo = "Disney aint paying lately.\nGots to collect!", SchuldnerAnrede = "", SchuldnerGeschlecht = 2, SchuldnerVorname = "", SchuldnerNachname = "KFZ - Sandisic", SchuldnerGeburtsdatum = DateTime.MinValue, SchuldnerLKZ = "AT", SchuldnerStrasse = "Gross Hain 31", SchuldnerPLZ = "3170", SchuldnerOrt = "Wien", // SchuldnerTelefonVorwahlLand = "43", // SchuldnerTelefonVorwahl = "1", SchuldnerTelefonNummer = "", SchuldnerEMail = "", SchuldnerMemo = "", WorkflowErsteMahnung = true, WorkflowErsteMahnungsfrist = 21, WorkflowIntervention = true, WorkflowInterventionsfrist = 21, WorkflowZweiteMahnung = true, WorkflowZweiteMahnungsfrist = 14, WorkflowDritteMahnung = true, WorkflowDritteMahnungsfrist = 14, WorkflowRechtsanwaltMahnung = true }; akt.Dokumente.Add(new InkassoAktDokument { DokumentBeschreibung = "Rechnung", DokumentURL = "http://localhost/v2/intranet/documents/files/22228_Kosten.xls" }); string newAktResponse = newAktService.CreateNewAkt(akt.ToXmlString()); //string newAktResponse = newAktService.CreateNewAkt(HTBUtils.GetFileText("C:\\temp\\TestAktData.txt")); Console.WriteLine(newAktResponse); } private static void TestWebServiceNewAkt() { var newAktService = new WsInkasso.WsNewInkassoSoapClient(); var akt = new InkassoAkt { RechnungDatum = DateTime.Now, RechnungNummer = "123 123", RechnungReferencenummer = "", RechnungForderungOffen = 100, RechnungMahnKosten = 10, RechnungMemo = "some memo", KlientAnrede = "Herr", KlientTitel = "Dr.", KlientVorname = "Mickey", KlientNachname = "Mouse", KlientGeschlecht = 1, KlientStrasse = "Rennbahnstrasse 10", KlientPLZ = "5020", KlientOrt = "Salzburg", KlientLKZ = "A", // KlientTelefonVorwahlLand = "43", // KlientTelefonVorwahl = "660", KlientTelefonNummer = "43 660 521144", KlientEMail = "b.bitri@ecp.or.at", KlientFirmenbuchnummer = "Firma: 123123123", // KlientVersicherungnummer = "Versicherung: 121241343434", // KlientPolizzennummer = "12 12 -21012091290", KlientAnschprechPartnerAnrede = "Frau", KlientAnschprechPartnerVorname = "Maria", KlientAnschprechPartnerNachname = "Mayr", KlientAnschprechPartnerGeburtsdatum = new DateTime(1990, 5, 6), // KlientAnschprechPartnerTelefonVorwahlLand = "43", // KlientAnschprechPartnerTelefonVorwahl = "662", KlientAnschprechPartnerTelefonNummer = "445566", KlientAnschprechPartnerEMail = "m.mayr@klientssite.at", // KlientMemo = "Disney aint paying lately.\nGots to collect!", SchuldnerAnrede = "Herr", SchuldnerGeschlecht = 1, SchuldnerVorname = "Franz", SchuldnerNachname = "Podolsky", SchuldnerGeburtsdatum = new DateTime(1980, 10, 4), SchuldnerLKZ = "A", SchuldnerStrasse = "Aignerstrasse 11", SchuldnerPLZ = "1010", SchuldnerOrt = "Wien", // SchuldnerTelefonVorwahlLand = "43", // SchuldnerTelefonVorwahl = "1", SchuldnerTelefonNummer = "20520", SchuldnerEMail = "f.podolskly@schuldnerdomain.at", SchuldnerMemo = "Sie vaehrt ein 100000 Euro Auto", WorkflowErsteMahnung = true, WorkflowErsteMahnungsfrist = 12, WorkflowIntervention = true, WorkflowInterventionsfrist = 21, WorkflowZweiteMahnung = true, WorkflowZweiteMahnungsfrist = 8, WorkflowDritteMahnung = true, WorkflowDritteMahnungsfrist = 15, WorkflowRechtsanwaltMahnung = true }; akt.Dokumente.Add(new InkassoAktDokument { DokumentBeschreibung = "Rechnung", DokumentURL = "http://localhost/v2/intranet/documents/files/22228_Kosten.xls" }); // string newAktResponse = newAktService.CreateNewAkt(akt.ToXmlString()); string newAktResponse = newAktService.CreateNewAkt(HTBUtils.GetFileText("C:\\temp\\TestAktData.txt")); Console.WriteLine(newAktResponse); } private static void TestWebServiceAktStatus() { var newAktService = new WsInkasso.WsNewInkassoSoapClient(); string response = newAktService.GetAktStatus(22225); Console.WriteLine(response); var ds = new DataSet(); ds.ReadXml(new StringReader(response)); var status = new InkassoAktStatusResponse(); foreach (DataTable tbl in ds.Tables) { if (tbl.TableName.ToUpper().Trim() == typeof (InkassoAktStatusResponse).Name.ToUpper()) { foreach (DataRow dr in tbl.Rows) // there should be only one row but one never knows status.LoadFromDataRow(dr); } if (tbl.TableName.ToUpper().Trim() == typeof (Aktion).Name.ToUpper()) { foreach (DataRow dr in tbl.Rows) { var rec = new Aktion(); rec.LoadFromDataRow(dr); status.Aktionen.Add(rec); } } } Console.WriteLine("CollectionInvoice Memo: " + status.Inkassomemo); Console.WriteLine("Intervention Memo: " + status.Interventionsmemo); foreach (Aktion aktion in status.Aktionen) { Console.WriteLine(aktion.AktionDatum.ToShortDateString() + " " + aktion.AktionDatum.ToShortTimeString() + " " + aktion.AktionBeschreibung + " " + aktion.AktionMemo); } } private static void TestWebServiceNewAktProduction() { var newAktService = new WsInkassoProduction.WsNewInkassoSoapClient(); var akt = new InkassoAkt { RechnungDatum = new DateTime(2013, 10, 18), RechnungNummer = "Rechnung Nr. 2013-224", RechnungReferencenummer = "", RechnungForderungOffen = 132, RechnungMahnKosten = 0, RechnungMemo = "", KlientAnrede = "Herr", KlientTitel = "", KlientVorname = "Anton Kraushofer", KlientNachname = "", KlientGeschlecht = 2, KlientStrasse = "Neugebäudeplatz 10", KlientPLZ = "3100", KlientOrt = "St. Pölten", KlientLKZ = "A", // KlientTelefonVorwahlLand = "43", // KlientTelefonVorwahl = "660", KlientTelefonNummer = "027422 7 65", KlientEMail = "office@fire-control.at", KlientBank = "Volksbank NÖ-Mitte", KlientKontonummer = "VBOEATWWNOM", KlientBLZ = "47150", KlientFirmenbuchnummer = "", // KlientVersicherungnummer = "Versicherung: 121241343434", // KlientPolizzennummer = "12 12 -21012091290", KlientAnschprechPartnerAnrede = "Frau", KlientAnschprechPartnerVorname = "Maria", KlientAnschprechPartnerNachname = "Mayr", KlientAnschprechPartnerGeburtsdatum = new DateTime(1990, 5, 6), KlientAnschprechPartnerTelefonNummer = "43 662 445566", KlientAnschprechPartnerEMail = "m.mayr@klientssite.at", // KlientMemo = "Disney aint paying lately.\nGots to collect!", SchuldnerAnrede = "", SchuldnerGeschlecht = 2, SchuldnerVorname = "", SchuldnerNachname = "KFZ - Sandisic", SchuldnerGeburtsdatum = DateTime.MinValue, SchuldnerLKZ = "AT", SchuldnerStrasse = "Gross Hain 31", SchuldnerPLZ = "3170", SchuldnerOrt = "Wien", // SchuldnerTelefonVorwahlLand = "43", // SchuldnerTelefonVorwahl = "1", SchuldnerTelefonNummer = "", SchuldnerEMail = "", SchuldnerMemo = "", WorkflowErsteMahnung = true, WorkflowErsteMahnungsfrist = 21, WorkflowIntervention = true, WorkflowInterventionsfrist = 21, WorkflowZweiteMahnung = true, WorkflowZweiteMahnungsfrist = 14, WorkflowDritteMahnung = true, WorkflowDritteMahnungsfrist = 14, WorkflowRechtsanwaltMahnung = true }; akt.Dokumente.Add(new InkassoAktDokument { DokumentBeschreibung = "Rechnung", DokumentURL = "http://localhost/v2/intranet/documents/files/22228_Kosten.xls" }); //string newAktResponse = newAktService.CreateNewAkt(akt.ToXmlString()); string newAktResponse = newAktService.CreateNewAkt(HTBUtils.GetFileText("C:\\temp\\TestAktData.txt")); Console.WriteLine(akt.ToXmlString()); Console.WriteLine(newAktResponse); } private static void TestWebServiceAktStatusProduction() { var newAktService = new WsInkassoProduction.WsNewInkassoSoapClient(); string response = newAktService.GetAktStatus(32519); Console.WriteLine(response); var ds = new DataSet(); ds.ReadXml(new StringReader(response)); var status = new InkassoAktStatusResponse(); foreach (DataTable tbl in ds.Tables) { if (tbl.TableName.ToUpper().Trim() == typeof (InkassoAktStatusResponse).Name.ToUpper()) { foreach (DataRow dr in tbl.Rows) // there should be only one row but one never knows status.LoadFromDataRow(dr); } if (tbl.TableName.ToUpper().Trim() == typeof (Aktion).Name.ToUpper()) { foreach (DataRow dr in tbl.Rows) { var rec = new Aktion(); rec.LoadFromDataRow(dr); status.Aktionen.Add(rec); } } if (tbl.TableName.ToUpper().Trim() == typeof (InkassoAktDokument).Name.ToUpper()) { foreach (DataRow dr in tbl.Rows) { var rec = new InkassoAktDokument(); rec.LoadFromDataRow(dr); status.Dokumente.Add(rec); } } } TextWriter tw = new StreamWriter("c:/temp/InkassoAktStatusResponse.txt"); tw.Write(status.ToXmlString()); tw.Close(); tw.Dispose(); Console.WriteLine("CollectionInvoice Memo: " + status.Inkassomemo); Console.WriteLine("Intervention Memo: " + status.Interventionsmemo); foreach (Aktion aktion in status.Aktionen) { Console.WriteLine(aktion.AktionDatum.ToShortDateString() + " " + aktion.AktionDatum.ToShortTimeString() + " " + aktion.AktionBeschreibung + " " + aktion.AktionMemo); } } private static InkassoAkt GetAkt(string xmlData) { var ds = new DataSet(); ds.ReadXml(new StringReader(xmlData)); var rec = new InkassoAkt(); foreach (DataTable tbl in ds.Tables) { if (tbl.TableName.ToUpper().Trim() == typeof(InkassoAkt).Name.ToUpper().Trim()) { foreach (DataRow dr in tbl.Rows) { rec.LoadFromDataRow(dr); } } else if (tbl.TableName.ToUpper().Trim() == typeof(InkassoAktDokument).Name.ToUpper().Trim()) { foreach (DataRow dr in tbl.Rows) { var rate = new InkassoAktDokument(); rate.LoadFromDataRow(dr); rec.Dokumente.Add(rate); } } } return rec; } private static void TestFinancialPmt() { double interest = 12 / 12; double nper = 4; double pv = 6122.67; double fv = 0; // future value of the load double pmt = 20; Console.WriteLine("[I: "+interest+"] [nper: "+nper+"] [pv: "+pv+"]"); Console.WriteLine("PMT: " + HTBUtils.FormatCurrencyNumber(Microsoft.VisualBasic.Financial.Pmt(interest, nper, -pv))); Console.WriteLine("PMT: " + Microsoft.VisualBasic.Financial.Pmt(interest, nper, -pv)); Console.WriteLine("PMT2: " + HTBUtils.FormatCurrencyNumber(pv*((interest*Math.Pow(1 + interest, nper))/(Math.Pow(1 + interest, nper) - 1)))); //Console.WriteLine("NPER: " + Financial.NPer(interest, pmt, -pv)); nper = Math.Log(1 - interest*pv/pmt)/Math.Log(1 + interest)*-1; Console.WriteLine("NPER2: " + HTBUtils.FormatCurrencyNumber(nper)); } private static void TestFinanacial_NumberOfInstallments() { const double balance = 6122.67; const double installmentAmount = 1950; const double annualInterestRate = .12; const double interestPeriod = 12; double numberOfInstallments = Microsoft.VisualBasic.Financial.NPer(annualInterestRate/interestPeriod, installmentAmount, -balance); double totalAmountToPay = numberOfInstallments * installmentAmount; double lastInstallment = totalAmountToPay - (installmentAmount*(int) numberOfInstallments); double totalInterest = totalAmountToPay - balance; Console.WriteLine("Total Amount To Pay: {0}", HTBUtils.FormatCurrency(totalAmountToPay)); Console.WriteLine("Number of installments: {0}", ((int)numberOfInstallments + 1)); Console.WriteLine("Last Installment: {0}", HTBUtils.FormatCurrency(lastInstallment)); Console.WriteLine("Total Interest: {0}", HTBUtils.FormatCurrency(totalInterest)); } private static void TestLogFileConverssion() { var directory = "C:\\temp\\ECP_LOGS"; var toName = directory+ "\\Good\\Access.log"; //tw.Write(text.Replace("\n", Environment.NewLine)); string[] fileEntries = Directory.GetFiles(directory); foreach (string fileName in fileEntries) { if (fileName.IndexOf(".log") > 0) { string text = HTBUtils.GetFileText(fileName); if (string.IsNullOrEmpty(text)) return; TextWriter tw = new StreamWriter(new FileStream(toName, FileMode.Append)); int dteIdxStart = text.IndexOf("["); while (dteIdxStart >= 0) { int dteIdxEnd = text.IndexOf("]", dteIdxStart); if (dteIdxEnd < 0) break; int ipIdxStart = dteIdxEnd + 2; int ipIdxEnd = text.IndexOf("-", ipIdxStart); if (ipIdxStart < 0) break; int nextLineIdx = text.IndexOf("[", dteIdxEnd); if (nextLineIdx < 0) break; try { string dateText = text.Substring(dteIdxStart + 1, dteIdxEnd - dteIdxStart - 6); string ipText = text.Substring(ipIdxStart, ipIdxEnd - ipIdxStart); string restText = text.Substring(ipIdxEnd + 1, nextLineIdx - ipIdxEnd - 1); string[] parts = dateText.Split(); string pattern = "yyyy-MM-dd"; DateTime dt; DateTime.TryParseExact(parts[0], pattern, null, DateTimeStyles.None, out dt); tw.Write(ipText); tw.Write("- anonymus ["); //tw.Write(dt.ToShortDateString() + ":" + parts[1]); tw.Write(dt.ToString("dd/MMM/yyyy", CultureInfo.InvariantCulture)); tw.Write(":" + parts[1]); tw.Write(" +0000]"); tw.Write(restText); if (!restText.EndsWith(Environment.NewLine)) tw.WriteLine(); dteIdxStart = text.IndexOf("[", dteIdxEnd); } catch (Exception) { int greatestReadIdx = dteIdxStart; if (greatestReadIdx > dteIdxEnd) greatestReadIdx = dteIdxEnd; if (greatestReadIdx > ipIdxStart) greatestReadIdx = ipIdxStart; if (greatestReadIdx > ipIdxEnd) greatestReadIdx = ipIdxEnd; if (greatestReadIdx > nextLineIdx) greatestReadIdx = nextLineIdx; //tw.Write(text.Substring(greatestReadIdx)); dteIdxStart = greatestReadIdx + 1; //break; } } tw.Close(); tw.Dispose(); } //new Process {StartInfo = {FileName = toName}}.Start(); //var lines = File.ReadAllLines(toName).Where(arg => !string.IsNullOrWhiteSpace(arg)); //File.WriteAllLines(fileName, lines); } } private static void TestErlagschein() { } private static void TestInterverntionAction() { try { int intAktEmailSentActionTypeId = HTBUtils.GetIntConfigValue("AktInt_EMail_Sent_Action_Type"); int intAktEmailNotSentActionTypeId = HTBUtils.GetIntConfigValue("AktInt_EMail_NOT_Sent_Action_Type"); tblControl control = HTBUtils.GetControlRecord(); HTBUtils.AddInterventionAction(147193, intAktEmailSentActionTypeId, "test EMail OK", control.DefaultSB); HTBUtils.AddInterventionAction(147193, intAktEmailNotSentActionTypeId, "test EMail NOT OK", control.DefaultSB); } catch (Exception e) { throw e; } } private static void TestLawyerMahnung() { //new LawyerMahnung().GenerateLawyerMahnungPdf(null, null); //var aktId = 22302; var aktId = 22301; var attachment = new HTBEmailAttachment(ReportFactory.GetZwischenbericht(aktId), "Zwischenbericht.pdf", "Application/pdf"); new AktUtils(aktId).SendInkassoPackageToLawyer(attachment, true, "c:/temp/lawyerTest/"); } } class AeCountRecord { public string caption; public int count; public List<string> priceList = new List<string>(); public List<string> dateList = new List<string>(); public AeCountRecord(string c, string p, string d) { caption = c; count = 1; priceList.Add(p); dateList.Add(d); } public void Increment(string price, string date) { count++; priceList.Add(price); dateList.Add(date); } } }
using Android.Content; using Android.Graphics; using Android.Graphics.Drawables; using Android.Views; using Android.Widget; using System; namespace AsNum.XFControls.Droid { /// <summary> /// http://www.netmite.com/android/mydroid/cupcake/frameworks/base/core/java/com/android/internal/widget/NumberPicker.java /// 不能正常使用, 构造函数居然在 AddView / OnViewAdded 后面执行,导致颜色设置无效 /// </summary> public class ColorNumberPicker : NumberPicker { private Color TextColor { get; } public ColorNumberPicker(Context ctx, Color textColor, Color dividerColor) : base(ctx) { this.TextColor = textColor; this.setDividerColor(dividerColor); } //public override void AddView(View child) { // base.AddView(child); // this.UpdateColor(child); //} //public override void AddView(View child, int index) { // base.AddView(child, index); // this.UpdateColor(child); //} //public override void AddView(View child, int index, ViewGroup.LayoutParams @params) { // base.AddView(child, index, @params); // this.UpdateColor(child); //} //public override void AddView(View child, int width, int height) { // base.AddView(child, width, height); // this.UpdateColor(child); //} //public override void AddView(View child, ViewGroup.LayoutParams @params) { // base.AddView(child, @params); // this.UpdateColor(child); //} //public override void OnViewAdded(View child) { // base.OnViewAdded(child); // this.UpdateColor(child); //} private void UpdateColor(View v) { if (this.TextColor == null) return; if (v is EditText) { var edt = (EditText)v; edt.SetTextColor(this.TextColor); edt.TextSize = 25; } } public void setDividerColor(Color color) { if (color == null) return; try { var fs = base.Class.GetDeclaredFields(); var f = base.Class.GetDeclaredField("mSelectionDivider"); f.Accessible = true; var d = (Drawable)f.Get(this); d.SetColorFilter(Color.Green, PorterDuff.Mode.SrcAtop); d.InvalidateSelf(); this.PostInvalidate(); // Drawable is dirty } catch (Exception) { } } } }
using System; using System.Collections; using System.Collections.Generic; using System.IO; using System.Runtime.InteropServices; using System.Windows.Forms; namespace W2___MixList { public partial class W2MixList : Form { public int IndexOfStruct = 0; public W2MixList() { InitializeComponent(); Read.ReadArquivo(); } public static IDictionary npcname = new Dictionary<string, string>(); public static int g_pRestante = 100; public static int[] Count = new int[100]; private void Form1_Load(object sender, EventArgs e) { npcname.Add("68", "Enhre"); npcname.Add("-1", "Nenhum"); npcname.Add("0", "Skill Alquimia"); npcname.Add("1", "Config. Soul"); npcname.Add("54", "Compositor Anct"); npcname.Add("56", "Combinação do Item_Arch"); npcname.Add("55", "Ailyn"); npcname.Add("67", "Alquimista Odin"); npcname.Add("66", "Dedekinto"); for (int i = 0; i < 100; i++) { if (Read.Npcs[0].npcs[i].face == -842150451) Read.Npcs[0].npcs[i].face = -1; if (Read.Npcs[0].npcs[i].face >= 0) g_pRestante--; if (Read.Npcs[0].npcs[i].Name == "����������������") { Read.Npcs[0].npcs[i].Name = "NoName"; } NPCList.Items.Add("Index(" + i + "): [" + Read.Npcs[0].npcs[i].face + "] - " + Read.Npcs[0].npcs[i].Name); // ITENS txtItemItens.Text = "0,0,0,0,0,0,0"; IndexOfStruct = 0; reqID.Text = IndexOfStruct.ToString(); txtStrdef.Text = "0"; txtAmount.Text = "0"; txtMin0.Text = "0"; txtMax0.Text = "0"; txtMin1.Text = "0"; txtMax1.Text = "0"; txtUnused.Text = "0"; txtUnused2.Text = "0"; txtMin2.Text = "0"; txtMax2.Text = "0"; txtUnk.Text = "0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 "; txtGold.Text = "0"; txtItem.Text = "0,0,0,0,0,0,0"; txtMapX.Text = "0"; txtMapY.Text = "0"; txtTipo.Text = "0x00"; txtItem1.Text = "0 0"; txtItem2.Text = "0 0"; txtItem3.Text = "0 0"; txtItem4.Text = "0 0"; txtItem5.Text = "0 0"; txtItem6.Text = "0 0"; txtItem7.Text = "0 0"; txtItem8.Text = "0 0"; nameNPC.Text = "Nenhum"; } for (int i = 0; i < 100; i++) { if (Read.Npcs[0].req[i].Item.sIndex < -2) { Read.Npcs[0].req[i].Item.sIndex = -1; // ITENS txtItemItens.Text = "0,0,0,0,0,0,0"; IndexOfStruct = 0; reqID.Text = IndexOfStruct.ToString(); txtStrdef.Text = "0"; txtAmount.Text = "0"; txtMin0.Text = "0"; txtMax0.Text = "0"; txtMin1.Text = "0"; txtMax1.Text = "0"; txtUnused.Text = "0"; txtUnused2.Text = "0"; txtMin2.Text = "0"; txtMax2.Text = "0"; txtUnk.Text = "0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 "; } RequestList.Items.Add("[" + i + "] " + " " + Read.Npcs[0].req[i].Item.sIndex.ToString()); } textFace.Text = "0"; restante.Text = ""+ g_pRestante + " / 100"; } private void lbNpc_SelectedIndexChanged(object sender, EventArgs e) // Ler dados do arquivo { var index = NPCList.SelectedIndex; textFace.Text = Read.Npcs[0].npcs[index].face.ToString(); txtGold.Text = Read.Npcs[0].npcs[index].Gold.ToString(); txtItem.Text = Read.Npcs[0].npcs[index].ItemSlot.sIndex.ToString() + "," + Read.Npcs[0].npcs[index].ItemSlot.sEffect[0].cEfeito.ToString() + "," + Read.Npcs[0].npcs[index].ItemSlot.sEffect[0].cValue.ToString() + "," + Read.Npcs[0].npcs[index].ItemSlot.sEffect[1].cEfeito.ToString() + "," + Read.Npcs[0].npcs[index].ItemSlot.sEffect[1].cValue.ToString() + "," + Read.Npcs[0].npcs[index].ItemSlot.sEffect[2].cEfeito.ToString() + "," + Read.Npcs[0].npcs[index].ItemSlot.sEffect[2].cValue.ToString(); txtMapX.Text = Read.Npcs[0].npcs[index].MapX.ToString(); txtMapY.Text = Read.Npcs[0].npcs[index].MapY.ToString(); txtTipo.Text = "0x"+Read.Npcs[0].npcs[index].Type.ToString("X"); txtItem1.Text = Read.Npcs[0].npcs[index].Item[0].Req.ToString() + " " + Read.Npcs[0].npcs[index].Item[0].Value.ToString(); txtItem2.Text = Read.Npcs[0].npcs[index].Item[1].Req.ToString() + " " + Read.Npcs[0].npcs[index].Item[1].Value.ToString(); txtItem3.Text = Read.Npcs[0].npcs[index].Item[2].Req.ToString() + " " + Read.Npcs[0].npcs[index].Item[2].Value.ToString(); txtItem4.Text = Read.Npcs[0].npcs[index].Item[3].Req.ToString() + " " + Read.Npcs[0].npcs[index].Item[3].Value.ToString(); txtItem5.Text = Read.Npcs[0].npcs[index].Item[4].Req.ToString() + " " + Read.Npcs[0].npcs[index].Item[4].Value.ToString(); txtItem6.Text = Read.Npcs[0].npcs[index].Item[5].Req.ToString() + " " + Read.Npcs[0].npcs[index].Item[5].Value.ToString(); txtItem7.Text = Read.Npcs[0].npcs[index].Item[6].Req.ToString() + " " + Read.Npcs[0].npcs[index].Item[6].Value.ToString(); txtItem8.Text = Read.Npcs[0].npcs[index].Item[7].Req.ToString() + " " + Read.Npcs[0].npcs[index].Item[7].Value.ToString(); // ITENS txtItemItens.Text = "0,0,0,0,0,0,0"; IndexOfStruct = 0; reqID.Text = IndexOfStruct.ToString(); txtStrdef.Text = "0"; txtAmount.Text = "0"; txtMin0.Text = "0"; txtMax0.Text = "0"; txtMin1.Text = "0"; txtMax1.Text = "0"; txtUnused.Text = "0"; txtUnused2.Text = "0"; txtMin2.Text = "0"; txtMax2.Text = "0"; nameNPC.Text = Read.Npcs[0].npcs[index].Name; txtUnk.Text = "0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 "; if (Read.Npcs[0].npcs[index].face == -842150451 || Read.Npcs[0].npcs[index].face == -1) { txtGold.Text = "0"; txtItem.Text = "0,0,0,0,0,0,0"; txtMapX.Text = "0"; txtMapY.Text = "0"; txtTipo.Text = "0x00"; txtItem1.Text = "0 0"; txtItem2.Text = "0 0"; txtItem3.Text = "0 0"; txtItem4.Text = "0 0"; txtItem5.Text = "0 0"; txtItem6.Text = "0 0"; txtItem7.Text = "0 0"; txtItem8.Text = "0 0"; } } private void button1_Click(object sender, EventArgs e) // Salvar dados e escrever arquivo { if (NPCList.SelectedIndex >= 0) { npcCompleto npc = Read.Npcs[0]; var index = NPCList.SelectedIndex; string[] split = txtItem.Text.Split(','); string[] split2 = txtItemItens.Text.Split(','); string[] split3 = txtItem1.Text.Split(' '); string[] split4 = txtItem2.Text.Split(' '); string[] split5 = txtItem3.Text.Split(' '); string[] split6 = txtItem4.Text.Split(' '); string[] split7 = txtItem5.Text.Split(' '); string[] split8 = txtItem6.Text.Split(' '); string[] split9 = txtItem7.Text.Split(' '); string[] split10 = txtItem8.Text.Split(' '); npc.npcs[index].Name = nameNPC.Text; npc.npcs[index].face = Convert.ToInt32(textFace.Text); npc.npcs[index].Gold = Convert.ToInt32(txtGold.Text); npc.npcs[index].MapX = Convert.ToInt32(txtMapX.Text); npc.npcs[index].MapY = Convert.ToInt32(txtMapY.Text); short intValue = Convert.ToInt16(txtTipo.Text, 16); npc.npcs[index].Type = intValue; npc.npcs[index].ItemSlot.sIndex = Convert.ToInt16(split[0]); npc.npcs[index].ItemSlot.sEffect[0].cEfeito = Convert.ToByte(split[1]); npc.npcs[index].ItemSlot.sEffect[0].cValue = Convert.ToByte(split[2]); npc.npcs[index].ItemSlot.sEffect[1].cEfeito = Convert.ToByte(split[3]); npc.npcs[index].ItemSlot.sEffect[1].cValue = Convert.ToByte(split[4]); npc.npcs[index].ItemSlot.sEffect[2].cEfeito = Convert.ToByte(split[5]); npc.npcs[index].ItemSlot.sEffect[2].cValue = Convert.ToByte(split[6]); npc.npcs[index].Item[0].Req = Convert.ToInt32(split3[0]); npc.npcs[index].Item[0].Value = Convert.ToInt32(split3[1]); npc.npcs[index].Item[1].Req = Convert.ToInt32(split4[0]); npc.npcs[index].Item[1].Value = Convert.ToInt32(split4[1]); npc.npcs[index].Item[2].Req = Convert.ToInt32(split5[0]); npc.npcs[index].Item[2].Value = Convert.ToInt32(split5[1]); npc.npcs[index].Item[3].Req = Convert.ToInt32(split6[0]); npc.npcs[index].Item[3].Value = Convert.ToInt32(split6[1]); npc.npcs[index].Item[4].Req = Convert.ToInt32(split7[0]); npc.npcs[index].Item[4].Value = Convert.ToInt32(split7[1]); npc.npcs[index].Item[5].Req = Convert.ToInt32(split8[0]); npc.npcs[index].Item[5].Value = Convert.ToInt32(split8[1]); npc.npcs[index].Item[6].Req = Convert.ToInt32(split9[0]); npc.npcs[index].Item[6].Value = Convert.ToInt32(split9[1]); npc.npcs[index].Item[7].Req = Convert.ToInt32(split10[0]); npc.npcs[index].Item[7].Value = Convert.ToInt32(split10[1]); //itens if (IndexOfStruct != 0 ) { npc.req[IndexOfStruct].Strdef = Convert.ToInt32(txtStrdef.Text); npc.req[IndexOfStruct].Amount = Convert.ToInt32(txtAmount.Text); string[] explode = txtItemItens.Text.Split(','); npc.req[IndexOfStruct].Item.sIndex = Convert.ToInt16(explode[0]); npc.req[IndexOfStruct].Item.sEffect[0].cEfeito = Convert.ToByte(explode[1]); npc.req[IndexOfStruct].Item.sEffect[0].cValue = Convert.ToByte(explode[2]); npc.req[IndexOfStruct].Item.sEffect[1].cEfeito = Convert.ToByte(explode[3]); npc.req[IndexOfStruct].Item.sEffect[1].cValue = Convert.ToByte(explode[4]); npc.req[IndexOfStruct].Item.sEffect[2].cEfeito = Convert.ToByte(explode[5]); npc.req[IndexOfStruct].Item.sEffect[2].cValue = Convert.ToByte(explode[6]); npc.req[IndexOfStruct].Mix[0].MinID = Convert.ToInt32(txtMin0.Text); npc.req[IndexOfStruct].Mix[0].MaxID = Convert.ToInt32(txtMax0.Text); npc.req[IndexOfStruct].Mix[1].MinID = Convert.ToInt32(txtMin1.Text); npc.req[IndexOfStruct].Mix[1].MaxID = Convert.ToInt32(txtMax1.Text); npc.req[IndexOfStruct].Mix[2].MinID = Convert.ToInt32(txtMin2.Text); npc.req[IndexOfStruct].Mix[2].MaxID = Convert.ToInt32(txtMax2.Text); npc.req[IndexOfStruct].Unused = Convert.ToInt32(txtUnused.Text); npc.req[IndexOfStruct].Unused_02 = Convert.ToInt32(txtUnused2.Text); string[] splitUnks = txtUnk.Text.Split(' '); for (int i = 0; i < 16; i++) { npc.req[IndexOfStruct].Unknow[i] = Convert.ToByte(splitUnks[i]); } } Read.SaveArquivo(npc); MessageBox.Show("Arquivo salvo com sucesso"); Reload(); } } private void button2_Click(object sender, EventArgs e) { var index = NPCList.SelectedIndex; string[] split = txtItem.Text.Split(','); string[] split2 = txtItemItens.Text.Split(','); string[] split3 = txtItem1.Text.Split(' '); string[] split4 = txtItem2.Text.Split(' '); string[] split5 = txtItem3.Text.Split(' '); string[] split6 = txtItem4.Text.Split(' '); string[] split7 = txtItem5.Text.Split(' '); string[] split8 = txtItem6.Text.Split(' '); string[] split9 = txtItem7.Text.Split(' '); string[] split10 = txtItem8.Text.Split(' '); npcCompleto npc = Read.Npcs[0]; if (Read.Npcs[0].npcs[index].Item[0].Req > 0 && Read.Npcs[0].npcs[index].Item[0].Req < 100) { var RequestStruct = Read.Npcs[0].npcs[index].Item[0].Req; IndexOfStruct = RequestStruct; reqID.Text = RequestStruct.ToString(); // ITENS txtItemItens.Text = Read.Npcs[0].req[RequestStruct].Item.sIndex.ToString() + "," + Read.Npcs[0].req[RequestStruct].Item.sEffect[0].cEfeito.ToString() + "," + Read.Npcs[0].req[index].Item.sEffect[0].cValue.ToString() + "," + Read.Npcs[0].req[index].Item.sEffect[1].cEfeito.ToString() + "," + Read.Npcs[0].req[index].Item.sEffect[1].cValue.ToString() + "," + Read.Npcs[0].req[index].Item.sEffect[2].cEfeito.ToString() + "," + Read.Npcs[0].req[index].Item.sEffect[2].cValue.ToString(); txtStrdef.Text = Read.Npcs[0].req[RequestStruct].Strdef.ToString(); txtAmount.Text = Read.Npcs[0].req[RequestStruct].Amount.ToString(); txtMin0.Text = npc.req[IndexOfStruct].Mix[0].MinID.ToString(); txtMax0.Text = npc.req[IndexOfStruct].Mix[0].MaxID.ToString(); txtMin1.Text = npc.req[IndexOfStruct].Mix[1].MinID.ToString(); txtMax1.Text = npc.req[IndexOfStruct].Mix[1].MaxID.ToString(); txtUnk.Text = String.Empty; for (int i = 0; i < 16; i++) { txtUnk.Text += npc.req[IndexOfStruct].Unknow[i] + " "; } txtMin2.Text = npc.req[IndexOfStruct].Mix[2].MinID.ToString(); txtMax2.Text = npc.req[IndexOfStruct].Mix[2].MaxID.ToString(); txtUnused.Text = npc.req[IndexOfStruct].Unused.ToString(); txtUnused2.Text = npc.req[IndexOfStruct].Unused_02.ToString(); } } private void txtItemItens_TextChanged(object sender, EventArgs e) { } private void button3_Click(object sender, EventArgs e) { { var index = NPCList.SelectedIndex; string[] split = txtItem.Text.Split(','); string[] split2 = txtItemItens.Text.Split(','); string[] split3 = txtItem1.Text.Split(' '); string[] split4 = txtItem2.Text.Split(' '); string[] split5 = txtItem3.Text.Split(' '); string[] split6 = txtItem4.Text.Split(' '); string[] split7 = txtItem5.Text.Split(' '); string[] split8 = txtItem6.Text.Split(' '); string[] split9 = txtItem7.Text.Split(' '); string[] split10 = txtItem8.Text.Split(' '); npcCompleto npc = Read.Npcs[0]; if (Read.Npcs[0].npcs[index].Item[1].Req > 0 && Read.Npcs[0].npcs[index].Item[1].Req < 100) { var RequestStruct = Read.Npcs[0].npcs[index].Item[1].Req; IndexOfStruct = RequestStruct; reqID.Text = RequestStruct.ToString(); // ITENS txtItemItens.Text = Read.Npcs[0].req[RequestStruct].Item.sIndex.ToString() + "," + Read.Npcs[0].req[RequestStruct].Item.sEffect[0].cEfeito.ToString() + "," + Read.Npcs[0].req[index].Item.sEffect[0].cValue.ToString() + "," + Read.Npcs[0].req[index].Item.sEffect[1].cEfeito.ToString() + "," + Read.Npcs[0].req[index].Item.sEffect[1].cValue.ToString() + "," + Read.Npcs[0].req[index].Item.sEffect[2].cEfeito.ToString() + "," + Read.Npcs[0].req[index].Item.sEffect[2].cValue.ToString(); txtStrdef.Text = Read.Npcs[0].req[RequestStruct].Strdef.ToString(); txtAmount.Text = Read.Npcs[0].req[RequestStruct].Amount.ToString(); txtMin0.Text = npc.req[IndexOfStruct].Mix[0].MinID.ToString(); txtMax0.Text = npc.req[IndexOfStruct].Mix[0].MaxID.ToString(); txtMin1.Text = npc.req[IndexOfStruct].Mix[1].MinID.ToString(); txtMax1.Text = npc.req[IndexOfStruct].Mix[1].MaxID.ToString(); txtMin2.Text = npc.req[IndexOfStruct].Mix[2].MinID.ToString(); txtMax2.Text = npc.req[IndexOfStruct].Mix[2].MaxID.ToString(); txtUnk.Text = String.Empty; for (int i = 0; i < 16; i++) { txtUnk.Text += npc.req[IndexOfStruct].Unknow[i] + " "; } txtUnused.Text = npc.req[IndexOfStruct].Unused.ToString(); txtUnused2.Text = npc.req[IndexOfStruct].Unused_02.ToString(); } } } private void button4_Click(object sender, EventArgs e) { { var index = NPCList.SelectedIndex; string[] split = txtItem.Text.Split(','); string[] split2 = txtItemItens.Text.Split(','); string[] split3 = txtItem1.Text.Split(' '); string[] split4 = txtItem2.Text.Split(' '); string[] split5 = txtItem3.Text.Split(' '); string[] split6 = txtItem4.Text.Split(' '); string[] split7 = txtItem5.Text.Split(' '); string[] split8 = txtItem6.Text.Split(' '); string[] split9 = txtItem7.Text.Split(' '); string[] split10 = txtItem8.Text.Split(' '); npcCompleto npc = Read.Npcs[0]; if (Read.Npcs[0].npcs[index].Item[2].Req > 0 && Read.Npcs[0].npcs[index].Item[2].Req < 100) { var RequestStruct = Read.Npcs[0].npcs[index].Item[2].Req; IndexOfStruct = RequestStruct; reqID.Text = RequestStruct.ToString(); // ITENS txtItemItens.Text = Read.Npcs[0].req[RequestStruct].Item.sIndex.ToString() + "," + Read.Npcs[0].req[RequestStruct].Item.sEffect[0].cEfeito.ToString() + "," + Read.Npcs[0].req[index].Item.sEffect[0].cValue.ToString() + "," + Read.Npcs[0].req[index].Item.sEffect[1].cEfeito.ToString() + "," + Read.Npcs[0].req[index].Item.sEffect[1].cValue.ToString() + "," + Read.Npcs[0].req[index].Item.sEffect[2].cEfeito.ToString() + "," + Read.Npcs[0].req[index].Item.sEffect[2].cValue.ToString(); txtStrdef.Text = Read.Npcs[0].req[RequestStruct].Strdef.ToString(); txtAmount.Text = Read.Npcs[0].req[RequestStruct].Amount.ToString(); txtMin0.Text = npc.req[IndexOfStruct].Mix[0].MinID.ToString(); txtMax0.Text = npc.req[IndexOfStruct].Mix[0].MaxID.ToString(); txtUnk.Text = String.Empty; for (int i = 0; i < 16; i++) { txtUnk.Text += npc.req[IndexOfStruct].Unknow[i] + " "; } txtMin1.Text = npc.req[IndexOfStruct].Mix[1].MinID.ToString(); txtMax1.Text = npc.req[IndexOfStruct].Mix[1].MaxID.ToString(); txtUnused.Text = npc.req[IndexOfStruct].Unused.ToString(); txtUnused2.Text = npc.req[IndexOfStruct].Unused_02.ToString(); txtMin2.Text = npc.req[IndexOfStruct].Mix[2].MinID.ToString(); txtMax2.Text = npc.req[IndexOfStruct].Mix[2].MaxID.ToString(); } } } private void button5_Click(object sender, EventArgs e) { { var index = NPCList.SelectedIndex; string[] split = txtItem.Text.Split(','); string[] split2 = txtItemItens.Text.Split(','); string[] split3 = txtItem1.Text.Split(' '); string[] split4 = txtItem2.Text.Split(' '); string[] split5 = txtItem3.Text.Split(' '); string[] split6 = txtItem4.Text.Split(' '); string[] split7 = txtItem5.Text.Split(' '); string[] split8 = txtItem6.Text.Split(' '); string[] split9 = txtItem7.Text.Split(' '); string[] split10 = txtItem8.Text.Split(' '); npcCompleto npc = Read.Npcs[0]; if (Read.Npcs[0].npcs[index].Item[3].Req > 0 && Read.Npcs[0].npcs[index].Item[3].Req < 100) { var RequestStruct = Read.Npcs[0].npcs[index].Item[3].Req; IndexOfStruct = RequestStruct; reqID.Text = RequestStruct.ToString(); // ITENS txtItemItens.Text = Read.Npcs[0].req[RequestStruct].Item.sIndex.ToString() + "," + Read.Npcs[0].req[RequestStruct].Item.sEffect[0].cEfeito.ToString() + "," + Read.Npcs[0].req[index].Item.sEffect[0].cValue.ToString() + "," + Read.Npcs[0].req[index].Item.sEffect[1].cEfeito.ToString() + "," + Read.Npcs[0].req[index].Item.sEffect[1].cValue.ToString() + "," + Read.Npcs[0].req[index].Item.sEffect[2].cEfeito.ToString() + "," + Read.Npcs[0].req[index].Item.sEffect[2].cValue.ToString(); txtStrdef.Text = Read.Npcs[0].req[RequestStruct].Strdef.ToString(); txtAmount.Text = Read.Npcs[0].req[RequestStruct].Amount.ToString(); txtMin0.Text = npc.req[IndexOfStruct].Mix[0].MinID.ToString(); txtMax0.Text = npc.req[IndexOfStruct].Mix[0].MaxID.ToString(); txtUnk.Text = String.Empty; for (int i = 0; i < 16; i++) { txtUnk.Text += npc.req[IndexOfStruct].Unknow[i] + " "; } txtMin1.Text = npc.req[IndexOfStruct].Mix[1].MinID.ToString(); txtMax1.Text = npc.req[IndexOfStruct].Mix[1].MaxID.ToString(); txtUnused.Text = npc.req[IndexOfStruct].Unused.ToString(); txtUnused2.Text = npc.req[IndexOfStruct].Unused_02.ToString(); txtMin2.Text = npc.req[IndexOfStruct].Mix[2].MinID.ToString(); txtMax2.Text = npc.req[IndexOfStruct].Mix[2].MaxID.ToString(); } } } private void button6_Click(object sender, EventArgs e) { { var index = NPCList.SelectedIndex; string[] split = txtItem.Text.Split(','); string[] split2 = txtItemItens.Text.Split(','); string[] split3 = txtItem1.Text.Split(' '); string[] split4 = txtItem2.Text.Split(' '); string[] split5 = txtItem3.Text.Split(' '); string[] split6 = txtItem4.Text.Split(' '); string[] split7 = txtItem5.Text.Split(' '); string[] split8 = txtItem6.Text.Split(' '); string[] split9 = txtItem7.Text.Split(' '); string[] split10 = txtItem8.Text.Split(' '); npcCompleto npc = Read.Npcs[0]; if (Read.Npcs[0].npcs[index].Item[4].Req > 0 && Read.Npcs[0].npcs[index].Item[4].Req < 100) { var RequestStruct = Read.Npcs[0].npcs[index].Item[4].Req; IndexOfStruct = RequestStruct; reqID.Text = RequestStruct.ToString(); // ITENS txtItemItens.Text = Read.Npcs[0].req[RequestStruct].Item.sIndex.ToString() + "," + Read.Npcs[0].req[RequestStruct].Item.sEffect[0].cEfeito.ToString() + "," + Read.Npcs[0].req[index].Item.sEffect[0].cValue.ToString() + "," + Read.Npcs[0].req[index].Item.sEffect[1].cEfeito.ToString() + "," + Read.Npcs[0].req[index].Item.sEffect[1].cValue.ToString() + "," + Read.Npcs[0].req[index].Item.sEffect[2].cEfeito.ToString() + "," + Read.Npcs[0].req[index].Item.sEffect[2].cValue.ToString(); txtStrdef.Text = Read.Npcs[0].req[RequestStruct].Strdef.ToString(); txtAmount.Text = Read.Npcs[0].req[RequestStruct].Amount.ToString(); txtMin0.Text = npc.req[IndexOfStruct].Mix[0].MinID.ToString(); txtMax0.Text = npc.req[IndexOfStruct].Mix[0].MaxID.ToString(); txtUnk.Text = String.Empty; for (int i = 0; i < 16; i++) { txtUnk.Text += npc.req[IndexOfStruct].Unknow[i] + " "; } txtMin1.Text = npc.req[IndexOfStruct].Mix[1].MinID.ToString(); txtMax1.Text = npc.req[IndexOfStruct].Mix[1].MaxID.ToString(); txtUnused.Text = npc.req[IndexOfStruct].Unused.ToString(); txtUnused2.Text = npc.req[IndexOfStruct].Unused_02.ToString(); txtMin2.Text = npc.req[IndexOfStruct].Mix[2].MinID.ToString(); txtMax2.Text = npc.req[IndexOfStruct].Mix[2].MaxID.ToString(); } } } private void button7_Click(object sender, EventArgs e) { { var index = NPCList.SelectedIndex; string[] split = txtItem.Text.Split(','); string[] split2 = txtItemItens.Text.Split(','); string[] split3 = txtItem1.Text.Split(' '); string[] split4 = txtItem2.Text.Split(' '); string[] split5 = txtItem3.Text.Split(' '); string[] split6 = txtItem4.Text.Split(' '); string[] split7 = txtItem5.Text.Split(' '); string[] split8 = txtItem6.Text.Split(' '); string[] split9 = txtItem7.Text.Split(' '); string[] split10 = txtItem8.Text.Split(' '); npcCompleto npc = Read.Npcs[0]; if (Read.Npcs[0].npcs[index].Item[5].Req > 0 && Read.Npcs[0].npcs[index].Item[5].Req < 100) { var RequestStruct = Read.Npcs[0].npcs[index].Item[5].Req; IndexOfStruct = RequestStruct; reqID.Text = RequestStruct.ToString(); // ITENS txtItemItens.Text = Read.Npcs[0].req[RequestStruct].Item.sIndex.ToString() + "," + Read.Npcs[0].req[RequestStruct].Item.sEffect[0].cEfeito.ToString() + "," + Read.Npcs[0].req[index].Item.sEffect[0].cValue.ToString() + "," + Read.Npcs[0].req[index].Item.sEffect[1].cEfeito.ToString() + "," + Read.Npcs[0].req[index].Item.sEffect[1].cValue.ToString() + "," + Read.Npcs[0].req[index].Item.sEffect[2].cEfeito.ToString() + "," + Read.Npcs[0].req[index].Item.sEffect[2].cValue.ToString(); txtStrdef.Text = Read.Npcs[0].req[RequestStruct].Strdef.ToString(); txtAmount.Text = Read.Npcs[0].req[RequestStruct].Amount.ToString(); txtMin0.Text = npc.req[IndexOfStruct].Mix[0].MinID.ToString(); txtMax0.Text = npc.req[IndexOfStruct].Mix[0].MaxID.ToString(); txtUnk.Text = String.Empty; for (int i = 0; i < 16; i++) { txtUnk.Text += npc.req[IndexOfStruct].Unknow[i] + " "; } txtMin1.Text = npc.req[IndexOfStruct].Mix[1].MinID.ToString(); txtMax1.Text = npc.req[IndexOfStruct].Mix[1].MaxID.ToString(); txtUnused.Text = npc.req[IndexOfStruct].Unused.ToString(); txtUnused2.Text = npc.req[IndexOfStruct].Unused_02.ToString(); txtMin2.Text = npc.req[IndexOfStruct].Mix[2].MinID.ToString(); txtMax2.Text = npc.req[IndexOfStruct].Mix[2].MaxID.ToString(); } } } private void button8_Click(object sender, EventArgs e) { { var index = NPCList.SelectedIndex; string[] split = txtItem.Text.Split(','); string[] split2 = txtItemItens.Text.Split(','); string[] split3 = txtItem1.Text.Split(' '); string[] split4 = txtItem2.Text.Split(' '); string[] split5 = txtItem3.Text.Split(' '); string[] split6 = txtItem4.Text.Split(' '); string[] split7 = txtItem5.Text.Split(' '); string[] split8 = txtItem6.Text.Split(' '); string[] split9 = txtItem7.Text.Split(' '); string[] split10 = txtItem8.Text.Split(' '); npcCompleto npc = Read.Npcs[0]; if (Read.Npcs[0].npcs[index].Item[6].Req > 0 && Read.Npcs[0].npcs[index].Item[6].Req < 100) { var RequestStruct = Read.Npcs[0].npcs[index].Item[6].Req; IndexOfStruct = RequestStruct; reqID.Text = RequestStruct.ToString(); // ITENS txtItemItens.Text = Read.Npcs[0].req[RequestStruct].Item.sIndex.ToString() + "," + Read.Npcs[0].req[RequestStruct].Item.sEffect[0].cEfeito.ToString() + "," + Read.Npcs[0].req[index].Item.sEffect[0].cValue.ToString() + "," + Read.Npcs[0].req[index].Item.sEffect[1].cEfeito.ToString() + "," + Read.Npcs[0].req[index].Item.sEffect[1].cValue.ToString() + "," + Read.Npcs[0].req[index].Item.sEffect[2].cEfeito.ToString() + "," + Read.Npcs[0].req[index].Item.sEffect[2].cValue.ToString(); txtStrdef.Text = Read.Npcs[0].req[RequestStruct].Strdef.ToString(); txtAmount.Text = Read.Npcs[0].req[RequestStruct].Amount.ToString(); txtMin0.Text = npc.req[IndexOfStruct].Mix[0].MinID.ToString(); txtMax0.Text = npc.req[IndexOfStruct].Mix[0].MaxID.ToString(); txtUnk.Text = String.Empty; for (int i = 0; i < 16; i++) { txtUnk.Text += npc.req[IndexOfStruct].Unknow[i] + " "; } txtMin1.Text = npc.req[IndexOfStruct].Mix[1].MinID.ToString(); txtMax1.Text = npc.req[IndexOfStruct].Mix[1].MaxID.ToString(); txtUnused.Text = npc.req[IndexOfStruct].Unused.ToString(); txtUnused2.Text = npc.req[IndexOfStruct].Unused_02.ToString(); txtMin2.Text = npc.req[IndexOfStruct].Mix[2].MinID.ToString(); txtMax2.Text = npc.req[IndexOfStruct].Mix[2].MaxID.ToString(); } } } private void button9_Click(object sender, EventArgs e) { { var index = NPCList.SelectedIndex; string[] split = txtItem.Text.Split(','); string[] split2 = txtItemItens.Text.Split(','); string[] split3 = txtItem1.Text.Split(' '); string[] split4 = txtItem2.Text.Split(' '); string[] split5 = txtItem3.Text.Split(' '); string[] split6 = txtItem4.Text.Split(' '); string[] split7 = txtItem5.Text.Split(' '); string[] split8 = txtItem6.Text.Split(' '); string[] split9 = txtItem7.Text.Split(' '); string[] split10 = txtItem8.Text.Split(' '); npcCompleto npc = Read.Npcs[0]; if (Read.Npcs[0].npcs[index].Item[7].Req > 0 && Read.Npcs[0].npcs[index].Item[7].Req < 100) { var RequestStruct = Read.Npcs[0].npcs[index].Item[7].Req; IndexOfStruct = RequestStruct; reqID.Text = RequestStruct.ToString(); // ITENS txtItemItens.Text = Read.Npcs[0].req[RequestStruct].Item.sIndex.ToString() + "," + Read.Npcs[0].req[RequestStruct].Item.sEffect[0].cEfeito.ToString() + "," + Read.Npcs[0].req[index].Item.sEffect[0].cValue.ToString() + "," + Read.Npcs[0].req[index].Item.sEffect[1].cEfeito.ToString() + "," + Read.Npcs[0].req[index].Item.sEffect[1].cValue.ToString() + "," + Read.Npcs[0].req[index].Item.sEffect[2].cEfeito.ToString() + "," + Read.Npcs[0].req[index].Item.sEffect[2].cValue.ToString(); txtStrdef.Text = Read.Npcs[0].req[RequestStruct].Strdef.ToString(); txtAmount.Text = Read.Npcs[0].req[RequestStruct].Amount.ToString(); txtMin0.Text = npc.req[IndexOfStruct].Mix[0].MinID.ToString(); txtMax0.Text = npc.req[IndexOfStruct].Mix[0].MaxID.ToString(); txtMin1.Text = npc.req[IndexOfStruct].Mix[1].MinID.ToString(); txtMax1.Text = npc.req[IndexOfStruct].Mix[1].MaxID.ToString(); txtUnused.Text = npc.req[IndexOfStruct].Unused.ToString(); txtUnused2.Text = npc.req[IndexOfStruct].Unused_02.ToString(); txtMin2.Text = npc.req[IndexOfStruct].Mix[2].MinID.ToString(); txtMax2.Text = npc.req[IndexOfStruct].Mix[2].MaxID.ToString(); txtUnk.Text = String.Empty; for (int i = 0; i < 16; i++) { txtUnk.Text += npc.req[IndexOfStruct].Unknow[i] + " "; } } } } public void Reload() { g_pRestante = 100; // ITENS txtItemItens.Text = "0,0,0,0,0,0,0"; IndexOfStruct = 0; reqID.Text = IndexOfStruct.ToString(); txtStrdef.Text = "0"; txtAmount.Text = "0"; txtMin0.Text = "0"; txtMax0.Text = "0"; txtMin1.Text = "0"; txtMax1.Text = "0"; txtUnused.Text = "0"; txtUnused2.Text = "0"; txtMin2.Text = "0"; txtMax2.Text = "0"; txtUnk.Text = "0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 "; txtGold.Text = "0"; txtItem.Text = "0,0,0,0,0,0,0"; txtMapX.Text = "0"; txtMapY.Text = "0"; txtTipo.Text = "0x00"; txtItem1.Text = "0 0"; txtItem2.Text = "0 0"; txtItem3.Text = "0 0"; txtItem4.Text = "0 0"; txtItem5.Text = "0 0"; txtItem6.Text = "0 0"; txtItem7.Text = "0 0"; txtItem8.Text = "0 0"; NPCList.Items.Clear(); RequestList.Items.Clear(); Read.Npcs.Clear(); Read.ReadArquivo(); for (int i = 0; i < 100; i++) { if (Read.Npcs[0].npcs[i].face == -842150451) { Read.Npcs[0].npcs[i].face = -1; } if (Read.Npcs[0].npcs[i].face >= 0) { g_pRestante--; } if (Read.Npcs[0].npcs[i].Name == "����������������") { Read.Npcs[0].npcs[i].Name = "NoName"; } NPCList.Items.Add("Index(" + i + "): [" + Read.Npcs[0].npcs[i].face + "] - " + Read.Npcs[0].npcs[i].Name); } restante.Text = "" + g_pRestante + " / 100"; for (int i = 0; i < 100; i++) { if (Read.Npcs[0].req[i].Item.sIndex < -2) { Read.Npcs[0].req[i].Item.sIndex = -1; // ITENS txtItemItens.Text = "0,0,0,0,0,0,0"; IndexOfStruct = 0; reqID.Text = IndexOfStruct.ToString(); txtStrdef.Text = "0"; txtAmount.Text = "0"; txtMin0.Text = "0"; txtMax0.Text = "0"; txtMin1.Text = "0"; txtMax1.Text = "0"; txtUnused.Text = "0"; txtUnused2.Text = "0"; txtMin2.Text = "0"; txtMax2.Text = "0"; txtUnk.Text = "0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 "; } RequestList.Items.Add("[" + i + "] " + " " + Read.Npcs[0].req[i].Item.sIndex.ToString()); } } private void button10_Click(object sender, EventArgs e) { Reload(); } private void button11_Click(object sender, EventArgs e) { // ITENS txtItemItens.Text = "0,0,0,0,0,0,0"; IndexOfStruct = 0; reqID.Text = IndexOfStruct.ToString(); txtStrdef.Text = "0"; txtAmount.Text = "0"; txtMin0.Text = "0"; txtMax0.Text = "0"; txtMin1.Text = "0"; txtMax1.Text = "0"; txtUnused.Text = "0"; txtUnused2.Text = "0"; txtMin2.Text = "0"; txtMax2.Text = "0"; txtUnk.Text = "0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 "; txtGold.Text = "0"; txtItem.Text = "0,0,0,0,0,0,0"; txtMapX.Text = "0"; txtMapY.Text = "0"; txtTipo.Text = "0x00"; txtItem1.Text = "0 0"; txtItem2.Text = "0 0"; txtItem3.Text = "0 0"; txtItem4.Text = "0 0"; txtItem5.Text = "0 0"; txtItem6.Text = "0 0"; txtItem7.Text = "0 0"; txtItem8.Text = "0 0"; nameNPC.Text = "Nenhum"; } private void requestBox_SelectedIndexChanged(object sender, EventArgs e) { var index = RequestList.SelectedIndex; npcCompleto npc = Read.Npcs[0]; // ITENS txtItemItens.Text = Read.Npcs[0].req[index].Item.sIndex.ToString() + "," + Read.Npcs[0].req[index].Item.sEffect[0].cEfeito.ToString() + "," + Read.Npcs[0].req[index].Item.sEffect[0].cValue.ToString() + "," + Read.Npcs[0].req[index].Item.sEffect[1].cEfeito.ToString() + "," + Read.Npcs[0].req[index].Item.sEffect[1].cValue.ToString() + "," + Read.Npcs[0].req[index].Item.sEffect[2].cEfeito.ToString() + "," + Read.Npcs[0].req[index].Item.sEffect[2].cValue.ToString(); txtStrdef.Text = Read.Npcs[0].req[index].Strdef.ToString(); txtAmount.Text = Read.Npcs[0].req[index].Amount.ToString(); for(int i = 0; i< 3;i++) { if (npc.req[index].Mix[i].MinID < 0) npc.req[index].Mix[i].MinID = 0; if(npc.req[index].Mix[i].MaxID < 0) npc.req[index].Mix[i].MaxID = 0; } txtMin0.Text = npc.req[index].Mix[0].MinID.ToString(); txtMax0.Text = npc.req[index].Mix[0].MaxID.ToString(); txtMin1.Text = npc.req[index].Mix[1].MinID.ToString(); txtMax1.Text = npc.req[index].Mix[1].MaxID.ToString(); if (npc.req[index].Unused < 0) npc.req[index].Unused = 0; if (npc.req[index].Unused_02 < 0) npc.req[index].Unused_02 = 0; txtUnused.Text = npc.req[index].Unused.ToString(); txtUnused2.Text = npc.req[index].Unused_02.ToString(); txtMin2.Text = npc.req[index].Mix[2].MinID.ToString(); txtMax2.Text = npc.req[index].Mix[2].MaxID.ToString(); txtUnk.Text = String.Empty; for (int i = 0; i < 16; i++) { if (npc.req[index].Unknow[i] == 205 || npc.req[index].Unknow[i] < 0) npc.req[index].Unknow[i] = 0; txtUnk.Text += npc.req[index].Unknow[i] + " "; } reqID.Text = index.ToString(); if (Read.Npcs[0].req[index].Item.sIndex == -1 || Read.Npcs[0].req[index].Item.sIndex < 0) { Read.Npcs[0].req[index].Item.sIndex = -1; // ITENS txtItemItens.Text = "0,0,0,0,0,0,0"; IndexOfStruct = index; reqID.Text = IndexOfStruct.ToString(); txtStrdef.Text = "0"; txtAmount.Text = "0"; txtMin0.Text = "0"; txtMax0.Text = "0"; txtMin1.Text = "0"; txtMax1.Text = "0"; txtUnused.Text = "0"; txtUnused2.Text = "0"; txtMin2.Text = "0"; txtMax2.Text = "0"; txtUnk.Text = "0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 "; } IndexOfStruct = index; } private void button12_Click(object sender, EventArgs e) { //itens var index = RequestList.SelectedIndex; npcCompleto npc = Read.Npcs[0]; if (index != -1) { npc.req[index].Strdef = Convert.ToInt32(txtStrdef.Text); npc.req[index].Amount = Convert.ToInt32(txtAmount.Text); string[] explode = txtItemItens.Text.Split(','); npc.req[index].Item.sIndex = Convert.ToInt16(explode[0]); npc.req[index].Item.sEffect[0].cEfeito = Convert.ToByte(explode[1]); npc.req[index].Item.sEffect[0].cValue = Convert.ToByte(explode[2]); npc.req[index].Item.sEffect[1].cEfeito = Convert.ToByte(explode[3]); npc.req[index].Item.sEffect[1].cValue = Convert.ToByte(explode[4]); npc.req[index].Item.sEffect[2].cEfeito = Convert.ToByte(explode[5]); npc.req[index].Item.sEffect[2].cValue = Convert.ToByte(explode[6]); npc.req[index].Mix[0].MinID = Convert.ToInt32(txtMin0.Text); npc.req[index].Mix[0].MaxID = Convert.ToInt32(txtMax0.Text); npc.req[index].Mix[1].MinID = Convert.ToInt32(txtMin1.Text); npc.req[index].Mix[1].MaxID = Convert.ToInt32(txtMax1.Text); npc.req[index].Mix[2].MinID = Convert.ToInt32(txtMin2.Text); npc.req[index].Mix[2].MaxID = Convert.ToInt32(txtMax2.Text); npc.req[index].Unused = Convert.ToInt32(txtUnused.Text); npc.req[index].Unused_02 = Convert.ToInt32(txtUnused2.Text); string[] splitUnks = txtUnk.Text.Split(' '); for (int i = 0; i < 16; i++) { npc.req[index].Unknow[i] = Convert.ToByte(splitUnks[i]); } } Read.SaveArquivo(npc); MessageBox.Show("Arquivo salvo com sucesso"); } private void label26_Click(object sender, EventArgs e) { } private void label17_Click(object sender, EventArgs e) { } private void groupBox1_Enter(object sender, EventArgs e) { } private void button2_Click_1(object sender, EventArgs e) { // ITENS txtItemItens.Text = "0,0,0,0,0,0,0"; IndexOfStruct = 0; reqID.Text = IndexOfStruct.ToString(); txtStrdef.Text = "0"; txtAmount.Text = "0"; txtMin0.Text = "0"; txtMax0.Text = "0"; txtMin1.Text = "0"; txtMax1.Text = "0"; txtUnused.Text = "0"; txtUnused2.Text = "0"; txtMin2.Text = "0"; txtMax2.Text = "0"; txtUnk.Text = "0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 "; //itens var index = RequestList.SelectedIndex; npcCompleto npc = Read.Npcs[0]; if (index != -1) { npc.req[index].Strdef = Convert.ToInt32(txtStrdef.Text); npc.req[index].Amount = Convert.ToInt32(txtAmount.Text); string[] explode = txtItemItens.Text.Split(','); npc.req[index].Item.sIndex = Convert.ToInt16(explode[0]); npc.req[index].Item.sEffect[0].cEfeito = Convert.ToByte(explode[1]); npc.req[index].Item.sEffect[0].cValue = Convert.ToByte(explode[2]); npc.req[index].Item.sEffect[1].cEfeito = Convert.ToByte(explode[3]); npc.req[index].Item.sEffect[1].cValue = Convert.ToByte(explode[4]); npc.req[index].Item.sEffect[2].cEfeito = Convert.ToByte(explode[5]); npc.req[index].Item.sEffect[2].cValue = Convert.ToByte(explode[6]); npc.req[index].Mix[0].MinID = Convert.ToInt32(txtMin0.Text); npc.req[index].Mix[0].MaxID = Convert.ToInt32(txtMax0.Text); npc.req[index].Mix[1].MinID = Convert.ToInt32(txtMin1.Text); npc.req[index].Mix[1].MaxID = Convert.ToInt32(txtMax1.Text); npc.req[index].Mix[2].MinID = Convert.ToInt32(txtMin2.Text); npc.req[index].Mix[2].MaxID = Convert.ToInt32(txtMax2.Text); npc.req[index].Unused = Convert.ToInt32(txtUnused.Text); npc.req[index].Unused_02 = Convert.ToInt32(txtUnused2.Text); string[] splitUnks = txtUnk.Text.Split(' '); for (int i = 0; i < 16; i++) { npc.req[index].Unknow[i] = Convert.ToByte(splitUnks[i]); } } RequestList.Items.Clear(); for (int i = 0; i < 100; i++) { if (Read.Npcs[0].req[i].Item.sIndex < -2) { Read.Npcs[0].req[i].Item.sIndex = -1; // ITENS txtItemItens.Text = "0,0,0,0,0,0,0"; IndexOfStruct = 0; reqID.Text = IndexOfStruct.ToString(); txtStrdef.Text = "0"; txtAmount.Text = "0"; txtMin0.Text = "0"; txtMax0.Text = "0"; txtMin1.Text = "0"; txtMax1.Text = "0"; txtUnused.Text = "0"; txtUnused2.Text = "0"; txtMin2.Text = "0"; txtMax2.Text = "0"; txtUnk.Text = "0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 "; } RequestList.Items.Add("[" + i + "] " + " " + Read.Npcs[0].req[i].Item.sIndex.ToString()); } } private void richTextBox1_TextChanged(object sender, EventArgs e) { } private void label3_Click(object sender, EventArgs e) { } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Configuration; using System.Security.Cryptography; using System.Net; using System.IO; using System.Text.RegularExpressions; namespace EasyDev.Taobao.Core { public class TaobaoInterfaceProxy { private string restUrl = "http://gw.api.tbsandbox.com/router/rest"; private string appKey = string.Empty; private string appSecret = string.Empty; private TaobaoInterfaceProxy() { if (ConfigurationManager.AppSettings[Constants.REST_URL].Length > 0) { restUrl = ConfigurationManager.AppSettings[Constants.REST_URL]; } appKey = ConfigurationManager.AppSettings[Constants.APPKEY]; appSecret = ConfigurationManager.AppSettings[Constants.APPSECRET]; } public static TaobaoInterfaceProxy GetInstance() { return new TaobaoInterfaceProxy(); } /// <summary> /// 返回自定义错误对象XML /// </summary> /// <param name="code">错误代号</param> /// <param name="exp">错误对象</param> /// <param name="put">附加请求参数</param> /// <returns></returns> private string CustomErrorXML(string code, Exception exp) { return string.Format(Constants.ERROR_XML, code, exp.Message.Replace("\"", "'").Replace("\'", "'").Replace("&", "&"), exp.StackTrace.Replace("\"", "'").Replace("\'", "'").Replace("<", "<").Replace(">", ">").Replace("&", "&")); } /// <summary> /// 组装普通文本请求参数。 /// </summary> /// <param name="parameters">Key-Value形式请求参数字典</param> /// <returns>URL编码后的请求数据</returns> private string PostData(IDictionary<string, string> parameters) { StringBuilder postData = new StringBuilder(); bool hasParam = false; IEnumerator<KeyValuePair<string, string>> dem = parameters.GetEnumerator(); while (dem.MoveNext()) { string name = dem.Current.Key; string value = dem.Current.Value; // 忽略参数名或参数值为空的参数 if (!string.IsNullOrEmpty(name) && !string.IsNullOrEmpty(value)) { if (hasParam) { postData.Append("&"); } postData.Append(name); postData.Append("="); postData.Append(Uri.EscapeDataString(value)); hasParam = true; } } return postData.ToString(); } /// <summary> /// 给TOP请求签名 API v2.0 /// </summary> /// <param name="parameters">所有字符型的TOP请求参数</param> /// <param name="secret">签名密钥</param> /// <returns>签名</returns> private string CreateSign(IDictionary<string, string> parameters, string secret) { //API2.0 签名算法详见:http://open.taobao.com/dev/index.php/API%E7%AD%BE%E5%90%8D%E7%AE%97%E6%B3%95 //md5:将secretcode同时拼接到参数字符串头、尾部进行md5加密,再转化成大写,格式是:uppercase(md5(secretkey1value1key2value2...secret)。 //例如:uppercase(md5(secretbar2baz3foo1secret)) parameters.Remove("sign"); // 第一步:把字典按Key的字母顺序排序 IDictionary<string, string> sortedParams = new SortedDictionary<string, string>(parameters); IEnumerator<KeyValuePair<string, string>> dem = sortedParams.GetEnumerator(); // 第二步:把所有参数名和参数值串在一起 StringBuilder query = new StringBuilder(secret); while (dem.MoveNext()) { string key = dem.Current.Key; string value = dem.Current.Value; if (!string.IsNullOrEmpty(key) && !string.IsNullOrEmpty(value)) { query.Append(key).Append(value); } } query.Append(secret);// API 2.0 新签名方法 // 第三步:使用MD5加密 MD5 md5 = MD5.Create(); byte[] bytes = md5.ComputeHash(Encoding.UTF8.GetBytes(query.ToString())); // 第四步:把二进制转化为大写的十六进制 StringBuilder result = new StringBuilder(); for (int i = 0; i < bytes.Length; i++) { string hex = bytes[i].ToString("X"); if (hex.Length == 1) { result.Append("0"); } result.Append(hex); } return result.ToString(); } /// <summary> /// TOP API POST 执行带文件上传的请求。 /// </summary> /// <param name="url">请求容器URL</param> /// <param name="appkey">AppKey</param> /// <param name="appSecret">AppSecret</param> /// <param name="method">API接口方法名</param> /// <param name="session">调用私有的sessionkey</param> /// <param name="textParams">请求参数</param> /// <param name="fileParams">请求文件参数</param> /// <returns></returns> private string Post(string url, string appkey, string appSecret, string method, string session, IDictionary<string, string> textParams, IDictionary<string, FileItem> fileParams) { try { // 如果没有文件参数,则走普通POST请求 if (fileParams == null || fileParams.Count == 0) { return Post(url, appkey, appSecret, method, session, textParams); } #region -----API系统参数---- textParams.Add("app_key", appkey);//应用key textParams.Add("method", method);//API接口名称。如taobao.item.get。 textParams.Add("session", session);//用户会话码。无需用户登录的时候可以不传。 textParams.Add("timestamp", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));//时间戳,格式为yyyy-mm-dd hh:mm:ss,例如:2008-01-25 20:23:30。淘宝API服务端允许客户端请求时间误差为10分钟。 textParams.Add("format", "xml");//响应格式。xml,json。 textParams.Add("v", "2.0");//API版本号 textParams.Add("sign_method", "md5");//签名类型 textParams.Add("sign", CreateSign(textParams, appSecret));//生成签名 #endregion string result = string.Empty; System.Net.ServicePointManager.DefaultConnectionLimit = 20; #region ---- 完成 HTTP POST 带文件的请求---- string boundary = DateTime.Now.Ticks.ToString("X"); // 随机分隔线 HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url); req.Method = "POST"; req.KeepAlive = true; req.UserAgent = "SpaceTimeApp2.0"; req.Timeout = 600000; req.ContentType = "multipart/form-data;charset=utf-8;boundary=" + boundary; Stream reqStream = req.GetRequestStream(); byte[] itemBoundaryBytes = Encoding.UTF8.GetBytes("\r\n--" + boundary + "\r\n"); byte[] endBoundaryBytes = Encoding.UTF8.GetBytes("\r\n--" + boundary + "--\r\n"); // 组装文本请求参数 string textTemplate = "Content-Disposition:form-data;name=\"{0}\"\r\nContent-Type:text/plain\r\n\r\n{1}"; IEnumerator<KeyValuePair<string, string>> textEnum = textParams.GetEnumerator(); while (textEnum.MoveNext()) { string textEntry = string.Format(textTemplate, textEnum.Current.Key, textEnum.Current.Value); byte[] itemBytes = Encoding.UTF8.GetBytes(textEntry); reqStream.Write(itemBoundaryBytes, 0, itemBoundaryBytes.Length); reqStream.Write(itemBytes, 0, itemBytes.Length); } // 组装文件请求参数 string fileTemplate = "Content-Disposition:form-data;name=\"{0}\";filename=\"{1}\"\r\nContent-Type:{2}\r\n\r\n"; IEnumerator<KeyValuePair<string, FileItem>> fileEnum = fileParams.GetEnumerator(); while (fileEnum.MoveNext()) { string key = fileEnum.Current.Key; FileItem fileItem = fileEnum.Current.Value; string fileEntry = string.Format(fileTemplate, key, fileItem.GetFileName(), fileItem.GetMimeType()); byte[] itemBytes = Encoding.UTF8.GetBytes(fileEntry); reqStream.Write(itemBoundaryBytes, 0, itemBoundaryBytes.Length); reqStream.Write(itemBytes, 0, itemBytes.Length); byte[] fileBytes = fileItem.GetContent(); reqStream.Write(fileBytes, 0, fileBytes.Length); } reqStream.Write(endBoundaryBytes, 0, endBoundaryBytes.Length); reqStream.Close(); HttpWebResponse rsp = (HttpWebResponse)req.GetResponse(); Encoding encoding = Encoding.GetEncoding(rsp.CharacterSet); Stream stream = null; StreamReader reader = null; stream = rsp.GetResponseStream(); reader = new StreamReader(stream, encoding); result = reader.ReadToEnd(); if (reader != null) reader.Close(); if (stream != null) stream.Close(); if (rsp != null) rsp.Close(); #endregion return Regex.Replace(result, @"[\x00-\x08\x0b-\x0c\x0e-\x1f]", ""); } catch (Exception exp) { return CustomErrorXML("8004", exp); } } /// <summary> /// TOP API POST 请求 /// </summary> /// <param name="url">请求容器URL</param> /// <param name="appkey">AppKey</param> /// <param name="appSecret">AppSecret</param> /// <param name="method">API接口方法名</param> /// <param name="session">调用私有的sessionkey</param> /// <param name="param">请求参数</param> /// <returns>返回字符串</returns> private string Post(string url, string appkey, string appSecret, string method, string session, IDictionary<string, string> param) { try { //给参数增加 -- API系统参数 此处详见文档:http://open.taobao.com/dev/index.php/API%E6%96%87%E6%A1%A3#API.E7.B3.BB.E7.BB.9F.E5.8F.82.E6.95.B0 #region -----API系统参数---- param.Add("app_key", appkey);//应用key param.Add("method", method);//API接口名称。如taobao.item.get。 param.Add("session", session);//用户会话码。无需用户登录的时候可以不传。 param.Add("timestamp", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));//时间戳,格式为yyyy-mm-dd hh:mm:ss,例如:2008-01-25 20:23:30。淘宝API服务端允许客户端请求时间误差为10分钟。 param.Add("format", "xml");//响应格式。xml,json。 param.Add("v", "2.0");//API版本号 param.Add("sign_method", "md5");//签名类型 param.Add("sign", CreateSign(param, appSecret));//生成签名 #endregion string result = string.Empty; #region ---- 完成 HTTP POST 请求---- HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url); req.Method = "POST"; req.KeepAlive = true; req.UserAgent = "SpaceTimeApp2.0"; req.Timeout = 300000; req.ContentType = "application/x-www-form-urlencoded;charset=utf-8"; byte[] postData = Encoding.UTF8.GetBytes(PostData(param)); Stream reqStream = req.GetRequestStream(); reqStream.Write(postData, 0, postData.Length); reqStream.Close(); HttpWebResponse rsp = (HttpWebResponse)req.GetResponse(); Encoding encoding = Encoding.GetEncoding(rsp.CharacterSet); Stream stream = null; StreamReader reader = null; stream = rsp.GetResponseStream(); reader = new StreamReader(stream, encoding); result = reader.ReadToEnd(); if (reader != null) reader.Close(); if (stream != null) stream.Close(); if (rsp != null) rsp.Close(); #endregion return Regex.Replace(result, @"[\x00-\x08\x0b-\x0c\x0e-\x1f]", ""); } catch (Exception exp) { //自定错误消息格式 return CustomErrorXML("8001", exp); } } /// <summary> /// TOP API POST 请求(无sessionkey) /// </summary> /// <param name="method">API接口方法名</param> /// <param name="parameters">请求参数</param> /// <returns>返回字符串</returns> public string Invoke(string method, IDictionary<string, string> parameters) { return Invoke(this.restUrl, method, "", parameters); } // <summary> /// TOP API POST 请求 /// </summary> /// <param name="url">请求容器URL</param> /// <param name="method">API接口方法名</param> /// <param name="session">调用私有的sessionkey</param> /// <param name="param">请求参数</param> /// <returns>返回字符串</returns> public string Invoke(string url, string method, string session, IDictionary<string, string> param) { return Post(url, this.appKey, this.appSecret, method, session, param); } } }
using Tools; namespace _001 { class Program { private const int LIMIT = 1000; static void Main(string[] args) { Decorators.Benchmark(Solve); } private static int Solve() { return SumOfDivisibleBy3And5(LIMIT); } private static int SumOfDivisibleBy3And5(int limit) { int countOf3s = (limit - 1) / 3; int countOf5s = (limit - 1) / 5; int countOf15s = (limit - 1) / 15; int res = ((countOf3s * (countOf3s + 1)) / 2) * 3 + ((countOf5s * (countOf5s + 1)) / 2) * 5 - ((countOf15s * (countOf15s + 1)) / 2) * 15; return res; } } }
public enum EnumAxis { X = 0, Y = 1, }
using Microsoft.AspNetCore.Http; using Microsoft.Extensions.Configuration; using SFA.DAS.Authorization.Context; using SFA.DAS.Authorization.Features.Services; using SFA.DAS.Authorization.ProviderFeatures.Configuration; using SFA.DAS.Authorization.ProviderFeatures.Models; using SFA.DAS.CommitmentsV2.Services.Shared; using SFA.DAS.CommitmentsV2.Shared.Interfaces; using SFA.DAS.CommitmentsV2.Shared.Services; using SFA.DAS.ProviderCommitments.Infrastructure; using SFA.DAS.ProviderCommitments.Interfaces; using SFA.DAS.ProviderCommitments.Web.Authentication; using SFA.DAS.ProviderCommitments.Web.Authorization; using SFA.DAS.ProviderCommitments.Web.Mappers; using SFA.DAS.ProviderRelationships.Api.Client; using SFA.DAS.ProviderUrlHelper; using StructureMap; using StructureMap.Building.Interception; namespace SFA.DAS.ProviderCommitments.Web.DependencyResolution { public class DefaultRegistry : Registry { private const string ServiceName = "SFA.DAS.ProviderCommitments"; public DefaultRegistry() { Scan( scan => { scan.AssembliesFromApplicationBaseDirectory(a => a.GetName().Name.StartsWith(ServiceName)); scan.RegisterConcreteTypesAgainstTheFirstInterface(); }); For(typeof(IMapper<,>)).DecorateAllWith(typeof(AttachUserInfoToSaveRequests<,>)); For(typeof(IMapper<,>)).DecorateAllWith(typeof(AttachApimUserInfoToSaveRequests<,>)); For<IModelMapper>().Use<ModelMapper>(); For<IFeatureTogglesService<ProviderFeatureToggle>>().Use<FeatureTogglesService<ProviderFeaturesConfiguration, ProviderFeatureToggle>>(); For<IAuthenticationService>().Use<AuthenticationService>().Singleton(); For<IAuthorizationContextProvider>().Use<AuthorizationContextProvider>(); For<ILinkGenerator>().Use<LinkGenerator>().Singleton(); For<IPolicyAuthorizationWrapper>().Use<PolicyAuthorizationWrapper>(); For<IAcademicYearDateProvider>().Use<AcademicYearDateProvider>().Singleton(); For(typeof(ICookieStorageService<>)).Use(typeof(CookieStorageService<>)).Singleton(); For(typeof(HttpContext)).Use(c => c.GetInstance<IHttpContextAccessor>().HttpContext); For<IApprovalsOuterApiHttpClientFactory>().Use<ApprovalsOuterApiHttpClientFactory>(); For<IApprovalsOuterApiClient>().Use(c => c.GetInstance<IApprovalsOuterApiHttpClientFactory>().CreateClient()).Singleton(); Toggle<IProviderRelationshipsApiClient, StubProviderRelationshipsApiClient>("UseStubProviderRelationships"); } private void Toggle<TPluginType, TConcreteType>(string configurationKey) where TConcreteType : TPluginType { For<TPluginType>().InterceptWith(new FuncInterceptor<TPluginType>((c, o) => c.GetInstance<IConfiguration>().GetValue<bool>(configurationKey) ? c.GetInstance<TConcreteType>() : o)); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace IBLLService { public partial interface IWeChat_MANAGER { string IsExistAccess_Token2(); } }