text
stringlengths
13
6.01M
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. namespace Microsoft.EntityFrameworkCore.TestModels.ManyToManyFieldsModel { public class JoinOneToThreePayloadFull { public int OneId; public int ThreeId; public EntityOne One; public EntityThree Three; public string Payload; } }
using System.Collections.Generic; using System.Collections.Immutable; using System.Composition; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Editing; namespace Meziantou.Analyzer.Rules; [ExportCodeFixProvider(LanguageNames.CSharp), Shared] public sealed class NamedParameterFixer : CodeFixProvider { public override ImmutableArray<string> FixableDiagnosticIds => ImmutableArray.Create(RuleIdentifiers.UseNamedParameter); public override FixAllProvider GetFixAllProvider() { return WellKnownFixAllProviders.BatchFixer; } public override async Task RegisterCodeFixesAsync(CodeFixContext context) { var root = await context.Document.GetSyntaxRootAsync(context.CancellationToken).ConfigureAwait(false); // In case the ArrayCreationExpressionSyntax is wrapped in an ArgumentSyntax or some other node with the same span, // get the innermost node for ties. var nodeToFix = root?.FindNode(context.Span, getInnermostNodeForTie: true); if (nodeToFix == null) return; var title = "Add parameter name"; var codeAction = CodeAction.Create( title, ct => AddParameterName(context.Document, nodeToFix, ct), equivalenceKey: title); context.RegisterCodeFix(codeAction, context.Diagnostics); } private static async Task<Document> AddParameterName(Document document, SyntaxNode nodeToFix, CancellationToken cancellationToken) { var editor = await DocumentEditor.CreateAsync(document, cancellationToken).ConfigureAwait(false); var semanticModel = editor.SemanticModel; var argument = nodeToFix.FirstAncestorOrSelf<ArgumentSyntax>(); if (argument == null || argument.NameColon != null) return document; var parameters = FindParameters(semanticModel, argument, cancellationToken); if (parameters == null) return document; var index = NamedParameterAnalyzer.ArgumentIndex(argument); if (index < 0 || index >= parameters.Count) return document; var parameter = parameters[index]; var argumentName = parameter.Name; editor.ReplaceNode(argument, argument.WithNameColon(SyntaxFactory.NameColon(argumentName))); return editor.GetChangedDocument(); } private static IReadOnlyList<IParameterSymbol>? FindParameters(SemanticModel semanticModel, SyntaxNode? node, CancellationToken cancellationToken) { while (node != null) { switch (node) { case InvocationExpressionSyntax invocationExpression: var method = (IMethodSymbol?)semanticModel.GetSymbolInfo(invocationExpression, cancellationToken).Symbol; return method?.Parameters; case ObjectCreationExpressionSyntax objectCreationExpression: var ctor = (IMethodSymbol?)semanticModel.GetSymbolInfo(objectCreationExpression, cancellationToken).Symbol; return ctor?.Parameters; case ImplicitObjectCreationExpressionSyntax implicitObjectCreationExpression: var implicitCtor = (IMethodSymbol?)semanticModel.GetSymbolInfo(implicitObjectCreationExpression, cancellationToken).Symbol; return implicitCtor?.Parameters; case ConstructorInitializerSyntax constructorInitializerSyntax: var ctor2 = (IMethodSymbol?)semanticModel.GetSymbolInfo(constructorInitializerSyntax, cancellationToken).Symbol; return ctor2?.Parameters; } node = node.Parent; } return null; } }
namespace Components.Value.Business.Models { using Components.Core.Domain.Base; public class ValueDomainModel : EntityDomainModel { public string Name { get; set; } } }
using UnityEngine; using System.Collections; public class PlatformFaceVelocity : MonoBehaviour { private PlatformMoveController platformMoveController; // Use this for initialization void Start () { platformMoveController = gameObject.GetComponent<PlatformMoveController>(); } // Update is called once per frame void Update () { if (!platformMoveController) return; //if (platformMoveController.Velocity.x > 0) //{ // gameObject.transform.rotation = Quaternion.identity; //} //else if(platformMoveController.Velocity.x < 0) //{ // gameObject.transform.rotation = Quaternion.EulerAngles(0, Mathf.PI, 0); //} } }
using System.Collections; using System.Collections.Generic; using System.Net; using UnityEngine; using UnityEngine.UI; namespace Game.Appearance.Styling { public class Skins : MonoBehaviour { [SerializeField] private Text SkinName, SkinPrice; public int price; private bool IsAvailable; public GameObject Error_Log; public void Start() { if (PlayerPrefs.GetFloat("TotalScore") < price) { IsAvailable = (false); SkinPrice.text = "you need " + (price - PlayerPrefs.GetFloat("TotalScore")).ToString("2F") + " points more"; } else { IsAvailable = (true); SkinPrice.text = "select skin"; } } public void SetUpSkin() { if (IsAvailable) { PlayerPrefs.SetString("CurrentlySkin", SkinName.text); Debug.Log(PlayerPrefs.GetString("CurrentlySkin")); } else { GameObject Clone = Instantiate(Error_Log); Clone.transform.parent = GameObject.FindGameObjectWithTag("SkinsParent").transform; Clone.transform.localScale = new Vector3(1, 1, 1); var z = Clone.transform.position.z; z = -55; Destroy(Clone,8); } } void Update() { if (PlayerPrefs.GetString("CurrentlySkin") == SkinName.text) { SkinPrice.text = "selected"; SkinPrice.color = Color.green; } if (PlayerPrefs.GetString("CurrentlySkin") != SkinName.text) { SkinPrice.color = Color.white; SkinPrice.text = "select"; } if ((PlayerPrefs.GetFloat("TotalScore") < price)) SkinPrice.text = "you need " + (price - PlayerPrefs.GetFloat("TotalScore")) + " points more"; } } }
using UnityEngine; using System.Collections; using UnityEngine.Networking; public class InventarController : MonoBehaviour { void Start() { } }
namespace TowerDefense { class Tower { public int X; public int Y; public static int FireRadius = 100; public bool Attacking; public static float Power = 0.1f; public static int Price = 30; public Tower(int x, int y) { X = x; Y = y; } } }
namespace PluginB { using ServiceBase.Plugins; }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Triangle { public class Triangle { double a, b, c; Triangle(double a, double b, double c) { this.a = a; this.b = b; this.c = c; } public static Triangle ConstructBySides(double sideA, double sideB, double sideC) { if (sideA <= 0 || sideB <= 0 || sideC <= 0) throw new ArgumentException("Side can't be less than 0."); if (sideA + sideB <= sideC || sideA + sideC <= sideB || sideB + sideC <= sideA) throw new ArgumentException("Sum of two sides can't be less than third side."); return new Triangle(sideA, sideB, sideC); } public static Triangle ConstructByAngleAnd2Sides(double angleA, double sideB, double sideC) { if (sideB <= 0 || sideC <= 0) throw new ArgumentException("Side can't be less than 0."); if (angleA <= 0 || angleA >= 180) throw new ArgumentException("Angle must be between 0 and 180 degrees."); double sideA = Math.Sqrt(Math.Pow(sideB, 2) + Math.Pow(sideC, 2) - 2 * sideB * sideC * Math.Cos(angleA * Math.PI / 180)); return new Triangle(sideA, sideB, sideC); } public static Triangle ConstructBySideAnd2Angles(double sideA, double angleB, double angleC) { if (sideA <= 0) throw new ArgumentException("Side can't be less than 0."); if (angleB <= 0 || angleC <= 0) throw new ArgumentException("Angle can't be less than 0."); if (angleB + angleC >= 180) throw new ArgumentException("Sum of two angles can't be more than 180 degrees."); double angleA = 180 - (angleB + angleC); angleA *= Math.PI / 180; angleB *= Math.PI / 180; angleC *= Math.PI / 180; return new Triangle(sideA, sideA * Math.Sin(angleB) / Math.Sin(angleA), sideA * Math.Sin(angleC) / Math.Sin(angleA)); } public double GetArea() { double p = (a + b + c) / 2; return Math.Sqrt(p * (p - a) * (p - b) * (p - c)); } } }
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Web; namespace Proyecto_ORM.Models { public class Boletas { [Key] public string Serie { get; set; } public string Numero { get; set; } public string Fecha { get; set; } public double Total { get; set; } public string Estado { get; set; } public string Ruc { get; set; } public string Dni { get; set; } public string Codigo { get; set; } public virtual Empresa Empresa { get; set; } public virtual Clientes Clientes { get; set; } public virtual Empleados Empleados { get; set; } } }
using JoggingDating.Models; using JoggingDating.Services; using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Text; using System.Threading.Tasks; using Template10.Mvvm; using Windows.UI.Xaml.Navigation; using Windows.Web.Http; namespace JoggingDating.ViewModels { class ImportPageViewModel : ViewModelBase { ServiceApi serviceApi; private string _Value; public string Value { get { return _Value; } set { Set(ref _Value, value); } } private String _noParcours; public String NoParcours { get { return _noParcours; } set { Set(ref _noParcours, value); } } private ObservableCollection<Parcours> _list = null; public ObservableCollection<Parcours> List { get { return _list; } set { Set(ref _list, value); } } public Parcours _parcours; public Parcours SelectedParcours { get { return _parcours = null; } set { Set(ref _parcours, value); String lvlIdParcours = _Value + _parcours.IdParcours; GotoImportCreationParcoursPage(lvlIdParcours); } } public ImportPageViewModel() { serviceApi = new ServiceApi(); } public override async Task OnNavigatedToAsync(object parameter, NavigationMode mode, IDictionary<string, object> suspensionState) { Value = (suspensionState.ContainsKey(nameof(Value))) ? suspensionState[nameof(Value)]?.ToString() : parameter?.ToString(); await Task.CompletedTask; await GetParcours(); } private async Task GetParcours() { List = await serviceApi.GetParcoursByUser(); if(List.Count == 0) { NoParcours = "There is no save parcours."; } } public void GotoCreateImportCoursePage() => NavigationService.Navigate(typeof(Views.CreateImportCoursePage)); public void GotoImportCreationParcoursPage(String lvlIdParcours) => NavigationService.Navigate(typeof(Views.ImportCreationParcoursPage), lvlIdParcours); } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; namespace Tetris.GUI { /// <summary> /// Interaction logic for MainMenuPage.xaml /// </summary> public partial class MainMenuPage : Page, ITetrisPage { private Brush[] colors = new Brush[10]; private Brush[] borderColors = new Brush[10]; public MainMenuPage() { InitializeComponent(); SetColors(); GenerateBorders(); GenerateBoard(); } private void GenerateBoard() { int[,] leftBoard = new int[,] { {4,4,5,5,6,6,0,7,1,3}, {4,7,0,5,6,6,6,3,1,1}, {4,7,0,6,2,2,0,5,5,1}, {3,3,3,0,2,2,5,5,0,1}, {4,4,4,6,6,3,0,2,2,3}, {0,7,4,5,6,6,0,2,2,3}, {3,7,7,5,5,1,1,1,1,0}, {3,7,1,0,5,0,0,5,5,0}, {3,3,1,0,7,0,5,5,2,2}, {0,6,1,7,7,7,6,6,2,2}, {6,6,1,0,4,4,0,6,6,4}, {6,7,7,7,4,5,0,1,0,4}, {0,0,7,0,4,5,5,1,5,5}, {2,2,1,3,5,5,0,1,2,2}, {0,6,1,5,5,3,3,4,4,4}, {6,6,1,0,0,7,3,5,0,4}, {6,0,6,6,7,7,3,5,5,0}, {4,4,4,6,6,7,0,3,5,0}, {0,7,4,2,2,3,3,3,0,0}, {7,7,7,2,2,0,1,1,1,1} }; DrawBoard(LeftGrid, leftBoard); int[,] rightBoard = new int[,] { {2,2,6,0,5,5,3,7,4,1}, {1,4,4,5,5,0,7,7,7,7}, {1,4,2,2,0,6,3,3,7,7}, {1,4,2,2,6,6,0,3,3,7}, {1,5,5,4,6,6,6,3,3,0}, {5,5,0,4,4,4,6,6,3,3}, {0,1,0,6,2,2,4,5,7,0}, {0,1,6,6,2,2,4,4,4,3}, {1,1,6,0,5,5,4,3,3,3}, {1,2,2,5,5,0,4,4,4,6}, {1,2,2,0,3,7,7,7,6,6}, {1,0,3,3,3,7,7,1,6,6}, {5,5,1,4,3,3,0,1,6,0}, {0,5,1,2,2,3,4,1,2,2}, {0,6,1,2,2,3,4,1,2,2}, {6,6,1,0,3,4,4,5,5,1}, {6,7,3,3,3,6,6,0,5,1}, {7,7,7,4,0,7,6,6,3,1}, {0,5,5,4,7,7,2,2,3,1}, {5,5,4,4,0,7,2,2,3,3}, }; DrawBoard(RightGrid, rightBoard); } private void DrawBoard(Grid g, int[,] board) { for(int i = 0; i < 20; i++) { g.RowDefinitions.Add(new RowDefinition()); if(i % 2 == 0) { g.ColumnDefinitions.Add(new ColumnDefinition()); } for(int j = 0; j < 10; j++) { Label piece = GenerateLabel(board[i, j]); Grid.SetRow(piece, i); Grid.SetColumn(piece, j); g.Children.Add(piece); } } } private void GenerateBorders() { //set left and right for(int i = 0; i < 2; i++) { Grid column = LeftBorder; if(i == 1 ) { column = RightBorder; } for(int j = 0; j < 20; j++) { column.RowDefinitions.Add(new RowDefinition()); Label piece = GenerateLabel(9); Grid.SetRow(piece, j); column.Children.Add(piece); } } } private void SetColors() { colors[0] = new SolidColorBrush(Colors.Black); colors[1] = new SolidColorBrush(Colors.Cyan); colors[2] = new SolidColorBrush(Colors.Yellow); colors[3] = new SolidColorBrush(Colors.DodgerBlue); colors[4] = new SolidColorBrush(Colors.DarkOrange); colors[5] = new SolidColorBrush(Colors.LawnGreen); colors[6] = new SolidColorBrush(Colors.Red); colors[7] = new SolidColorBrush(Colors.MediumPurple); colors[8] = new SolidColorBrush(Colors.LightGray); colors[9] = new SolidColorBrush(Colors.Gray); borderColors[0] = new SolidColorBrush(Colors.Black); borderColors[1] = new SolidColorBrush(Color.FromRgb(16, 200, 200)); borderColors[2] = new SolidColorBrush(Color.FromRgb(200, 200, 16)); borderColors[3] = new SolidColorBrush(Color.FromRgb(26, 48, 202)); borderColors[4] = new SolidColorBrush(Color.FromRgb(230, 93, 46)); borderColors[5] = new SolidColorBrush(Color.FromRgb(58, 197, 15)); borderColors[6] = new SolidColorBrush(Color.FromRgb(200, 16, 16)); borderColors[7] = new SolidColorBrush(Color.FromRgb(92, 37, 92)); borderColors[8] = new SolidColorBrush(Colors.Gray); borderColors[9] = new SolidColorBrush(Color.FromRgb(67, 52, 52)); } private Label GenerateLabel(int color) { Label piece = new Label(); piece.Background = colors[color]; piece.BorderBrush = borderColors[color]; piece.BorderThickness = new Thickness(2); return piece; } public void Page_KeyDown(object sender, KeyEventArgs e) { } private void NewGameButton_Click(object sender, RoutedEventArgs e) { MainWindow mw = (MainWindow)this.Parent; mw.StartNewGame(); } private void UltraButton_Click(object sender, RoutedEventArgs e) { MainWindow mw = (MainWindow)this.Parent; mw.StartUltraGame(); } private void MusicButton_Click(object sender, RoutedEventArgs e) { MainWindow mw = (MainWindow)this.Parent; mw.MusicSelection(); } } }
using UnityEngine; using System.Collections; public class GameOverScreen : MonoBehaviour { // Use this for initialization void Start () { } // Update is called once per frame void Update () { } // Uses for a button to go back to main menu public void ReturnToTitle() { Application.LoadLevel("MainMenu"); } }
using Shared.DomainShared; using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations.Schema; using System.Text; namespace Domain.Entities { public class Produto:Entity { protected Produto() { } public Produto(float preco_desconto, float preco, string nome, string descricao, string url_imagem, Guid vendedor_id, int quantidade, bool desconto_aplicado, DateTime oferta_inicio, DateTime oferta_fim, int desconto_porcentagem, Guid categoria_id) { Preco_desconto = preco_desconto; Preco = preco; Nome = nome; Descricao = descricao; Url_imagem = url_imagem; Vendedor_id = vendedor_id; Quantidade = quantidade; Desconto_aplicado = desconto_aplicado; Oferta_inicio = oferta_inicio; Oferta_fim = oferta_fim; Desconto_porcentagem = desconto_porcentagem; Categoria_id = categoria_id; } public float Preco_desconto { get; set; } public float Preco { get; set; } public string Nome { get; set; } public string Descricao { get; set; } public string Url_imagem { get; set; } public Guid Vendedor_id { get; set; } [ForeignKey("Vendedor_id")] public Vendedor Vendedor { get; set; } public int Quantidade { get; set; } public bool Desconto_aplicado { get; set; } public DateTime Oferta_inicio { get; set; } public DateTime Oferta_fim { get; set; } public int Desconto_porcentagem { get; set; } public Guid Categoria_id { get; set; } [ForeignKey("Categoria_id")] public Categoria Categoria { get; set; } } }
/* DotNetMQ - A Complete Message Broker For .NET Copyright (C) 2011 Halil ibrahim KALKAN This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ using System; using System.Collections.Generic; using System.Reflection; #if __DOT_NET__ using log4net; #endif using MDS.Communication; using MDS.Communication.Messages; using MDS.Exceptions; namespace MDS.Client.MDSServices { /// <summary> /// This class ensures to use a class that is derived from MDSService class, as a service on MDS. /// </summary> public class MDSServiceApplication : IDisposable { #region Private fields /// <summary> /// Underlying MDSClient object to send/receive MDS messages. /// </summary> private readonly MDSClient _mdsClient; #if __DOT_NET__ /// <summary> /// Reference to logger. /// </summary> private static readonly ILog Logger = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); #endif /// <summary> /// The service object that handles all method invokes. /// </summary> private SortedList<string, ServiceObject> _serviceObjects; #endregion #region Constructors /// <summary> /// Creates a new MDSServiceApplication object with default values to connect to MDS server. /// </summary> /// <param name="applicationName">Name of the application</param> public MDSServiceApplication(string applicationName) { _mdsClient = new MDSClient(applicationName, CommunicationConsts.DefaultIpAddress, CommunicationConsts.DefaultMDSPort); Initialize(); } /// <summary> /// Creates a new MDSServiceApplication object with default port to connect to MDS server. /// </summary> /// <param name="applicationName">Name of the application</param> /// <param name="ipAddress">IP address of MDS server</param> public MDSServiceApplication(string applicationName, string ipAddress) { _mdsClient = new MDSClient(applicationName, ipAddress, CommunicationConsts.DefaultMDSPort); Initialize(); } /// <summary> /// Creates a new MDSServiceApplication object. /// </summary> /// <param name="applicationName">Name of the application</param> /// <param name="ipAddress">IP address of MDS server</param> /// <param name="port">TCP port of MDS server</param> public MDSServiceApplication(string applicationName, string ipAddress, int port) { _mdsClient = new MDSClient(applicationName, ipAddress, port); Initialize(); } #endregion #region Public methods /// <summary> /// This method connects to MDS server using underlying MDSClient object. /// </summary> public void Connect() { _mdsClient.Connect(); } /// <summary> /// This method disconnects from MDS server using underlying MDSClient object. /// </summary> public void Disconnect() { _mdsClient.Disconnect(); } /// <summary> /// Adds a new MDSService for this service application. /// </summary> /// <param name="service">Service to add</param> public void AddService(MDSService service) { if (service == null) { throw new ArgumentNullException("service"); } var type = service.GetType(); var attributes = type.GetCustomAttributes(typeof (MDSServiceAttribute), true); if(attributes.Length <= 0) { throw new MDSException("Service class must has MDSService attribute to be added."); } if (_serviceObjects.ContainsKey(type.Name)) { throw new MDSException("Service '" + type.Name + "' is already added."); } _serviceObjects.Add(type.Name, new ServiceObject(service, (MDSServiceAttribute)attributes[0])); } /// <summary> /// Removes a MDSService from this service application. /// </summary> /// <param name="service">Service to add</param> public void RemoveService(MDSService service) { if (service == null) { throw new ArgumentNullException("service"); } var type = service.GetType(); if (!_serviceObjects.ContainsKey(type.Name)) { return; } _serviceObjects.Remove(type.Name); } /// <summary> /// Disposes this object, disposes/closes underlying MDSClient object. /// </summary> public void Dispose() { _mdsClient.Dispose(); } #endregion #region Private methods /// <summary> /// Initializes this object. /// </summary> private void Initialize() { _serviceObjects = new SortedList<string, ServiceObject>(); _mdsClient.MessageReceived += MdsClient_MessageReceived; } /// <summary> /// This method handles all incoming messages from MDS server. /// </summary> /// <param name="sender">Creator object of method (MDSClient object)</param> /// <param name="e">Message event arguments</param> private void MdsClient_MessageReceived(object sender, MessageReceivedEventArgs e) { //Deserialize message MDSRemoteInvokeMessage invokeMessage; try { invokeMessage = (MDSRemoteInvokeMessage)GeneralHelper.DeserializeObject(e.Message.MessageData); } catch (Exception ex) { AcknowledgeMessage(e.Message); SendException(e.Message, new MDSRemoteException("Incoming message can not be deserialized to MDSRemoteInvokeMessage.", ex)); return; } //Check service class name if (!_serviceObjects.ContainsKey(invokeMessage.ServiceClassName)) { AcknowledgeMessage(e.Message); SendException(e.Message, new MDSRemoteException("There is no service with name '" + invokeMessage.ServiceClassName + "'")); return; } //Get service object var serviceObject = _serviceObjects[invokeMessage.ServiceClassName]; //Invoke service method and get return value object returnValue; try { //Set request variables to service object and invoke method serviceObject.Service.IncomingMessage = e.Message; returnValue = serviceObject.InvokeMethod(invokeMessage.MethodName, invokeMessage.Parameters); } catch (Exception ex) { SendException(e.Message, new MDSRemoteException( ex.Message + Environment.NewLine + "Service Class: " + invokeMessage.ServiceClassName + " " + Environment.NewLine + "Service Version: " + serviceObject.ServiceAttribute.Version, ex)); return; } //Send return value to sender application SendReturnValue(e.Message, returnValue); } /// <summary> /// Sends an Exception to the remote application that invoked a service method /// </summary> /// <param name="incomingMessage">Incoming invoke message from remote application</param> /// <param name="exception">Exception to send</param> private static void SendException(IIncomingMessage incomingMessage, MDSRemoteException exception) { if (incomingMessage.TransmitRule != MessageTransmitRules.DirectlySend) { return; } try { //Create return message var returnMessage = new MDSRemoteInvokeReturnMessage { RemoteException = exception }; //Create response message and send var responseMessage = incomingMessage.CreateResponseMessage(); responseMessage.MessageData = GeneralHelper.SerializeObject(returnMessage); responseMessage.Send(); } catch (Exception ex) { #if __DOT_NET__ Logger.Error(ex.Message, ex); #endif } } /// <summary> /// Sends return value to the remote application that invoked a service method. /// </summary> /// <param name="incomingMessage">Incoming invoke message from remote application</param> /// <param name="returnValue">Return value to send</param> private static void SendReturnValue(IIncomingMessage incomingMessage, object returnValue) { if (incomingMessage.TransmitRule != MessageTransmitRules.DirectlySend) { return; } try { //Create return message var returnMessage = new MDSRemoteInvokeReturnMessage { ReturnValue = returnValue }; //Create response message and send var responseMessage = incomingMessage.CreateResponseMessage(); responseMessage.MessageData = GeneralHelper.SerializeObject(returnMessage); responseMessage.Send(); } catch (Exception ex) { #if __DOT_NET__ Logger.Error(ex.Message, ex); #endif } } /// <summary> /// Acknowledges a message. /// </summary> /// <param name="message">Message to acknowledge</param> private static void AcknowledgeMessage(IIncomingMessage message) { try { message.Acknowledge(); } catch (Exception ex) { #if __DOT_NET__ Logger.Error(ex.Message, ex); #endif } } #endregion #region Sub classes /// <summary> /// Represents a MDSService object. /// </summary> private class ServiceObject { /// <summary> /// The service object that is used to invoke methods on. /// </summary> public MDSService Service { get; private set; } /// <summary> /// MDSService attribute of Service object's class. /// </summary> public MDSServiceAttribute ServiceAttribute { get; private set; } /// <summary> /// Name of the Service object's class. /// </summary> private readonly string _serviceClassName; /// <summary> /// This collection stores a list of all methods of T, if that can be invoked from remote applications or not. /// Key: Method name /// Value: True, if it can be invoked from remote application. /// </summary> private readonly SortedList<string, bool> _methods; /// <summary> /// Creates a new ServiceObject. /// </summary> /// <param name="service">The service object that is used to invoke methods on</param> /// <param name="serviceAttribute">MDSService attribute of service object's class</param> public ServiceObject(MDSService service, MDSServiceAttribute serviceAttribute) { Service = service; ServiceAttribute = serviceAttribute; _serviceClassName = service.GetType().Name; //Find all methods _methods = new SortedList<string, bool>(); foreach (var methodInfo in Service.GetType().GetMethods()) { var attributes = methodInfo.GetCustomAttributes(typeof(MDSServiceMethodAttribute), true); _methods.Add(methodInfo.Name, attributes.Length > 0); } } /// <summary> /// Invokes a method of Service object. /// </summary> /// <param name="methodName">Name of the method to invoke</param> /// <param name="parameters">Parameters of method</param> /// <returns>Return value of method</returns> public object InvokeMethod(string methodName, params object[] parameters) { //Check if there is a method with name methodName if (!_methods.ContainsKey(methodName)) { AcknowledgeMessage(Service.IncomingMessage); throw new MethodAccessException("There is not a method with name '" + methodName + "' in service '" + _serviceClassName + "'."); } //Check if method has MDSServiceMethod attribute if (!_methods[methodName]) { AcknowledgeMessage(Service.IncomingMessage); throw new MethodAccessException("Method '" + methodName + "' has not MDSServiceMethod attribute. It can not be invoked from remote applications."); } //Set object properties before method invocation Service.RemoteApplication = new MDSRemoteAppEndPoint(Service.IncomingMessage.SourceServerName, Service.IncomingMessage.SourceApplicationName, Service.IncomingMessage.SourceCommunicatorId); //If Transmit rule is DirectlySend than message must be acknowledged now. //If any exception occurs on method invocation, exception will be sent to //remote application in a MDSRemoteInvokeReturnMessage. if (Service.IncomingMessage.TransmitRule == MessageTransmitRules.DirectlySend) { AcknowledgeMessage(Service.IncomingMessage); } //Invoke method and get return value try { var returnValue = Service.GetType().GetMethod(methodName).Invoke(Service, parameters); if (Service.IncomingMessage.TransmitRule != MessageTransmitRules.DirectlySend) { AcknowledgeMessage(Service.IncomingMessage); } return returnValue; } catch (Exception ex) { if (Service.IncomingMessage.TransmitRule != MessageTransmitRules.DirectlySend) { RejectMessage(Service.IncomingMessage, ex.Message); } if (ex.InnerException != null) { throw ex.InnerException; } throw; } } /// <summary> /// Rejects a message. /// </summary> /// <param name="message">Message to reject</param> /// <param name="reason">Reject reason</param> private static void RejectMessage(IIncomingMessage message, string reason) { try { message.Reject(reason); } catch (Exception ex) { #if __DOT_NET__ Logger.Error(ex.Message, ex); #endif } } } #endregion } }
using System; namespace Singleton { class Program { static void Main(string[] args) { Singleton jogadorUm = Singleton.GetInstancia; jogadorUm.Mensagem("Jogador Um: A bola está comigo no meio do campo."); Singleton jogadorDois = Singleton.GetInstancia; jogadorDois.Mensagem("Jogador Dois: recebeu a bola."); Singleton jogadorTres = Singleton.GetInstancia; jogadorTres.Mensagem("Jogador Tres: recebeu o lançamento."); Console.ReadKey(); } } }
using System; using System.Collections.Generic; using System.Text; namespace CheeseSystem { public class CheeseProductionLine : IProductionLine { public Production Produce() { return new Cheese(); } } }
using UnityEngine; using System.Collections; public class GrowDandelionInMenu : MonoBehaviour { public float maxDandelions; public int level; // Use this for initialization void Start () { // Debug.Log(DataManagement.data.savedDandelions[level]); float scaleX = DataManagement.data.savedDandelions[level] / maxDandelions * 1.5f + 1; Vector3 scale = new Vector3(scaleX, scaleX, scaleX); transform.localScale = scale; } // Update is called once per frame void Update () { } }
using System; namespace KRF.Core.Entities.Sales { public class Proposal { /// <summary> /// Holds Proposal unique identifier /// </summary> public int Id { get; set; } /// <summary> /// Proposal name /// </summary> public string Name { get; set; } /// <summary> /// Details of the job. /// </summary> public Job JobDetail { get; set; } /// <summary> /// Proposal status (Prepared / Uploaded) /// </summary> public string Status { get; set; } /// <summary> /// Proposal price submitted to the customer. /// </summary> public decimal ProposalPrice { get; set; } /// <summary> /// Is Proposal signed (holds True / False) /// </summary> public bool IsApproved { get; set; } /// <summary> /// If signed, holds date and time. /// </summary> public DateTime ApprovedDateAndTime { get; set; } /// <summary> /// Proposal approved user details. /// </summary> public Lead ApprovedBy { get; set; } } }
using Amazon; using Amazon.Runtime; using Amazon.S3; using Amazon.S3.Model; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Moq; using PdfUploder.Controllers; using PdfUploder.Data; using PdfUploder.Models; using PdfUploder.Services; using PdfUploder.Validators; using System; using System.IO; using System.Net; using System.Threading; using System.Threading.Tasks; using Xunit; namespace PdfUploder.Tests { public class DocumentControllerTests { public DocumentControllerTests() { } [Fact(DisplayName = "Valid pdf upload case - done ")] public async Task VaildPdfFileShouldStoreInDatabase() { //Given I have a PDF to upload var formFile = SetupFile("Sample.pdf"); var forms = new Mock<IFormCollection>(); forms.Setup(f => f.Files[It.IsAny<int>()]).Returns(formFile.Object); var client = SetupClient(); SetSinglePutReturn(client); var documentFactory = new DocumentFactory(); var iAmazonClientConnection = new Mock<IAmazonClientConnection>(); iAmazonClientConnection.Setup(f => f.Create()).Returns(new AmazonS3Data() { Cient = client.Object }); var _mockDataContext = new DocumentContext(new AmazonWebServicesS3(iAmazonClientConnection.Object)); var controller = new DocumentController(_mockDataContext, documentFactory, new PdfValidator()); controller.ControllerContext.HttpContext = new DefaultHttpContext(); controller.Request.Form = forms.Object; //When I send the PDF to the API var response = await controller.Upload(formFile.Object); //Then it is uploaded successfully var result = response as CreatedResult; Assert.Equal(201, result.StatusCode); } [Fact(DisplayName = "Invalid pdf case - done ")] public async Task InvaildPdfFileShouldNotBeSavedInDatabase() { //Given I have a non - pdf to upload var _mockDataContext = new Mock<IDocumentContext>(); var formFile = SetupFile("Sample.txt"); var documentFactory = new Mock<IDocumentFactory>(); documentFactory.Setup(f => f.Create(It.IsAny<Stream>())).Returns(new Document() { }); var forms = new Mock<IFormCollection>(); forms.Setup(f => f.Files[It.IsAny<int>()]).Returns(formFile.Object); var controller = new DocumentController(_mockDataContext.Object, documentFactory.Object, new PdfValidator()); controller.ControllerContext.HttpContext = new DefaultHttpContext(); controller.Request.Form = forms.Object; //When I send the non - pdf to the API var response = await controller.Upload(formFile.Object); //Then the API does not accept the file and returns the appropriate messaging and status var result = response as BadRequestObjectResult; Assert.Equal(400, result.StatusCode); Assert.Equal("please upload a valid pdf", result.Value.ToString()); } [Fact(DisplayName = "Large/Max size pdf case - done ")] public async Task MaxSizePdfFileShouldStoreNotInDatabase() { //Given I have a max pdf size of 5MB var _mockDataContext = new Mock<IDocumentContext>(); var formFile = SetupFile("5mb.pdf"); var documentFactory = new Mock<IDocumentFactory>(); documentFactory.Setup(f => f.Create(It.IsAny<Stream>())).Returns(new Document() { }); var forms = new Mock<IFormCollection>(); forms.Setup(f => f.Files[It.IsAny<int>()]).Returns(formFile.Object); var controller = new DocumentController(_mockDataContext.Object, documentFactory.Object, new PdfValidator()); controller.ControllerContext.HttpContext = new DefaultHttpContext(); controller.Request.Form = forms.Object; //When I send the pdf to the API var response = await controller.Upload(formFile.Object); //Then the API does not accept the file and returns the appropriate messaging and status var result = response as BadRequestObjectResult; Assert.Equal(400, result.StatusCode); Assert.Equal("File length should be greater than 0 and less than 5 MB", result.Value.ToString()); } [Fact(DisplayName = "Get documents with properties - done")] public async Task ShouldAllDocumentsWithPropertires() { //Given I call the new document service API var client = SetupClient(); SetMultipleObjectReturn(client); var documentFactory = new Mock<IDocumentFactory>(); var iAmazonClientConnection = new Mock<IAmazonClientConnection>(); iAmazonClientConnection.Setup(f => f.Create()).Returns(new AmazonS3Data() { Cient = client.Object }); var _mockDataContext = new DocumentContext(new AmazonWebServicesS3(iAmazonClientConnection.Object)); var controller = new DocumentController(_mockDataContext, documentFactory.Object, new PdfValidator()); controller.ControllerContext.HttpContext = new DefaultHttpContext(); //When I call the API to get a list of documents var result = await controller.Get(false); //Then a list of PDFs’ is returned with the following properties: name, location, file - size Assert.Equal(2, result.Length); Assert.Equal("media/abc/object1", result[0].Name); Assert.Equal(100, result[0].Size); } [Fact(DisplayName = "Sort order and get list of documents - done")] public async Task ShouldSetOrderForSubsequentCalls() // seems integration test!! { //Given I have a list of PDFs’ var client = SetupClient(); SetMultipleObjectReturn(client); var documentFactory = new Mock<IDocumentFactory>(); var iAmazonClientConnection = new Mock<IAmazonClientConnection>(); iAmazonClientConnection.Setup(f => f.Create()).Returns(new AmazonS3Data() { Cient = client.Object }); var _mockDataContext = new DocumentContext(new AmazonWebServicesS3(iAmazonClientConnection.Object)); var controller = new DocumentController(_mockDataContext, documentFactory.Object, new PdfValidator()); controller.ControllerContext.HttpContext = new DefaultHttpContext(); //When I choose to re-order the list of PDFs’ await controller.Reorder(); var result = await controller.Get(true); //Then the list of PDFs’ is returned in the new order for subsequent calls to the API Assert.Equal(2, result.Length); Assert.Equal("media/abc/object2", result[0].Name); Assert.Equal(200, result[0].Size); } [Fact(DisplayName = "Download file case - done")] public async Task ShouldDownloadPdfForGivenId() { //Given I have chosen a PDF from the list API var client = SetupClient(); SetSingleGetReturn(client); var documentFactory = new Mock<IDocumentFactory>(); var iAmazonClientConnection = new Mock<IAmazonClientConnection>(); iAmazonClientConnection.Setup(f => f.Create()).Returns(new AmazonS3Data() { Cient = client.Object }); var _mockDataContext = new DocumentContext(new AmazonWebServicesS3(iAmazonClientConnection.Object)); var controller = new DocumentController(_mockDataContext, documentFactory.Object, new PdfValidator()); controller.ControllerContext.HttpContext = new DefaultHttpContext(); //When I request the location for one of the PDF's var result = await controller.Get(Guid.Parse("4222bf69-b536-4d19-86a8-b84aeb6643b2")) as FileStreamResult; //The PDF is downloaded Assert.NotNull(result.FileStream); Assert.True(result.FileDownloadName.Equals("download.pdf")); } [Fact(DisplayName = "Should not download file after delete ")] public async Task ShouldNoDownloadPdfForAGivenIdAfterDelete() { //Given I have selected a PDF from the list API that I no longer require var client = SetupClient(); SetSingleGetReturn(client); SetSingleDeleteReturn(client); var documentFactory = new Mock<IDocumentFactory>(); var iAmazonClientConnection = new Mock<IAmazonClientConnection>(); iAmazonClientConnection.Setup(f => f.Create()).Returns(new AmazonS3Data() { Cient = client.Object }); var _mockDataContext = new DocumentContext(new AmazonWebServicesS3(iAmazonClientConnection.Object)); var controller = new DocumentController(_mockDataContext, documentFactory.Object, new PdfValidator()); controller.ControllerContext.HttpContext = new DefaultHttpContext(); //When I request to delete the PDF await controller.Delete(Guid.Parse("4222bf69-b536-4d19-86a8-b84aeb6643b0")); var response = await controller.Get(Guid.Parse("4222bf69-b536-4d19-86a8-b84aeb6643b0")); var result = response as NotFoundResult; //Then the PDF is deleted and will no longer return from the list API and can no longer be downloaded from its location directly Assert.Equal(404, result.StatusCode); } [Fact(DisplayName = "Should get message for non existant - done ")] public async Task ShouldGetMessageForNonExistantDelete() { // Given I attempt to delete a file that does not exist var client = SetupClient(); SetMultipleObjectReturn(client); SetSingleDeleteReturn(client); var documentFactory = new Mock<IDocumentFactory>(); var iAmazonClientConnection = new Mock<IAmazonClientConnection>(); iAmazonClientConnection.Setup(f => f.Create()).Returns(new AmazonS3Data() { Cient = client.Object }); var _mockDataContext = new DocumentContext(new AmazonWebServicesS3(iAmazonClientConnection.Object)); var controller = new DocumentController(_mockDataContext, documentFactory.Object, new PdfValidator()); controller.ControllerContext.HttpContext = new DefaultHttpContext(); //When I request to delete the non-existing pdf var response = await controller.Delete(Guid.Parse("4222bf69-b536-4d19-86a8-b84aeb6643b0")); //Then the API returns an appropriate response var result = response as NotFoundResult; Assert.Equal(404, result.StatusCode); } #region private methods private Mock<IFormFile> SetupFile(string fileName) { var file = new Mock<IFormFile>(); var source = File.ReadAllBytes(fileName); var stream = new MemoryStream(); var writer = new StreamWriter(stream); writer.Write(source); writer.Flush(); stream.Position = 0; file.Setup(f => f.OpenReadStream()).Returns(stream); file.Setup(f => f.FileName).Returns(fileName); file.Setup(f => f.Length).Returns(source.Length); return file; } private Mock<AmazonS3Client> SetupClient() { return new Mock<AmazonS3Client>(FallbackCredentialsFactory.GetCredentials(true), new AmazonS3Config { RegionEndpoint = RegionEndpoint.EUWest2 }); } private Stream SetSingleGetReturn(Mock<AmazonS3Client> s3ClientMock, string pathToTestDoc = "sample.pdf") { var docStream = new FileInfo(pathToTestDoc).OpenRead(); s3ClientMock .Setup(x => x.GetObjectAsync( It.IsAny<string>(), It.IsAny<string>(), It.IsAny<CancellationToken>())) .ReturnsAsync( GetObjectResponsetSetup(docStream)); return docStream; } private void SetSinglePutReturn(Mock<AmazonS3Client> s3ClientMock) { s3ClientMock .Setup(x => x.PutObjectAsync( It.IsAny<PutObjectRequest>(), It.IsAny<CancellationToken>())) .ReturnsAsync( PutObjectResponseSetup()); } private void SetMultipleObjectReturn(Mock<AmazonS3Client> s3ClientMock) { var response = new ListObjectsResponse { IsTruncated = false }; response.S3Objects.AddRange(new[] { new S3Object { Key = "media/abc/object1", Size=100 }, new S3Object { Key = "media/abc/object2", Size=200 } }); s3ClientMock.Setup(x => x.ListObjectsAsync( It.IsAny<string>(), It.IsAny<CancellationToken>() )).ReturnsAsync(response); } private static Func<PutObjectRequest, CancellationToken, PutObjectResponse> PutObjectResponseSetup() { return (PutObjectRequest request, CancellationToken ct) => PutObjectResponse(); } private static PutObjectResponse PutObjectResponse() { return new PutObjectResponse { HttpStatusCode = HttpStatusCode.OK }; } private static Func<string, string, CancellationToken, GetObjectResponse> GetObjectResponsetSetup(FileStream docStream) { return (string bucket, string key, CancellationToken ct) => GetObjectResponse(bucket, key, docStream); } private static GetObjectResponse GetObjectResponse(string bucket, string key, FileStream docStream) { return new GetObjectResponse { BucketName = bucket, Key = key, HttpStatusCode = HttpStatusCode.OK, ResponseStream = docStream, }; } private void SetSingleDeleteReturn(Mock<AmazonS3Client> s3ClientMock) { s3ClientMock .Setup(x => x.DeleteObjectAsync( It.IsAny<DeleteObjectRequest>(), It.IsAny<CancellationToken>())) .ReturnsAsync( DeleteObjectResponse()); } private static DeleteObjectResponse DeleteObjectResponse() { return new DeleteObjectResponse { HttpStatusCode = HttpStatusCode.OK }; } #endregion private methods } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using SmallHouseManagerBLL; using SmallHouseManagerModel; namespace SmallHouseManagerWeb { public partial class AboutUs : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { BaseInfoBLL bll = new BaseInfoBLL(); List<BaseInfoModel> list = bll.ShowBaseInfo(); if (list.Count != 0) { MainHead.Text = list[0].MainHead; Tel.Text = list[0].Tel; Address.Text = list[0].Address; } } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.EventSystems; using UnityEngine.UI; public class CreditsScript : MonoBehaviour, IDragHandler { public float speed; private ScrollRect credits; private float timer; // Start is called before the first frame update void Start() { credits = GetComponent<ScrollRect>(); } void OnEnable() { timer = 0.25f; } // Update is called once per frame void Update() { if (timer > 0) { timer -= Time.deltaTime; } else { if (credits.verticalNormalizedPosition > 0) { credits.verticalNormalizedPosition -= Time.deltaTime*(speed/100); } } } public void OnDrag(PointerEventData eventData) { timer = 2; } }
using System; using System.Collections.Generic; using System.Text; namespace OPG5TCP { public class Beer { // 4 ins private string _name; private int _id; private double _price; private double _adv; // 4 props public string Name { get => _name; set { if (value.Length < 4) throw new ArgumentException(); _name = value; } } public int ID { get => _id; set { _id = value; } } public double Price { get => _price; set { if (value <= 0) throw new ArgumentOutOfRangeException(); _price = value; } } public double Adv { get => _adv; set { if (value >= 100 || value <= 0) throw new ArgumentOutOfRangeException(); _adv = value; } } // Constructor for 4 props public Beer(string name, int id, double price, double adv) { Name = name; ID = id; Price = price; Adv = adv; } // Const for server public Beer() { } // og en ToString til at get by id: public override string ToString() { return "Name: " + Name + " Id: " + ID + " Price: " + Price + " %: " + Adv; } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; [System.Serializable] public class ObstaclePrefab { public int difficulty; public GameObject obstaclePrefab; } public class SurvivalModeManagerScript : MonoBehaviour { public GameObject startGameText; public PlayerControllerScript playerControllerScript; // Contains SurvivalModeWallScripts public ArrayList environmentObjects = new ArrayList(); public int currentDifficulty = 0; // For future reference, this SHOULD be put to a dictionary for quickly referencing difficulty to obstacle arrays public ObstaclePrefab[] spawnablePrefabs; public float scrollSpeed = 5.0f; public float spawnDistance = 12.0f; // Absolute vertical distance from y public float spawnMidpointDistance = 5.0f; public Vector2 cullingDistanceFromCenter = new Vector2(12.0f, 8.0f); public Vector2 playerKillBoundsFromCenter = new Vector2(12.0f, 8.0f); public float timeBetweenSpawns = 10.0f; float timeBetweenSpawnsAcc = 0.0f; int removedObject = 0; bool gameStart = false; bool shouldSpawn = false; private bool GameObjectCulling(GameObject observedGameObject, Vector2 objectPos) { // This code is to be removed once the object spawning system is added if (objectPos.x < -1 * cullingDistanceFromCenter.x || objectPos.y < -1 * cullingDistanceFromCenter.y) { Destroy(observedGameObject); removedObject++; return true; } return false; } private void GameObjectSpawning() { /// Spawn Decision code if (!shouldSpawn) { timeBetweenSpawnsAcc += Time.deltaTime; if (timeBetweenSpawnsAcc >= timeBetweenSpawns) shouldSpawn = true; } else { /// Spawning Code // This is all to be changed Instantiate(spawnablePrefabs[0].obstaclePrefab, new Vector2(spawnDistance, Random.Range(-1 * spawnMidpointDistance, spawnMidpointDistance)), Quaternion.Euler(0, 0, 90)); shouldSpawn = false; timeBetweenSpawnsAcc = 0; } } void Update() { if(!gameStart) { /// Pre-gameplay Code // Input starts the game and removes the start game text if (Input.GetMouseButtonUp(0) || Input.GetMouseButtonUp(1)) { gameStart = true; startGameText.SetActive(false); } } else { /// Gameplay Code // Obstacle Updating foreach (GameObject o in environmentObjects) { Vector2 t = o.transform.position; t.x -= scrollSpeed * Time.deltaTime; if (GameObjectCulling(o, t)) continue; o.transform.position = t; } // Obstacle Spawning GameObjectSpawning(); // Player Object Updating // Check for game over if (playerControllerScript.gameObject.transform.position.x < -1.0f * playerKillBoundsFromCenter.x || playerControllerScript.gameObject.transform.position.y < -1.0f * playerKillBoundsFromCenter.y) { // Destroy Player and Trigger Gameover Debug.Log("Game Over"); } } } }
using Microsoft.ServiceBus; using Microsoft.ServiceBus.Messaging; using System; using System.Collections.Generic; using System.Configuration; using System.Linq; using System.Web; using System.Web.Mvc; namespace WebRole1.Models { public class ServiceBusController : Controller { static public int cnt = 0; // GET: ServiceBus public ActionResult ServiceBus() { return View(); } [HttpPost] public ActionResult ServiceBus(ServiceBusQueue objServiceBusQueue) { QueueClient client=CreateBusConnection(objServiceBusQueue); BrokeredMessage objbrokeredmsg = new BrokeredMessage(objServiceBusQueue); objbrokeredmsg.Properties["TestProperty"] = objServiceBusQueue.TestProperty; cnt = cnt+1; objbrokeredmsg.Properties["Message number"] = cnt; client.Send(objbrokeredmsg); return View(); } private QueueClient CreateBusConnection(ServiceBusQueue objServiceBusQueue) { string connectionstring = ConfigurationManager.ConnectionStrings["servicebuscon"].ConnectionString; var namespacemanager = NamespaceManager.CreateFromConnectionString(connectionstring); QueueDescription qd = new QueueDescription(objServiceBusQueue.QueueName); qd.MaxSizeInMegabytes = 5120; qd.DefaultMessageTimeToLive = new TimeSpan(0, 10, 0); if (!namespacemanager.QueueExists(objServiceBusQueue.QueueName)) { namespacemanager.CreateQueue(qd); } QueueClient client = QueueClient.CreateFromConnectionString(connectionstring, objServiceBusQueue.QueueName); return client; } string msg = ""; public ActionResult Receive(ServiceBusQueue objServiceBusQueue) { string connectionstring = ConfigurationManager.ConnectionStrings["servicebuscon"].ConnectionString; QueueClient client = QueueClient.CreateFromConnectionString(connectionstring, objServiceBusQueue.QueueName); List<ServiceBusQueue> lstQueue = new List<ServiceBusQueue>(); OnMessageOptions options = new OnMessageOptions(); options.AutoComplete = false; options.AutoRenewTimeout = TimeSpan.FromMinutes(1); BrokeredMessage BM = new BrokeredMessage(); for (int i = 0; i < cnt; i++) { try { BM = new BrokeredMessage(); BM = client.Receive(TimeSpan.FromMinutes(1)); if (BM != null) { objServiceBusQueue = new ServiceBusQueue(); objServiceBusQueue = BM.GetBody<ServiceBusQueue>(); lstQueue.Add(objServiceBusQueue); } } catch (Exception) { } } cnt = 0; //BM = client.Receive(TimeSpan.FromMinutes(1)); //if (BM!=null) //{ // //objServiceBusQueue.Message = "Body: " + BM.GetBody<string>(); // //objServiceBusQueue.ID = "MessageID: " + BM.MessageId; // lstQueue = BM.GetBody<List<ServiceBusQueue>>(); //} //client.OnMessage(message => //{ // msg = "Body: " + message.GetBody<string>(); // msg += "MessageID: " + message.MessageId; // message.Complete(); //}, options); return Json(lstQueue); } public static int topiccnt = 0; [HttpPost] public ActionResult CreateTopic(ServiceBusTopic objServiceBusTopic) { string connectionstring = ConfigurationManager.ConnectionStrings["servicebuscon"].ConnectionString; TopicDescription td = new TopicDescription("AnandTopic"); td.MaxSizeInMegabytes = 5130; td.DefaultMessageTimeToLive = new TimeSpan(0, 50, 0); var namespacemanager = NamespaceManager.CreateFromConnectionString(connectionstring); if (!namespacemanager.TopicExists("AnandTopic")) { namespacemanager.CreateTopic("AnandTopic"); } if (!namespacemanager.SubscriptionExists("AnandTopic", "SUB1")) { SqlFilter sqlfilter = new SqlFilter("MessageNumber > 2"); namespacemanager.CreateSubscription("AnandTopic", "SUB1", sqlfilter); } if (!namespacemanager.SubscriptionExists("AnandTopic", "SUB2")) { SqlFilter sqlfilter = new SqlFilter("MessageNumber <= 2"); namespacemanager.CreateSubscription("AnandTopic", "SUB2", sqlfilter); } TopicClient cl = TopicClient.CreateFromConnectionString(connectionstring, "AnandTopic"); BrokeredMessage BM = new BrokeredMessage(objServiceBusTopic.TPMessage); topiccnt += 1; BM.Properties["MessageNumber"] = topiccnt; cl.Send(BM); return View("ServiceBus"); } public ActionResult ReceiveTopic() { string connectionstring = ConfigurationManager.ConnectionStrings["servicebuscon"].ConnectionString; ServiceBusTopic objServiceBusTopic = new ServiceBusTopic(); var namespaceManager = NamespaceManager.CreateFromConnectionString(connectionstring); var ss = namespaceManager.GetSubscriptions("AnandTopic"); List<ServiceBusTopic> lstTopic = new List<ServiceBusTopic>(); foreach (var item in ss) { SubscriptionClient client = SubscriptionClient.CreateFromConnectionString(connectionstring, "AnandTopic", item.Name); BrokeredMessage bm = new BrokeredMessage(); for (int i = 0; i < topiccnt; i++) { bm = new BrokeredMessage(); bm = client.Receive(TimeSpan.FromMinutes(1)); if (bm != null) { objServiceBusTopic = new ServiceBusTopic(); objServiceBusTopic.TPMessage = bm.GetBody<string>(); objServiceBusTopic.Subcription = item.Name; lstTopic.Add(objServiceBusTopic); } } } return Json(lstTopic); } } }
#region Usings using CoreModel.Interfaces.Interfaces; #endregion Usings namespace CoreModel.Impl.Impl { public class Hybrid : Dancer, IHybrid { public Hybrid(string name) : base(name) { } } }
using UnityEngine; using System.Collections; using UnityEngine.UI; using UnityEngine.SceneManagement; public class EndGameManager : MonoBehaviour { [SerializeField] private Text endGameMessage; [SerializeField] private string loseMessage; [SerializeField] private string winMessage; [SerializeField] private string tieMessage; public static int experienceGained; public static PlayerProperties.GameResult gameResult; void Start() { PhotonNetwork.automaticallySyncScene = false; PhotonNetwork.LeaveRoom(); InputState.ActivateMenuInput(); SetMessage(gameResult); GetComponent<ExperienceBarManager>().AddExperienceAndAnimate(experienceGained); ResetEndGameState(); } private void ResetEndGameState() { experienceGained = 0; gameResult = PlayerProperties.GameResult.None; } private void SetMessage(PlayerProperties.GameResult result) { switch(result) { case PlayerProperties.GameResult.None: endGameMessage.text = "None maybe error?"; break; case PlayerProperties.GameResult.Lose: endGameMessage.text = loseMessage; break; case PlayerProperties.GameResult.Tie: endGameMessage.text = tieMessage; break; case PlayerProperties.GameResult.Win: endGameMessage.text = winMessage; break; } } public void OnMainMenuButtonPressed() { SceneManager.LoadScene("MainMenu"); } }
using GameTOP.Interface; namespace GameTOP { public class JogoFoda { private readonly iJogador _jogadorA; private readonly iJogador _jogadorB; public JogoFoda(iJogador jogadorA, iJogador jogadorB) { _jogadorA = jogadorA; _jogadorB = jogadorB; } public void IniciarJogo() { //System.Console.WriteLine($"{_jogador._Nome} deu um passe"); System.Console.WriteLine(_jogadorA.Corre()); System.Console.WriteLine(_jogadorA.Chuta()); System.Console.WriteLine(_jogadorA.Passa()); System.Console.Write("\nPRÓXIMO JOGADOR \n"); System.Console.WriteLine(_jogadorB.Corre()); System.Console.WriteLine(_jogadorB.Chuta()); System.Console.WriteLine(_jogadorB.Passa()); } } }
using System; using System.Collections.Generic; namespace Paralect.Schematra.SDO { /** * A representation of a Property in the {@link Type type} of a {@link DataObject data object}. */ public interface IProperty { /** * Returns the name of the Property. * @return the Property name. */ String GetName(); /** * Returns the type of the Property. * @return the Property type. */ IType GetType(); /** * Returns whether the Property is many-valued. * @return <code>true</code> if the Property is many-valued. */ Boolean IsMany(); /** * Returns whether the Property is containment, i.e., whether it represents by-value composition. * @return <code>true</code> if the Property is containment. */ Boolean IsContainment(); /** * Returns the containing type of this Property. * @return the Property's containing type. * @see Type#getProperties() */ Type GetContainingType(); /** * Returns the default value this Property will have in a {@link DataObject data object} where the Property hasn't been set. * @return the default value. */ Object GetDefault(); /** * Returns true if values for this Property cannot be modified using the SDO APIs. * When true, DataObject.set(Property property, Object value) throws an exception. * Values may change due to other factors, such as services operating on DataObjects. * @return true if values for this Property cannot be modified. */ Boolean IsReadOnly(); /** * Returns the opposite Property if the Property is bi-directional or null otherwise. * @return the opposite Property if the Property is bi-directional or null */ IProperty GetOpposite(); /** * Returns a list of alias names for this Property. * @return a list of alias names for this Property. */ List<String> GetAliasNames(); /** * Returns whether or not instances of this property can be set to null. The effect of calling set(null) on a non-nullable * property is not specified by SDO. * @return true if this property is nullable. */ Boolean IsNullable(); /** * Returns whether or not this is an open content Property. * * Open Content Property is just properties that wasn't defined in the IType. * * From (3.1.9 of Java-SDO-Spec-v2.1.0-FINAL.pdf) * DataObjects can have two kinds of Properties: * 1. Those specified by their Type (see Type) * 2. Those not specified by their Type. These additional properties are called open content. * * @return true if this property is an open content Property. */ Boolean IsOpenContent(); /** * Returns a read-only List of instance Properties available on this Property. * <p> * This list includes, at a minimum, any open content properties (extensions) added to * the object before {@link commonj.sdo.helper.TypeHelper#define(DataObject) defining * the Property's Type}. Implementations may, but are not required to in the 2.1 version * of SDO, provide additional instance properties. * @return the List of instance Properties on this Property. */ List<IProperty> GetInstanceProperties(); /** * Returns the value of the specified instance property of this Property. * @param property one of the properties returned by {@link #getInstanceProperties()}. * @return the value of the specified property. * @see DataObject#get(Property) */ Object Get(IProperty property); } }
using Newtonsoft.Json; using System; using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEditor; using NetMQ; using NetMQ.Sockets; public class HololensMessage : MonoBehaviour { //type of touch(one tap,double tap) public int Type { get; set; } //name of object touched public string Name { get; set; } //position of cursor public Vector3 Position { get; set; } public HololensMessage(Vector3 position) { this.Position = position; } public HololensMessage(int type, string name, Vector3 position) { this.Type = type; this.Name = name; this.Position = position; } public HololensMessage(int type, string name, float[] position) { this.Type = type; this.Name = name; this.Position = new Vector3(position[0], position[1], position[2]); } public static string GetHololensMessage(HololensMessage hololensMessage) { string message = ""; try { // message = JsonConvert.SerializeObject(hololensMessage); } catch (Exception e) { print("Failed to serialize object"); } return message; } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Text; using System.Threading.Tasks; using NewsMooseClassLibrary.Interfaces; using NewsMooseClassLibrary.Models; using NewsMooseClassLibrary.DataBase; namespace NewsMooseClassLibrary.ViewModels { public class TuiViewModel : IViewModel { private IDataBase database; private List<Publisher> publishers; public List<Publisher> Publishers { get { return publishers ?? (publishers = new List<Publisher>()); } set { if (publishers != value) { publishers = value; OnPropertyChanged(nameof(Publishers)); } } } private List<NewsPaper> newspapers; public List<NewsPaper> NewsPapers { get { return newspapers ?? (newspapers = new List<NewsPaper>()); } set { if (newspapers != value) { newspapers = value; OnPropertyChanged(nameof(NewsPapers)); } } } public TuiViewModel() { //database = new XmlStorage(); database = new DatabaseStorage(); XmlDataBase loadedDataBase = database.LoadDataBase(); Publishers = loadedDataBase?.Publishers.ToList(); NewsPapers = loadedDataBase?.NewsPapers.ToList(); } public event PropertyChangedEventHandler PropertyChanged; public void OnPropertyChanged(string name) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name)); } public void CreateNewNewsPaper(string name) { NewsPaper newspaper = new NewsPaper(name); NewsPapers.Add(newspaper); OnPropertyChanged(nameof(NewsPapers)); SaveDataBase(); } public void CreateNewPublisher(string name) { Publisher publisher = new Publisher(name); Publishers.Add(publisher); OnPropertyChanged(nameof(Publishers)); SaveDataBase(); } public void DeleteNewsPaper(NewsPaper newsPaper) { NewsPapers.Remove(newsPaper); OnPropertyChanged(nameof(NewsPapers)); SaveDataBase(); } public void DeletePublisher(Publisher publisher) { Publishers.Remove(publisher); OnPropertyChanged(nameof(Publishers)); SaveDataBase(); } public void ShowNewsPaper() { foreach (NewsPaper paper in NewsPapers) { Console.WriteLine($"Name: {paper.Name} | Publisher: {paper.Publisher?.Name}"); } } public void ShowPublishers() { foreach (Publisher publisher in Publishers) { Console.WriteLine($"Publisher: {publisher.Name}"); Console.WriteLine("NewsPapers:"); foreach (NewsPaper paper in publisher.NewsPapers) { Console.WriteLine($"- {paper.Name}"); } } } public void UpdateNewsPaper(NewsPaper newsPaper, string newName) { newsPaper.Name = newName; OnPropertyChanged(nameof(NewsPapers)); SaveDataBase(); } public void UpdatePublisher(Publisher publisher, string newName) { publisher.Name = newName; OnPropertyChanged(nameof(Publishers)); SaveDataBase(); } private void SaveDataBase() { database.SaveDataBase(new XmlDataBase(NewsPapers.ToArray(), Publishers.ToArray())); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class Announcer : MonoBehaviour { [Header("Sound Effects")] [SerializeField] AudioClip[] readyClips = null; [SerializeField] float startDelay = 1.0f; [Range(0.0f, 1.0f)] [SerializeField] float readyVolume = 1.0f; // Cached References AudioSource audioSource = null; private void Awake() { audioSource = GetComponent<AudioSource>(); } private void Start() { StartCoroutine(AnnounceFightStart()); } IEnumerator AnnounceFightStart() { yield return new WaitForSeconds(startDelay); if(audioSource && readyClips.Length > 0) { int index = Random.Range(0, readyClips.Length); audioSource.volume = readyVolume; audioSource.clip = readyClips[index]; audioSource.Play(); } } }
using OpenQA.Selenium; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using workshopWithPOM.Controls; namespace workshopWithPOM { public class CareerPage : BasePage { public CareerPage() : base(By.XPath("")) { } public Link Link { get { return new Link(By.XPath("//a[contains(text(),'Plan de Carrera')]")); } } // para locators, y metodos con varios pasos/acciones } }
using System; using System.Collections.Generic; namespace LinkeListImplementation { public class LinkedList<T> : IEnumerable<ListItem<T>> { public LinkedList(ListItem<T> firstElement) { this.FirstElement = firstElement; } public ListItem<T> FirstElement { get; private set; } public IEnumerator<ListItem<T>> GetEnumerator() { var currentElement = this.FirstElement; while (true) { yield return currentElement; if (currentElement.NextItem == null) { break; } currentElement = currentElement.NextItem; } } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return this.GetEnumerator(); } } }
using DebugTools; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; using System.Windows.Forms; namespace SupercapController { /// <summary> /// Send commands to all selected devices in dataGridView, with selected time period /// </summary> class CapSequencer { int isActive = 0; /// <summary> /// When CapSequencer is active this value will show which capacitor array is being worked with /// </summary> public int IsActive { get { return isActive; } } DataGridView _dgv; public CapSequencer(DataGridView dgv) { _dgv = dgv; } /// <summary> /// Send commands based on textfields to selected cells in dataGridView /// </summary> public async void SendCommandsToSelectedCells() { // Get selected devices var list = ExtractSelectedCheckboxesFromDataGridView(_dgv); if (list.Count == 0) { MessageBox.Show("Select one or more devices first!"); return; } // Return cell painting to default foreach (var item in list) { ConfigClass.UpdateWorkingDeviceAddress(item); // Send Commands // Paint the cell FormCustomConsole.WriteLineWithConsole("Sending to ID:" + item); // Wait await Task.Delay(1000); FormCustomConsole.WriteLineWithConsole("ID:" + item + " finished"); } } public async void ReadMeasurementsFromSelectedCells() { // Get selected devices var list = ExtractSelectedCheckboxesFromDataGridView(_dgv); if (list.Count == 0) { MessageBox.Show("Select one or more devices first!"); return; } foreach (var item in list) { ConfigClass.UpdateWorkingDeviceAddress(item); Console.WriteLine("Sending to ID:" + item); // Wait await Task.Delay(1000); Console.WriteLine("ID:" + item + " finished"); } } private List<int> ExtractSelectedCheckboxesFromDataGridView(DataGridView dgv) { List<int> list = new List<int>(); int rowIndex = 0; int colIndex = 0; foreach (DataGridViewRow item in dgv.Rows) { colIndex = 0; foreach (DataGridViewCell item2 in item.Cells) { if (item2 is DataGridViewCheckBoxCell) { if (item2.Value != null && item2.Value is bool) { if ((bool)item2.Value) { list.Add((int)dgv.Rows[rowIndex].Cells[colIndex - 1].Value); } } } colIndex++; } rowIndex++; } return list; } } }
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.Xml; using System.IO; namespace checkProject { public partial class FormMain : Form { public FormMain() { InitializeComponent(); } private void FormMain_Load(object sender, EventArgs e) { this.Text = Application.ProductName; this.Text += " (check UseDebugLibraries)"; try { // checkProject(@"C:\T\Win32Project1\Win32Project1\Win32Project1.vcxproj"); } catch (Exception ex) { MessageBox.Show(ex.Message); } } string getSafeAttribute(XmlNode node, string attr) { if (node.Attributes[attr] == null) return string.Empty; return node.Attributes[attr].Value; } void checkProject(string file) { XmlDocument xmlDocument = new XmlDocument(); StringBuilder sb = new StringBuilder(); xmlDocument.Load(file); var nsmgr = new XmlNamespaceManager(xmlDocument.NameTable); nsmgr.AddNamespace("a", "http://schemas.microsoft.com/developer/msbuild/2003"); XmlNodeList nodeList = xmlDocument.SelectNodes("//a:PropertyGroup",nsmgr); foreach(XmlNode node in nodeList) { if (getSafeAttribute(node,"Label") != "Configuration") continue; string cond = node.Attributes["Condition"].Value; if (cond.ToLower().IndexOf("debug") != -1) { checkNode(node, sb, true); } else if (cond.ToLower().IndexOf("release") != -1) { checkNode(node, sb, false); } else if (cond.ToLower().IndexOf("ship") != -1) { checkNode(node, sb, false); } else { sb.AppendLine("Unknown Node: " + cond); } } appendResult(sb.ToString()); } void appendResult(string s) { txtResult.Text += s; txtResult.SelectionStart = txtResult.Text.Length; // add some logic if length is 0 txtResult.SelectionLength = 0; } void checkNode(XmlNode node, StringBuilder sb, bool isdebug) { XmlNode udl = null; foreach (XmlNode cn in node.ChildNodes) { if (cn.Name == "UseDebugLibraries") { udl = cn; break; } } bool ok = false; if (isdebug) { ok = udl != null && udl.InnerText == "true"; } else { ok = udl != null && udl.InnerText == "false"; } if (ok) { sb.Append("OK"); } else { sb.Append("NG"); } sb.Append(" : "); string s = string.Format("{0}={1}", "Condition", node.Attributes["Condition"].Value); s += " "; s += string.Format("{0}={1}", "UseDebugLibraries", udl != null ? udl.InnerText : "NA"); sb.AppendLine(s); } private void btnBrowse_Click(object sender, EventArgs e) { using (FolderBrowserDialog dlg = new FolderBrowserDialog()) { if (DialogResult.OK != dlg.ShowDialog()) return; txtFolder.Text = dlg.SelectedPath; } } private void btnStart_Click(object sender, EventArgs e) { try { doStart(new DirectoryInfo(txtFolder.Text)); } catch (Exception ex) { MessageBox.Show(ex.Message); } } bool isFilterProject(string projname) { if (string.IsNullOrEmpty(txtFilter.Text)) return false; if (-1 != projname.ToLower().IndexOf(txtFilter.Text.ToLower())) { // found text same as filter return false; } return true; } void doStart(DirectoryInfo di) { foreach (FileInfo proj in di.GetFiles("*.vcxproj")) { if (isFilterProject(proj.Name)) continue; appendResult(string.Format("===== analyzing {0} =====\r\n", proj.FullName)); checkProject(proj.FullName); } foreach (DirectoryInfo childdi in di.GetDirectories()) { doStart(childdi); } } private void btnClear_Click(object sender, EventArgs e) { txtResult.Text = string.Empty; } } }
using MetroFramework; using MetroFramework.Forms; using PDV.CONTROLER.Funcoes; using PDV.DAO.DB.Utils; using PDV.DAO.Entidades; using PDV.DAO.Enum; using PDV.VIEW.App_Context; using System; using System.Windows.Forms; namespace PDV.VIEW.Forms.Cadastro { public partial class FCA_Pais : DevExpress.XtraEditors.XtraForm { private string NOME_TELA = "CADASTRO DE PAIS"; private Pais _Pais = null; public FCA_Pais(Pais _P) { InitializeComponent(); _Pais = _P; PreencherTela(); } private void PreencherTela() { ovTXT_Codigo.Text = _Pais.Codigo; ovTXT_Descricao.Text = _Pais.Descricao; } private void ovBTN_Cancelar_Click(object sender, System.EventArgs e) { Close(); } private void ovBTN_Salvar_Click(object sender, System.EventArgs e) { try { PDVControlador.BeginTransaction(); if (string.IsNullOrEmpty(ovTXT_Codigo.Text.Trim())) throw new Exception("Informe O Código."); if (string.IsNullOrEmpty(ovTXT_Descricao.Text.Trim())) throw new Exception("Informe a Descrição."); _Pais.Codigo = ovTXT_Codigo.Text; _Pais.Descricao = ovTXT_Descricao.Text; DAO.Enum.TipoOperacao Op = DAO.Enum.TipoOperacao.UPDATE; if (!FuncoesPais.Existe(_Pais.IDPais)) { _Pais.IDPais = Sequence.GetNextID("PAIS", "IDPAIS"); Op = DAO.Enum.TipoOperacao.INSERT; } if (!FuncoesPais.Salvar(_Pais, Op)) throw new Exception("Não foi possível salvar o Pais."); PDVControlador.Commit(); MessageBox.Show(this, "Pais salvo com sucesso.", NOME_TELA, MessageBoxButtons.OK, MessageBoxIcon.Information); Close(); } catch (Exception Ex) { PDVControlador.Rollback(); MessageBox.Show(this, Ex.Message, NOME_TELA, MessageBoxButtons.OK, MessageBoxIcon.Error); } } private void FCA_Pais_KeyDown(object sender, KeyEventArgs e) { switch (e.KeyCode) { case Keys.Escape: this.Close(); break; } } } }
using System; using System.Collections.Generic; using System.Configuration; namespace OnlineTrainTicketBooking { internal class UserRepository { public static Dictionary<string, User> userCredential = new Dictionary<string, User>(); private string AdminId { get; set; } = ConfigurationManager.AppSettings["admin"].ToString(); private string AdminPassword { get; set; } = ConfigurationManager.AppSettings["password"].ToString(); public static string LoggedInUserId ; static UserRepository() { userCredential.Add("abc@gmail.com", new User("User", "1234", DateTime.Today, 1234567890)); } public void Register(string mailId, User user) { userCredential.Add(mailId, user); } //Checks the Login credentials public bool CheckLoginCredentials(string loginId, string password) { try { if (loginId == AdminId && password == AdminPassword) //Checks for Admin { HomePage.adminStatus = true; HomePage.LoggedInStatus = true; return true; } else if (UserRepository.userCredential.ContainsKey(loginId)) //Checks for User { if (UserRepository.userCredential[loginId].Password == password) { HomePage.LoggedInStatus = true; LoggedInUserId = loginId; return true; } } } catch { Console.WriteLine("[INFO] Values Cannot be Null"); } return false; } } }
using System.Web.UI; using Aqueduct.SitecoreLib.Examples.SampleApplication.Business.Domain.Widgets; namespace Aqueduct.SitecoreLib.Examples.SampleApplication.Web.Controls.Widgets { public partial class GooglePlusWidgetControl : UserControl, IWidgetControl { public IWidget Widget { set { } } } }
using FFImageLoading.Extensions; using Foundation; using Kit.Forms.Services.Interfaces; using Kit.iOS.Services; using System; using System.IO; using System.Threading.Tasks; using UIKit; using Xamarin.Forms; [assembly: Dependency(typeof(ImageCompressService))] namespace Kit.iOS.Services { [Preserve(AllMembers = true)] public class ImageCompressService : IImageCompressService { public async Task<FileStream> CompressImage(Stream imageData, int Quality) { await Task.Yield(); string path = System.IO.Path.Combine(Kit.Tools.Instance.TemporalPath, $"{Guid.NewGuid():N}.jpeg"); using (NSData nsData = NSData.FromStream(imageData)) { using (UIImage uiimage = UIImage.LoadFromData(nsData)) { using (Stream compressed = uiimage.AsJpegStream(Quality)) { FileStream stream = new FileStream(path, FileMode.OpenOrCreate); await compressed.CopyToAsync(stream); return stream; } } } } } }
using System; namespace exe_15 { class Program { static void Main(string[] args) { Console.Clear(); System.Console.WriteLine("======* Meses *======"); System.Console.Write("Insira um número de 1 a 12 e eu direi qual é o mês: "); int num = int.Parse(Console.ReadLine()); switch(num) { case 1: System.Console.WriteLine($"Mês {num} é igual a: Janeiro"); break; case 2: System.Console.WriteLine($"Mês {num} é igual a: Fevereiro"); break; case 3: System.Console.WriteLine($"Mês {num} é igual a: Março"); break; case 4: System.Console.WriteLine($"Mês {num} é igual a: Abril"); break; case 5: System.Console.WriteLine($"Mês {num} é igual a: Maio"); break; case 6: System.Console.WriteLine($"Mês {num} é igual a: Junho"); break; case 7: System.Console.WriteLine($"Mês {num} é igual a: Julho"); break; case 8: System.Console.WriteLine($"Mês {num} é igual a: Agosto"); break; case 9: System.Console.WriteLine($"Mês {num} é igual a: Setembro"); break; case 10: System.Console.WriteLine($"Mês {num} é igual a: Outrubro"); break; case 11: System.Console.WriteLine($"Mês {num} é igual a: Novembro"); break; case 12: System.Console.WriteLine($"Mês {num} é igual a: Dezembro"); break; default: System.Console.WriteLine("Número invalido."); break; } } } }
using System; using System.Collections.Generic; using System.Data; using System.Configuration; using System.Linq; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.HtmlControls; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Xml.Linq; /// <summary> /// This file defines the PlayerCharacter class. It is one of the core types of the game, /// representing the user's character. It is primarily a container class, as it mostly stores /// and displays the current player character information. /// </summary> public class PlayerCharacter : Character { #region Class Data Members private Equipment equipment; #endregion #region Class Methods public PlayerCharacter(CharAttacks attacks, CharBio bio, CharInv inv, CharStats stats, Equipment equipment) : base(attacks, bio, inv, stats) { this.equipment = equipment; } public void LevelUp() { this.stats.TotalHP += (this.stats.TotalHP / 10) * this.stats.CharClass.HPMultiplier; this.stats.TotalTP += (this.stats.TotalTP / 10) * this.stats.CharClass.TPMultiplier; this.stats.DMGModifier += 0.10f; this.stats.ChanceToHit += 0.05f; this.stats.DMG += (this.stats.DMG / 10) * this.stats.CharClass.BaseDMGMultiplier; if ((this.stats.Level % 3) == 0) { try { AttackRegistry attackReg = new AttackRegistry(); Attack newAttack = attackReg.GetAttack(this); this.attacks.AddAttack(newAttack); } catch (Exception e) { Console.Write(e.Message); } } } #endregion #region Class Properties public Weapon LeftHand { get { return this.equipment.LeftHand; } set { this.equipment.LeftHand = value; } } public Weapon RightHand { get { return this.equipment.RightHand; } set { this.equipment.RightHand = value; } } public Armor Armor { get { return this.equipment.Armor; } set { this.equipment.Armor = value; } } #endregion }
// ----------------------------------------------------------------------- // Copyright (c) David Kean. All rights reserved. // ----------------------------------------------------------------------- using System; using System.Text; using System.Threading; using Moq; using Moq.Protected; namespace Portable { public class MockFactory<T> where T : class { public static T Create() { return MockFactory.Create<T>(); } public static Mock<T> CreateMock() { return MockFactory.CreateMock<T>(); } } }
using System; using Microsoft.VisualStudio.TestTools.UnitTesting; using OakIdeas.Volunteer.Models; namespace OakIdeas.Volunteer.Data.Tests { [TestClass] public class UnitTest1 { [TestMethod] public void Adding_a_project() { using (VolunteerContext context = new VolunteerContext()) { Project project = new Project(); project.Name = "test"; project.Description = " some decription "; project.State = ProjectState.Open; context.Projects.Add(project); context.SaveChanges(); } } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; [System.Serializable] public class TestData { public int ID; public float testDuration = 0f; public float distanceToCarCrash = 0f; public string s; }
using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Http; using System; using System.Collections.Generic; using System.Net; using System.Text; using System.Threading.Tasks; namespace Zhouli.Common.Middleware { public class RealIpMiddleware { private readonly RequestDelegate _next; public RealIpMiddleware(RequestDelegate next) { _next = next; } public Task Invoke(HttpContext context) { var headers = context.Request.Headers; if (headers.ContainsKey("X-Forwarded-For")) { context.Connection.RemoteIpAddress = IPAddress.Parse(headers["X-Forwarded-For"].ToString().Split(',', StringSplitOptions.RemoveEmptyEntries)[0]); } return _next(context); } } public static class RealIpMiddlewareExtensions { /// <summary> /// 搭配了nginx获取真实IP /// </summary> /// <param name="app"></param> /// <returns></returns> public static IApplicationBuilder UseRealIp(this IApplicationBuilder app) { return app.UseMiddleware<RealIpMiddleware>(); } } }
using Student.Service.interfaces; using System; using System.Linq; using System.Threading.Tasks; using System.Web.Http; using System.Web.Http.Cors; namespace Student.API.API { [EnableCors(origins: "*", headers: "*", methods: "*")] public class StudentController : ApiController { private IStudentService _studentService; public StudentController(IStudentService studentService) { _studentService = studentService; } public async Task<IHttpActionResult> Get() { var studentList = await Task.Run(() => _studentService.GetAll()); return Ok(studentList); } // POST: api/Student public async Task<IHttpActionResult> Post(Model.StudentInformation student) { try { var _student = await Task.Run(() => _studentService.Create(student)); return Ok(_student); } catch (Exception ex) { return BadRequest(ex.Message); } } // PUT: api/Student/5 public async Task<IHttpActionResult> Put([FromBody] Model.StudentInformation student) { try { await Task.Run(() => _studentService.Update(student)); return Ok(student); } catch (Exception ex) { return BadRequest(ex.Message); } } // DELETE: api/Student/5 public async Task<IHttpActionResult> Delete(int id) { try { var student = await Task.Run(() => _studentService.FindById(id)); _studentService.Delete(student); return Ok(); } catch (Exception ex) { return BadRequest(ex.Message); } } } }
using UnityEngine; public sealed class Board : MonoBehaviour { private const float T = 0.866025f; // 斜辺と高さの比。 public TriangleCell part; public float stride = 1f; public int xMin = -10; public int xMax = 10; public int yMin = -10; public int yMax = 10; private void OnEnable() { Build(); } private void Update() { if (Input.GetMouseButtonDown(0)) { Vector3 mPos = Input.mousePosition; mPos.z = -Camera.main.transform.position.z; mPos = Camera.main.ScreenToWorldPoint(mPos); Vector3Int tPos = SquareToTriangularInt(mPos); Debug.Log(mPos + "->" + tPos + ","); } } private void Build() { CleanUp(); if (part == null) return; for (int x = xMin; x < xMax; ++x) { for (int y = yMin; y < yMax; ++y) { var p = Instantiate(part, transform); p.size = stride; Place(p.transform, new Vector3Int(x, y, 0), stride); p.text.text = SquareToTriangularInt(p.GetCenterPosition()).ToString(); } } } private void CleanUp() { if (transform.childCount == 0) return; foreach (Transform child in transform) { if (child != null) { Destroy(child.gameObject); } } } /// <summary> /// 三角グリッド上の座標に配置する。 /// 三角グリッドは平面だがxyzの3軸で表現する。 /// </summary> /// <param name="position"></param> private void Place(Transform transform, Vector3Int position, float stride) { int xa = position.x & 1; // 回転に対して影響。偶数 : 0, 奇数 : 180 int xb = (position.x + 1) >> 1; // 位置に対して影響。(1, 2, 2, 3, 3, 4, 4, ... ) という数列を生成。 Vector3 pos = new Vector3(xb * stride + position.y * stride * 0.5f, position.y * stride * T); Quaternion rot = Quaternion.Euler(0f, 0f, 60f * xa); transform.rotation = rot; transform.position = pos; // 色分けしてみる。 var sprite = transform.GetComponent<SpriteRenderer>(); if (sprite) { sprite.color = xa == 0 ? Color.white : Color.gray; } } /// <summary> /// 正方格子上の座標を三角格子上の座標に変換する。 /// </summary> /// <param name="sPos"></param> /// <returns></returns> public Vector3 SquareToTriangular(Vector2 sPos) { float x = sPos.x / stride; float y = sPos.y / (stride * T); Vector3 tPos = new Vector3( x - 0.5f * y, y ); // z軸は、xとyの端数の加算が1を超えているかどうかで tPos.z = (tPos.x - Mathf.Floor(tPos.x) + tPos.y - Mathf.Floor(tPos.y)) >= 1f ? 1f : 0f; return tPos; } /// <summary> /// 正方格子上の座標を三角格子上の座標に変換する /// </summary> /// <param name="sPos"></param> /// <returns></returns> public Vector3Int SquareToTriangularInt(Vector2 sPos) { Vector3 tPos = SquareToTriangular(sPos); return new Vector3Int( Mathf.FloorToInt(tPos.x), Mathf.FloorToInt(tPos.y), (int)tPos.z ); } }
using Caliburn.Light; using System; using System.Threading.Tasks; using Windows.UI.Popups; namespace Demo.HelloSpecialValues { public class MainPageViewModel : Screen { public MainPageViewModel() { Characters = new BindableCollection<CharacterViewModel> { new CharacterViewModel("Arya Stark", "ms-appx:///resources/images/arya.jpg"), new CharacterViewModel("Catelyn Stark", "ms-appx:///resources/images/catelyn.jpg"), new CharacterViewModel("Cercei Lannister", "ms-appx:///resources/images/cercei.jpg"), new CharacterViewModel("Jamie Lannister", "ms-appx:///resources/images/jamie.jpg"), new CharacterViewModel("Jon Snow", "ms-appx:///resources/images/jon.jpg"), new CharacterViewModel("Rob Stark", "ms-appx:///resources/images/rob.jpg"), new CharacterViewModel("Sandor Clegane", "ms-appx:///resources/images/sandor.jpg"), new CharacterViewModel("Sansa Stark", "ms-appx:///resources/images/sansa.jpg"), new CharacterViewModel("Tyrion Lannister", "ms-appx:///resources/images/tyrion.jpg") }; CharacterSelectedCommand = DelegateCommandBuilder.WithParameter<CharacterViewModel>() .OnExecute(CharacterSelected) .Build(); } private async Task CharacterSelected(CharacterViewModel character) { var dialog = new MessageDialog(string.Format("{0} selected.", character.Name), "Character Selected"); await dialog.ShowAsyncEx(); } public IReadOnlyBindableCollection<CharacterViewModel> Characters { get; } public AsyncCommand CharacterSelectedCommand { get; } } }
using System; using System.Collections.Generic; using System.Text; using System.Threading.Tasks; using OCP.AppFramework.Utility; using Quartz; namespace OCP.BackgroundJob { /** * Simple base class to extend to run periodic background jobs. * Call setInterval with your desired interval in seconds from the constructor. * * @since 15.0.0 */ abstract class TimedJob : Job { /** @var int */ protected int interval = 0; public TimedJob(ITimeFactory time) : base(time) { } /** * set the interval for the job * * @since 15.0.0 */ void setInterval(int interval) { this.interval = interval; } /** * run the job if the last run is is more than the interval ago * * @param JobList jobList * @param ILogger|null logger * * @since 15.0.0 */ public void execute(IJobList jobList, ILogger logger = null) { if ((this.time.getTime() - this.lastRun) > this.interval) { execute(jobList, logger); } } } }
using System.Windows; using System.Windows.Controls.Primitives; namespace Torshify.Radio.Framework.Controls { public class ToggleContentButton : ToggleButton { #region Fields public static readonly DependencyProperty CheckedContentProperty = DependencyProperty.Register("CheckedContent", typeof(object), typeof(ToggleContentButton), new FrameworkPropertyMetadata((object)null)); public static readonly DependencyProperty NonCheckedContentProperty = DependencyProperty.Register("NonCheckedContent", typeof(object), typeof(ToggleContentButton), new FrameworkPropertyMetadata((object)null)); #endregion Fields #region Constructors static ToggleContentButton() { DefaultStyleKeyProperty.OverrideMetadata(typeof(ToggleContentButton), new FrameworkPropertyMetadata(typeof(ToggleContentButton))); } #endregion Constructors #region Properties public object NonCheckedContent { get { return (object)GetValue(NonCheckedContentProperty); } set { SetValue(NonCheckedContentProperty, value); } } public object CheckedContent { get { return (object)GetValue(CheckedContentProperty); } set { SetValue(CheckedContentProperty, value); } } #endregion Properties } }
namespace E01_ClassChefInCSharp { using System; public class MainProgram { static void Main(string[] args) { const int ExpectedValue = 666; const int MinX = int.MinValue; const int MinY = int.MinValue; const int MaxX = int.MaxValue; const int MaxY = int.MaxValue; Chef chef = new Chef(); // Task 2. Refactor the following if statement: var potato = GetPotato(); if (potato != null) { if (potato.IsRotten && !potato.IsPeeled) { chef.Cook(potato); } } ////////// int x = 0; int y = 0; bool inRange = ((MinX <= x && x <= MaxX) && (MinY <= y && y <= MaxY)); bool shouldVisitCell = true; if (inRange && shouldVisitCell) { VisitCell(); } // Task 3. Refactor the following loop: int[] array = new int[100]; for (int index = 0; index < array.Length; index++) { array[index] = index; if (index % 10 == 0) { Console.WriteLine(array[index]); if (array[index] == ExpectedValue) { Console.WriteLine("Value Found"); break; } } else { Console.WriteLine(array[index]); } } ////// } private static Vegetable GetPotato() { return new Vegetable("potato", true, false); } private static Vegetable GetCarrot() { return new Vegetable("carrot", false, false); } private static void VisitCell() { Console.WriteLine("Do something !"); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.IO; namespace oopsconcepts { // ---Inner Exception // The InnerException property returns the exception instance that caused the current //exception. //To retain the original exception pass it as a parameter to the constructor, //of the current exception. //Always check if inner exception is not null before accessing any property of the inner //exception object ,else,you may get Null reference exception //To get the type of inner exception use GetType() method class InnerException { public static void Main() { try { try { Console.Write("Please enter First Number: "); int i = Convert.ToInt32(Console.ReadLine()); Console.WriteLine("Enter second number"); int j = Convert.ToInt32(Console.ReadLine()); int k = i / j; Console.WriteLine("Result:{0} ", k); Console.ReadKey(); } catch (Exception ex) { string filepath = @"C:\Users\SURESH\Desktop\Exce.txt"; if (File.Exists(filepath)) { StreamWriter wr = new StreamWriter(filepath); wr.Write(ex.Message); wr.Close(); } else { throw new FileNotFoundException("File not found", ex); } } } catch (Exception exception) { Console.WriteLine("this is inner exception: {0}",exception.InnerException.Message); Console.WriteLine("this is Catch block exception: {0}", exception.Message); Console.ReadKey(); } } } }
using System.Collections.Generic; namespace Enrollment.Forms.View.Common { public class CellListTemplateView { public string TemplateName { get; set; } public string DisplayMember { get; set; } } }
using System; using System.Collections.Generic; using Models; namespace IBL { public interface IBl { List<Restaurant> ViewAllRestaurants(); Restaurant SearchRestaurant(string x); Customer AddUser(Customer x); Restaurant AddRestaurant(Restaurant a); Review AddAReview(Review review); List<Review> ViewAllReviews(); Restaurant SearchCuisine(string x); List<Customer> ViewAllUsers(); } }
using UnityEngine; [CreateAssetMenu(fileName = "Area Self Ability", menuName = "Custom/Ability/Area Self Ability", order = 1)] public class AreaSelfAbility : Ability { [SerializeField] HitBox hitboxPrefab; [SerializeField] ParticleSystem particlePrefab; float hitDuration = .1f; Vector3 hitboxCenter; public override void Cast(Vector3 targetpos, Transform caster) { var hitbox = Instantiate(hitboxPrefab, caster.position, Quaternion.identity) as HitBox; hitbox.onHit += OnHit; hitbox.StartCollisionCheck(hitDuration); hitboxCenter = hitbox.Center; Destroy(hitbox.gameObject, 1); var particlePos = new Vector3(caster.position.x, 0, caster.position.z); ParticleSystem particles = Instantiate(particlePrefab, particlePos, Quaternion.identity) as ParticleSystem; particles.Play(); Destroy(particles.gameObject, 2); } private void OnHit(Collider other) { if (base.TryHit(other)) return; Health health = other.GetComponent<Health>(); if(health != null) { health.TakeDamage(30); } Rigidbody rb = other.GetComponent<Rigidbody>(); if (rb != null) { // Calculate distance from center Vector3 dir = other.transform.position - hitboxCenter; float distance = Vector3.Distance(other.transform.position, hitboxCenter); distance = 1 / distance; Debug.Log(distance); // Set velocity based on distance % rb.velocity = dir.normalized * distance * 30; } } }
 using Lobster.ViewModels; using Xamarin.Forms; namespace Lobster.Views { public partial class MainPage : ContentPage { protected MainViewModel ViewModel { get; } public MainPage(MainViewModel viewModel) { InitializeComponent(); BindingContext = ViewModel = viewModel; } protected override async void OnAppearing() => await ViewModel.Initialize(); } }
using System; using System.Windows.Forms; using SharpDX; using SharpDX.D3DCompiler; using SharpDX.DXGI; using SharpDX.Direct3D; using SharpDX.Direct3D11; using SharpDX.DirectInput; using VoxelEngine; using VoxelEngine.Cameras; using VoxelEngine.Cameras.Controllers; using Buffer = SharpDX.Direct3D11.Buffer; using Keyboard = VoxelEngine.Input.Keyboard; using MapFlags = SharpDX.Direct3D11.MapFlags; using Resource = SharpDX.Direct3D11.Resource; namespace Program { public class MyGame : BaseGame { private ShaderBytecode vertexShaderByteCode; private ShaderBytecode pixelShaderByteCode; private VertexShader vertexShader; private PixelShader pixelShader; private Resource skybox; private ShaderResourceView skyboxResource; private InputLayout layout; private Buffer vertices; private PerspectiveCamera cam = new PerspectiveCamera(10 * Vector3.BackwardRH, Vector3.ForwardRH, Vector3.Up, (float)Math.PI / 4.0f, 1f, 100f); protected override void Initialize() { base.Initialize(); cam.Controller = new PlayerCameraController(); vertices = new Buffer(device, 32 * 4, ResourceUsage.Dynamic, BindFlags.VertexBuffer, CpuAccessFlags.Write, ResourceOptionFlags.None, 0); } protected override void Load() { vertexShaderByteCode = ShaderBytecode.CompileFromFile("MiniTri.hlsl", "VS", "vs_4_0"); vertexShader = new VertexShader(device, vertexShaderByteCode); pixelShaderByteCode = ShaderBytecode.CompileFromFile("MiniTri.hlsl", "PS", "ps_4_0"); pixelShader = new PixelShader(device, pixelShaderByteCode); //skyboxShaderByteCode = ShaderBytecode.CompileFromFile("MiniTri.hlsl", "PS_Skybox", "ps_4_0"); //skyboxPS = new PixelShader(device, skyboxShaderByteCode); // Layout from VertexShader input signature layout = new InputLayout( device, ShaderSignature.GetInputSignature(vertexShaderByteCode), new[] { new InputElement("POSITION", 0, Format.R32G32_Float, 0, 0), new InputElement("TEXCOORD", 0, Format.R32G32B32_Float, 8, 0), new InputElement("TEXCOORD", 1, Format.R32G32B32_Float, 20, 0) }); skybox = Texture2D.FromFile(device, "skybox.dds", new ImageLoadInformation() { Width = -1, Height = -1, Depth = 1, FirstMipLevel = 0, MipLevels = 1, Usage = ResourceUsage.Immutable, BindFlags = BindFlags.ShaderResource, CpuAccessFlags = CpuAccessFlags.None, OptionFlags = ResourceOptionFlags.TextureCube, Format = Format.R8G8B8A8_UNorm, Filter = FilterFlags.None, MipFilter = FilterFlags.None, PSrcInfo = IntPtr.Zero }); skyboxResource = new ShaderResourceView(device, skybox, new ShaderResourceViewDescription() { Dimension = ShaderResourceViewDimension.TextureCube, Format = Format.R8G8B8A8_UNorm, TextureCube = new ShaderResourceViewDescription.TextureCubeResource() { MipLevels = 1, MostDetailedMip = 0 } }); // Prepare All the stages context.InputAssembler.InputLayout = layout; context.InputAssembler.PrimitiveTopology = PrimitiveTopology.TriangleStrip; context.InputAssembler.SetVertexBuffers(0, new VertexBufferBinding(vertices, 32, 0)); context.VertexShader.Set(vertexShader); context.PixelShader.SetShaderResource(0, skyboxResource); } protected override void Unload(CloseReason reason) { } protected override void Update(IGameTime time) { base.Update(time); cam.Update(time); if (Keyboard.KeyDown(Key.LeftAlt)) { _form.Text = _fpsCounter.FPS.ToString(); //System.Diagnostics.Debug.WriteLine(_fpsCounter.FPS.ToString()); } if (Keyboard.KeyDown(Key.Escape)) { Exit(); } } protected override void Draw(IGameTime time) { DataStream dataStream; context.MapSubresource(vertices, MapMode.WriteDiscard, MapFlags.None, out dataStream); Vector3[] corners = cam.Frustum.GetCorners(); dataStream.WriteRange(new [] { new VertexPositionRay(new Vector2(-1f, 1f), cam.Position, corners[2]), new VertexPositionRay(Vector2.One, cam.Position, corners[1]), new VertexPositionRay(-Vector2.One, cam.Position, corners[3]), new VertexPositionRay(new Vector2(1f, -1f), cam.Position, corners[0]), }); context.UnmapSubresource(vertices, 0); dataStream.Dispose(); //context.PixelShader.Set(skyboxPS); //context.Draw(4, 0); context.PixelShader.Set(pixelShader); context.Draw(4, 0); } protected override void Dispose(bool disposing) { base.Dispose(disposing); if (disposing) { layout.Dispose(); pixelShaderByteCode.Dispose(); pixelShader.Dispose(); vertexShaderByteCode.Dispose(); vertexShader.Dispose(); vertices.Dispose(); skyboxResource.Dispose(); skybox.Dispose(); } } } }
namespace RedLine.Models { public enum MachineType { Unknown, VMWare, VirtualBox, Parallels, HyperV } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class Math2D { public static Vector2 GetIntersectionPointCoordinates(Vector2 A1, Vector2 A2, Vector2 B1, Vector2 B2) { float tmp = (B2.x - B1.x) * (A2.y - A1.y) - (B2.y - B1.y) * (A2.x - A1.x); if (tmp == 0) { Debug.LogWarning("NO SOLUTION!"); return Vector2.zero; } float mu = ((A1.x - B1.x) * (A2.y - A1.y) - (A1.y - B1.y) * (A2.x - A1.x)) / tmp; return new Vector2( B1.x + (B2.x - B1.x) * mu, B1.y + (B2.y - B1.y) * mu ); } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class opticSpawn : MonoBehaviour { //dual eoTech public GameObject eoTechGO; public Transform sightJoint; public GameObject sightJointGO; private bool eoTechSpawned = false; public GameObject rearMBUSGO; private bool rearMBUSSpawned = false; public GameObject frontMBUSGO; public static bool replacement = false; public GameObject reddotGO; private bool reddotSpawned = false; public GameObject scopeGO; private bool scopeSpawned = false; public Transform frontSightJoint; public GameObject frontSightJointGO; public Transform frontSightJointCarbine; public GameObject frontSightJointGOCarbine; public Transform frontSightJointPistol; public GameObject frontSightJointGOPistol; // Use this for initialization void Start() { replacement = false; rearBMUSSpawn(); } // Update is called once per frame void Update() { checkBarrelChange(); } public void eoTechSpawn() { if (!eoTechSpawned) { sightJointGO = Instantiate(eoTechGO, sightJoint.position, sightJoint.rotation); sightJointGO.transform.parent = transform; eoTechSpawned = true; } } public void scopeSpawn() { if (!scopeSpawned) { sightJointGO = Instantiate(scopeGO, sightJoint.position, sightJoint.rotation); sightJointGO.transform.parent = transform; scopeSpawned = true; } } public void rearBMUSSpawn() { if (!rearMBUSSpawned) { sightJointGO = Instantiate(rearMBUSGO, sightJoint.position, sightJoint.rotation); sightJointGO.transform.parent = transform; rearMBUSSpawned = true; if (spawnBarrel.longBool) { frontSightJointGO = Instantiate(frontMBUSGO, frontSightJoint.position, frontSightJoint.rotation); frontSightJointGO.transform.parent = transform; replacement = false; } if (spawnBarrel.carbineBool) { frontSightJointGOCarbine = Instantiate(frontMBUSGO, frontSightJointCarbine.position, frontSightJointCarbine.rotation); frontSightJointGOCarbine.transform.parent = transform; replacement = false; } if (spawnBarrel.pistolBool) { frontSightJointGOPistol = Instantiate(frontMBUSGO, frontSightJointPistol.position, frontSightJointPistol.rotation); frontSightJointGOPistol.transform.parent = transform; replacement = false; } } } public void reddotSpawn() { if (!reddotSpawned) { sightJointGO = Instantiate(reddotGO, sightJoint.position, sightJoint.rotation); sightJointGO.transform.parent = transform; reddotSpawned = true; } } public void othersOFFOptic() { if (reddotSpawned) { Destroy(GameObject.Find("RedDot(Clone)")); reddotSpawned = false; } if (rearMBUSSpawned) { Destroy(GameObject.Find("RearMBUS(Clone)")); Destroy(GameObject.Find("FrontMBUS(Clone)")); rearMBUSSpawned = false; } if (eoTechSpawned) { Destroy(GameObject.Find("EOtech(Clone)")); eoTechSpawned = false; } if (scopeSpawned) { Destroy(GameObject.Find("scope(Clone)")); scopeSpawned = false; } } public void checkBarrelChange() { if (spawnBarrel.carbineBool && !replacement) { if (rearMBUSSpawned && !replacement) { Destroy(GameObject.Find("FrontMBUS(Clone)")); frontSightJointGOCarbine = Instantiate(frontMBUSGO, frontSightJointCarbine.position, frontSightJointCarbine.rotation); frontSightJointGOCarbine.transform.parent = transform; replacement = true; } } if (spawnBarrel.pistolBool && !replacement) { if (rearMBUSSpawned && !replacement) { Destroy(GameObject.Find("FrontMBUS(Clone)")); frontSightJointGOPistol = Instantiate(frontMBUSGO, frontSightJointPistol.position, frontSightJointPistol.rotation); frontSightJointGOPistol.transform.parent = transform; replacement = true; } } if (spawnBarrel.longBool && !replacement) { if (rearMBUSSpawned && !replacement) { Destroy(GameObject.Find("FrontMBUS(Clone)")); frontSightJointGO = Instantiate(frontMBUSGO, frontSightJoint.position, frontSightJoint.rotation); frontSightJointGO.transform.parent = transform; replacement = true; } } } public void killExtraFront() { if (rearMBUSSpawned) { Destroy(GameObject.Find("FrontMBUS(Clone)")); GameObject.Find("FrontMBUS(Clone)").SetActive(false); Destroy(GameObject.Find("FrontMBUS(Clone)")); Destroy(GameObject.Find("RearMBUS(Clone)")); GameObject.Find("RearMBUS(Clone)").SetActive(false); Destroy(GameObject.Find("RearMBUS(Clone)")); rearMBUSSpawned = false; } } }
using PlatformRacing3.Common.Config; using StackExchange.Redis; namespace PlatformRacing3.Common.Redis; public class RedisConnection { private static ConnectionMultiplexer Redis; public static void Init(IRedisConfig redisConfig) { RedisConnection.Redis = ConnectionMultiplexer.Connect(redisConfig.RedisHost + ":" + redisConfig.RedisPort); } public static ConnectionMultiplexer GetConnectionMultiplexer() => RedisConnection.Redis; public static IDatabase GetDatabase() => RedisConnection.GetConnectionMultiplexer().GetDatabase(); /*public static Task<RedisResult> HashExchangeAsync(RedisKey key, RedisKey field, RedisValue value) { return RedisConnection.GetDatabase().ScriptEvaluateAsync(@" local serverId = redis.call('hget', KEYS[1], KEYS[2]) if serverId != ARGV[1] then redis.call('hset', KEYS[1], KEYS[2], ARGV[1]) end return serverId", new RedisKey[]{ key, field }, new RedisValue[] { value }); }*/ }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.SceneManagement; public class Perfil : MonoBehaviour { public void setSexo(string sexo) { ControllerCaptura.captura.sexo = sexo; } public void setFaixaEtaria(string faixa) { ControllerCaptura.captura.faixaEtaria = faixa; SceneManager.LoadScene("Menu"); } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using BUS; using DTO; using DAL; namespace GUI { public partial class BookingDetail : Form { public BookingDetail() { InitializeComponent(); } Data br = new Data(); BUS_BookingRoom bbr = new BUS_BookingRoom(); DTO_BookingRoom dbr = new DTO_BookingRoom(); private void BookingDetail_Load(object sender, EventArgs e) { DataTable dt = new DataTable(); dt = bbr.show_BookingRoom(); dvgdanhsachdadat.DataSource = dt; } private void btnthoat_Click(object sender, EventArgs e) { this.Close(); } private void dvgdanhsachdadat_CellContentClick(object sender, DataGridViewCellEventArgs e) { } private void lbltieude_Click(object sender, EventArgs e) { } } }
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.Collections; using System.Data.SqlClient; namespace RSMS { public partial class CardManagerFrm : MyFrmBase { string historySQL = "select [cSeqNum],[cICNum],case isnull([cFaCode],'') when '' then '禁用' else '正常' end ,[cPlateNum],[cDriverName],[dInWeightDate],[iInWeighing],[cInWBNum],[cInUserName],[cBillNo],[cBillType],[dMadeDate],[cOrgPlateNum],[cCusName],[cCusCode],[cBSCreatedName],[cBSCreatedDate] ,[cBSEditedName],[cBSEditedDate],[bOut] ,[bIsNoPlan] from realWeighing "; string lastFilterSQL =" where dInWeightDate bewteen '" + DateTime.Now.ToString("yyyy-MM-dd") + "' and '" + DateTime.Now.ToString("yyyy-MM-dd 23:59:59.999") + "' "; ArrayList lastFilterPar; //上次查询值 public Dictionary<int, object> lastValues; /// <summary> /// 查询函数 /// </summary> /// <param name="sql"></param> /// <param name="sqlPara"></param> public void queryDb(string sql, ArrayList sqlPara) { lastFilterPar = sqlPara; lastFilterSQL = sql; myHelper.loadDataToGridView(myHelper.getDataTable(historySQL + sql + " order by cSeqNum", sqlPara), dataGridView1); myHelper.opMsg(" | 找到 " + dataGridView1.RowCount.ToString() + " 条记录!"); } public CardManagerFrm() { InitializeComponent(); } private void CardManagerFrm_Load(object sender, EventArgs e) { myHelper.loadAuth((myHelper.subWin)this.Tag, toolStrip); queryDb(lastFilterSQL, lastFilterPar); } private void refresh_Click(object sender, EventArgs e) { queryDb(lastFilterSQL, lastFilterPar); } private void fastfind_Click(object sender, EventArgs e) { string icCardNum = WSICReader.getCarNum(); if (string.IsNullOrEmpty(icCardNum)) { myHelper.emsg("错误", "获取卡号失败!"); return; } myHelper.loadDataToGridView(myHelper.getDataTable(historySQL + " where cICNum=@v1",new SqlParameter("@v1",icCardNum)), dataGridView1); myHelper.opMsg(" | 找到 " + dataGridView1.RowCount.ToString() + " 条记录!"); } private void filter_Click(object sender, EventArgs e) { CardManagerFrmFilter cmff = new CardManagerFrmFilter(); cmff.lastValues = lastValues; cmff.parentFrm = this; cmff.showDlg(); } private void disablecard_Click(object sender, EventArgs e) { if (dataGridView1.SelectedRows.Count > 0) { SqlConnection sqlConn = myHelper.getDbConn(); if (sqlConn == null) { myHelper.emsg("警告", "网络异常!"); } SqlTransaction sqlTran = sqlConn.BeginTransaction(); try { for (int i = 0, m = dataGridView1.SelectedRows.Count; i < m; i++) { if (myHelper.update("update realWeighing with(xlock) set [cFaCode] ='' where [cSeqNum]=@v1 and isnull(cFaCode,'')<>'' ", new SqlParameter("@v1", dataGridView1.SelectedRows[i].Cells[0].Value.ToString()), sqlTran) <= 0) { sqlTran.Rollback(); OpLog("禁用卡片号码", "失败", dataGridView1.SelectedRows[i].Cells[1].Value.ToString()); myHelper.emsg("警告", "禁用卡片号码状态异常!"); return; } OpLog("禁用卡片号码", "成功", dataGridView1.SelectedRows[i].Cells[1].Value.ToString()); } } catch (Exception) { sqlTran.Rollback(); myHelper.emsg("警告", "禁用卡片号码状态异常!"); return; } sqlTran.Commit(); queryDb(lastFilterSQL, lastFilterPar); myHelper.smsg("警告", "禁用卡片号码状态成功!"); return; } myHelper.emsg("警告", "请选择行项(可多选)!"); } private void enblecard_Click(object sender, EventArgs e) { if (dataGridView1.SelectedRows.Count > 0) { SqlConnection sqlConn = myHelper.getDbConn(); if (sqlConn == null) { myHelper.emsg("警告", "网络异常!"); } string noUpdateICCard = ""; string split = ""; SqlTransaction sqlTran = sqlConn.BeginTransaction(); try { for (int i = 0, m = dataGridView1.SelectedRows.Count; i < m; i++) { if (myHelper.getFirst("select cSeqNum from realWeighing with(xlock) where cICNum=@v1 and isnull(cFaCode,'')<>''", new SqlParameter("@v1", dataGridView1.SelectedRows[i].Cells[1].Value.ToString()), sqlTran) == null) { if (myHelper.update("update realWeighing with(xlock) set [cFaCode] =@v2 where [cSeqNum]=@v1", new SqlParameter[2] { new SqlParameter("@v2", myHelper.getFaCode()), new SqlParameter("@v1", dataGridView1.SelectedRows[i].Cells[0].Value.ToString()) }, sqlTran) <= 0) { sqlTran.Rollback(); myHelper.emsg("警告", "启用卡片号码状态异常!"); return; } OpLog("启用卡片号码", "成功", dataGridView1.SelectedRows[i].Cells[1].Value.ToString()); } else { OpLog("启用卡片号码", "失败", dataGridView1.SelectedRows[i].Cells[1].Value.ToString() + "占用中!"); noUpdateICCard += split + dataGridView1.SelectedRows[i].Cells[1].Value.ToString(); split = " , "; } } } catch (Exception) { sqlTran.Rollback(); myHelper.emsg("警告", "启用卡片号码状态异常!"); return; } sqlTran.Commit(); myHelper.smsg("警告", "启用卡片号码状态成功" + (string.IsNullOrEmpty(noUpdateICCard) ? "!" : (",其中:" + noUpdateICCard + "在使用中暂不能启用!"))); queryDb(lastFilterSQL, lastFilterPar); return; } myHelper.emsg("警告", "请选择行项(可多选)!"); } private void export_Click(object sender, EventArgs e) { myHelper.GenerateExcelCurrent(dataGridView1); } } }
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 E_Ticaret { public partial class profil : Form { public profil() { InitializeComponent(); } private void btnanasayfa_Click_1(object sender, EventArgs e) { anasayfa anasayfa = new anasayfa(); anasayfa.Show(); this.Hide(); } private void btnkategori_Click_1(object sender, EventArgs e) { kategoriler kategoriler = new kategoriler(); kategoriler.Show(); this.Hide(); } private void btnmesaj_Click_1(object sender, EventArgs e) { mesajlar mesajlar = new mesajlar(); mesajlar.Show(); this.Hide(); } } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Twitter.Models; using TwitterLogic; namespace Twitter.Controllers { public class HomeController : Controller { private TweetManager _tweets; public HomeController(TweetManager tweetManager) { _tweets = tweetManager; } public IActionResult Index() { //TweetModel model = new TweetModel(); //model.TweetsList = _tweets.GetAll(); return View(); } [HttpPost] public IActionResult Index(TweetModel model) { //if (ModelState.IsValid) //{ // var tweet = new GeoTwitterDataEntry() // { // TweetCreationDateTimeUtc = DateTime.Now, // TweetText = model.Text, // // Author = HttpContext.Session.GetUserEmail(), // }; // _tweets.Create(tweet); // return RedirectToAction("About", "Home"); //} //// kategorijas nepieciešams atlasīt arī POST pieprasījumā //model.TweetsList= _tweets.GetAll(); return View(model); // return RedirectToAction("Index", "Home"); } public IActionResult About() { ViewData["Message"] = "Your application description page."; return View(); } public IActionResult Contact() { ViewData["Message"] = "Your contact page."; return View(); } public IActionResult Privacy() { return View(); } [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)] public IActionResult Error() { return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier }); } } }
using UnityEngine; using System.Collections; using UnityEngine.UI; using UnityEngine.Audio; public class GameController : MonoBehaviour { public int score; public int gameState; public Text scoreText; public GameObject spider; public GameObject appender; public Text gameOverText; public Text scoreTextOver; public Text bestTextOver; public Text restartText; public AudioClip endMusic; public GameObject audio; public void Start() { this.score = 0; this.gameState = 0; this.scoreText.text = "Score " + this.score; Time.timeScale = 0; this.gameOverText.text = "Space for hook"; this.scoreTextOver.text = "Try not to die"; this.restartText.text = "Press Space to start"; } public void Update() { if (Input.GetButtonDown("Jump") && this.gameState!=3) { Time.timeScale = 1; this.gameOverText.text = ""; this.scoreTextOver.text = ""; this.restartText.text = ""; } if (this.gameState == 3) { Destroy(audio.gameObject); } if (this.gameState == 3 && Input.GetKeyDown(KeyCode.R)) { Application.LoadLevel(Application.loadedLevelName); } } public void UpdateScore() { this.score += 10; this.scoreText.text = "Score " + this.score; if (this.score % 100 == 0) { this.gameState = 1; } } public void GameOver() { AudioSource.PlayClipAtPoint(endMusic, this.transform.position); var highScore = PlayerPrefs.GetInt("HighScore", 0); if (this.score > PlayerPrefs.GetInt("HighScore", 0)) { PlayerPrefs.SetInt("HighScore", this.score); highScore = PlayerPrefs.GetInt("HighScore", 0); } var spiderController = spider.GetComponent<SpiderController>(); var appendController = appender.GetComponent<AppendController>(); appendController.Stop(); spiderController.forwardSpeed = 0; spiderController.animator.SetInteger("SpiderState", 3); this.gameOverText.text = "GAME OVER"; this.scoreTextOver.text = "Score " + this.score; this.bestTextOver.text = "Best " + highScore; this.restartText.text = "Press 'R' to restart"; } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.ComponentModel.DataAnnotations; using CP.i8n; //------------------------------------------------------------------------------ // // This code was generated by OzzCodeGen. // // Manual changes to this file will be overwritten if the code is regenerated. // //------------------------------------------------------------------------------ namespace CriticalPath.Data { [MetadataTypeAttribute(typeof(Country.CountryMetadata))] public partial class Country { internal sealed partial class CountryMetadata { // This metadata class is not intended to be instantiated. private CountryMetadata() { } [StringLength(100, ErrorMessageResourceType = typeof(ErrorStrings), ErrorMessageResourceName = "MaxLeght")] [Required(ErrorMessageResourceType = typeof(ErrorStrings), ErrorMessageResourceName = "Required")] [Display(ResourceType = typeof(EntityStrings), Name = "CountryName")] public string CountryName { get; set; } [StringLength(2, ErrorMessageResourceType = typeof(ErrorStrings), ErrorMessageResourceName = "MaxLeght")] [Display(ResourceType = typeof(EntityStrings), Name = "TwoLetterIsoCode")] public string TwoLetterIsoCode { get; set; } [StringLength(3, ErrorMessageResourceType = typeof(ErrorStrings), ErrorMessageResourceName = "MaxLeght")] [Display(ResourceType = typeof(EntityStrings), Name = "ThreeLetterIsoCode")] public string ThreeLetterIsoCode { get; set; } [Required(ErrorMessageResourceType = typeof(ErrorStrings), ErrorMessageResourceName = "Required")] [Display(ResourceType = typeof(EntityStrings), Name = "NumericIsoCode")] public int NumericIsoCode { get; set; } [Required(ErrorMessageResourceType = typeof(ErrorStrings), ErrorMessageResourceName = "Required")] [Display(ResourceType = typeof(EntityStrings), Name = "DisplayOrder")] public int DisplayOrder { get; set; } [Display(ResourceType = typeof(EntityStrings), Name = "IsPublished")] public bool IsPublished { get; set; } } } }
using System; using System.Data.Entity.Core.Common.EntitySql; using System.Linq; using System.Reflection.Emit; using System.Web; using Dentist.Models; using Dentist.Models.Tags; namespace Dentist.ViewModels { }
// // Copyright (c) .NET Foundation. All rights reserved. // Licensed under the MIT License. See LICENSE file in the project root for full license information. // using System; using System.Collections.Generic; using System.Data; using System.Drawing; using System.IO; using System.Reflection; using System.Text; using DotNetNuke.Common.Internal; using DotNetNuke.Common.Utilities; using DotNetNuke.Data; using DotNetNuke.Entities.Content; using DotNetNuke.Entities.Content.Workflow; using DotNetNuke.Entities.Content.Workflow.Entities; using DotNetNuke.Entities.Portals; using DotNetNuke.Services.Cache; using DotNetNuke.Services.FileSystem; using DotNetNuke.Services.FileSystem.Internal; using DotNetNuke.Tests.Utilities; using DotNetNuke.Tests.Utilities.Mocks; using DotNetNuke.Security.Permissions; using Moq; using NUnit.Framework; namespace DotNetNuke.Tests.Core.Providers.Folder { [TestFixture] public class FileContentTypeManagerTests { #region Private Variables #endregion #region Setup & TearDown [SetUp] public void Setup() { var _mockData = MockComponentProvider.CreateDataProvider(); var _mockCache = MockComponentProvider.CreateDataCacheProvider(); var _globals = new Mock<IGlobals>(); var _cbo = new Mock<ICBO>(); _mockData.Setup(m => m.GetProviderPath()).Returns(String.Empty); TestableGlobals.SetTestableInstance(_globals.Object); CBO.SetTestableInstance(_cbo.Object); } [TearDown] public void TearDown() { TestableGlobals.ClearInstance(); CBO.ClearInstance(); } #endregion #region GetContentType [Test] public void GetContentType_Returns_Known_Value_When_Extension_Is_Not_Managed() { const string notManagedExtension = "asdf609vas21AS:F,l/&%/(%$"; var contentType = FileContentTypeManager.Instance.GetContentType(notManagedExtension); Assert.AreEqual("application/octet-stream", contentType); } [Test] public void GetContentType_Returns_Correct_Value_For_Extension() { const string notManagedExtension = "htm"; var contentType = FileContentTypeManager.Instance.GetContentType(notManagedExtension); Assert.AreEqual("text/html", contentType); } #endregion } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class CollisionCtlr : RuntimeMonoBehaviour { // -------------------------------- PRIVATE ATTRIBUTES ------------------------------- // private ICollidable[] m_collidables; private GameObject m_touchingWall; private GameObject m_touchingGround; private bool m_isTouchingGround; private bool m_isTouchingWall; // ------------------------------------ ACCESSORS ------------------------------------ // public GameObject Wall { get { return m_touchingWall; } } public GameObject Ground { get { return m_touchingGround; } } // ====================================================================================== // PUBLIC MEMBERS // ====================================================================================== public void Awake() { m_collidables = this.gameObject.GetComponents<ICollidable>(); Physics2D.IgnoreLayerCollision(this.gameObject.layer, this.gameObject.layer, true); } // ====================================================================================== public void OnCollisionEnter2D(Collision2D collision) { ContactPoint2D contact = collision.GetContact(0); if (collision.gameObject.layer == LayerMask.NameToLayer("Platforms")) { if (contact.normal == Vector2.up) { OnTouchingGround(collision.gameObject, contact.normal, collision.contacts); return; } else if (Vector2.Dot(contact.normal, Vector2.up) == 0) { OnTouchingWall(collision.gameObject, contact.normal, collision.contacts); return; } } OnTouchingAnother(collision.gameObject, contact.normal, collision.contacts); } // ====================================================================================== public void OnCollisionExit2D(Collision2D collision) { if (collision.gameObject.layer == LayerMask.NameToLayer("Platforms")) { if (m_isTouchingGround && collision.gameObject == m_touchingGround) OnLeavingGround(); if (m_isTouchingWall && collision.gameObject == m_touchingWall) OnLeavingWall(); } } // ====================================================================================== // PRIVATE MEMBERS // ====================================================================================== private void OnTouchingGround(GameObject _ground, Vector2 _normal, ContactPoint2D[] _contacts) { m_isTouchingGround = true; m_touchingGround = _ground; foreach (ICollidable collidable in m_collidables) collidable.OnTouchingGround(_normal, _contacts); } // ====================================================================================== private void OnTouchingWall(GameObject _wall, Vector2 _normal, ContactPoint2D[] _contacts) { m_isTouchingWall = true; m_touchingWall = _wall; foreach (ICollidable collidable in m_collidables) collidable.OnTouchingWall(_normal, _contacts); } // ====================================================================================== private void OnTouchingAnother(GameObject _obj, Vector2 _normal, ContactPoint2D[] _contacts) { if (_obj.layer == LayerMask.NameToLayer("Platforms")) { if (_obj.GetComponent<PlatformEffector2D>() == null) { Debug.LogError("The GameObject " + _obj.name + " is in 'Platforms' layer and seems to be a floor... check if it has a PlatformEffector!"); foreach (ICollidable collidable in m_collidables) collidable.OnTouchingAnother(_normal, _contacts); } else { #if UNITY_EDITOR bool hasUsedByEffector = false; foreach (Collider2D col in _obj.GetComponents<Collider2D>()) if (col.usedByEffector) hasUsedByEffector |= col.usedByEffector; if (!hasUsedByEffector) Debug.LogError("The GameObject " + _obj.name + " is in 'Platforms' layer and seems to be a floor... check if its collider is 'UsedByEffector'!"); #endif } } } // ====================================================================================== private void OnLeavingGround() { m_isTouchingGround = false; m_touchingGround = null; foreach (ICollidable collidable in m_collidables) collidable.OnLeavingGround(); } // ====================================================================================== private void OnLeavingWall() { m_isTouchingWall = false; m_touchingWall = null; foreach (ICollidable collidable in m_collidables) collidable.OnLeavingWall(); } }
using System; using System.Collections.Generic; using System.IO; [Serializable] public class SessionToken { public string accessToken; public string clientToken; public SelectedProfile selectedProfile; public List<AvailableProfile> availableProfiles; [Serializable] public class SelectedProfile { public string name; public string id; } [Serializable] public class AvailableProfile { public string name; public string id; } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace CodingEvents.Models { public class Event { public int Id { get; set; } public string Name { get; set; } public string Description { get; set; } public string Email { get; set; } public EventType Type { get; set; } public Event() { } public Event(string name, string description, string email) { Name = name; Description = description; Email = email; } public override string ToString() { return Name; } } }
 namespace MFW.LALLib { public enum ICEStatusEnum { PLCM_MFW_ICE_STATUS_IDLE , PLCM_MFW_ICE_STATUS_FAIL_CONN_TURN , PLCM_MFW_ICE_STATUS_FAIL_CONNECTIVITY_CHECK , PLCM_MFW_ICE_STATUS_FAIL_TOKEN_AUTHENTICATION_WITH_TURN , PLCM_MFW_ICE_STATUS_FAIL_ALLOCATION_TIMEOUT , PLCM_MFW_ICE_STATUS_FAIL_CONN_TURN_BY_PROXY , PLCM_MFW_ICE_STATUS_FAIL_ACTIVE_NODE_DOWN } }
using UnityEngine; using TMPro; public class SetUsername : MonoBehaviour { public TMP_InputField nameField; public GameObject homePanel, namePanel; public void OnSubmit() { PlayerPrefs.DeleteAll(); PlayerPrefs.SetString("Username",nameField.text); PlayerPrefs.SetInt("Position", 0); PlayerPrefs.SetInt("Level", 0); //PlayerPrefs.SetInt("Intro", 1); PlayerPrefs.SetInt("ShowPretest", 1); PlayerPrefs.SetInt("Pretest", 0); PlayerPrefs.SetInt("PretestDone", 0); PlayerPrefs.SetInt("KuisionerDone", 0); PlayerPrefs.SetInt("Postest", 0); PlayerPrefs.SetInt("nilaiKuis", 0); PlayerPrefs.SetInt("mainLevel", 0); PlayerPrefs.SetInt("LevelERD", 0); PlayerPrefs.SetInt("LevelDDL", 0); PlayerPrefs.SetInt("LevelDML", 0); PlayerPrefs.SetInt("LevelERD2", 0); PlayerPrefs.SetInt("LevelDDL2", 0); PlayerPrefs.SetInt("LevelDML2", 0); PlayerPrefs.Save(); } void Start() { homePanel = GameObject.Find("HomePanel"); namePanel = GameObject.Find("NamePanel"); if(PlayerPrefs.GetInt("ShowPretest") == 1) { namePanel.gameObject.SetActive(false); homePanel.gameObject.SetActive(true); //PlayerPrefs.SetInt("ShowPretest", 0); } else { namePanel.gameObject.SetActive(true); homePanel.gameObject.SetActive(false); } } public void Reset(){ PlayerPrefs.SetInt("ShowPretest", 1); } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.ComponentModel.DataAnnotations; using System.Threading.Tasks; using System.Web.Mvc; // Remote namespace TaxiApp.Models { public class AppUser { [key] [DatabaseGeneratedAttribute(DatabaseGenerateOPtion.Identity)] public int ID { get; set; } [Display(Name = "Имя")] [Required] [StringLength(32,MinimumLength = 2, ErrorMessage = "Не допустимая длинна поля")] public string UserName { get; set; } [Display(Name = "EMail")] [Required] [StringLength(32, MinimumLength = 2, ErrorMessage = "Не допустимая длинна поля")] [EmailAddress] public string Email { get; set; } [Display(Name = "EMail")] [EmailAddress] public string EmailConfirm { get; set; } [Display(Name = "Телефон")] [Phone] public string Phone { get; set; } [Display(Name = "Телефон")] [Phone] public string PhoneConfirm { get; set; } [Display(Name = "Пароль")] [DataType(DataType.Password)] public string Password { get; set; } [Display(Name = "Пароль")] [DataType(DataType.Password)] public string PasswordHash { get; set; } [Display(Name = "Аватар")] public string Avatar { get; set; } [Display(Name = "Дата входа")] [DataType(DataType.DateTime)] public DateTime LastLogin { get; set; } [Display(Name = "Дата online")] [DataType(DataType.DateTime)] public DateTime LastOnline { get; set; } [Display(Name = "IP входа")] public string LastIP { get; set; } [Display(Name = "Token")] public string AccessToken { get; set; } [Display(Name = "Ошибок")] public int FailCount { get; set; } [Display(Name = "Разрешения")] public string Allow { get; set; } [Display(Name = "Роль")] public int AppUserRoleID { get; set; } public AppUserRole AppUserRole { get; set; } } }
using Panoptes.Model.Charting; using QuantConnect; using System; using System.Collections.Generic; using System.Linq; namespace Panoptes.Model { // For many elements we use custom objects in this tool. public static class ResultMapper { public static Dictionary<string, ChartDefinition> MapToChartDefinitionDictionary(this IDictionary<string, Chart> sourceDictionary) { return sourceDictionary == null ? new Dictionary<string, ChartDefinition>() : sourceDictionary.ToDictionary(entry => entry.Key, entry => MapToChartDefinition(entry.Value)); } public static Dictionary<string, Chart> MapToChartDictionary(this IDictionary<string, ChartDefinition> sourceDictionary) { return sourceDictionary.ToDictionary(entry => entry.Key, entry => MapToChart(entry.Value)); } private static InstantChartPoint MapToTimeStampChartPoint(this ChartPoint point) { return new InstantChartPoint { X = DateTimeOffset.FromUnixTimeSeconds(point.x), //Instant.FromUnixTimeSeconds(point.x), Y = point.y }; } private static ChartPoint MapToChartPoint(this InstantChartPoint point) { return new ChartPoint { // QuantConnect chartpoints are always in Unix TimeStamp (seconds) x = point.X.ToUnixTimeSeconds(), y = point.Y }; } private static ChartDefinition MapToChartDefinition(this Chart sourceChart) { return new ChartDefinition { Name = sourceChart.Name, Series = sourceChart.Series.MapToSeriesDefinitionDictionary() }; } private static Chart MapToChart(this ChartDefinition sourceChart) { return new Chart { Name = sourceChart.Name, Series = sourceChart.Series.MapToSeriesDictionary() }; } private static Dictionary<string, SeriesDefinition> MapToSeriesDefinitionDictionary(this IDictionary<string, Series> sourceSeries) { return sourceSeries.ToDictionary(entry => entry.Key, entry => entry.Value.MapToSeriesDefinition()); } private static Dictionary<string, Series> MapToSeriesDictionary(this IDictionary<string, SeriesDefinition> sourceSeries) { return sourceSeries.ToDictionary(entry => entry.Key, entry => entry.Value.MapToSeries()); } private static SeriesDefinition MapToSeriesDefinition(this Series sourceSeries) { return new SeriesDefinition { Color = sourceSeries.Color, Index = sourceSeries.Index, Name = sourceSeries.Name, ScatterMarkerSymbol = sourceSeries.ScatterMarkerSymbol, SeriesType = sourceSeries.SeriesType, Unit = sourceSeries.Unit, Values = sourceSeries.Values.ConvertAll(v => v.MapToTimeStampChartPoint()) }; } private static Series MapToSeries(this SeriesDefinition sourceSeries) { return new Series { Color = sourceSeries.Color, Index = sourceSeries.Index, Name = sourceSeries.Name, ScatterMarkerSymbol = sourceSeries.ScatterMarkerSymbol, SeriesType = sourceSeries.SeriesType, Unit = sourceSeries.Unit, Values = sourceSeries.Values.ConvertAll(v => v.MapToChartPoint()) }; } } }
using NLog; using System; using System.Text; using System.Windows.Forms; using System.Runtime.InteropServices; namespace ScriptClient.Services { class ExecuteCommandEngine { private static readonly ILogger ErrorLogger = LogManager.GetLogger("fileErrorLogger"); private IntPtr _selectedHWND = IntPtr.Zero; public const int SWP_NOSIZE = 0x0001; public const int SWP_NOZORDER = 0x0004; public const int SWP_SHOWWINDOW = 0x0040; public bool SendKeys(string str) { try { System.Windows.Forms.SendKeys.SendWait(str); Console.WriteLine($"SendKeys({str})"); return true; } catch (Exception ex) { ErrorLogger.Error(ex); return false; } } public bool SetCursor(int X, int Y) { try { Win32.POINT p = new Win32.POINT(); p.x = X; p.y = Y; Win32.ClientToScreen(_selectedHWND, ref p); Win32.SetCursorPos(p.x, p.y); Console.WriteLine($"SetCursor({X},{Y})"); return true; } catch (Exception ex) { ErrorLogger.Error(ex); return false; } } // returns the HWND of the window (if found), otherwise IntPtr.Zero public bool SelectWindow(string win_title) { try { StringBuilder sb = new StringBuilder(win_title); if (win_title.Contains("\"")) sb.Replace("\"", ""); string transformedString = sb.ToString(); _selectedHWND = Win32.FindWindow(null, transformedString); if (_selectedHWND != IntPtr.Zero) { Win32.SetWindowPos(_selectedHWND, new IntPtr(0), 0, 0, 0, 0, SWP_NOSIZE | SWP_SHOWWINDOW); Win32.ShowWindow(_selectedHWND, 5); Win32.SetForegroundWindow(_selectedHWND); Console.WriteLine($"SelectWindow({win_title}): SUCCESS :: _selectedHWND={_selectedHWND}"); return true; } } catch (Exception ex) { ErrorLogger.Error(ex); return false; } Console.WriteLine($"SelectWindow({win_title}): Failure :: _selectedHWND={_selectedHWND}"); return false; } public bool DoMouseClick() { try { //Call the imported function with the cursor's current position uint X = (uint)Cursor.Position.X; uint Y = (uint)Cursor.Position.Y; Win32.mouse_event(Win32.MOUSEEVENTF_LEFTDOWN | Win32.MOUSEEVENTF_LEFTUP, X, Y, 0, UIntPtr.Zero); Console.WriteLine($"DoMouseClick"); return true; } catch (Exception ex) { ErrorLogger.Error(ex); return false; } } } public class Win32 { [DllImport("user32.Dll")] public static extern bool SetForegroundWindow(IntPtr hwnd); [DllImport("User32.Dll")] public static extern long SetCursorPos(int x, int y); [DllImport("User32.Dll")] public static extern bool ClientToScreen(IntPtr hWnd, ref POINT point); [StructLayout(LayoutKind.Sequential)] public struct POINT { public int x; public int y; } [DllImport("user32.dll")] public static extern void mouse_event(uint dwFlags, uint dx, uint dy, uint dwData, UIntPtr dwExtraInfo); public const int MOUSEEVENTF_LEFTDOWN = 0x02; public const int MOUSEEVENTF_LEFTUP = 0x04; public const int MOUSEEVENTF_MOVE = 0x0001; [DllImport("user32.dll", EntryPoint = "FindWindow")] public static extern IntPtr FindWindow(string sClass, string sWindow); [DllImport("user32.dll", SetLastError = true)] public static extern bool SetWindowPos(IntPtr hWnd, IntPtr hWndInsertAfter, int X, int Y, int cx, int cy, int uFlags); [DllImport("user32.dll", SetLastError = true)] public static extern bool ShowWindow(IntPtr hWnd, int X); } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace suc.calc.distance { public class Geocoder { public string status { get; set; } public Result result { get; set; } } public class Result { public Location location { get; set; } public int precise { get; set; } public int confidence { get; set; } public string level { get; set; } public List<Route> routes { get; set; } } /// <summary> /// 路由 /// </summary> public class Route { public int distance { get; set; } public int duration { get; set; } public List<Step> steps { get; set; } } public class Location { public double lng { get; set; } public double lat { get; set; } } /// <summary> /// 规划路线 /// </summary> public class Step { /// <summary> /// 道路名 /// </summary> public string road_name { get; set; } } }
/*********************** @ author:zlong @ Date:2015-01-11 @ Desc:场地出租信息界面层 * ********************/ using System; using System.Collections.Generic; using System.Linq; using System.Web; using DriveMgr; using DriveMgr.BLL; namespace DriveMgr.WebUI.FinancialMgr { /// <summary> /// bg_siteRentalHandler 的摘要说明 /// </summary> public class bg_siteRentalHandler : IHttpHandler { DriveMgr.Model.UserOperateLog userOperateLog = null; //操作日志对象 SiteRentalBLL siteRentalBll = new SiteRentalBLL(); public void ProcessRequest(HttpContext context) { context.Response.ContentType = "application/json"; string action = context.Request.Params["action"]; try { DriveMgr.Model.User userFromCookie = DriveMgr.Common.UserHelper.GetUser(context); //获取cookie里的用户对象 userOperateLog = new Model.UserOperateLog(); userOperateLog.UserIp = context.Request.UserHostAddress; userOperateLog.UserName = userFromCookie.UserId; switch (action) { case "search": SearchSiteRental(context); break; case "add": AddSiteRental(userFromCookie, context); break; case "edit": EditSiteRental(userFromCookie, context); break; case "delete": DelSiteRental(userFromCookie, context); break; case "getPriceConfigDT": PriceConfigBLL priceConfigBll = new PriceConfigBLL(); context.Response.Write(priceConfigBll.GetPriceConfigDT(1)); break; case "setTotalPrice": string priceConfigID = context.Request.Params["priceConfigID"] ?? ""; string longer = context.Request.Params["longer"] ?? ""; if (priceConfigID != string.Empty) { PriceConfigBLL configBll = new PriceConfigBLL(); Model.PriceConfigModel model = configBll.GetPriceConfigModel(Int32.Parse(priceConfigID)); try { decimal aaa = model.Price.Value * decimal.Parse(longer); context.Response.Write("{\"totalPrice\":" + model.Price.Value * decimal.Parse(longer) + "}"); } catch (System.Exception ex) { context.Response.Write("{\"totalPrice\":\"0\"}"); } } else { context.Response.Write("{\"totalPrice\":\"0\"}"); } break; default: context.Response.Write("{\"msg\":\"参数错误!\",\"success\":false}"); break; } } catch (Exception ex) { context.Response.Write("{\"msg\":\"" + DriveMgr.Common.JsonHelper.StringFilter(ex.Message) + "\",\"success\":false}"); userOperateLog.OperateInfo = "用户功能异常"; userOperateLog.IfSuccess = false; userOperateLog.Description = DriveMgr.Common.JsonHelper.StringFilter(ex.Message); DriveMgr.BLL.UserOperateLog.InsertOperateInfo(userOperateLog); } } public bool IsReusable { get { return false; } } /// <summary> /// 查询场地出租信息 /// </summary> /// <param name="context"></param> private void SearchSiteRental(HttpContext context) { string sort = context.Request.Params["sort"]; //排序列 string order = context.Request.Params["order"]; //排序方式 asc或者desc int pageindex = int.Parse(context.Request.Params["page"]); int pagesize = int.Parse(context.Request.Params["rows"]); string ui_siteRental_rentObject = context.Request.Params["ui_siteRental_rentObject"] ?? ""; string ui_siteRental_licencePlateNum = context.Request.Params["ui_siteRental_licencePlateNum"] ?? ""; string ui_siteRental_priceConfig = context.Request.Params["ui_siteRental_priceConfig"] ?? ""; string ui_siteRental_createStartDate = context.Request.Params["ui_siteRental_createStartDate"] ?? ""; string ui_siteRental_createEndDate = context.Request.Params["ui_siteRental_createEndDate"] ?? ""; int totalCount; //输出参数 string strJson = siteRentalBll.GetPagerData(ui_siteRental_rentObject, ui_siteRental_licencePlateNum,ui_siteRental_priceConfig, ui_siteRental_createStartDate, ui_siteRental_createEndDate, sort + " " + order, pagesize, pageindex, out totalCount); context.Response.Write("{\"total\": " + totalCount.ToString() + ",\"rows\":" + strJson + "}"); userOperateLog.OperateInfo = "查询场地出租信息"; userOperateLog.IfSuccess = true; userOperateLog.Description = "排序:" + sort + " " + order + " 页码/每页大小:" + pageindex + " " + pagesize; DriveMgr.BLL.UserOperateLog.InsertOperateInfo(userOperateLog); } /// <summary> /// 添加场地出租信息 /// </summary> /// <param name="userFromCookie"></param> /// <param name="context"></param> private void AddSiteRental(DriveMgr.Model.User userFromCookie, HttpContext context) { if (userFromCookie != null && new DriveMgr.BLL.Authority().IfAuthority("siteRental", "add", userFromCookie.Id)) { string ui_siteRental_RentObject_add = context.Request.Params["ui_siteRental_RentObject_add"] ?? ""; string ui_siteRental_RentDate_add = context.Request.Params["ui_siteRental_RentDate_add"] ?? ""; string ui_siteRental_LicencePlateNum_add = context.Request.Params["ui_siteRental_LicencePlateNum_add"] ?? ""; string ui_siteRental_PriceConfig_add = context.Request.Params["ui_siteRental_PriceConfig_add"] ?? ""; string ui_siteRental_Longer_add = context.Request.Params["ui_siteRental_Longer_add"] ?? ""; string ui_siteRental_TotalPrice_add = context.Request.Params["ui_siteRental_TotalPrice_add"] ?? ""; string ui_siteRental_Remark_add = context.Request.Params["ui_siteRental_Remark_add"] ?? ""; DriveMgr.Model.SiteRentalModel siteRentalAdd = new Model.SiteRentalModel(); siteRentalAdd.RentObject = ui_siteRental_RentObject_add.Trim(); if (string.IsNullOrEmpty(ui_siteRental_PriceConfig_add.Trim())) { siteRentalAdd.VehicleId = null; } else { siteRentalAdd.VehicleId = Int32.Parse(ui_siteRental_LicencePlateNum_add.Trim()); } siteRentalAdd.PriceConfigID = Int32.Parse(ui_siteRental_PriceConfig_add.Trim()); siteRentalAdd.Longer = decimal.Parse(ui_siteRental_Longer_add.Trim()); siteRentalAdd.TotalPrice = decimal.Parse(ui_siteRental_TotalPrice_add.Trim()); siteRentalAdd.RentDate = DateTime.Parse(ui_siteRental_RentDate_add.Trim()); siteRentalAdd.Remark = ui_siteRental_Remark_add.Trim(); siteRentalAdd.CreateDate = DateTime.Now; siteRentalAdd.CreatePerson = userFromCookie.UserId; siteRentalAdd.UpdatePerson = userFromCookie.UserId; siteRentalAdd.UpdateDate = DateTime.Now; if (siteRentalBll.AddSiteRental(siteRentalAdd)) { userOperateLog.OperateInfo = "添加场地出租信息"; userOperateLog.IfSuccess = true; userOperateLog.Description = "添加成功,场地出租信息:" + ui_siteRental_LicencePlateNum_add.Trim(); context.Response.Write("{\"msg\":\"添加成功!\",\"success\":true}"); } else { userOperateLog.OperateInfo = "添加场地出租信息"; userOperateLog.IfSuccess = false; userOperateLog.Description = "添加失败"; context.Response.Write("{\"msg\":\"添加失败!\",\"success\":false}"); } } else { userOperateLog.OperateInfo = "添加场地出租信息"; userOperateLog.IfSuccess = false; userOperateLog.Description = "无权限,请联系管理员"; context.Response.Write("{\"msg\":\"无权限,请联系管理员!\",\"success\":false}"); } DriveMgr.BLL.UserOperateLog.InsertOperateInfo(userOperateLog); } /// <summary> /// 编辑车辆 /// </summary> /// <param name="userFromCookie"></param> /// <param name="context"></param> private void EditSiteRental(DriveMgr.Model.User userFromCookie, HttpContext context) { if (userFromCookie != null && new DriveMgr.BLL.Authority().IfAuthority("siteRental", "edit", userFromCookie.Id)) { int id = Convert.ToInt32(context.Request.Params["id"]); DriveMgr.Model.SiteRentalModel siteRentalEdit = siteRentalBll.GetSiteRentalModel(id); string ui_siteRental_RentObject_edit = context.Request.Params["ui_siteRental_RentObject_edit"] ?? ""; string ui_siteRental_RentDate_edit = context.Request.Params["ui_siteRental_RentDate_edit"] ?? ""; string ui_siteRental_LicencePlateNum_edit = context.Request.Params["ui_siteRental_LicencePlateNum_edit"] ?? ""; string ui_siteRental_PriceConfig_edit = context.Request.Params["ui_siteRental_PriceConfig_edit"] ?? ""; string ui_siteRental_Longer_edit = context.Request.Params["ui_siteRental_Longer_edit"] ?? ""; string ui_siteRental_TotalPrice_edit = context.Request.Params["ui_siteRental_TotalPrice_edit"] ?? ""; string ui_siteRental_Remark_edit = context.Request.Params["ui_siteRental_Remark_edit"] ?? ""; siteRentalEdit.RentObject = ui_siteRental_RentObject_edit.Trim(); if (string.IsNullOrEmpty(ui_siteRental_LicencePlateNum_edit.Trim())) { siteRentalEdit.VehicleId = null; } else { siteRentalEdit.VehicleId = Int32.Parse(ui_siteRental_LicencePlateNum_edit.Trim()); } siteRentalEdit.PriceConfigID = Int32.Parse(ui_siteRental_PriceConfig_edit.Trim()); siteRentalEdit.Longer = decimal.Parse(ui_siteRental_Longer_edit.Trim()); siteRentalEdit.TotalPrice = decimal.Parse(ui_siteRental_TotalPrice_edit.Trim()); siteRentalEdit.RentDate = DateTime.Parse(ui_siteRental_RentDate_edit.Trim()); siteRentalEdit.Remark = ui_siteRental_Remark_edit.Trim(); siteRentalEdit.UpdatePerson = userFromCookie.UserId; siteRentalEdit.UpdateDate = DateTime.Now; if (siteRentalBll.UpdateSiteRental(siteRentalEdit)) { userOperateLog.OperateInfo = "修改场地出租信息"; userOperateLog.IfSuccess = true; userOperateLog.Description = "修改成功,场地出租信息主键:" + siteRentalEdit.Id; context.Response.Write("{\"msg\":\"修改成功!\",\"success\":true}"); } else { userOperateLog.OperateInfo = "修改场地出租信息"; userOperateLog.IfSuccess = false; userOperateLog.Description = "修改失败"; context.Response.Write("{\"msg\":\"修改失败!\",\"success\":false}"); } } else { userOperateLog.OperateInfo = "修改场地出租信息"; userOperateLog.IfSuccess = false; userOperateLog.Description = "无权限,请联系管理员"; context.Response.Write("{\"msg\":\"无权限,请联系管理员!\",\"success\":false}"); } DriveMgr.BLL.UserOperateLog.InsertOperateInfo(userOperateLog); } /// <summary> /// 删除车辆 /// </summary> /// <param name="userFromCookie"></param> /// <param name="context"></param> private void DelSiteRental(DriveMgr.Model.User userFromCookie, HttpContext context) { if (userFromCookie != null && new DriveMgr.BLL.Authority().IfAuthority("siteRental", "delete", userFromCookie.Id)) { string ids = context.Request.Params["id"].Trim(','); if (siteRentalBll.DeleteSiteRentalList(ids)) { userOperateLog.OperateInfo = "删除场地出租信息"; userOperateLog.IfSuccess = true; userOperateLog.Description = "删除成功,场地出租信息主键:" + ids; context.Response.Write("{\"msg\":\"删除成功!\",\"success\":true}"); } else { userOperateLog.OperateInfo = "删除场地出租信息"; userOperateLog.IfSuccess = false; userOperateLog.Description = "删除失败"; context.Response.Write("{\"msg\":\"删除失败!\",\"success\":false}"); } } else { userOperateLog.OperateInfo = "删除场地出租信息"; userOperateLog.IfSuccess = false; userOperateLog.Description = "无权限,请联系管理员"; context.Response.Write("{\"msg\":\"无权限,请联系管理员!\",\"success\":false}"); } DriveMgr.BLL.UserOperateLog.InsertOperateInfo(userOperateLog); } } }
namespace SampleApp.Samples { using System.ComponentModel.Composition; using TomsToolbox.Wpf.Composition; /// <summary> /// Interaction logic for TextBoxView.xaml /// </summary> [DataTemplate(typeof(TextBoxViewModel))] [PartCreationPolicy(CreationPolicy.NonShared)] public partial class TextBoxView { public TextBoxView() { InitializeComponent(); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class LayerMaskBool : MonoBehaviour { public GameObject spriteM; public GameObject lm; public Dialogue d; // Start is called before the first frame update void Start() { d = lm.GetComponent<Dialogue>(); } // Update is called once per frame void Update() { if(d.layerMaskOpen == true) { spriteM.SetActive(true); } } }
using Sitecore.Data.Items; using Sitecore.Links; namespace Aqueduct.SitecoreLib.DataAccess.SitecoreResolvers { public class RichTextResolver : ISitecoreResolver { private readonly string _fieldName; public RichTextResolver(string fieldName) { _fieldName = fieldName; } public object Resolve(Item item) { return LinkManager.ExpandDynamicLinks(item.Fields[_fieldName].Value); } } }
using System; using System.Collections.Generic; namespace Microsoft.DataStudio.Services.MachineLearning.Contracts { public class ExperimentInfo { public string ExperimentId { get; set; } public string RunId { get; set; } public string ParentExperimentId { get; set; } public string OriginalExperimentDocumentationLink { get; set; } public string Summary { get; set; } public string Description { get; set; } public string Creator { get; set; } public string Category { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.IO; using InvoiceClient.Properties; using System.Xml; using Utility; using InvoiceClient.Helper; using Model.Schema.EIVO; using System.Threading; using Model.Schema.TXN; using System.Diagnostics; using System.Globalization; using Model.Locale; using System.Net; namespace InvoiceClient.Agent { public class AllowanceContentToPDFWatcher : InvoiceWatcher { public static readonly String[] ThermalPOSPaper = new string[] { "0 0 162 792" }; public AllowanceContentToPDFWatcher(String fullPath) : base(fullPath) { } protected override void prepareStorePath(String fullPath) { _inProgressPath = Path.Combine(fullPath + "(Processing)", $"{Process.GetCurrentProcess().Id}"); _inProgressPath.CheckStoredPath(); } protected override void processFile(String invFile) { if (!File.Exists(invFile)) return; String fileName = Path.GetFileName(invFile); String fullPath = Path.Combine(_inProgressPath, fileName); try { if (File.Exists(fullPath)) File.Delete(fullPath); File.Move(invFile, fullPath); } catch (Exception ex) { Logger.Warn("move file error: " + invFile); Logger.Error(ex); return; } try { XmlDocument docInv = new XmlDocument(); docInv.Load(fullPath); AllowanceRoot root = docInv.TrimAll().ConvertTo<AllowanceRoot>(); AllowanceRoot dummy = new AllowanceRoot(); String tmpPath = Path.Combine(Logger.LogDailyPath, $"{Guid.NewGuid()}"); tmpPath.CheckStoredPath(); using (WebClientEx client = new WebClientEx { Timeout = 43200000 }) { client.Headers[HttpRequestHeader.ContentType] = "application/xml"; client.Encoding = Encoding.UTF8; foreach (var item in root.Allowance) { dummy.Allowance = new AllowanceRootAllowance[] { item }; String tmpHtml = Path.Combine(tmpPath, $"{item.AllowanceNumber}.htm"); do { try { File.WriteAllText(tmpHtml, client.UploadString(Settings.Default.ConvertDataToAllowance, dummy.ConvertToXml().OuterXml)); } catch(Exception ex) { Logger.Error(ex); } } while (!File.Exists(tmpHtml)); String pdfFile = Path.Combine(tmpPath, $"taiwan_uxb2b_scanned_sac_pdf_{item.AllowanceNumber}.pdf"); do { tmpPath.CheckStoredPath(); Logger.Info($"Allowance Content:{tmpHtml} => {pdfFile}"); tmpHtml.ConvertHtmlToPDF(pdfFile, 1, ThermalPOSPaper); } while (!File.Exists(pdfFile)); } } String args = $"taiwan_uxb2b_scanned_sac_pdf_{DateTime.Now:yyyyMMddHHmmssffff}_{root.Allowance.Length} \"{tmpPath}\" \"{_ResponsedPath}\""; Logger.Info($"zip PDF:{Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "ZipAllowancePDF.bat")} {args}"); "ZipAllowancePDF.bat".RunBatch(args); storeFile(fullPath, Path.Combine(Logger.LogDailyPath, fileName)); } catch (Exception ex) { Logger.Error(ex); } } } }
using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.DependencyInjection; namespace Server { public class Startup { public void ConfigureServices(IServiceCollection services) { services.AddSignalR(x => { #if DEBUG x.EnableDetailedErrors = true; #endif }) //.AddAzureSignalR() .AddMessagePackProtocol() ; services.AddSingleton<GameHubState>(); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { //UseSignalR //.UseAzureSignalR app .UseSignalR(routes => //.UseAzureSignalR(routes => { routes.MapHub<GameHub>($"/{nameof(GameHub)}"); }); //app.UseRouting(); //app.UseEndpoints(endpoints => //{ // endpoints.MapHub<GameHub>($"/{nameof(GameHub)}"); //}); //app.Run(async (context) => //{ // await context.Response.WriteAsync("Hello World!"); //}); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace OOP4.Details { class SquareDetail:Detail { public SquareDetail() { TimeShaping = 1000; } public override string Message { get { return "Квадартная деталь обработана"; } } public override int TimeShaping { get; } } }
using System; using System.Collections.Generic; namespace AdvancedIoCTechniques { internal class Program { private static void Main(string[] args) { } } public class Disposable : IDisposable { public bool IsDisposed { get; private set; } public void Dispose() { this.IsDisposed = true; this.Dispose(true); } protected virtual void Dispose(bool disposing) { } } public interface IRepository<T> where T : IHaveId { IEnumerable<T> FindAll(); T Find(Guid id); void Save(T item); } public class InMemoryRepository<T> : IRepository<T> where T : IHaveId { private readonly Dictionary<Guid, T> collection = new Dictionary<Guid, T>(); public IEnumerable<T> FindAll() { return this.collection.Values; } public T Find(Guid id) { T result; this.collection.TryGetValue(id, out result); return result; } public void Save(T item) { this.collection[item.Id] = item; } } public class SqlRepository<T> : InMemoryRepository<T> where T : IHaveId { } public class MongoRepository<T> : InMemoryRepository<T> where T : IHaveId { } public class Foo : Disposable, IHaveId { public Guid Id { get; set; } } public class Bar : Disposable, IHaveId { public Guid Id { get; set; } } public interface IHaveId { Guid Id { get; } } public class Post : IHaveId { public Guid Id { get; set; } public DateTime CreatedDate { get; set; } public DateTime ModifiedDate { get; set; } public string Author { get; set; } public string Content { get; set; } public IList<Post> Comments { get; set; } } public class Blog { } }
using _2014118187_ENT.Entities; using _2014118187_ENT.IRepositories; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace _2014118187_PER.Repositories { public class BasedeDatosRepository : Repository<BasedeDatos>, IBasedeDatosRepository { public BasedeDatosRepository(_2014118187DbContext context) : base(context) { } /*private readonly _2014118187DbContext _Context; public BasedeDatosRepository(_2014118265DbContext context) { _Context = context; } private BasedeDatosRepository() { } */ } }
using System; using TreeStore.Messaging; namespace TreeStore.Model { public interface ITreeStorePersistence : IDisposable { ITreeStoreMessageBus MessageBus { get; } ITagRepository Tags { get; } ICategoryRepository Categories { get; } IEntityRepository Entities { get; } IRelationshipRepository Relationships { get; } bool DeleteCategory(Category category, bool recurse); void CopyCategory(Category category, Category parent, bool recurse); } }
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.IO; namespace PKHeX { public partial class SAV_SecretBase : Form { public SAV_SecretBase(Form1 frm1) { InitializeComponent(); m_parent = frm1; Array.Copy(m_parent.savefile, sav, 0x100000); savindex = m_parent.savindex; specieslist = Form1.specieslist; movelist = Form1.movelist; itemlist = Form1.itemlist; abilitylist = Form1.abilitylist; natures = Form1.natures; setupComboBoxes(); popFavorite(); popFavorite(); LB_Favorite.SelectedIndex = 0; MT_Flags.Text = BitConverter.ToUInt32(sav, 0x2942C).ToString(); B_SAV2FAV(null, null); } Form1 m_parent; public byte[] sav = new Byte[0x100000]; public byte[] wondercard_data = new Byte[0x108]; public bool editing = false; public int savindex; int sv = 0; private int fav_offset = 0x23A00; private bool loading = true; public static string[] specieslist = { }; public static string[] movelist = { }; public static string[] itemlist = { }; public static string[] abilitylist = { }; public static string[] natures = { }; private void setupComboBoxes() { #region Balls { // Allowed Balls int[] ball_nums = { 7, 576, 13, 492, 497, 14, 495, 493, 496, 494, 11, 498, 8, 6, 12, 15, 9, 5, 499, 10, 1, 16 }; int[] ball_vals = { 7, 25, 13, 17, 22, 14, 20, 18, 21, 19, 11, 23, 8, 6, 12, 15, 9, 5, 24, 10, 1, 16 }; // Set up List<cbItem> ball_list = new List<cbItem>(); for (int i = 4; i > 1; i--) // add 4,3,2 { // First 3 Balls are always first cbItem ncbi = new cbItem(); ncbi.Text = itemlist[i]; ncbi.Value = i; ball_list.Add(ncbi); } // Sort the Rest based on String Name string[] ballnames = new string[ball_nums.Length]; for (int i = 0; i < ball_nums.Length; i++) ballnames[i] = itemlist[ball_nums[i]]; string[] sortedballs = new string[ball_nums.Length]; Array.Copy(ballnames, sortedballs, ballnames.Length); Array.Sort(sortedballs); // Add the rest of the balls for (int i = 0; i < sortedballs.Length; i++) { cbItem ncbi = new cbItem(); ncbi.Text = sortedballs[i]; ncbi.Value = ball_vals[Array.IndexOf(ballnames, sortedballs[i])]; ball_list.Add(ncbi); } CB_Ball.DisplayMember = "Text"; CB_Ball.ValueMember = "Value"; CB_Ball.DataSource = ball_list; } #endregion #region Held Items { // List of valid items to hold int[] item_nums = { 000,001,002,003,004,005,006,007,008,009,010,011,012,013,014,015,017,018,019,020,021,022,023,024,025,026,027,028,029,030,031,032,033,034,035, 036,037,038,039,040,041,042,043,044,045,046,047,048,049,050,051,052,053,054,055,056,057,058,059,060,061,062,063,064,065,066,067,068,069,070, 071,072,073,074,075,076,077,078,079,080,081,082,083,084,085,086,087,088,089,090,091,092,093,094,099,100,101,102,103,104,105,106,107,108,109, 110,112,116,117,118,119,134,135,136,149,150,151,152,153,154,155,156,157,158,159,160,161,162,163,164,165,166,167,168,169,170,171,172,173,174, 175,176,177,178,179,180,181,182,183,184,185,186,187,188,189,190,191,192,193,194,195,196,197,198,199,200,201,202,203,204,205,206,207,208,209, 210,211,212,213,214,215,217,218,219,220,221,222,223,224,225,226,227,228,229,230,231,232,233,234,235,236,237,238,239,240,241,242,243,244, 245,246,247,248,249,250,251,252,253,254,255,256,257,258,259,260,261,262,263,264,265,266,267,268,269,270,271,272,273,274,275,276,277,278,279, 280,281,282,283,284,285,286,287,288,289,290,291,292,293,294,295,296,297,298,299,300,301,302,303,304,305,306,307,308,309,310,311,312,313,314, 315,316,317,318,319,320,321,322,323,324,325,326,327,504,537,538,539,540,541,542,543,544,545,546,547,548,549,550,551,552,553,554,555,556,557, 558,559,560,561,562,563,564,565,566,567,568,569,570,571,572,573,577,580,581,582,583,584,585,586,587,588,589,590,591,639,640,644,645,646,647, 648,649,650,652,653,654,655,656,657,658,659,660,661,662,663,664,665,666,667,668,669,670,671,672,673,674,675,676,677,678,679,680,681,682,683, 684,685,686,687,688,699,704,708,709,710,711,715, // Appended ORAS Items (Orbs & Mega Stones) 534,535, 752,753,754,755,756,757,758,759,760,761,762,763,764,767,768,769,770, }; List<cbItem> item_list = new List<cbItem>(); // Sort the Rest based on String Name string[] itemnames = new string[item_nums.Length]; for (int i = 0; i < item_nums.Length; i++) itemnames[i] = itemlist[item_nums[i]]; string[] sorteditems = new string[item_nums.Length]; Array.Copy(itemnames, sorteditems, itemnames.Length); Array.Sort(sorteditems); // Add the rest of the items for (int i = 0; i < sorteditems.Length; i++) { cbItem ncbi = new cbItem(); ncbi.Text = sorteditems[i]; ncbi.Value = item_nums[Array.IndexOf(itemnames, sorteditems[i])]; item_list.Add(ncbi); } CB_HeldItem.DisplayMember = "Text"; CB_HeldItem.ValueMember = "Value"; CB_HeldItem.DataSource = item_list; } #endregion #region Species { List<cbItem> species_list = new List<cbItem>(); // Sort the Rest based on String Name string[] sortedspecies = new string[specieslist.Length]; Array.Copy(specieslist, sortedspecies, specieslist.Length); Array.Sort(sortedspecies); // Add the rest of the items for (int i = 0; i < sortedspecies.Length; i++) { cbItem ncbi = new cbItem(); ncbi.Text = sortedspecies[i]; ncbi.Value = Array.IndexOf(specieslist, sortedspecies[i]); species_list.Add(ncbi); } CB_Species.DisplayMember = "Text"; CB_Species.ValueMember = "Value"; CB_Species.DataSource = species_list; } #endregion #region Natures { List<cbItem> natures_list = new List<cbItem>(); // Sort the Rest based on String Name string[] sortednatures = new string[natures.Length]; Array.Copy(natures, sortednatures, natures.Length); Array.Sort(sortednatures); // Add the rest of the items for (int i = 0; i < sortednatures.Length; i++) { cbItem ncbi = new cbItem(); ncbi.Text = sortednatures[i]; ncbi.Value = Array.IndexOf(natures, sortednatures[i]); natures_list.Add(ncbi); } CB_Nature.DisplayMember = "Text"; CB_Nature.ValueMember = "Value"; CB_Nature.DataSource = natures_list; } #endregion #region Moves { List<cbItem> move_list = new List<cbItem>(); // Sort the Rest based on String Name string[] sortedmoves = new string[movelist.Length]; Array.Copy(movelist, sortedmoves, movelist.Length); Array.Sort(sortedmoves); // Add the rest of the items for (int i = 0; i < sortedmoves.Length; i++) { cbItem ncbi = new cbItem(); ncbi.Text = sortedmoves[i]; ncbi.Value = Array.IndexOf(movelist, sortedmoves[i]); move_list.Add(ncbi); } CB_Move1.DisplayMember = CB_Move2.DisplayMember = CB_Move3.DisplayMember = CB_Move4.DisplayMember = "Text"; CB_Move1.ValueMember = CB_Move2.ValueMember = CB_Move3.ValueMember = CB_Move4.ValueMember = "Value"; var move1_list = new BindingSource(move_list, null); CB_Move1.DataSource = move1_list; var move2_list = new BindingSource(move_list, null); CB_Move2.DataSource = move2_list; var move3_list = new BindingSource(move_list, null); CB_Move3.DataSource = move3_list; var move4_list = new BindingSource(move_list, null); CB_Move4.DataSource = move4_list; } #endregion } // Repopulation Functions private void popFavorite() { LB_Favorite.Items.Clear(); int playeroff = fav_offset + 0x5400 + 0x326; int favoff = fav_offset + 0x5400 + 0x63A; string OT = Util.TrimFromZero(Encoding.Unicode.GetString(sav, sv + playeroff + 0x218, 0x1A)); LB_Favorite.Items.Add("* " + OT); for (int i = 0; i < 30; i++) { string BaseTrainer = Util.TrimFromZero(Encoding.Unicode.GetString(sav, sv + favoff + i * 0x3E0 + 0x218, 0x1A)); if (BaseTrainer.Length < 1 || BaseTrainer[0] == '\0') BaseTrainer = "Empty"; LB_Favorite.Items.Add(i.ToString() + " " + BaseTrainer); } } private void B_SAV2FAV(object sender, EventArgs e) { loading = true; int index = LB_Favorite.SelectedIndex; if (index < 0) return; int offset = fav_offset + 0x5400 + 0x25A; // Base Offset Changing if (index == 0) offset = fav_offset + 0x5400 + 0x326; else offset += 0x3E0 * index; string TrainerName = Util.TrimFromZero(Encoding.Unicode.GetString(sav, sv + offset + 0x218, 0x1A)); TB_FOT.Text = TrainerName; TB_FT1.Text = Util.TrimFromZero(Encoding.Unicode.GetString(sav, sv + offset + 0x232 + 0x22 * 0, 0x22)); TB_FT2.Text = Util.TrimFromZero(Encoding.Unicode.GetString(sav, sv + offset + 0x232 + 0x22 * 1, 0x22)); string saying1 = Util.TrimFromZero(Encoding.Unicode.GetString(sav, sv + offset + 0x276 + 0x22 * 0, 0x22)); string saying2 = Util.TrimFromZero(Encoding.Unicode.GetString(sav, sv + offset + 0x276 + 0x22 * 1, 0x22)); string saying3 = Util.TrimFromZero(Encoding.Unicode.GetString(sav, sv + offset + 0x276 + 0x22 * 2, 0x22)); string saying4 = Util.TrimFromZero(Encoding.Unicode.GetString(sav, sv + offset + 0x276 + 0x22 * 3, 0x22)); int baseloc = BitConverter.ToInt16(sav, sv + offset); NUD_FBaseLocation.Value = baseloc; TB_FSay1.Text = saying1; TB_FSay2.Text = saying2; TB_FSay3.Text = saying3; TB_FSay4.Text = saying4; // Gather data for Object Array objdata = new byte[25, 12]; for (int i = 0; i < 25; i++) for (int z = 0; z < 12; z++) objdata[i, z] = sav[sv + offset + 2 + 12 * i + z]; NUD_FObject.Value = 1; // Trigger Update changeObjectIndex(null, null); GB_PKM.Enabled = (index > 0); // Trainer Pokemon pkmdata = new byte[3, 0x34]; if (index > 0) for (int i = 0; i < 3; i++) for (int z = 0; z < 0x34; z++) pkmdata[i, z] = sav[sv + offset + 0x32E + 0x34 * i + z]; NUD_FPKM.Value = 1; changeFavPKM(null, null); // Trigger Update loading = false; } private byte[,] objdata; private byte[,] pkmdata; private void B_FAV2SAV(object sender, EventArgs e) { // Write data back to save int index = LB_Favorite.SelectedIndex; // store for restoring if (!GB_PKM.Enabled && index > 0) { MessageBox.Show("Sorry, no overwriting someone else's base with your own data.", "Error"); return; } if (GB_PKM.Enabled && index == 0) { MessageBox.Show("Sorry, no overwriting of your own base with someone else's.","Error"); return; } if (LB_Favorite.Items[index].ToString().Substring(LB_Favorite.Items[index].ToString().Length - 5, 5) == "Empty") { MessageBox.Show("Sorry, no overwriting an empty base with someone else's.", "Error"); return; } if (index < 0) return; int offset = fav_offset + 0x5400 + 0x25A; // Base Offset Changing if (index == 0) offset = fav_offset + 0x5400 + 0x326; else offset += 0x3E0 * index; string TrainerName = TB_FOT.Text; byte[] tr = Encoding.Unicode.GetBytes(TrainerName); Array.Resize(ref tr, 0x22); Array.Copy(tr, 0, sav, sv + offset + 0x218, 0x1A); string team1 = TB_FT1.Text; string team2 = TB_FT2.Text; byte[] t1 = Encoding.Unicode.GetBytes(team1); Array.Resize(ref t1, 0x22); Array.Copy(t1, 0, sav, sv + offset + 0x232 + 0x22 * 0, 0x22); byte[] t2 = Encoding.Unicode.GetBytes(team2); Array.Resize(ref t2, 0x22); Array.Copy(t2, 0, sav, sv + offset + 0x232 + 0x22 * 1, 0x22); string saying1 = TB_FSay1.Text; string saying2 = TB_FSay2.Text; string saying3 = TB_FSay3.Text; string saying4 = TB_FSay4.Text; byte[] s1 = Encoding.Unicode.GetBytes(saying1); Array.Resize(ref s1, 0x22); Array.Copy(s1, 0, sav, sv + offset + 0x276 + 0x22 * 0, 0x22); byte[] s2 = Encoding.Unicode.GetBytes(saying2); Array.Resize(ref s2, 0x22); Array.Copy(s2, 0, sav, sv + offset + 0x276 + 0x22 * 1, 0x22); byte[] s3 = Encoding.Unicode.GetBytes(saying3); Array.Resize(ref s3, 0x22); Array.Copy(s3, 0, sav, sv + offset + 0x276 + 0x22 * 2, 0x22); byte[] s4 = Encoding.Unicode.GetBytes(saying4); Array.Resize(ref s4, 0x22); Array.Copy(s4, 0, sav, sv + offset + 0x276 + 0x22 * 3, 0x22); int baseloc = (int)NUD_FBaseLocation.Value; if (baseloc < 3) baseloc = 0; // skip 1/2 baselocs as they are dummied out ingame. Array.Copy(BitConverter.GetBytes(baseloc), 0, sav, sv + offset, 2); TB_FOT.Text = TrainerName; TB_FSay1.Text = saying1; TB_FSay2.Text = saying2; TB_FSay3.Text = saying3; TB_FSay4.Text = saying4; // Copy back Objects for (int i = 0; i < 25; i++) for (int z = 0; z < 12; z++) sav[sv + offset + 2 + 12 * i + z] = objdata[i, z]; if (GB_PKM.Enabled) // Copy pkm data back in for (int i = 0; i < 3; i++) for (int z = 0; z < 0x34; z++) sav[sv + offset + 0x32E + 0x34 * i + z] = pkmdata[i, z]; popFavorite(); LB_Favorite.SelectedIndex = index; } // Button Specific private void B_Cancel_Click(object sender, EventArgs e) { Close(); } private void B_Save_Click(object sender, EventArgs e) { uint flags = Util.ToUInt32(MT_Flags); Array.Copy(BitConverter.GetBytes(flags), 0, sav, 0x2942C, 4); Array.Copy(sav, m_parent.savefile, 0x100000); m_parent.savedited = true; Close(); } private void B_GiveDecor_Click(object sender, EventArgs e) { int offset = sv + 0x23A00 + 0x5400; for (int i = 0; i < 173; i++) { // int qty = BitConverter.ToUInt16(sav, offset + i * 4); // int has = BitConverter.ToUInt16(sav, offset + i * 4 + 2); sav[offset + i * 4] = (byte)25; sav[offset + i * 4 + 2] = 1; } } private void changeObjectIndex(object sender, EventArgs e) { int objindex = (int)(NUD_FObject.Value) - 1; byte[] objinfo = new Byte[12]; for (int i = 0; i < 12; i++) objinfo[i] = objdata[objindex, i]; // Array with object data acquired. Fill data. int val = objinfo[0]; if (val == 0xFF) val = -1; byte x = objinfo[2]; byte y = objinfo[4]; byte rot = objinfo[6]; byte unk1 = objinfo[7]; ushort unk2 = BitConverter.ToUInt16(objinfo, 0x8); // Set values to display editing = true; NUD_FObjType.Value = val; NUD_FX.Value = x; NUD_FY.Value = y; NUD_FRot.Value = rot; editing = false; } private void changeObjectQuality(object sender, EventArgs e) { if (editing) return; int objindex = (int)(NUD_FObject.Value) - 1; byte val = (byte)(NUD_FObjType.Value); byte x = (byte)(NUD_FX.Value); byte y = (byte)(NUD_FY.Value); byte rot = (byte)(NUD_FRot.Value); objdata[objindex, 0] = val; objdata[objindex, 2] = x; objdata[objindex, 4] = y; objdata[objindex, 6] = rot; } private int currentpkm; private void changeFavPKM(object sender, EventArgs e) { int index = (int)(NUD_FPKM.Value); saveFavPKM(); // Save existing PKM currentpkm = index; loadFavPKM(); } private void saveFavPKM() { if (loading || !GB_PKM.Enabled) return; int index = currentpkm; byte[] pkm = new Byte[0x34]; Array.Copy(BitConverter.GetBytes(Util.getHEXval(TB_EC)), 0, pkm, 0, 4); // EC Array.Copy(BitConverter.GetBytes(Util.getIndex(CB_Species)), 0, pkm, 8, 2); Array.Copy(BitConverter.GetBytes(Util.getIndex(CB_HeldItem)), 0, pkm, 0xA, 2); pkm[0xC] = (byte)Array.IndexOf(abilitylist, (CB_Ability.Text).Remove((CB_Ability.Text).Length - 4)); // Ability pkm[0xD] = (byte)(CB_Ability.SelectedIndex << 1); // Number pkm[0x14] = (byte)Util.getIndex(CB_Nature); int fegform = 0; fegform += PKX.getGender(Label_Gender.Text) << 1; // Gender fegform += ((Util.getIndex(CB_Form)) * 8); pkm[0x15] = (byte)fegform; pkm[0x16] = (byte)(Convert.ToByte( TB_HPEV.Text) & 0x1F); pkm[0x17] = (byte)(Convert.ToByte(TB_ATKEV.Text) & 0x1F); pkm[0x18] = (byte)(Convert.ToByte(TB_DEFEV.Text) & 0x1F); pkm[0x19] = (byte)(Convert.ToByte(TB_SPAEV.Text) & 0x1F); pkm[0x1A] = (byte)(Convert.ToByte(TB_SPDEV.Text) & 0x1F); pkm[0x1B] = (byte)(Convert.ToByte(TB_SPEEV.Text) & 0x1F); Array.Copy(BitConverter.GetBytes(Util.getIndex(CB_Move1)), 0, pkm, 0x1C, 2); Array.Copy(BitConverter.GetBytes(Util.getIndex(CB_Move2)), 0, pkm, 0x1E, 2); Array.Copy(BitConverter.GetBytes(Util.getIndex(CB_Move3)), 0, pkm, 0x20, 2); Array.Copy(BitConverter.GetBytes(Util.getIndex(CB_Move4)), 0, pkm, 0x22, 2); pkm[0x24] = (byte)CB_PPu1.SelectedIndex; pkm[0x25] = (byte)CB_PPu2.SelectedIndex; pkm[0x26] = (byte)CB_PPu3.SelectedIndex; pkm[0x27] = (byte)CB_PPu4.SelectedIndex; pkm[0x28] = (byte)(Convert.ToByte(TB_HPIV.Text) & 0x1F); pkm[0x29] = (byte)(Convert.ToByte(TB_ATKIV.Text) & 0x1F); pkm[0x2A] = (byte)(Convert.ToByte(TB_DEFIV.Text) & 0x1F); pkm[0x2B] = (byte)(Convert.ToByte(TB_SPAIV.Text) & 0x1F); pkm[0x2C] = (byte)(Convert.ToByte(TB_SPDIV.Text) & 0x1F); pkm[0x2D] = (byte)(Convert.ToByte(TB_SPEIV.Text) & 0x1F); int shiny = (CHK_Shiny.Checked? 1 : 0) << 6; pkm[0x2D] |= (byte)shiny; pkm[0x2E] = Convert.ToByte(TB_Friendship.Text); pkm[0x2F] = (byte)Util.getIndex(CB_Ball); pkm[0x30] = Convert.ToByte(TB_Level.Text); for (int i = 0; i < 0x34; i++) // Copy data back to storage. pkmdata[index - 1, i] = pkm[i]; } private void loadFavPKM() { int index = currentpkm - 1; byte[] fpkm = new Byte[0x34]; for (int i = 0; i < 0x34; i++) fpkm[i] = pkmdata[index, i]; uint ec = BitConverter.ToUInt32(fpkm, 0); uint unk = BitConverter.ToUInt32(fpkm, 4); int spec = BitConverter.ToInt16(fpkm, 8); int item = BitConverter.ToInt16(fpkm, 0xA); int abil = fpkm[0xC]; int abil_no = fpkm[0xD]; MT_AbilNo.Text = abil_no.ToString(); // 6 unknown bytes, contest? int nature = fpkm[0x14]; byte genform = fpkm[0x15]; genderflag = (genform >> 1) & 0x3; setGenderLabel(); byte HP_EV = fpkm[0x16]; byte AT_EV = fpkm[0x17]; byte DE_EV = fpkm[0x18]; byte SA_EV = fpkm[0x19]; byte SD_EV = fpkm[0x1A]; byte SP_EV = fpkm[0x1B]; int move1 = BitConverter.ToInt16(fpkm, 0x1C); int move2 = BitConverter.ToInt16(fpkm, 0x1E); int move3 = BitConverter.ToInt16(fpkm, 0x20); int move4 = BitConverter.ToInt16(fpkm, 0x22); byte ppu1 = fpkm[0x24]; byte ppu2 = fpkm[0x25]; byte ppu3 = fpkm[0x26]; byte ppu4 = fpkm[0x27]; byte HP_IV = fpkm[0x28]; byte AT_IV = fpkm[0x29]; byte DE_IV = fpkm[0x2A]; byte SA_IV = fpkm[0x2B]; byte SD_IV = fpkm[0x2C]; byte SP_IV = fpkm[0x2D]; bool isshiny = ((SP_IV & 0x40) > 0); SP_IV &= 0x1F; byte friendship = fpkm[0x2E]; int ball = fpkm[0x2F]; byte level = fpkm[0x30]; // Put data into fields. TB_EC.Text = ec.ToString("X8"); CB_Species.SelectedValue = spec; CB_HeldItem.SelectedValue = item; CB_Nature.SelectedValue = nature; CB_Ball.SelectedValue = ball; TB_HPIV.Text = HP_IV.ToString(); TB_ATKIV.Text = AT_IV.ToString(); TB_DEFIV.Text = DE_IV.ToString(); TB_SPAIV.Text = SA_IV.ToString(); TB_SPDIV.Text = SD_IV.ToString(); TB_SPEIV.Text = SP_IV.ToString(); TB_HPEV.Text = HP_EV.ToString(); TB_ATKEV.Text = AT_EV.ToString(); TB_DEFEV.Text = DE_EV.ToString(); TB_SPAEV.Text = SA_EV.ToString(); TB_SPDEV.Text = SD_EV.ToString(); TB_SPEEV.Text = SP_EV.ToString(); TB_Friendship.Text = friendship.ToString(); TB_Level.Text = level.ToString(); CB_Move1.SelectedValue = move1; CB_Move2.SelectedValue = move2; CB_Move3.SelectedValue = move3; CB_Move4.SelectedValue = move4; CB_PPu1.SelectedIndex = ppu1; CB_PPu2.SelectedIndex = ppu2; CB_PPu3.SelectedIndex = ppu3; CB_PPu4.SelectedIndex = ppu4; CHK_Shiny.Checked = isshiny; // Set Form m_parent.setForms(spec, CB_Form); int form = genform >> 3; CB_Form.SelectedIndex = form; // Set Ability m_parent.updateAbilityList(MT_AbilNo, spec, CB_Ability, CB_Form); } private void updateSpecies(object sender, EventArgs e) { int species = Util.getIndex(CB_Species); // Get Forms for Given Species m_parent.setForms(species, CB_Form); // Check for Gender Changes // Get Gender Threshold species = Util.getIndex(CB_Species); DataTable spectable = PKX.SpeciesTable(); gt = (int)spectable.Rows[species][8]; if (gt == 258) // Genderless genderflag = 2; else if (gt == 257) // Female Only genderflag = 1; else if (gt == 256) // Male Only genderflag = 0; setGenderLabel(); m_parent.updateAbilityList(MT_AbilNo, Util.getIndex(CB_Species), CB_Ability, CB_Form); } private void updateForm(object sender, EventArgs e) { m_parent.updateAbilityList(MT_AbilNo, Util.getIndex(CB_Species), CB_Ability, CB_Form); // If form has a single gender, account for it. if (PKX.getGender(CB_Form.Text) == 0) // ♂ Label_Gender.Text = Form1.gendersymbols[0]; // ♂ else if (PKX.getGender(CB_Form.Text) == 1) // ♀ Label_Gender.Text = Form1.gendersymbols[1]; // ♀ } private int species; private int gt; private int genderflag; private void Label_Gender_Click(object sender, EventArgs e) { // Get Gender Threshold species = Util.getIndex(CB_Species); DataTable spectable = PKX.SpeciesTable(); gt = (int)spectable.Rows[species][8]; if (gt > 255) // Single gender/genderless return; if (gt < 256) // If not a single gender(less) species: { if (PKX.getGender(Label_Gender.Text) == 0) Label_Gender.Text = Form1.gendersymbols[1]; else Label_Gender.Text = Form1.gendersymbols[0]; } } private void setGenderLabel() { if (genderflag == 0) // Gender = Male Label_Gender.Text = Form1.gendersymbols[0]; else if (genderflag == 1) // Gender = Female Label_Gender.Text = Form1.gendersymbols[1]; else Label_Gender.Text = Form1.gendersymbols[2]; } } }
using Microsoft.AspNetCore.Identity; using SeniorLibrary.Models; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text.Json; using System.Threading.Tasks; namespace SeniorLibrary.Data { public class ContextSeed { public enum Roles { Admin, Student, Staff, Lecturer } public static async Task SeedRolesAsync(UserManager<ApplicationUser> userManager, RoleManager<IdentityRole> roleManager) { //Seed Roles await roleManager.CreateAsync(new IdentityRole(Roles.Admin.ToString())); await roleManager.CreateAsync(new IdentityRole(Roles.Student.ToString())); await roleManager.CreateAsync(new IdentityRole(Roles.Staff.ToString())); await roleManager.CreateAsync(new IdentityRole(Roles.Lecturer.ToString())); } public static async Task SeedSuperAdminAsync(UserManager<ApplicationUser> userManager, RoleManager<IdentityRole> roleManager) { //Seed Default User var defaultUser = new ApplicationUser { UserName = "ictadmin", Email = "ictadmin@gmail.com", EmailConfirmed = true, PhoneNumberConfirmed = true }; if (userManager.Users.All(u => u.Id != defaultUser.Id)) { var user = await userManager.FindByEmailAsync(defaultUser.Email); if (user == null) { // id, password await userManager.CreateAsync(defaultUser, "123Pa$$word."); await userManager.AddToRoleAsync(defaultUser, Roles.Admin.ToString()); } } } public static async Task AddBookAsync(SeniorLibraryContext context) { System.Diagnostics.Debug.WriteLine("Adding Books"); string currentDir = Directory.GetCurrentDirectory(); string bookRoot = currentDir + @"/book"; string addedRoot = bookRoot + @"/Added"; string[] entries = Directory.GetFiles(bookRoot); Console.WriteLine(currentDir); foreach (string filePath in entries) { string fileName = Path.GetFileName(filePath); //Prepare tools needed for filereading //Console.WriteLine(Path.GetFileName(filePath)); byte[] fileContent = null; FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read); BinaryReader binaryReader = new System.IO.BinaryReader(fs); long byteLength = new FileInfo(filePath).Length; fileContent = binaryReader.ReadBytes((Int32)byteLength); fs.Close(); fs.Dispose(); binaryReader.Close(); //Create a book object var book = new Book(); book.Name = fileName; book.DataFiles = fileContent; book.CreatedOn = DateTime.Now; //Insert to database File.Move(filePath, addedRoot + @"/" + fileName); await context.Book.AddAsync(book); await context.SaveChangesAsync(); System.Diagnostics.Debug.WriteLine("Successfully Added"+fileName+"!! to the database"); } System.Diagnostics.Debug.WriteLine("DONE !!!!!!!!!!!!!!"); } public static async Task AddUserAsync(UserManager<ApplicationUser> userManager, RoleManager<IdentityRole> roleManager) { string text = await System.IO.File.ReadAllTextAsync("users.json"); using JsonDocument doc = JsonDocument.Parse(text); JsonElement root = doc.RootElement; //Seed Users from Json foreach (var item in root.EnumerateArray()) { string email = item.GetProperty("email").ToString(); string password = item.GetProperty("password").ToString(); string firstName = item.GetProperty("firstname").ToString(); string lastName = item.GetProperty("lastname").ToString(); int studentID = int.Parse(item.GetProperty("studentid").ToString()); string role = item.GetProperty("role").ToString(); var defaultUser = new ApplicationUser { UserName = email.Split("@")[0], Email = email, FirstName = firstName, LastName = lastName, StudentID = studentID, EmailConfirmed = true, PhoneNumberConfirmed = true }; if (userManager.Users.All(u => u.Id != defaultUser.Id)) { var user = await userManager.FindByEmailAsync(defaultUser.Email); if (user == null) { // id, password if (Enum.IsDefined(typeof(Roles), role)) { await userManager.CreateAsync(defaultUser, password); await userManager.AddToRoleAsync(defaultUser, role); } } } } } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using System.Data.OleDb; namespace ERP.project { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void panel1_Paint(object sender, PaintEventArgs e) { // this.panel1.ResetText ="3E33E"; } private void comboBox2_SelectedIndexChanged(object sender, EventArgs e) { } private void Form1_Load(object sender, EventArgs e) { textBox2.PasswordChar = '.'; //this.BackColor = Color.BurlyWood; this.MaximizeBox = false; this.MinimizeBox = false; } private void label1_Click(object sender, EventArgs e) { } private void button1_Click(object sender, EventArgs e) { Form1 conn = new Form1(); conn.oleDbConnection1.Open(); OleDbCommand cmd = new OleDbCommand("Select *from Login where USERID = '" + textBox1.Text + "' and USERPAS='" + textBox2.Text + "' ", conn.oleDbConnection1); OleDbDataReader dr = cmd.ExecuteReader(); if (dr.Read()) { MessageBox.Show("WELCOME TO MY ERP", "", MessageBoxButtons.OK, MessageBoxIcon.Information); this.Hide(); Form2 f2 = new Form2(); f2.Show(); } else { MessageBox.Show("Password is not correct"); } conn.oleDbConnection1.Close(); } private void button2_Click(object sender, EventArgs e) { Application.Exit(); } private void textBox1_TextChanged(object sender, EventArgs e) { } } }
/* * User: Jason D. Jimenez * Date: 12/8/2005 * Time: 6:31 AM * */ using System; using System.ComponentModel; using System.Drawing; using System.Xml; using System.Reflection; using Microsoft.VisualBasic; namespace JasonJimenez.ClassicReport.Common.Widgets { using JasonJimenez.ClassicReport.Common; internal abstract class BaseWidget : IXmlWriter, ICloneable { // design properties protected int m_col = 0; protected int m_row = 0; protected int m_width = 10; protected int m_height = 1; protected CasingEnum m_conv; protected JustifyEnum m_justify = JustifyEnum.JustifyNone; protected ReportModel m_owner = null; protected bool m_selected = false; public BaseWidget() { } public BaseWidget(XmlNode node) { this.Col = Convert.ToInt32(ReportReader.GetValue(node, "col")); this.Row = Convert.ToInt32(ReportReader.GetValue(node, "row")); this.Height = Convert.ToInt32(ReportReader.GetValue(node, "height")); this.Casing = (CasingEnum)Enum.Parse(typeof(CasingEnum), ReportReader.GetValue(node, "conversion")); this.Justify = (JustifyEnum)Enum.Parse(typeof(JustifyEnum), ReportReader.GetValue(node, "justify")); this.IsBold = ReportReader.GetValue(node, "bold") == "True"; this.IsItalic = ReportReader.GetValue(node, "italic") == "True"; this.IsUnderline = ReportReader.GetValue(node, "underline") == "True"; } protected abstract void Write(XmlWriter writer); bool _bold; bool _underline; bool _italic; [Category("Appearance")] public bool IsBold { get { return _bold; } set { _bold = value; } } [Category("Appearance")] public bool IsUnderline { get { return _underline; } set { _underline = value; } } [Category("Appearance")] public bool IsItalic { get { return _italic; } set { _italic = value; } } [Browsable(false)] public ReportModel Owner { get { return m_owner; } set { m_owner = value; } } [Category("Layout")] public virtual int Width { get {return m_width;} set { } } [Category("Appearance")] public CasingEnum Casing { get {return m_conv;} set {m_conv = value;} } [Browsable(false)] public bool IsSelected { get {return m_selected;} set {m_selected = value;} } [Category("Layout")] public JustifyEnum Justify { get {return m_justify;} set {m_justify = value;} } [Browsable(false)] public int Row { get {return m_row;} set {m_row = value;} } [Category("Layout")] public int Col { get { switch (m_justify) { case JustifyEnum.JustifyLeft: return 0; case JustifyEnum.JustifyRight: return Owner.PageWidth - this.Width; case JustifyEnum.JustifyCenter: return (Owner.PageWidth - this.Width) / 2; default: return m_col; } } set {m_col = value;} } [Browsable(true)] public int Height { get {return m_height;} set { if (value>0) m_height = value; } } public override string ToString() { return base.ToString(); } public System.Drawing.Rectangle GetRectangle() { return new Rectangle(this.Col, this.Row, this.Width, this.Height); } [Browsable(false)] public virtual string Value { get {return this.ToString();} } public string StrConv(string s) { VbStrConv conv = VbStrConv.None; switch (m_conv) { case CasingEnum.None: conv = VbStrConv.None; break; case CasingEnum.Upper: conv = VbStrConv.Uppercase; break; case CasingEnum.Lower: conv = VbStrConv.Lowercase; break; case CasingEnum.Proper: conv = VbStrConv.ProperCase; break; } return Microsoft.VisualBasic.Strings.StrConv(s,conv,0); } public virtual void WriteXml(XmlTextWriter writer) { writer.WriteStartElement("widget"); writer.WriteElementString("col", m_col.ToString()); writer.WriteElementString("row", m_row.ToString()); writer.WriteElementString("conversion", m_conv.ToString()); writer.WriteElementString("height", m_height.ToString()); writer.WriteElementString("justify", m_justify.ToString()); writer.WriteElementString("width", m_width.ToString()); writer.WriteElementString("bold", _bold.ToString()); writer.WriteElementString("italic", _italic.ToString()); writer.WriteElementString("underline", _underline.ToString()); this.Write(writer); writer.WriteEndElement(); } public virtual void Write(IPage page) { if (this.Justify != JustifyEnum.JustifyNone) { page.Write(this, this.Justify); } else { page.Write(this, this.Col); } } public void SetValue(string propertyName, object value) { PropertyInfo prop = this.GetType().GetProperty(propertyName); try { prop.SetValue(this, value, null); } catch { } } #region ICloneable Members public object Clone() { object clone = Activator.CreateInstance(this.GetType()); PropertyInfo[] pi = this.GetType().GetProperties(); foreach (PropertyInfo info in pi) { if (info.CanWrite) { info.SetValue(clone, info.GetValue(this, null),null); } } return clone; } #endregion public void BringToFront() { Band band = m_owner.Bands[m_row]; band.Remove(this); band.AddFront(this); } public void SendToBack() { Band band = m_owner.Bands[m_row]; band.Remove(this); band.Add(this); } } //internal class TemplateWidget : BaseWidget //{ // public override void Write(IWriter Document) // { // throw new Exception("The method or operation is not implemented."); // } // public override void Write(XmlWriter writer) // { // throw new Exception("The method or operation is not implemented."); // } // public override int Width // { // get // { // return base.Width; // } // set // { // if (value>0) m_width = value; // } // } //} }
using System; using System.Collections.Generic; using System.Text; namespace OCP { /** * Interface IL10N * * @package OCP * @since 6.0.0 */ public interface IL10N { /** * Translating * @param string text The text we need a translation for * @param array|string parameters default:array() Parameters for sprintf * @return string Translation or the same text * * Returns the translation. If no translation is found, text will be * returned. * @since 6.0.0 */ string t(string text, params string[] parameters); // string t(string text); /** * Translating * @param string text_singular the string to translate for exactly one object * @param string text_plural the string to translate for n objects * @param integer count Number of objects * @param array parameters default:array() Parameters for sprintf * @return string Translation or the same text * * Returns the translation. If no translation is found, text will be * returned. %n will be replaced with the number of objects. * * The correct plural is determined by the plural_forms-function * provided by the po file. * @since 6.0.0 * */ string n(string text_singular, string text_plural, int count, IList<string> parameters); /** * Localization * @param string type Type of localization * @param \DateTime|int|string data parameters for this localization * @param array options currently supports following options: * - 'width': handed into \Punic\Calendar::formatDate as second parameter * @return string|int|false * * Returns the localized data. * * Implemented types: * - date * - Creates a date * - l10n-field: date * - params: timestamp (int/string) * - datetime * - Creates date and time * - l10n-field: datetime * - params: timestamp (int/string) * - time * - Creates a time * - l10n-field: time * - params: timestamp (int/string) * @since 6.0.0 - parameter options was added in 8.0.0 */ object l(string type,object data, IList<string> options ); /** * The code (en, de, ...) of the language that is used for this IL10N object * * @return string language * @since 7.0.0 */ string getLanguageCode(); /** * * The code (en_US, fr_CA, ...) of the locale that is used for this IL10N object * * @return string locale * @since 14.0.0 */ string getLocaleCode(); } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace RNC.Donnees { public class MnistImage { public int largeur; // 28 public int hauteur; // 28 public byte[][] pixels1; // 0(white) - 255(black) public byte label; // '0' - '9' public byte[] pixels; //public MnistImage1(int largeur, int hauteur, byte[][] pixels, byte label) //{ // this.largeur = largeur; // this.hauteur = hauteur; // this.pixels1 = new Byte[hauteur][]; // for (int i = 0; i < this.pixels.Length; ++i) // this.pixels[i] = new byte[largeur]; // for (int i = 0; i < hauteur; ++i) // for (int j = 0; j < largeur; ++j) // this.pixels1[i][j] = Convert.ToByte(255 - Convert.ToInt32(pixels[i][j])); // this.label = label; //} public MnistImage(int largeur, int hauteur, byte[][] pixels, byte label) { this.largeur = largeur; this.hauteur = hauteur; this.pixels = new byte[largeur * hauteur]; for (int i = 0; i < hauteur; i++) for (int j = 0; j < largeur; j++) this.pixels[(i * hauteur) + j] = Convert.ToByte(255 - pixels[i][j]); this.label = label; // Convert.ToByte(255 - Convert.ToInt32(pArray[ii])); } } }
 using System; using System.Collections.Generic; using System.Data; using System.Data.Common; using System.Data.SqlClient; using System.Text; using Karkas.Core.DataUtil; using Karkas.Ornek.TypeLibrary; using Karkas.Ornek.TypeLibrary.Ornekler; namespace Karkas.Ornek.Dal.Ornekler { public partial class IdentityIntDal : BaseDal<IdentityInt> { public override string DatabaseName { get { return "Karkas.Ornek"; } } protected override void identityKolonDegeriniSetle(IdentityInt pTypeLibrary,long pIdentityKolonValue) { pTypeLibrary.IdentityIntKey = (int )pIdentityKolonValue; } protected override string SelectCountString { get { return @"SELECT COUNT(*) FROM ORNEKLER.IDENTITY_INT"; } } protected override string SelectString { get { return @"SELECT IdentityIntKey,Adi FROM ORNEKLER.IDENTITY_INT"; } } protected override string DeleteString { get { return @"DELETE FROM ORNEKLER.IDENTITY_INT WHERE IdentityIntKey = @IdentityIntKey "; } } protected override string UpdateString { get { return @"UPDATE ORNEKLER.IDENTITY_INT SET Adi = @Adi WHERE IdentityIntKey = @IdentityIntKey "; } } protected override string InsertString { get { return @"INSERT INTO ORNEKLER.IDENTITY_INT (Adi) VALUES (@Adi);SELECT scope_identity();"; } } public IdentityInt SorgulaIdentityIntKeyIle(int p1) { List<IdentityInt> liste = new List<IdentityInt>(); SorguCalistir(liste,String.Format(" IdentityIntKey = '{0}'", p1)); if (liste.Count > 0) { return liste[0]; } else { return null; } } protected override bool IdentityVarMi { get { return true; } } protected override bool PkGuidMi { get { return false; } } public override string PrimaryKey { get { return "IdentityIntKey"; } } public virtual void Sil(int IdentityIntKey) { IdentityInt satir = new IdentityInt(); satir.IdentityIntKey = IdentityIntKey; base.Sil(satir); } protected override void ProcessRow(IDataReader dr, IdentityInt satir) { satir.IdentityIntKey = dr.GetInt32(0); if (!dr.IsDBNull(1)) { satir.Adi = dr.GetString(1); } } protected override void InsertCommandParametersAdd(DbCommand cmd, IdentityInt satir) { ParameterBuilder builder = Template.getParameterBuilder(); builder.Command = cmd; builder.parameterEkle("@Adi",SqlDbType.VarChar, satir.Adi,50); } protected override void UpdateCommandParametersAdd(DbCommand cmd, IdentityInt satir) { ParameterBuilder builder = Template.getParameterBuilder(); builder.Command = cmd; builder.parameterEkle("@IdentityIntKey",SqlDbType.Int, satir.IdentityIntKey); builder.parameterEkle("@Adi",SqlDbType.VarChar, satir.Adi,50); } protected override void DeleteCommandParametersAdd(DbCommand cmd, IdentityInt satir) { ParameterBuilder builder = Template.getParameterBuilder(); builder.Command = cmd; builder.parameterEkle("@IdentityIntKey",SqlDbType.Int, satir.IdentityIntKey); } public override string DbProviderName { get { return "System.Data.SqlClient"; } } } }
using System; using DeferredTask.Models; namespace DeferredTask.Test.Models { public class ConcreteDeferredTaskWithDate : AbstractDeferredTask { public DateTime Date { get; set; } } }
using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Dapr; using Dapr.Client; namespace DaprBackEnd.Controllers { [ApiController] [Route("[controller]")] public class WeatherForecastController : ControllerBase { private readonly DaprClient _daprClient; private static readonly string[] Summaries = new[] { "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching" }; private static List<Order> Orders = new List<Order>(){ new Order(){ orderId="001", amount="0", productId="001"} }; private readonly ILogger<WeatherForecastController> _logger; public WeatherForecastController(ILogger<WeatherForecastController> logger, DaprClient daprClient) { _logger = logger; _daprClient = daprClient ?? throw new ArgumentNullException(nameof(daprClient)); } [HttpGet] public IEnumerable<WeatherForecast> Get() { var rng = new Random(); return Enumerable.Range(1, 5).Select(index => new WeatherForecast { Date = DateTime.Now.AddDays(index), TemperatureC = rng.Next(-20, 55), Summary = Summaries[rng.Next(Summaries.Length)] }) .ToArray(); } [HttpGet("/orders")] public IEnumerable<Order> GetOrders() { return Orders; } /// <summary> /// /// post http://localhost:3502/v1.0/publish/pubsub/newOrder /// data { "orderId": "123678", "productId": "5678", "amount": "2" } /// </summary> [HttpPost("/publishorder")] public async Task<ActionResult> PublishOrderAsync(Order order) { await _daprClient.PublishEventAsync<Order>("pubsub", "newOrder", order); return Ok(); } /// <param name="order"></param> /// <returns></returns> [Topic("pubsub", "newOrder")] [HttpPost("/orders")] public async Task<ActionResult> CreateOrder(Order order) { Orders.Add(order); await Task.Delay(0); return Ok(); } } }