text
stringlengths
13
6.01M
using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; namespace Data.Models { public class GameEvent { [Key] public int EventId { get; set; } [ForeignKey("MatchId")] public Game Match { get; set; } public int Minute { get; set; } public GameEventType Type { get; set; } public bool HomeTeamEvent { get; set; } public string PlayerName { get; set; } public enum GameEventType { Goal, OwnGoal, YellowCard, RedCard, Penalty } } }
using System.Collections.Generic; using System.Threading.Tasks; using MeterReadings.Schema; namespace MeterReading.Logic.Facades { public interface IAccountFacade { Task<int?> AddAccount(Account account); Task<IEnumerable<Account>> GetAccounts(); Task<Account> GetAccount(int id); Task DeleteAccount(int id); } }
using System; using System.Collections.Immutable; using System.Composition; using System.Globalization; using System.Linq; 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; using Microsoft.CodeAnalysis.Operations; using Microsoft.CodeAnalysis.Simplification; using Microsoft.CodeAnalysis.Text; using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory; namespace Meziantou.Analyzer.Rules; [ExportCodeFixProvider(LanguageNames.CSharp), Shared] public sealed class OptimizeLinqUsageFixer : CodeFixProvider { public override ImmutableArray<string> FixableDiagnosticIds => ImmutableArray.Create( RuleIdentifiers.UseListOfTMethodsInsteadOfEnumerableExtensionMethods, RuleIdentifiers.UseIndexerInsteadOfElementAt, RuleIdentifiers.DuplicateEnumerable_OrderBy, RuleIdentifiers.OptimizeEnumerable_CombineMethods, RuleIdentifiers.OptimizeEnumerable_Count, RuleIdentifiers.OptimizeEnumerable_CastInsteadOfSelect); public override FixAllProvider GetFixAllProvider() { return WellKnownFixAllProviders.BatchFixer; } public override async Task RegisterCodeFixesAsync(CodeFixContext context) { var root = await context.Document.GetSyntaxRootAsync(context.CancellationToken).ConfigureAwait(false); var nodeToFix = root?.FindNode(context.Span, getInnermostNodeForTie: true); if (nodeToFix == null) return; var diagnostic = context.Diagnostics.FirstOrDefault(); if (diagnostic == null) return; if (!Enum.TryParse(diagnostic.Properties.GetValueOrDefault("Data", ""), out OptimizeLinqUsageData data) || data == OptimizeLinqUsageData.None) return; // If the so-called nodeToFix is a Name (most likely a method name such as 'Select' or 'Count'), // adjust it so that it refers to its InvocationExpression ancestor instead. if ((nodeToFix.IsKind(SyntaxKind.IdentifierName) || nodeToFix.IsKind(SyntaxKind.GenericName)) && !TryGetInvocationExpressionAncestor(ref nodeToFix)) return; var title = "Optimize linq usage"; switch (data) { case OptimizeLinqUsageData.UseLengthProperty: context.RegisterCodeFix(CodeAction.Create(title, ct => UseLengthProperty(context.Document, nodeToFix, ct), equivalenceKey: title), context.Diagnostics); break; case OptimizeLinqUsageData.UseLongLengthProperty: context.RegisterCodeFix(CodeAction.Create(title, ct => UseLongLengthProperty(context.Document, nodeToFix, ct), equivalenceKey: title), context.Diagnostics); break; case OptimizeLinqUsageData.UseCountProperty: context.RegisterCodeFix(CodeAction.Create(title, ct => UseCountProperty(context.Document, nodeToFix, ct), equivalenceKey: title), context.Diagnostics); break; case OptimizeLinqUsageData.UseFindMethod: context.RegisterCodeFix(CodeAction.Create(title, ct => UseListMethod(context.Document, nodeToFix, "Find", convertPredicate: false, ct), equivalenceKey: title), context.Diagnostics); break; case OptimizeLinqUsageData.UseFindMethodWithConversion: context.RegisterCodeFix(CodeAction.Create(title, ct => UseListMethod(context.Document, nodeToFix, "Find", convertPredicate: true, ct), equivalenceKey: title), context.Diagnostics); break; case OptimizeLinqUsageData.UseTrueForAllMethod: context.RegisterCodeFix(CodeAction.Create(title, ct => UseListMethod(context.Document, nodeToFix, "TrueForAll", convertPredicate: false, ct), equivalenceKey: title), context.Diagnostics); break; case OptimizeLinqUsageData.UseTrueForAllMethodWithConversion: context.RegisterCodeFix(CodeAction.Create(title, ct => UseListMethod(context.Document, nodeToFix, "TrueForAll", convertPredicate: true, ct), equivalenceKey: title), context.Diagnostics); break; case OptimizeLinqUsageData.UseExistsMethod: context.RegisterCodeFix(CodeAction.Create(title, ct => UseListMethod(context.Document, nodeToFix, "Exists", convertPredicate: false, ct), equivalenceKey: title), context.Diagnostics); break; case OptimizeLinqUsageData.UseExistsMethodWithConversion: context.RegisterCodeFix(CodeAction.Create(title, ct => UseListMethod(context.Document, nodeToFix, "Exists", convertPredicate: true, ct), equivalenceKey: title), context.Diagnostics); break; case OptimizeLinqUsageData.UseIndexer: context.RegisterCodeFix(CodeAction.Create(title, ct => UseIndexer(context.Document, nodeToFix, ct), equivalenceKey: title), context.Diagnostics); break; case OptimizeLinqUsageData.UseIndexerFirst: context.RegisterCodeFix(CodeAction.Create(title, ct => UseIndexerFirst(context.Document, nodeToFix, ct), equivalenceKey: title), context.Diagnostics); break; case OptimizeLinqUsageData.UseIndexerLast: context.RegisterCodeFix(CodeAction.Create(title, ct => UseIndexerLast(context.Document, nodeToFix, ct), equivalenceKey: title), context.Diagnostics); break; case OptimizeLinqUsageData.DuplicatedOrderBy: var useThenByTitle = "Use " + diagnostic.Properties["ExpectedMethodName"]; var removeOrderByTitle = "Remove " + diagnostic.Properties["MethodName"]; context.RegisterCodeFix(CodeAction.Create(useThenByTitle, ct => UseThenBy(context.Document, diagnostic, ct), equivalenceKey: "UseThenBy"), context.Diagnostics); context.RegisterCodeFix(CodeAction.Create(removeOrderByTitle, ct => RemoveDuplicatedOrderBy(context.Document, diagnostic, ct), equivalenceKey: "RemoveOrderBy"), context.Diagnostics); break; case OptimizeLinqUsageData.CombineWhereWithNextMethod: context.RegisterCodeFix(CodeAction.Create(title, ct => CombineWhereWithNextMethod(context.Document, diagnostic, ct), equivalenceKey: title), context.Diagnostics); break; case OptimizeLinqUsageData.UseTrue: context.RegisterCodeFix(CodeAction.Create(title, ct => UseConstantValue(context.Document, nodeToFix, constantValue: true, ct), equivalenceKey: title), context.Diagnostics); break; case OptimizeLinqUsageData.UseFalse: context.RegisterCodeFix(CodeAction.Create(title, ct => UseConstantValue(context.Document, nodeToFix, constantValue: false, ct), equivalenceKey: title), context.Diagnostics); break; case OptimizeLinqUsageData.UseNotAny: context.RegisterCodeFix(CodeAction.Create(title, ct => UseAny(context.Document, diagnostic, nodeToFix, constantValue: false, ct), equivalenceKey: title), context.Diagnostics); break; case OptimizeLinqUsageData.UseAny: context.RegisterCodeFix(CodeAction.Create(title, ct => UseAny(context.Document, diagnostic, nodeToFix, constantValue: true, ct), equivalenceKey: title), context.Diagnostics); break; case OptimizeLinqUsageData.UseTakeAndCount: context.RegisterCodeFix(CodeAction.Create(title, ct => UseTakeAndCount(context.Document, diagnostic, ct), equivalenceKey: title), context.Diagnostics); break; case OptimizeLinqUsageData.UseSkipAndAny: context.RegisterCodeFix(CodeAction.Create(title, ct => UseSkipAndAny(context.Document, diagnostic, nodeToFix, comparandValue: true, ct), equivalenceKey: title), context.Diagnostics); break; case OptimizeLinqUsageData.UseSkipAndNotAny: context.RegisterCodeFix(CodeAction.Create(title, ct => UseSkipAndAny(context.Document, diagnostic, nodeToFix, comparandValue: false, ct), equivalenceKey: title), context.Diagnostics); break; case OptimizeLinqUsageData.UseCastInsteadOfSelect: context.RegisterCodeFix(CodeAction.Create(title, ct => UseCastInsteadOfSelect(context.Document, nodeToFix, ct), equivalenceKey: title), context.Diagnostics); break; } } private static bool TryGetInvocationExpressionAncestor(ref SyntaxNode nodeToFix) { var node = nodeToFix; while (node != null) { if (node.IsKind(SyntaxKind.InvocationExpression)) { nodeToFix = node; return true; } node = node.Parent; } return false; } private static async Task<Document> UseAny(Document document, Diagnostic diagnostic, SyntaxNode nodeToFix, bool constantValue, CancellationToken cancellationToken) { var countOperationStart = int.Parse(diagnostic.Properties["CountOperationStart"]!, NumberStyles.Integer, CultureInfo.InvariantCulture); var countOperationLength = int.Parse(diagnostic.Properties["CountOperationLength"]!, NumberStyles.Integer, CultureInfo.InvariantCulture); var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); var countNode = root?.FindNode(new TextSpan(countOperationStart, countOperationLength), getInnermostNodeForTie: true); if (countNode == null) return document; var editor = await DocumentEditor.CreateAsync(document, cancellationToken).ConfigureAwait(false); var semanticModel = editor.SemanticModel; if (semanticModel.GetOperation(countNode, cancellationToken) is not IInvocationOperation countOperation) return document; var generator = editor.Generator; var newExpression = generator.InvocationExpression( generator.MemberAccessExpression(countOperation.Arguments[0].Syntax, "Any"), countOperation.Arguments.Skip(1).Select(arg => arg.Syntax)); if (!constantValue) { newExpression = generator.LogicalNotExpression(newExpression); } editor.ReplaceNode(nodeToFix, newExpression); return editor.GetChangedDocument(); } private static async Task<Document> UseTakeAndCount(Document document, Diagnostic diagnostic, CancellationToken cancellationToken) { var countOperationStart = int.Parse(diagnostic.Properties["CountOperationStart"]!, NumberStyles.Integer, CultureInfo.InvariantCulture); var countOperationLength = int.Parse(diagnostic.Properties["CountOperationLength"]!, NumberStyles.Integer, CultureInfo.InvariantCulture); var operandOperationStart = int.Parse(diagnostic.Properties["OperandOperationStart"]!, NumberStyles.Integer, CultureInfo.InvariantCulture); var operandOperationLength = int.Parse(diagnostic.Properties["OperandOperationLength"]!, NumberStyles.Integer, CultureInfo.InvariantCulture); var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); var countNode = root?.FindNode(new TextSpan(countOperationStart, countOperationLength), getInnermostNodeForTie: true); var operandNode = root?.FindNode(new TextSpan(operandOperationStart, operandOperationLength), getInnermostNodeForTie: true); if (countNode == null || operandNode == null) return document; var editor = await DocumentEditor.CreateAsync(document, cancellationToken).ConfigureAwait(false); var semanticModel = editor.SemanticModel; var operandOperation = semanticModel?.GetOperation(operandNode, cancellationToken); if (semanticModel?.GetOperation(countNode, cancellationToken) is not IInvocationOperation countOperation || operandOperation == null) return document; var generator = editor.Generator; var newExpression = countOperation.Arguments[0].Syntax; if (countOperation.Arguments.Length > 1) { newExpression = generator.InvocationExpression( generator.MemberAccessExpression(newExpression, "Where"), countOperation.Arguments.Skip(1).Select(arg => arg.Syntax)); } SyntaxNode takeArgument; if (operandOperation.ConstantValue.Value is int value) { takeArgument = generator.LiteralExpression(value + 1); } else { takeArgument = generator.AddExpression(operandOperation.Syntax, generator.LiteralExpression(1)); } newExpression = generator.InvocationExpression( generator.MemberAccessExpression(newExpression, "Take"), takeArgument); newExpression = generator.InvocationExpression(generator.MemberAccessExpression(newExpression, "Count")); editor.ReplaceNode(countOperation.Syntax, newExpression); return editor.GetChangedDocument(); } private static async Task<Document> UseSkipAndAny(Document document, Diagnostic diagnostic, SyntaxNode nodeToFix, bool comparandValue, CancellationToken cancellationToken) { var countOperationStart = int.Parse(diagnostic.Properties["CountOperationStart"]!, NumberStyles.Integer, CultureInfo.InvariantCulture); var countOperationLength = int.Parse(diagnostic.Properties["CountOperationLength"]!, NumberStyles.Integer, CultureInfo.InvariantCulture); var operandOperationStart = int.Parse(diagnostic.Properties["OperandOperationStart"]!, NumberStyles.Integer, CultureInfo.InvariantCulture); var operandOperationLength = int.Parse(diagnostic.Properties["OperandOperationLength"]!, NumberStyles.Integer, CultureInfo.InvariantCulture); var skipMinusOne = diagnostic.Properties.ContainsKey("SkipMinusOne"); var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); var countNode = root?.FindNode(new TextSpan(countOperationStart, countOperationLength), getInnermostNodeForTie: true); var operandNode = root?.FindNode(new TextSpan(operandOperationStart, operandOperationLength), getInnermostNodeForTie: true); if (countNode == null || operandNode == null) return document; var editor = await DocumentEditor.CreateAsync(document, cancellationToken).ConfigureAwait(false); var semanticModel = editor.SemanticModel; var operandOperation = semanticModel.GetOperation(operandNode, cancellationToken); if (semanticModel.GetOperation(countNode, cancellationToken) is not IInvocationOperation countOperation || operandOperation == null) return document; var generator = editor.Generator; var newExpression = countOperation.Arguments[0].Syntax; if (countOperation.Arguments.Length > 1) { newExpression = generator.InvocationExpression( generator.MemberAccessExpression(newExpression, "Where"), countOperation.Arguments.Skip(1).Select(arg => arg.Syntax)); } SyntaxNode skipArgument; if (operandOperation.ConstantValue.Value is int value) { if (skipMinusOne) { skipArgument = generator.LiteralExpression(value - 1); } else { skipArgument = generator.LiteralExpression(value); } } else { if (skipMinusOne) { skipArgument = generator.SubtractExpression(operandOperation.Syntax, generator.LiteralExpression(1)); } else { skipArgument = operandOperation.Syntax; } } newExpression = generator.InvocationExpression( generator.MemberAccessExpression(newExpression, "Skip"), skipArgument); newExpression = generator.InvocationExpression(generator.MemberAccessExpression(newExpression, "Any")); if (!comparandValue) { newExpression = generator.LogicalNotExpression(newExpression); } editor.ReplaceNode(nodeToFix, newExpression); return editor.GetChangedDocument(); } private static async Task<Document> UseCastInsteadOfSelect(Document document, SyntaxNode nodeToFix, CancellationToken cancellationToken) { if (nodeToFix is not InvocationExpressionSyntax selectInvocationExpression) return document; if (selectInvocationExpression.Expression is not MemberAccessExpressionSyntax memberAccessExpression) return document; var editor = await DocumentEditor.CreateAsync(document, cancellationToken).ConfigureAwait(false); var generator = editor.Generator; var operation = editor.SemanticModel.GetOperation(selectInvocationExpression, cancellationToken) as IInvocationOperation; if (operation == null) return document; var type = operation.TargetMethod.TypeArguments[1]; var typeSyntax = (TypeSyntax)generator.TypeExpression(type); var castNameSyntax = GenericName(Identifier("Cast")) .WithTypeArgumentList(TypeArgumentList(SingletonSeparatedList(typeSyntax))); // Is the 'source' (i.e. the sequence of values 'Select' is invoked on) passed in as argument? // If there is 1 argument -> No 'source' argument, only 'selector' // If there are 2 arguments -> The 1st argument is the 'source' var argumentListArguments = selectInvocationExpression.ArgumentList.Arguments; var sourceArg = argumentListArguments.Reverse().Skip(1).FirstOrDefault(); SyntaxNode castInvocationExpression; if (sourceArg is null) { castInvocationExpression = generator.InvocationExpression( generator.MemberAccessExpression(memberAccessExpression.Expression, castNameSyntax)); } else { castInvocationExpression = generator.InvocationExpression( generator.MemberAccessExpression(memberAccessExpression.Expression, castNameSyntax), sourceArg); } editor.ReplaceNode(selectInvocationExpression, castInvocationExpression.WithAdditionalAnnotations(Simplifier.Annotation)); return editor.GetChangedDocument(); } private static async Task<Document> UseConstantValue(Document document, SyntaxNode nodeToFix, bool constantValue, CancellationToken cancellationToken) { var editor = await DocumentEditor.CreateAsync(document, cancellationToken).ConfigureAwait(false); var generator = editor.Generator; var literalNode = constantValue ? generator.TrueLiteralExpression() : generator.FalseLiteralExpression(); editor.ReplaceNode(nodeToFix, literalNode); return editor.GetChangedDocument(); } private async static Task<Document> UseLengthProperty(Document document, SyntaxNode nodeToFix, CancellationToken cancellationToken) { var expression = GetParentMemberExpression(nodeToFix); if (expression == null) return document; var editor = await DocumentEditor.CreateAsync(document, cancellationToken).ConfigureAwait(false); var generator = editor.Generator; var propertyAccess = generator.MemberAccessExpression(expression, "Length"); editor.ReplaceNode(nodeToFix, propertyAccess); return editor.GetChangedDocument(); } private async static Task<Document> UseLongLengthProperty(Document document, SyntaxNode nodeToFix, CancellationToken cancellationToken) { var expression = GetParentMemberExpression(nodeToFix); if (expression == null) return document; var editor = await DocumentEditor.CreateAsync(document, cancellationToken).ConfigureAwait(false); var generator = editor.Generator; var propertyAccess = generator.MemberAccessExpression(expression, "LongLength"); editor.ReplaceNode(nodeToFix, propertyAccess); return editor.GetChangedDocument(); } private async static Task<Document> UseCountProperty(Document document, SyntaxNode nodeToFix, CancellationToken cancellationToken) { var expression = GetParentMemberExpression(nodeToFix); if (expression == null) return document; var editor = await DocumentEditor.CreateAsync(document, cancellationToken).ConfigureAwait(false); var generator = editor.Generator; var propertyAccess = generator.MemberAccessExpression(expression, "Count"); editor.ReplaceNode(nodeToFix, propertyAccess); return editor.GetChangedDocument(); } private async static Task<Document> UseListMethod(Document document, SyntaxNode nodeToFix, string methodName, bool convertPredicate, CancellationToken cancellationToken) { var expression = GetMemberAccessExpression(nodeToFix); if (expression == null) return document; var editor = await DocumentEditor.CreateAsync(document, cancellationToken).ConfigureAwait(false); var newExpression = expression.WithName(IdentifierName(methodName)); editor.ReplaceNode(expression, newExpression); if (convertPredicate) { var compilation = editor.SemanticModel.Compilation; var symbol = editor.SemanticModel.GetSymbolInfo(nodeToFix, cancellationToken: cancellationToken).Symbol as IMethodSymbol; if (symbol == null || symbol.TypeArguments.Length != 1) return document; var type = symbol.TypeArguments[0]; if (type != null) { var predicateType = compilation.GetBestTypeByMetadataName("System.Predicate`1")?.Construct(type); if (predicateType != null) { var predicate = ((InvocationExpressionSyntax)nodeToFix).ArgumentList.Arguments.Last().Expression; if (predicate != null) { var newObject = editor.Generator.ObjectCreationExpression(predicateType, predicate); editor.ReplaceNode(predicate, newObject); } } } } return editor.GetChangedDocument(); } private async static Task<Document> UseIndexer(Document document, SyntaxNode nodeToFix, CancellationToken cancellationToken) { var expression = GetParentMemberExpression(nodeToFix); if (expression == null) return document; var editor = await DocumentEditor.CreateAsync(document, cancellationToken).ConfigureAwait(false); var generator = editor.Generator; var semanticModel = editor.SemanticModel; if (semanticModel.GetOperation(nodeToFix, cancellationToken) is not IInvocationOperation operation) return document; var newExpression = generator.ElementAccessExpression(operation.Arguments[0].Syntax, operation.Arguments[1].Syntax); editor.ReplaceNode(nodeToFix, newExpression); return editor.GetChangedDocument(); } private async static Task<Document> UseIndexerFirst(Document document, SyntaxNode nodeToFix, CancellationToken cancellationToken) { var expression = GetParentMemberExpression(nodeToFix); if (expression == null) return document; var editor = await DocumentEditor.CreateAsync(document, cancellationToken).ConfigureAwait(false); var generator = editor.Generator; var semanticModel = editor.SemanticModel; if (semanticModel.GetOperation(nodeToFix, cancellationToken) is not IInvocationOperation operation) return document; var newExpression = generator.ElementAccessExpression(operation.Arguments[0].Syntax, generator.LiteralExpression(0)); editor.ReplaceNode(nodeToFix, newExpression); return editor.GetChangedDocument(); } private async static Task<Document> UseIndexerLast(Document document, SyntaxNode nodeToFix, CancellationToken cancellationToken) { var expression = GetParentMemberExpression(nodeToFix); if (expression == null) return document; var editor = await DocumentEditor.CreateAsync(document, cancellationToken).ConfigureAwait(false); var generator = editor.Generator; var semanticModel = editor.SemanticModel; if (semanticModel.GetOperation(nodeToFix, cancellationToken) is not IInvocationOperation operation) return document; var newExpression = generator.ElementAccessExpression(operation.Arguments[0].Syntax, generator.SubtractExpression( generator.MemberAccessExpression(operation.Arguments[0].Syntax, GetMemberName()), generator.LiteralExpression(1))); editor.ReplaceNode(nodeToFix, newExpression); return editor.GetChangedDocument(); string GetMemberName() { var type = operation.Arguments[0].Value.GetActualType(); var isArray = type != null && type.TypeKind == TypeKind.Array; if (isArray) return "Length"; return "Count"; } } private static async Task<Document> RemoveDuplicatedOrderBy(Document document, Diagnostic diagnostic, CancellationToken cancellationToken) { // a."b()".c() // a.c() var firstOperationStart = int.Parse(diagnostic.Properties["FirstOperationStart"]!, NumberStyles.Integer, CultureInfo.InvariantCulture); var firstOperationLength = int.Parse(diagnostic.Properties["FirstOperationLength"]!, NumberStyles.Integer, CultureInfo.InvariantCulture); var lastOperationStart = int.Parse(diagnostic.Properties["LastOperationStart"]!, NumberStyles.Integer, CultureInfo.InvariantCulture); var lastOperationLength = int.Parse(diagnostic.Properties["LastOperationLength"]!, NumberStyles.Integer, CultureInfo.InvariantCulture); var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); var firstNode = root?.FindNode(new TextSpan(firstOperationStart, firstOperationLength), getInnermostNodeForTie: true); var lastNode = root?.FindNode(new TextSpan(lastOperationStart, lastOperationLength), getInnermostNodeForTie: true); if (firstNode == null || lastNode == null) return document; var editor = await DocumentEditor.CreateAsync(document, cancellationToken).ConfigureAwait(false); var semanticModel = editor.SemanticModel; if (semanticModel?.GetOperation(firstNode, cancellationToken) is not IInvocationOperation firstOperation || semanticModel?.GetOperation(lastNode, cancellationToken) is not IInvocationOperation lastOperation) return document; var method = editor.Generator.MemberAccessExpression(firstOperation.Arguments[0].Syntax, lastOperation.TargetMethod.Name); var newExpression = editor.Generator.InvocationExpression(method, lastOperation.Arguments.Skip(1).Select(arg => arg.Syntax)); editor.ReplaceNode(lastOperation.Syntax, newExpression); return editor.GetChangedDocument(); } private static async Task<Document> UseThenBy(Document document, Diagnostic diagnostic, CancellationToken cancellationToken) { var lastOperationStart = int.Parse(diagnostic.Properties["LastOperationStart"]!, NumberStyles.Integer, CultureInfo.InvariantCulture); var lastOperationLength = int.Parse(diagnostic.Properties["LastOperationLength"]!, NumberStyles.Integer, CultureInfo.InvariantCulture); var expectedMethodName = diagnostic.Properties["ExpectedMethodName"]!; var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); var nodeToFix = root?.FindNode(new TextSpan(lastOperationStart, lastOperationLength), getInnermostNodeForTie: true); if (nodeToFix == null) return document; var expression = GetMemberAccessExpression(nodeToFix); if (expression == null) return document; var editor = await DocumentEditor.CreateAsync(document, cancellationToken).ConfigureAwait(false); var newExpression = expression.WithName(IdentifierName(expectedMethodName)); editor.ReplaceNode(expression, newExpression); return editor.GetChangedDocument(); } private static async Task<Document> CombineWhereWithNextMethod(Document document, Diagnostic diagnostic, CancellationToken cancellationToken) { // enumerable.Where(x=> x).C() => enumerable.C(x=> x) // enumerable.Where(x=> x).C(y=>y) => enumerable.C(y=> y && y) // enumerable.Where(Condition).C(y=>y) => enumerable.C(y=> Condition(y) && y) var firstOperationStart = int.Parse(diagnostic.Properties["FirstOperationStart"]!, NumberStyles.Integer, CultureInfo.InvariantCulture); var firstOperationLength = int.Parse(diagnostic.Properties["FirstOperationLength"]!, NumberStyles.Integer, CultureInfo.InvariantCulture); var lastOperationStart = int.Parse(diagnostic.Properties["LastOperationStart"]!, NumberStyles.Integer, CultureInfo.InvariantCulture); var lastOperationLength = int.Parse(diagnostic.Properties["LastOperationLength"]!, NumberStyles.Integer, CultureInfo.InvariantCulture); var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); var firstNode = root?.FindNode(new TextSpan(firstOperationStart, firstOperationLength), getInnermostNodeForTie: true); var lastNode = root?.FindNode(new TextSpan(lastOperationStart, lastOperationLength), getInnermostNodeForTie: true); if (firstNode == null || lastNode == null) return document; var editor = await DocumentEditor.CreateAsync(document, cancellationToken).ConfigureAwait(false); var semanticModel = editor.SemanticModel; if (semanticModel?.GetOperation(firstNode, cancellationToken) is not IInvocationOperation firstOperation || semanticModel?.GetOperation(lastNode, cancellationToken) is not IInvocationOperation lastOperation) return document; var generator = editor.Generator; var method = generator.MemberAccessExpression(firstOperation.Arguments[0].Syntax, lastOperation.TargetMethod.Name); var argument = CombineArguments(firstOperation.Arguments.ElementAtOrDefault(1), lastOperation.Arguments.ElementAtOrDefault(1)); var newExpression = argument is null ? generator.InvocationExpression(method) : generator.InvocationExpression(method, argument); editor.ReplaceNode(lastOperation.Syntax, newExpression); return editor.GetChangedDocument(); SyntaxNode? CombineArguments(IArgumentOperation? argument1, IArgumentOperation? argument2) { if (argument2 == null) return argument1?.Syntax; if (argument1 == null) return argument2?.Syntax; if (argument1.Value is not IDelegateCreationOperation value1 || argument2.Value is not IDelegateCreationOperation value2) return null; var anonymousMethod1 = value1.Target as IAnonymousFunctionOperation; var anonymousMethod2 = value2.Target as IAnonymousFunctionOperation; var newParameterName = anonymousMethod1?.Symbol.Parameters.ElementAtOrDefault(0)?.Name ?? anonymousMethod2?.Symbol.Parameters.ElementAtOrDefault(0)?.Name ?? "x"; var left = PrepareSyntaxNode(generator, value1, newParameterName); var right = PrepareSyntaxNode(generator, value2, newParameterName); return generator.ValueReturningLambdaExpression(newParameterName, generator.LogicalAndExpression(left, right)); } static SyntaxNode PrepareSyntaxNode(SyntaxGenerator generator, IDelegateCreationOperation delegateCreationOperation, string parameterName) { if (delegateCreationOperation.Target is IAnonymousFunctionOperation anonymousMethod) { return ReplaceParameter(anonymousMethod, parameterName); } if (delegateCreationOperation.Target is IMethodReferenceOperation) { return generator.InvocationExpression( delegateCreationOperation.Syntax, generator.IdentifierName("x")); } return delegateCreationOperation.Syntax; } } private static SyntaxNode ReplaceParameter(IAnonymousFunctionOperation method, string newParameterName) { var semanticModel = method.SemanticModel!; var parameterSymbol = method.Symbol.Parameters[0]; return new ParameterRewriter(semanticModel, parameterSymbol, newParameterName).Visit(method.Body.Syntax); } private static MemberAccessExpressionSyntax? GetMemberAccessExpression(SyntaxNode invocationExpressionSyntax) { if (invocationExpressionSyntax is not InvocationExpressionSyntax invocationExpression) return null; return invocationExpression.Expression as MemberAccessExpressionSyntax; } private static SyntaxNode? GetParentMemberExpression(SyntaxNode invocationExpressionSyntax) { var memberAccessExpression = GetMemberAccessExpression(invocationExpressionSyntax); if (memberAccessExpression == null) return null; return memberAccessExpression.Expression; } private sealed class ParameterRewriter : CSharpSyntaxRewriter { private readonly SemanticModel _semanticModel; private readonly IParameterSymbol _parameterSymbol; private readonly string _newParameterName; public ParameterRewriter(SemanticModel semanticModel, IParameterSymbol parameterSymbol, string newParameterName) { _semanticModel = semanticModel; _parameterSymbol = parameterSymbol; _newParameterName = newParameterName; } public override SyntaxNode? VisitIdentifierName(IdentifierNameSyntax node) { var symbol = _semanticModel.GetSymbolInfo(node).Symbol; if (symbol != null && symbol.IsEqualTo(_parameterSymbol)) { return IdentifierName(_newParameterName); } return base.VisitIdentifierName(node); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Xamarin.Forms; using App1.Views; namespace App1 { public class App { public static Page GetMainPage() { // Demo 1 //return new MainPage(); // Demo 2 //return new MainPageTwoWayBindings(); // Demo 3 return new TodoPage(); // Demo 4 //return new AnimationsPage(); } } }
using System; using System.Collections.Generic; using zoologico.Interfaces; using zoologico.Models; namespace zoologico.Models { public class Pinguim : Animais, IQuinofilo { public string ResisteAoFrio() { return this.GetType().Name+ "Consegue resistir ao frio"; } } }
// Copyright 2021 Google LLC. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using NtApiDotNet.Win32; using System; using System.Net; using System.Net.Sockets; using System.Runtime.InteropServices; using System.Text; namespace NtApiDotNet.Net.Sockets { /// <summary> /// Utilities for socket security. /// </summary> public static class SocketSecurityUtils { #region Private Members private static byte[] ToArray(this IPEndPoint ep) { var addr = ep.Serialize(); byte[] buffer = new byte[addr.Size]; for (int i = 0; i < addr.Size; ++i) { buffer[i] = addr[i]; } return buffer; } private static ulong[] ToSocketStorage(this IPEndPoint ep) { ulong[] ret = new ulong[16]; if (ep == null) return ret; byte[] buffer = ep.ToArray(); Buffer.BlockCopy(buffer, 0, ret, 0, buffer.Length); return ret; } private static NtStatus GetNtStatus(this int error, bool throw_on_error) { if (error >= 0) return NtStatus.STATUS_SUCCESS; return SocketNativeMethods.WSAGetLastError().ToNtException(throw_on_error); } private static NtResult<T> CreateWSAResult<T>(this int error, bool throw_on_error, Func<T> create_func) { if (error >= 0) return create_func().CreateResult(); return SocketNativeMethods.WSAGetLastError().CreateResultFromDosError<T>(throw_on_error); } #endregion #region Static Methods /// <summary> /// Impersonate the socket's peer. /// </summary> /// <param name="socket">The socket to impersonate.</param> /// <param name="peer_address">Optional peer address. Only needed for datagram sockets.</param> /// <param name="throw_on_error">True to throw on error.</param> /// <returns>The impersonation context.</returns> public static NtResult<ThreadImpersonationContext> Impersonate(this Socket socket, IPEndPoint peer_address, bool throw_on_error) { byte[] addr = peer_address?.ToArray(); return SocketNativeMethods.WSAImpersonateSocketPeer(socket.Handle, addr, addr?.Length ?? 0) .CreateWSAResult(throw_on_error, () => new ThreadImpersonationContext()); } /// <summary> /// Impersonate the socket's peer. /// </summary> /// <param name="socket">The socket to impersonate.</param> /// <param name="peer_address">Optional peer address. Only needed for datagram sockets.</param> /// <returns>The impersonation context.</returns> public static ThreadImpersonationContext Impersonate(this Socket socket, IPEndPoint peer_address = null) { return Impersonate(socket, peer_address, true).Result; } /// <summary> /// Impersonate the socket's peer. /// </summary> /// <param name="client">The TCP client to impersonate.</param> /// <param name="throw_on_error">True to throw on error.</param> /// <returns>The impersonation context.</returns> public static NtResult<ThreadImpersonationContext> Impersonate(this TcpClient client, bool throw_on_error) { return client.Client.Impersonate(null, throw_on_error); } /// <summary> /// Impersonate the socket's peer. /// </summary> /// <param name="client">The TCP client to impersonate.</param> /// <returns>The impersonation context.</returns> public static ThreadImpersonationContext Impersonate(this TcpClient client) { return Impersonate(client, true).Result; } /// <summary> /// Query the socket security information. /// </summary> /// <param name="socket">The socket to query.</param> /// <param name="peer_address">Optional peer address. Only needed for datagram sockets.</param> /// <param name="desired_access">Optional desired access for peer tokens. If set to None then no tokens will be returned.</param> /// <param name="throw_on_error">True to throw on error.</param> /// <returns>The socket security information.</returns> public static NtResult<SocketSecurityInformation> QuerySecurity(this Socket socket, IPEndPoint peer_address, TokenAccessRights desired_access, bool throw_on_error) { var query = new SOCKET_SECURITY_QUERY_TEMPLATE_IPSEC2 { SecurityProtocol = SOCKET_SECURITY_PROTOCOL.IPsec2, PeerAddress = peer_address.ToSocketStorage(), PeerTokenAccessMask = desired_access, FieldMask = SocketSecurityQueryFieldMask.MmSaId | SocketSecurityQueryFieldMask.QmSaId }; using (var template = query.ToBuffer()) { int length = 0; SocketNativeMethods.WSAQuerySocketSecurity(socket.Handle, template, template.Length, SafeHGlobalBuffer.Null, ref length, IntPtr.Zero, IntPtr.Zero); Win32Error error = SocketNativeMethods.WSAGetLastError(); if (error != Win32Error.WSAEMSGSIZE) return error.CreateResultFromDosError<SocketSecurityInformation>(throw_on_error); using (var buffer = new SafeStructureInOutBuffer<SOCKET_SECURITY_QUERY_INFO>(length, false)) { return SocketNativeMethods.WSAQuerySocketSecurity(socket.Handle, template, template.Length, buffer, ref length, IntPtr.Zero, IntPtr.Zero).CreateWSAResult(throw_on_error, () => new SocketSecurityInformation(buffer)); } } } /// <summary> /// Query the socket security information. /// </summary> /// <param name="socket">The socket to query.</param> /// <param name="peer_address">Optional peer address. Only needed for datagram sockets.</param> /// <param name="desired_access">Optional desired access for peer tokens. If set to None then no tokens will be returned.</param> /// <returns>The socket security information.</returns> public static SocketSecurityInformation QuerySecurity(this Socket socket, IPEndPoint peer_address = null, TokenAccessRights desired_access = TokenAccessRights.None) { return QuerySecurity(socket, peer_address, desired_access, true).Result; } /// <summary> /// Query the socket security information. /// </summary> /// <param name="client">The TCP client to query.</param> /// <param name="desired_access">Optional desired access for peer tokens. If set to None then no tokens will be returned.</param> /// <param name="throw_on_error">True to throw on error.</param> /// <returns>The socket security information.</returns> public static NtResult<SocketSecurityInformation> QuerySecurity(this TcpClient client, TokenAccessRights desired_access, bool throw_on_error) { return QuerySecurity(client.Client, null, desired_access, throw_on_error); } /// <summary> /// Query the socket security information. /// </summary> /// <param name="client">The TCP client to query.</param> /// <param name="desired_access">Optional desired access for peer tokens. If set to None then no tokens will be returned.</param> /// <returns>The socket security information.</returns> public static SocketSecurityInformation QuerySecurity(this TcpClient client, TokenAccessRights desired_access = TokenAccessRights.None) { return QuerySecurity(client, desired_access, true).Result; } /// <summary> /// Set the socket security information. /// </summary> /// <param name="socket">The socket to set.</param> /// <param name="settings">The security settings.</param> /// <param name="throw_on_error">True to throw on error.</param> /// <returns>The NT status code.</returns> public static NtStatus SetSecurity(this Socket socket, SocketSecuritySettings settings, bool throw_on_error) { using (var buffer = settings?.ToBuffer() ?? SafeHGlobalBuffer.Null) { return SocketNativeMethods.WSASetSocketSecurity(socket.Handle, buffer, buffer.Length, IntPtr.Zero, IntPtr.Zero).GetNtStatus(throw_on_error); } } /// <summary> /// Set the socket security information. /// </summary> /// <param name="socket">The socket to set.</param> /// <param name="settings">The security settings.</param> public static void SetSecurity(this Socket socket, SocketSecuritySettings settings = null) { SetSecurity(socket, settings, true); } /// <summary> /// Set the socket security information. /// </summary> /// <param name="listener">The TCP listener to set.</param> /// <param name="settings">The security settings.</param> /// <param name="throw_on_error">True to throw on error.</param> /// <returns>The NT status code.</returns> public static NtStatus SetSecurity(this TcpListener listener, SocketSecuritySettings settings, bool throw_on_error) { return SetSecurity(listener.Server, settings, throw_on_error); } /// <summary> /// Set the socket security information. /// </summary> /// <param name="listener">The TCP listener to set.</param> /// <param name="settings">The security settings.</param> public static void SetSecurity(this TcpListener listener, SocketSecuritySettings settings = null) { SetSecurity(listener, settings, true); } /// <summary> /// Set the socket security information. /// </summary> /// <param name="client">The TCP client to set.</param> /// <param name="settings">The security settings.</param> /// <param name="throw_on_error">True to throw on error.</param> /// <returns>The NT status code.</returns> public static NtStatus SetSecurity(this TcpClient client, SocketSecuritySettings settings, bool throw_on_error) { return SetSecurity(client.Client, settings, throw_on_error); } /// <summary> /// Set the socket security information. /// </summary> /// <param name="client">The TCP client to set.</param> /// <param name="settings">The security settings.</param> public static void SetSecurity(this TcpClient client, SocketSecuritySettings settings = null) { SetSecurity(client, settings, true); } /// <summary> /// Set target peer for socket. /// </summary> /// <param name="socket">The socket to set.</param> /// <param name="target_name">The target name.</param> /// <param name="peer_address">Optional peer address. Only needed for datagram sockets.</param> /// <param name="throw_on_error">True to throw on error.</param> /// <returns>The NT status code.</returns> public static NtStatus SetPeerTargetName(this Socket socket, string target_name, IPEndPoint peer_address, bool throw_on_error) { byte[] target_name_bytes = Encoding.Unicode.GetBytes(target_name); int target_name_length = target_name_bytes.Length; int total_length = Marshal.SizeOf(typeof(SOCKET_PEER_TARGET_NAME)) + target_name_bytes.Length; using (var buffer = new SOCKET_PEER_TARGET_NAME() { SecurityProtocol = SOCKET_SECURITY_PROTOCOL.IPsec2, PeerAddress = peer_address.ToSocketStorage(), PeerTargetNameStringLen = target_name_length }.ToBuffer(total_length, false)) { buffer.Data.WriteBytes(target_name_bytes); return SocketNativeMethods.WSASetSocketPeerTargetName( socket.Handle, buffer, buffer.Length, IntPtr.Zero, IntPtr.Zero).GetNtStatus(throw_on_error); } } /// <summary> /// Set target peer for socket. /// </summary> /// <param name="socket">The socket to set.</param> /// <param name="target_name">The target name.</param> /// <param name="peer_address">Optional peer address. Only needed for datagram sockets.</param> public static void SetPeerTargetName(this Socket socket, string target_name, IPEndPoint peer_address = null) { SetPeerTargetName(socket, target_name, peer_address, true); } /// <summary> /// Set target peer for socket. /// </summary> /// <param name="socket">The socket to set.</param> /// <param name="target_name">The target name.</param> /// <param name="throw_on_error">True to throw on error.</param> /// <returns>The NT status code.</returns> public static NtStatus SetPeerTargetName(this TcpClient socket, string target_name, bool throw_on_error) { return SetPeerTargetName(socket.Client, target_name, null, throw_on_error); } /// <summary> /// Set target peer for socket. /// </summary> /// <param name="socket">The socket to set.</param> /// <param name="target_name">The target name.</param> public static void SetPeerTargetName(this TcpClient socket, string target_name) { SetPeerTargetName(socket, target_name, true); } /// <summary> /// Set target peer for socket. /// </summary> /// <param name="listener">The socket to set.</param> /// <param name="target_name">The target name.</param> /// <param name="throw_on_error">True to throw on error.</param> /// <returns>The NT status code.</returns> public static NtStatus SetPeerTargetName(this TcpListener listener, string target_name, bool throw_on_error) { return SetPeerTargetName(listener.Server, target_name, null, throw_on_error); } /// <summary> /// Set target peer for socket. /// </summary> /// <param name="listener">The socket to set.</param> /// <param name="target_name">The target name.</param> public static void SetPeerTargetName(this TcpListener listener, string target_name) { SetPeerTargetName(listener, target_name, true); } /// <summary> /// Delete target peer for socket. /// </summary> /// <param name="socket">The socket to set.</param> /// <param name="peer_address">Peer address.</param> /// <param name="throw_on_error">True to throw on error.</param> /// <returns>The NT status code.</returns> public static NtStatus DeletePeerTargetName(this Socket socket, IPEndPoint peer_address, bool throw_on_error) { byte[] addr = peer_address.ToArray(); return SocketNativeMethods.WSADeleteSocketPeerTargetName( socket.Handle, addr, addr.Length, IntPtr.Zero, IntPtr.Zero).GetNtStatus(throw_on_error); } #endregion } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ConsoleApp1 { class Program { static void Main(string[] args) { string firstNum = Console.ReadLine(); string operand = Console.ReadLine(); string secondNum = Console.ReadLine(); int parsed1; int parsed2; bool check1 = int.TryParse(firstNum, out parsed1); bool check2 = int.TryParse(secondNum, out parsed2); if(!check1 || !check2){ Console.WriteLine("Error: non-integer value detected"); } else if (operand=="*") { Console.WriteLine(parsed1 * parsed2); } else if (operand == "/") { Console.WriteLine(parsed1 / parsed2); } else if (operand == "+") { Console.WriteLine(parsed1 + parsed2); } else if (operand == "-") { Console.WriteLine(parsed1 - parsed2); } else { Console.WriteLine("Error: Unsupported operand"); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Pathfinder { public static class Dice { private static Random rollDice = new Random(); public static int d4() { return rollDice.Next(1, 5); } public static int d6() { return rollDice.Next(1, 7); } public static int d8() { return rollDice.Next(1, 9); } public static int d10() { return rollDice.Next(1, 11); } public static int d12() { return rollDice.Next(1, 13); } public static int d20() { return rollDice.Next(1, 21); } } }
using System.Configuration; using MongoDB.Driver; using Braspag.Domain.Interfaces.Context; namespace Braspag.Infrastructure.Context { public class DataContext : IDataContext { private readonly MongoDatabase MongoDatabase; private MongoServer Server; public MongoDatabase Context { get { return this.MongoDatabase; } } public DataContext() { //MongoUrl url = new MongoUrl(ConfigurationManager.ConnectionStrings["conexaoMongoDB"].ConnectionString); MongoUrl url = new MongoUrl("mongodb://braspagteste:uyt9Cb5kD2Fh1Br4sPFcyXBHjGG0IiQNgLrwu9OrKTxCuNn4DUjIDtvgMO3FsJykwz9QrNywV0dfH5ItEgAnOw==@braspagteste.documents.azure.com:10255/?ssl=true&replicaSet=globaldb"); MongoClient client = new MongoClient(url); Server = client.GetServer(); this.MongoDatabase = Server.GetDatabase("Braspag"); } public void RequestStart() { //Server.RequestStart(this.MongoDatabase); } public void RequestDone() { // Server.RequestDone(); } public void Dispose() { } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Runtime.CompilerServices; using ERP_Palmeiras_RH.Core; using System.Data.Entity.Infrastructure; namespace ERP_Palmeiras_RH.Models.Facade { public partial class RecursosHumanos { public IEnumerable<Pendencia> BuscarPendencias() { return model.TblPendencias.Where<Pendencia>(b => true); } public Pendencia BuscarPendencia(int id) { return model.TblPendencias.Where<Pendencia>(b => b.Id == id).First<Pendencia>(); } public void InserirPendencia(Pendencia pendencia) { IEnumerable<Pendencia> result = model.TblPendencias.Where(b => (b.Funcionario.Id == pendencia.Funcionario.Id)); if (result == null || result.Count<Pendencia>() == 0) { model.TblPendencias.Add(pendencia); } else { throw new ERPException("Já existe uma pendência para este funcionário."); } model.SaveChanges(); } public void ExcluirPendencia(Int32 pid) { try { Pendencia pendencia = model.TblPendencias.Find(pid); model.TblPendencias.Remove(pendencia); model.SaveChanges(); } catch (DbUpdateException) { throw new ERPException("Não foi possível remover a pendência do funcionário."); } } } }
namespace Application.Stock { public class Stock { public string Symbol { get; set; } public string CompanyName { get; set; } public string PrimaryExchange { get; set; } public float OpenPrice { get; set; } public float ClosePrice { get; set; } public float PriceChange { get; set; } public int Volume { get; set; } public float YearlyHigh { get; set; } public float YearlyLow { get; set; } } }
using System.Collections.Generic; using Asset.DataAccess.Library.AssetModelGetways.AssetEntryGetways; using Asset.Models.Library.EntityModels.AssetsModels.AssetEntrys; namespace Asset.BisnessLogic.Library.AssetModelManagers.AssetEntryManagers { public class FinanceManager : IRepositoryManager<Finance> { private readonly FinanceGetway _financeGetway; public FinanceManager() { _financeGetway = new FinanceGetway(); } public Finance Get(int id) { return _financeGetway.Get(id); } public IEnumerable<Finance> GetAll() { return _financeGetway.GetAll(); } public int Add(Finance entity) { return _financeGetway.Add(entity); } public int AddRange(IEnumerable<Finance> entities) { return _financeGetway.AddRange(entities); } public int Update(Finance entity) { return _financeGetway.Update(entity); } public int Remove(Finance entity) { return _financeGetway.Remove(entity); } public int RemoveRange(IEnumerable<Finance> entities) { return _financeGetway.RemoveRange(entities); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using ProyectoASPEmenic.Clases; namespace ProyectoASPEmenic.Paginas.Personas { public partial class ActualizarJuridicos : System.Web.UI.Page { Conexion conexion = new Conexion(); Validacion validacion = new Validacion(); string query = ""; DateTime Hoy = DateTime.Today; int Resultado_servicio = 0; //bandera del contacto bool bandera_dui_c = false, bandera_nit_c = false; //bandera de la empresa bool bandera_nrc_e = false, bandera_nit_e = false; //contenidos del contacto bool contenido_c = false, contenido_dui_c = false, contenido_nit_c = false, contenido_email_c = false, contenido_telefono_c = false, contenido_celular_c = false; //contenidos de la empresa bool contenido_nrc_e = false, contenido_nit_e = false; protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { string VarAct = Request.QueryString["act"]; string query = "SELECT NombreLegal,NombreComercial,Giro,Tamano,Ubicacion,MunicipioCiudad," + "DepartamentoEstado,Pais,Telefono1,Telefono2,Telefono3,Fax,Email1,Email2,CodigoPostal,NIT," + "FechaExpedicionNIT,NombreSegunNIT,NRC,FechaExpedicionNRC,NombreSegunNRC,NombreContacto," + "DUIContacto,NITContacto,EmailContacto,TelefonoContacto,CelularContacto,Observaciones, " + "Cliente,Proveedor,Socio,Activo FROM persona WHERE IdPersona=" + VarAct; conexion.IniciarConexion(); conexion.RecibeQuery(query); while (conexion.reg.Read()) { //asignando los valores recuperados de la bdd y validando su contenido if (conexion.reg.GetValue(0) != null || conexion.reg.GetValue(0).ToString() != "") txtnombrelegal.Text = conexion.reg.GetValue(0).ToString(); else txtnombrelegal.Text = ""; if (conexion.reg.GetValue(1) != null || conexion.reg.GetValue(1).ToString() != "") txtnombrecomercial.Text = conexion.reg.GetValue(1).ToString(); else txtnombrecomercial.Text = ""; if (conexion.reg.GetValue(2) != null || conexion.reg.GetValue(2).ToString() != "") txtgiroactividadeconomica.Text = conexion.reg.GetValue(2).ToString(); else txtgiroactividadeconomica.Text = ""; ddltamanoempresa.SelectedValue = conexion.reg.GetString(3); if (conexion.reg.GetValue(4) != null || conexion.reg.GetValue(4).ToString() != "") txtdireccionubicacion.Text = conexion.reg.GetValue(4).ToString(); else txtdireccionubicacion.Text = ""; if (conexion.reg.GetValue(5) != null || conexion.reg.GetValue(5).ToString() != "") txtmunicipiociudad.Text = conexion.reg.GetValue(5).ToString(); else txtmunicipiociudad.Text = ""; if (conexion.reg.GetValue(6) != null || conexion.reg.GetValue(6).ToString() != "") txtdepartamentoestado.Text = conexion.reg.GetValue(6).ToString(); else txtdepartamentoestado.Text = ""; if (conexion.reg.GetValue(7) != null || conexion.reg.GetValue(7).ToString() != "") txtpais.Text = conexion.reg.GetValue(7).ToString(); else txtpais.Text = ""; if (conexion.reg.GetValue(8) != null || conexion.reg.GetValue(8).ToString() != "") txttelefono1.Text = conexion.reg.GetValue(8).ToString(); else txttelefono1.Text = ""; if (conexion.reg.GetValue(9) != null || conexion.reg.GetValue(9).ToString() != "") txttelefono2.Text = conexion.reg.GetValue(9).ToString(); else txttelefono2.Text = ""; if (conexion.reg.GetValue(10) != null || conexion.reg.GetValue(10).ToString() != "") txttelefono3.Text = conexion.reg.GetValue(10).ToString(); else txttelefono3.Text = ""; if (conexion.reg.GetValue(11) != null || conexion.reg.GetValue(11).ToString() != "") txtFax.Text = conexion.reg.GetValue(11).ToString(); else txtFax.Text = ""; if (conexion.reg.GetValue(12) != null || conexion.reg.GetValue(12).ToString() != "") txtcorreo1.Text = conexion.reg.GetValue(12).ToString(); else txtcorreo1.Text = ""; if (conexion.reg.GetValue(13) != null || conexion.reg.GetValue(13).ToString() != "") txtcorreo2.Text = conexion.reg.GetValue(13).ToString(); else txtcorreo2.Text = ""; if (conexion.reg.GetValue(14) != null || conexion.reg.GetValue(14).ToString() != "") txtcodigopostal.Text = conexion.reg.GetValue(14).ToString(); else txtcodigopostal.Text = ""; if (conexion.reg.GetValue(15) != null || conexion.reg.GetValue(15).ToString() != "") txtNIT.Text = conexion.reg.GetValue(15).ToString(); else txtNIT.Text = ""; if (conexion.reg.GetValue(16) != null || conexion.reg.GetValue(16).ToString() != "") { string fecha = FormatoFecha(conexion.reg.GetValue(16).ToString()); txtfechaexpedicionNIT.Text = fecha; } else txtfechaexpedicionNIT.Text = ""; if (conexion.reg.GetValue(17) != null || conexion.reg.GetValue(17).ToString() != "") txtnombreNIT.Text = conexion.reg.GetValue(17).ToString(); else txtnombreNIT.Text = ""; if (conexion.reg.GetValue(18) != null || conexion.reg.GetValue(18).ToString() != "") txtNRC.Text = conexion.reg.GetValue(18).ToString(); else txtNRC.Text = ""; if (conexion.reg.GetValue(19) != null || conexion.reg.GetValue(19).ToString() != "") { string fecha = FormatoFecha(conexion.reg.GetValue(19).ToString()); txtfechaexpedicionNRC.Text = fecha; } else txtfechaexpedicionNRC.Text = ""; if (conexion.reg.GetValue(20) != null || conexion.reg.GetValue(20).ToString() != "") txtnombreNRC.Text = conexion.reg.GetValue(20).ToString(); else txtnombreNRC.Text = ""; if (conexion.reg.GetValue(21) != null || conexion.reg.GetValue(21).ToString() != "") txtnombrecontacto.Text = conexion.reg.GetValue(21).ToString(); else txtnombrecontacto.Text = ""; if (conexion.reg.GetValue(22) != null || conexion.reg.GetValue(22).ToString() != "") txtDUIcontacto.Text = conexion.reg.GetValue(22).ToString(); else txtDUIcontacto.Text = ""; if (conexion.reg.GetValue(23) != null || conexion.reg.GetValue(23).ToString() != "") txtNITcontacto.Text = conexion.reg.GetValue(23).ToString(); else txtNITcontacto.Text = ""; if (conexion.reg.GetValue(24) != null || conexion.reg.GetValue(24).ToString() != "") txtemailcontacto.Text = conexion.reg.GetValue(24).ToString(); else txtemailcontacto.Text = ""; if (conexion.reg.GetValue(25) != null || conexion.reg.GetValue(25).ToString() != "") txttelefonocontacto.Text = conexion.reg.GetValue(25).ToString(); else txttelefonocontacto.Text = ""; if (conexion.reg.GetValue(26) != null || conexion.reg.GetValue(26).ToString() != "") txtcelularcontacto.Text = conexion.reg.GetValue(26).ToString(); else txtcelularcontacto.Text = ""; if (conexion.reg.GetValue(27) != null || conexion.reg.GetValue(27).ToString() != "") txtobservaciones.Text = conexion.reg.GetValue(27).ToString(); else txtobservaciones.Text = ""; checkCliente.Checked = conexion.reg.GetBoolean(28); checkProveedor.Checked = conexion.reg.GetBoolean(29); checkSocio.Checked = conexion.reg.GetBoolean(30); checkActivo.Checked = conexion.reg.GetBoolean(31); } conexion.CerrarConexion(); } } protected string FormatoFecha(string fecha) { DateTime nueva = DateTime.Parse(fecha); string nueva2 = nueva.ToShortDateString(); string[] words = nueva2.Split('/'); string devuelve = words[2] + "-" + words[1] + "-" + words[0]; return devuelve; } protected void btnActualizarJuridicos_Click(object sender, EventArgs e) { string VarAct = Request.QueryString["act"]; //recuperando entradas string NombreLegal = txtnombrelegal.Text; string NombreComercial = txtnombrecomercial.Text; string Giro = txtgiroactividadeconomica.Text; string Tamano = ddltamanoempresa.SelectedValue; string DireccionUbicacion = txtdireccionubicacion.Text; string MunicipioCiudad = txtmunicipiociudad.Text; string DepartamentoEstado = txtdepartamentoestado.Text; string Pais = txtpais.Text; string Telefono1 = txttelefono1.Text; string Telefono2 = txttelefono2.Text; string Telefono3 = txttelefono3.Text; string Fax = txtFax.Text; string Email1 = txtcorreo1.Text; string Email2 = txtcorreo2.Text; string CodigoPostal = txtcodigopostal.Text; string NIT = txtNIT.Text; string FechaExpedicionNIT = txtfechaexpedicionNIT.Text; string NombreSegunNIT = txtnombreNIT.Text; string NRC = txtNRC.Text; string FechaExpedicionNRC = txtfechaexpedicionNRC.Text; string NombreSegunNRC = txtnombreNRC.Text; string NombreContacto = txtnombrecontacto.Text; string DUIContacto = txtDUIcontacto.Text; string NITContacto = txtNITcontacto.Text; string EmailContacto = txtemailcontacto.Text; string TelefonoContacto = txttelefonocontacto.Text; string CelularContacto = txtcelularcontacto.Text; string Observaciones = txtobservaciones.Text; Boolean Cliente = checkCliente.Checked; Boolean Proveedor = checkProveedor.Checked; Boolean Socio = checkSocio.Checked; Boolean Activo = checkActivo.Checked; //Verificar si la persona posee o ha tenido servicios contratados de emenic if (Cliente == false) { query = "SELECT IF( EXISTS(SELECT * FROM serviciocontratado WHERE IdCliente = '" + VarAct + "'), 1, 0) as Resultado"; conexion.IniciarConexion(); conexion.RecibeQuery(query); while (conexion.reg.Read()) { Resultado_servicio = conexion.reg.GetInt32(0); } conexion.reg.Close(); conexion.CerrarConexion(); //verificar si es o no eliminado if (Resultado_servicio == 1) { //no puede ser eliminado porque tiene registros hijos ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "alertMessage", "alert('Este registro es cliente activo, tiene registros de servicios contratados, NO puede desactivar la bandera Cliente.')", true); } } if (NombreContacto.Length > 0 && NombreContacto != " ") { contenido_c = true; //verificar si hay contenidos o no en las siguientes variables if (TelefonoContacto.Length > 0 && TelefonoContacto != " ") { contenido_telefono_c = true; } if (EmailContacto.Length > 0 && EmailContacto != " ") { contenido_email_c = true; } if (CelularContacto.Length > 0 && TelefonoContacto != " ") { contenido_celular_c = true; } //verificar que haya alguna de esas variables esta en true if (contenido_telefono_c == false && contenido_email_c == false && contenido_celular_c == false) { ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "alertMessage", "alert('Ingresar Telefono, Email o Celular del la Persona de contacto.')", true); } if (DUIContacto.Length > 0 && DUIContacto != " ") { if (validacion.EsDui(DUIContacto) == false) { ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "alertMessage", "alert('Dui de Persona de contacto NO Valido')", true); } } } //verificar que la empresa registre su NIT o NRC //validando Nit if (NIT.Length > 0 && NIT != " ") { contenido_nit_e = true; //verificar si no hay personas juridicas en bdd con ese mismo nit query = "SELECT IF( EXISTS(SELECT * FROM persona WHERE NIT = '" + NIT + "' AND IdPersona != "+ VarAct +"), 1, 0) as Resultado"; conexion.IniciarConexion(); conexion.RecibeQuery(query); while (conexion.reg.Read()) { int Resultado_nit = conexion.reg.GetInt32(0); if (Resultado_nit == 1) { ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "alertMessage", "alert('Nit existente.')", true); } else { bandera_nit_e = true; } } conexion.reg.Close(); conexion.CerrarConexion(); } else { bandera_nit_e = true; } //validando NRC if (NRC.Length > 0 && NRC != " ") { contenido_nrc_e = true; //verificar si no hay personas juridicas en bdd con ese mismo nrc query = "SELECT IF( EXISTS(SELECT * FROM persona WHERE NRC = '" + NRC + "'), 1, 0) as Resultado"; conexion.IniciarConexion(); conexion.RecibeQuery(query); while (conexion.reg.Read()) { int Resultado_nrc = conexion.reg.GetInt32(0); if (Resultado_nrc == 1) { ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "alertMessage", "alert('NRC existente.')", true); } else { bandera_nrc_e = true; } } conexion.reg.Close(); conexion.CerrarConexion(); } else { bandera_nrc_e = true; } //verificar fechas de NIT y NRC if (FechaExpedicionNIT == "" || FechaExpedicionNIT == " ") { FechaExpedicionNIT = FormatoFecha(Hoy.ToShortDateString()); } if (FechaExpedicionNRC == "" || FechaExpedicionNRC == " ") { FechaExpedicionNRC = FormatoFecha(Hoy.ToShortDateString()); } //inicia el update del registro if (bandera_nit_e == true && bandera_nrc_e == true) { if (contenido_nit_e == true || contenido_nrc_e == true) { //consulta que se ingresa a la base de datos query = "UPDATE persona SET NombreLegal ='" + NombreLegal + "',NombreComercial = '" + NombreComercial + "', Giro = '" + Giro + "', Tamano = '" + Tamano + "', Ubicacion = '" + DireccionUbicacion + "', MunicipioCiudad = '" + MunicipioCiudad+ "', DepartamentoEstado = '" + DepartamentoEstado + "', Pais = '" + Pais + "', Telefono1 = '" + Telefono1 + "', Telefono2 = '" + Telefono2 + "', Telefono3 = '" + Telefono3 + "', Fax = '" + Fax +"', Email1 = '" + Email1 + "', Email2 = '" + Email2 + "', CodigoPostal = '" + CodigoPostal + "', NIT = '" + NIT + "', FechaExpedicionNIT = '" + FechaExpedicionNIT+ "', NombreSegunNIT = '" + NombreSegunNIT + "', NRC = '" + NRC + "', FechaExpedicionNRC = '" + FechaExpedicionNRC + "', NombreSegunNRC = '" + NombreSegunNRC + "', NombreContacto = '" + NombreContacto + "', DUIContacto = '" + DUIContacto + "', NITContacto = '" + NITContacto + "', EmailContacto = '" + EmailContacto + "', TelefonoContacto = '" + TelefonoContacto + "', CelularContacto = '" + CelularContacto + "', Observaciones = '" + Observaciones + "', Cliente = " + Cliente + ", Proveedor = " + Proveedor + ", Socio = " + Socio + ", Activo = " + Activo + " WHERE IdPersona like " + VarAct; //enviar consulta a Mysql conexion.IniciarConexion(); conexion.EnviarQuery(query); ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "alertMessage", "alert('Se ha actualizado con exito.')", true); conexion.CerrarConexion(); } else { ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "alertMessage", "alert('Debe haber al menos un documento de identificación de la empresa.')", true); } } else { ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "alertMessage", "alert('No se ha podido ingresar registro, verificar que los documentos de identificación son correctos.')", true); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using WarMachines.Interfaces; namespace WarMachines.Machines { class Pilot : IPilot { List<IMachine> machines; private string name; public Pilot(string n) { this.name = n; machines = new List<IMachine>(); } public string Name { get { return this.name; } } public void AddMachine(IMachine machine) { //if (machine.Pilot != null) { machine.Pilot = this; machines.Add(machine); } } public string Report() { StringBuilder str = new StringBuilder(); if (machines == null || machines.Count == 0) { str.Append(String.Format("{0} - no machines", this.name)); } else if (machines.Count == 1) { str.Append(String.Format("{0} - 1 machine\n", this.name)); } else { str.Append(String.Format("{0} - {1} machines\n", this.name, this.machines.Count)); } if (machines != null) { int cnt = 0; foreach (Machine machine in machines) { if (cnt != 0) { str.Append(String.Format("\n")); } str.Append(String.Format("- {0}\n", machine.Name)); if (machine is Tank) { str.Append(String.Format(" *Type: Tank\n")); } else if (machine is Fighter) { str.Append(String.Format(" *Type: Fighter\n")); } str.Append(String.Format(" *Health: {0}\n", machine.HealthPoints)); str.Append(String.Format(" *Attack: {0}\n", machine.AttackPoints)); str.Append(String.Format(" *Defense: {0}\n", machine.DefensePoints)); if (machine.Targets.Count == 0) { str.Append(String.Format(" *Targets: None\n")); } else { str.Append(String.Format(" *Targets: ")); for (int i = 0; i < machine.Targets.Count; i++) { str.Append(String.Format("{0}", machine.Targets[i])); if (i != machine.Targets.Count - 1) str.Append(String.Format(", ")); } str.Append(String.Format("\n")); } if (machine is Tank) { str.Append(String.Format(" *Defense: {0}", (machine as Tank).DefenseMode == true ? "ON" : "OFF")); } if (machine is Fighter) { str.Append(String.Format(" *Stealth: {0}", (machine as Fighter).StealthMode == true ? "ON" : "OFF")); } cnt++; } } return str.ToString(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Android.App; using Android.Content; using Android.OS; using Android.Runtime; using Android.Views; using Android.Widget; using SimpleCRUD.Models; using SimpleCRUD.Resources; namespace SimpleCRUD { [Activity(Label = "ViewActivity")] public class ViewActivity : Activity { ListView listData; List<Item> listSource = new List<Item>(); DataHelper.DataHelper db; private void LoadData() { listSource = db.GetAll(); ListViewAdapter _adapter = new ListViewAdapter(this, listSource); listData.Adapter = _adapter; } void _searchview_QueryTextChange(object sender, SearchView.QueryTextChangeEventArgs e) { } protected override void OnCreate(Bundle savedInstanceState) { base.OnCreate(savedInstanceState); SetContentView(Resource.Layout.View); var btnMainView = FindViewById<Button>(Resource.Id.mainviewbtn); db = new DataHelper.DataHelper(); listData = FindViewById<ListView>(Resource.Id.MainlistView); LoadData(); btnMainView.Click += (sender, e) => { var intent = new Intent(this, typeof(MainActivity)); StartActivity(intent); }; } } }
using Mis_Recetas.Controlador; using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Drawing.Printing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace Mis_Recetas.Vista { public partial class FormArchivarRecetas : Form { public FormArchivarRecetas() { InitializeComponent(); } CmdArchivarRecetas com = new CmdArchivarRecetas(); private void FormArchivarRecetas_Load(object sender, EventArgs e) { actulizarDataGrid(); DataGridViewCheckBoxColumn chek = new DataGridViewCheckBoxColumn(); chek.HeaderText = " "; chek.Name = "Seleccionar"; chek.DisplayIndex = 0; chek.ReadOnly = false; dgvRecetasArchivar.Columns.Add(chek); dgvRecetasArchivar.ColumnHeadersDefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter; dgvRecetasArchivar.Columns["Seleccionar"].Width = 25; dgvRecetasArchivar.Columns[0].Width = 50; dgvRecetasArchivar.Columns[1].Width = 150; dgvRecetasArchivar.Columns[2].Width = 120; dgvRecetasArchivar.Columns[3].Width = 150; dgvRecetasArchivar.Columns[4].Width = 70; dgvRecetasArchivar.Columns[5].Width = 150; dgvRecetasArchivar.Columns[0].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter; dgvRecetasArchivar.Columns[1].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter; dgvRecetasArchivar.Columns[2].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter; dgvRecetasArchivar.Columns[3].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter; dgvRecetasArchivar.Columns[4].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter; dgvRecetasArchivar.Columns[5].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter; dgvRecetasArchivar.Columns[0].ReadOnly = true; dgvRecetasArchivar.Columns[1].ReadOnly = true; dgvRecetasArchivar.Columns[2].ReadOnly = true; dgvRecetasArchivar.Columns[3].ReadOnly = true; dgvRecetasArchivar.Columns[4].ReadOnly = true; dgvRecetasArchivar.Columns[5].ReadOnly = true; dgvRecetasArchivar.RowHeadersVisible = false; dgvRecetasArchivar.RowsDefaultCellStyle.SelectionBackColor = System.Drawing.Color.White; dgvRecetasArchivar.RowsDefaultCellStyle.SelectionForeColor = System.Drawing.Color.Black; ActivarDesactivarCheck(false); lblCant.Text = Convert.ToString(contarItemSelect()); } private void actulizarDataGrid() { com.listarRecetasArchivar(dgvRecetasArchivar); } private void btnCancelar_Click(object sender, EventArgs e) { this.Close(); } private void ActivarDesactivarCheck(bool vBool) { foreach (DataGridViewRow row in dgvRecetasArchivar.Rows) { DataGridViewCheckBoxCell chk = (DataGridViewCheckBoxCell)row.Cells["Seleccionar"]; chk.Value = vBool; dgvRecetasArchivar.RefreshEdit(); } } private int contarItemSelect() { int cantSelect = 0; if (dgvRecetasArchivar.Rows.Count != 0) { foreach (DataGridViewRow R in dgvRecetasArchivar.Rows) { if (Convert.ToBoolean(R.Cells["Seleccionar"].Value) == true) { cantSelect += 1; } } } else cantSelect = 0; return cantSelect; } private void pictureBox1_MouseEnter(object sender, EventArgs e) { Cursor = Cursors.Hand; } private void pictureBox1_MouseLeave(object sender, EventArgs e) { Cursor = Cursors.Default; } private void pictureBox1_Click(object sender, EventArgs e) { ActivarDesactivarCheck(true); } private void pictureBox2_MouseEnter(object sender, EventArgs e) { Cursor = Cursors.Hand; } private void pictureBox2_MouseLeave(object sender, EventArgs e) { Cursor = Cursors.Default; } private void pictureBox2_Click(object sender, EventArgs e) { ActivarDesactivarCheck(false); } private void btnArchivar_Click(object sender, EventArgs e) { List<int> idRecetasList = new List<int>(); DialogResult dialogResult = DialogResult.No; foreach (DataGridViewRow R in dgvRecetasArchivar.Rows) { if (Convert.ToBoolean(R.Cells["Seleccionar"].Value) == true) { idRecetasList.Add(Convert.ToInt32(R.Cells["N° Receta"].Value)); } } int[] idRecetasArray = idRecetasList.ToArray(); if (idRecetasArray.Length > 0) { dialogResult = MessageBox.Show("¿Guardar cambios?", "", MessageBoxButtons.YesNo, MessageBoxIcon.Question); } else { MessageBox.Show("Debe seleccionar al menos una receta ", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } if (dialogResult == DialogResult.Yes) { com.archivarRecetas(idRecetasArray); if (idRecetasArray.Length > 1) //Si la cantidad de recetas seleccionadas es mayor a 1 { MessageBox.Show("Se han archivado " + idRecetasArray.Length + " recetas", " ", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); actulizarDataGrid(); lblCant.Text = Convert.ToString(contarItemSelect()); } else if (idRecetasArray.Length == 1) { MessageBox.Show("Se ha archivado " + idRecetasArray.Length + " receta", " ", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); actulizarDataGrid(); lblCant.Text = Convert.ToString(contarItemSelect()); } } lblCant.Text = Convert.ToString(contarItemSelect()); } private void dgvRecetasArchivar_CellContentClick(object sender, DataGridViewCellEventArgs e) { dgvRecetasArchivar.CommitEdit(DataGridViewDataErrorContexts.Commit); } private void dgvRecetasArchivar_CellValueChanged(object sender, DataGridViewCellEventArgs e) { if (dgvRecetasArchivar.DataSource != null) { lblCant.Text = Convert.ToString(contarItemSelect()); } } private void btnImprimir_Click(object sender, EventArgs e) { PrintDocument doc = new PrintDocument(); doc.DefaultPageSettings.Landscape = false; doc.PrinterSettings.PrinterName = "Microsoft Print to PDF"; PrintPreviewDialog ppd = new PrintPreviewDialog { Document = doc }; ((Form)ppd).WindowState = FormWindowState.Maximized; doc.PrintPage += delegate (object ev, PrintPageEventArgs ep) { const int DGV_ALTO = 40; Font fontTitulo = new Font("Segoe UI", 16, FontStyle.Bold); Font fontSubTitulo = new Font("Segoe UI", 14, FontStyle.Regular); Font fontHeader = new Font("Segoe UI", 12, FontStyle.Bold); Font fontBody = new Font("Segoe UI", 12, FontStyle.Regular); String titulo = "Enviar recetas al archivo"; String subTitulo = "Imprime la lista de recetas llevadas al archivo"; int left = ep.MarginBounds.Left - 50, top = ep.MarginBounds.Top + 50; ep.Graphics.DrawImage(Properties.Resources.Logo_50_x_15, ep.MarginBounds.Right - 150, 40); //ep.Graphics.DrawImage(Properties.Resources.Logo_CDF_Blanco, ep.MarginBounds.Right - 150, 40); ep.Graphics.DrawString(titulo, fontTitulo, Brushes.DeepSkyBlue, left + 100, 60); ep.Graphics.DrawString(subTitulo, fontSubTitulo, Brushes.Black, left + 50, 50 + DGV_ALTO); foreach (DataGridViewColumn col in dgvRecetasArchivar.Columns) { if (col.Index > 1) { ep.Graphics.DrawString(col.HeaderText, fontHeader, Brushes.DeepSkyBlue, left, top + 10); left += col.Width; if (col.Index < dgvRecetasArchivar.ColumnCount - 1) ep.Graphics.DrawLine(Pens.Gray, left - 5, top, left - 5, top + 43 + (dgvRecetasArchivar.RowCount) * DGV_ALTO); } } left = ep.MarginBounds.Left - 50; ep.Graphics.FillRectangle(Brushes.Black, left, top + 40, ep.MarginBounds.Right - left, 3); top += 43; foreach (DataGridViewRow row in dgvRecetasArchivar.Rows) { // if (row.Index == dgvRecetas.RowCount - 1) break; if (dgvRecetasArchivar.RowCount == 0) break; left = ep.MarginBounds.Left - 50; foreach (DataGridViewCell cell in row.Cells) { //cell.ColumnIndex > 1 if (cell.ColumnIndex > 1) { ep.Graphics.DrawString(Convert.ToString(cell.Value), fontBody, Brushes.Black, new RectangleF(left, top + 6, cell.OwningColumn.Width - 4, cell.OwningRow.Height - 2)); left += cell.OwningColumn.Width; } } top += DGV_ALTO; ep.Graphics.DrawLine(Pens.Gray, ep.MarginBounds.Left - 50, top, ep.MarginBounds.Right, top); } }; ppd.ShowDialog(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using DataObject; using Service.Interface; using DataAccessLayer; namespace Service.Implements { public class PhongHocService:IPhongHoc { public int ThemPhong(PhongHoc P) { return 1; } public int CapNhatThongTinPhong(PhongHoc P) { return 1; } public int CapNhatTrangThaiPhong(int MaPhong) { return 1; } public int NhapDuLieuTuFile(string FileName) { return 1; } public int XoaPhong(int MaPhong) { return 1; } public int CapNhatNgaySuaChuaPhong(int Ngay) { return 1; } } }
namespace Triton.Game.Mapping { using ns26; using System; using Triton.Game.Mono; [Attribute38("ChatMgrPrefabs")] public class ChatMgrPrefabs : MonoClass { public ChatMgrPrefabs(IntPtr address) : this(address, "ChatMgrPrefabs") { } public ChatMgrPrefabs(IntPtr address, string className) : base(address, className) { } public ChatBubbleFrame m_ChatBubbleOneLineFrame { get { return base.method_3<ChatBubbleFrame>("m_ChatBubbleOneLineFrame"); } } public ChatBubbleFrame m_ChatBubbleSmallFrame { get { return base.method_3<ChatBubbleFrame>("m_ChatBubbleSmallFrame"); } } public FriendListFrame m_friendListFramePrefab { get { return base.method_3<FriendListFrame>("m_friendListFramePrefab"); } } } }
public void MoveZeroes(int[] nums) { int length = nums.Length; for (int i = 0; i < length; i++) { for (int j = i; j < length; j++) { if (nums[i] == 0) { //=C8=E7=B9=FB=B5=C8=D3=DA0=A3=AC=D4=F2=B8=FA=BA=F3=C3=E6=B5=C4=D4=AA=CB=D8=BD=BB=BB=BB int temp = nums[i]; nums[i] = nums[j]; nums[j] = temp; } } } }
namespace KPI.Model.Migrations { using System; using System.Data.Entity.Migrations; public partial class vertion13 : DbMigration { public override void Up() { AddColumn("dbo.NotificationDetails", "Action", c => c.String()); DropColumn("dbo.Uploader", "KPILevelID"); DropColumn("dbo.Manager", "KPILevelID"); DropColumn("dbo.Owner", "KPILevelID"); } public override void Down() { DropColumn("dbo.NotificationDetails", "Action"); } } }
 namespace PICSimulator.Model.Events { public class ExternalClockChangedEvent : PICEvent { public uint ClockID; public bool Enabled; public uint Frequency; public uint Register; public uint Bit; public override string ToString() { return @"ExternalClockChangedEvent ..."; } } }
using UnityEngine; [RequireComponent(typeof(CharacterController))] public class FPSrot : MonoBehaviour { CharacterController characterController; public float speed; public float jumpSpeed; public float gravity; private Vector3 moveDirection = Vector3.zero; //public AudioSource audioSource; // public FloatData RotX, RotY, RotZ; private Vector3 rotDirection; // private CharacterController controller; void Start() { controller = GetComponent<CharacterController>(); } void Update() { if (controller.isGrounded) { moveDirection = new Vector3(Input.GetAxis("Horizontal"), 0, 0); moveDirection = transform.TransformDirection(moveDirection); moveDirection = moveDirection * speed; if (Input.GetButton("Jump")) { moveDirection.y = jumpSpeed; } } else { // Left/Right movement in mid air allowed moveDirection.x = Input.GetAxis("Horizontal") * speed; } moveDirection.y -= gravity * Time.deltaTime; controller.Move(moveDirection * Time.deltaTime); } protected void MoveTran(Transform transform) { rotDirection.Set(RotX.Value, RotY.Value, RotZ.Value); } }
using System; using System.Collections.Generic; using System.Linq; using Pubquiz.Domain.ViewModels; using Pubquiz.Persistence; // ReSharper disable CollectionNeverUpdated.Global // ReSharper disable UnusedAutoPropertyAccessor.Global // ReSharper disable AutoPropertyCanBeMadeGetOnly.Global // ReSharper disable MemberCanBePrivate.Global namespace Pubquiz.Domain.Models { /// <summary> /// A planned instance of a game that uses a certain quiz. /// Changes in time throughout the game, e.g. has state. /// </summary> public class Game : Model { public string Title { get; set; } public GameState State { get; set; } public Guid QuizId { get; set; } public List<Guid> TeamIds { get; set; } public List<Guid> QuizMasterIds { get; set; } public string InviteCode { get; set; } public Question CurrentQuestion { get; set; } public int CurrentQuestionIndex { get; set; } public Guid CurrentQuestionId { get; set; } public int CurrentQuizSectionIndex { get; set; } public Guid CurrentQuizSectionId { get; set; } public Game() { Id = Guid.NewGuid(); State = GameState.Closed; QuizId = Guid.Empty; TeamIds = new List<Guid>(); } public void SetState(GameState newGameState) { switch (newGameState) { case GameState.Closed: if (State != GameState.Open) { throw new DomainException(ErrorCodes.InvalidGameStateTransition, "Can only close the game from the open state.", true); } break; case GameState.Open: if (State != GameState.Closed) { throw new DomainException(ErrorCodes.InvalidGameStateTransition, "Can only open the game from the closed state.", true); } if (State == GameState.Closed && (QuizId == Guid.Empty || string.IsNullOrWhiteSpace(Title))) { throw new DomainException(ErrorCodes.InvalidGameStateTransition, "Can't open the game without a quiz and/or a title.", true); } break; case GameState.Running: if (State != GameState.Open && State != GameState.Paused) { throw new DomainException(ErrorCodes.InvalidGameStateTransition, "Can only start the game from the open and paused states.", true); } if (!TeamIds.Any()) { throw new DomainException(ErrorCodes.InvalidGameStateTransition, "Can't start the game without teams.", true); } break; case GameState.Paused: if (State != GameState.Running) { throw new DomainException(ErrorCodes.InvalidGameStateTransition, "Can only pause the game from the running state.", true); } break; case GameState.Finished: if (State != GameState.Running && State != GameState.Paused) { throw new DomainException(ErrorCodes.InvalidGameStateTransition, "Can only finish the game from the running and paused states.", true); } break; default: throw new ArgumentOutOfRangeException(nameof(newGameState), newGameState, null); } State = newGameState; } public GameViewModel ToViewModel() { return new GameViewModel { GameId = Id, State = State, GameTitle = Title }; } } public enum GameState { Closed, Open, // e.g. open for registration Running, // InSession? Started? Paused, Finished // Ended? } }
using System; using System.Collections.Generic; using System.Text; using Xunit; using Arrays; namespace MyXUnitTests { public class TicTacToesTest { [Fact] public static void TestRun_Row() { string description = "XXX OO. ..."; TicTacToes.Mark[,] vMark = TicTacToes.CreateFromString(description); TicTacToes.GameResult vExpected = TicTacToes.GameResult.CrossWin; TicTacToes.GameResult vActual = TicTacToes.GetGameResult(vMark); Assert.Equal(vExpected, vActual); } [Fact] public static void TestRun_Draw() { string[] ds = { "XXX OOO ..." }; TicTacToes.GameResult[] vExpecteds = { TicTacToes.GameResult.Draw }; for (int i = 0; i < ds.Length; i++) { TicTacToes.Mark[,] vMark = TicTacToes.CreateFromString(ds[i]); TicTacToes.GameResult vActual = TicTacToes.GetGameResult(vMark); Assert.Equal(vExpecteds[i], vActual); } } [Fact] public static void TestRun_Diagonal() { string[] ds = { "OXO XOX OX." }; TicTacToes.GameResult[] vExpecteds = { TicTacToes.GameResult.CircleWin, }; for (int i = 0; i < ds.Length; i++) { TicTacToes.Mark[,] vMark = TicTacToes.CreateFromString(ds[i]); TicTacToes.GameResult vActual = TicTacToes.GetGameResult(vMark); Assert.True(vExpecteds[i] == vActual, i.ToString()); } } [Fact] public static void TestRun_All() { string[] ds = { "XXX OO. ...", "OXO XO. .XO", "OXO XOX OX.", "XOX OXO OXO", "... ... ...", "XXX OOO ...", "XOO XOO XX.", ".O. XO. XOX" }; TicTacToes.GameResult[] vExpecteds = { TicTacToes.GameResult.CrossWin, TicTacToes.GameResult.CircleWin, TicTacToes.GameResult.CircleWin, TicTacToes.GameResult.Draw, TicTacToes.GameResult.Draw, TicTacToes.GameResult.Draw, TicTacToes.GameResult.CrossWin, TicTacToes.GameResult.CircleWin }; for (int i = 0; i < ds.Length; i++) { TicTacToes.Mark[,] vMark = TicTacToes.CreateFromString(ds[i]); TicTacToes.GameResult vActual = TicTacToes.GetGameResult(vMark); Assert.True(vExpecteds[i] == vActual, i.ToString()); } } } }
using System.Collections.Generic; using System.Linq; using items; using peasants; using peasants.workers; using UnityEngine; namespace buildings { public class Mine : WorkBuilding { public int oreCapacity = 10000; public float energyPerPoint = 100f; public float oreMined = 0; public int maxDropOrePoints = 5; public string oreType = ItemType.COAL; public List<Miner> workers; public int Mining(float energy) { oreMined += energy/energyPerPoint; if (oreMined >= maxDropOrePoints) { oreMined -= maxDropOrePoints; oreCapacity -= maxDropOrePoints; return maxDropOrePoints; } return 0; } //-----------------OVERRIDE--------------------- public override int WorkersCount { get { return workers.Count; } } public override void WorkerArrived(Peasant p) { var w = p.gameObject.GetComponent<Miner>() ?? p.gameObject.AddComponent<Miner>(); w.workplace = this; if (!workers.Contains(w)) workers.Add(w); } public override void WorkerLeft(Peasant p) { var worker = workers.First(w => w.Peasant == p); workers.Remove(worker); Destroy(worker); } public override void ReleaseWorkers() { foreach (var w in workers) { w.Peasant.workplace = null; w.Peasant.GoHome(); Destroy(w); } workers = new List<Miner>(); } //----------------\OVERRIDE--------------------- } }
using System; using System.Collections.Generic; //using System.Linq; //using System.Text; using Buffers.Lists; using Buffers.Memory; using Buffers.Utilities; namespace Buffers.Managers { class LIRS_ByWu : BufferManagerBase { private long lirSize; private long hirSize; private long lirNum; private LinkedList<lirFrame> lirList = new LinkedList<lirFrame>(); private IDictionary<uint, LinkedListNode<lirFrame>> lirMap = new Dictionary<uint, LinkedListNode<lirFrame>>(); private LinkedList<lirFrame> hirList = new LinkedList<lirFrame>(); private IDictionary<uint, LinkedListNode<lirFrame>> hirMap = new Dictionary<uint, LinkedListNode<lirFrame>>(); public LIRS_ByWu(uint npages, float hirPercent) : this(null, npages, hirPercent) { } public LIRS_ByWu(IBlockDevice dev, uint npages, float hirPercent) : base(dev, npages) { hirSize = Math.Max((int)(npages * hirPercent),1); lirSize = npages - hirSize; lirNum = 0; } public override string Name { get { return "LIRS"; } } public override string Description { get { return Utils.FormatDesc("lirPages", lirSize, "hirPages", hirSize); } } protected override void OnPoolFull() { lirFrame frame = hirList.Last.Value; hirList.RemoveLast(); hirMap.Remove(frame.Id); WriteIfDirty(frame); pool.FreeSlot(frame.DataSlotId); // Console.WriteLine("evict frame:" + frame.ToString()); frame.DataSlotId = -1; LinkedListNode<lirFrame> node; if (lirMap.TryGetValue(frame.Id, out node)) { if (node.Value.Resident) { throw new Exception("in lirs-bywu, line 50, this frame should be nonresident!"); } } } protected override void DoAccess(uint pageid, byte[] resultOrData, AccessType type) { // Console.WriteLine("\n\nafter\t" + pageid + "\t" + (type == AccessType.Read ? "Read" : "Write")); LinkedListNode<lirFrame> node; LinkedListNode<lirFrame> hirNode; lirFrame frame; //in LIR-list if (lirMap.TryGetValue(pageid, out node)) { frame = node.Value; //LIRS frame if (!frame.IsHir) { lirList.Remove(node); lirMap.Remove(pageid); PerformAccess(frame, resultOrData, type); lirList.AddFirst(frame); lirMap[pageid] = lirList.First; sprunning(); } //HIRS resident frame else if (frame.Resident) { if (hirMap.TryGetValue(pageid, out hirNode)) { lirList.Remove(node); lirMap.Remove(pageid); hirList.Remove(hirNode); hirMap.Remove(pageid); PerformAccess(frame, resultOrData, type); frame.IsHir = false; lirList.AddFirst(frame); lirMap[pageid] = lirList.First; frame = lirList.Last.Value; if (frame.IsHir) { throw new Exception("in Lirs_ByWu,line 94, this frame should be lirs!"); } frame.IsHir = true; lirList.RemoveLast(); lirMap.Remove(frame.Id); sprunning(); hirList.AddFirst(frame); hirMap[frame.Id] = hirList.First; } else { throw new Exception("in lirs_ByWu, line 106, this frame should be in hirList!"); } } //HIRS nonresident frame else { if (hirMap.TryGetValue(pageid, out hirNode)) { throw new Exception("in lirs_bywu, line 116, this frame should not be in hirList!"); } lirList.Remove(node); lirMap.Remove(pageid); PerformAccess(frame, resultOrData, type); frame.IsHir = false; lirList.AddFirst(frame); lirMap[pageid] = lirList.First; frame = lirList.Last.Value; if (frame.IsHir) { throw new Exception("in lirs_bywu, this frame should be LIRS"); } frame.IsHir = true; lirList.RemoveLast(); lirMap.Remove(frame.Id); sprunning(); hirList.AddFirst(frame); hirMap[frame.Id] = hirList.First; } } //HIRS resident and not in LIRS-list else if (hirMap.TryGetValue(pageid, out node)) { frame = node.Value; hirList.Remove(node); hirMap.Remove(pageid); PerformAccess(frame, resultOrData, type); lirList.AddFirst(frame); lirMap[pageid] = lirList.First; hirList.AddFirst(frame); hirMap[pageid] = hirList.First; } //frame which appears at the first time else { frame = new lirFrame(pageid); if (lirNum < lirSize) { frame.IsHir = false; lirNum++; } else { frame.IsHir = true; } PerformAccess(frame, resultOrData, type); lirList.AddFirst(frame); lirMap[pageid] = lirList.First; if (frame.IsHir) { hirList.AddFirst(frame); hirMap[pageid] = hirList.First; } } /* Console.WriteLine("LIRS list is"); foreach (var item in lirList) { Console.WriteLine(item.ToString()); } Console.WriteLine("HIRS list is"); foreach (var item in hirList) { Console.WriteLine(item.ToString()); }*/ } protected override void DoFlush() { foreach (var item in lirList) { WriteIfDirty(item); } foreach (var item in hirList) { WriteIfDirty(item); } } private void sprunning() { lirFrame frame = lirList.Last.Value; // Console.Write("\n"); while (frame.IsHir) { // Console.WriteLine("spunning:" + frame.ToString()); lirMap.Remove(frame.Id); lirList.RemoveLast(); frame = lirList.Last.Value; } } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; using UnityEngine.SceneManagement; public class StartGame : MonoBehaviour { public Button StartButton; // Start is called before the first frame update void Start() { StartButton.onClick.AddListener(TaskOnClick); } void TaskOnClick() { var scenesNumber = SceneManager.sceneCount; for (int i = 0; i < scenesNumber; i++) { Debug.Log(SceneManager.GetSceneAt(i).name); //Chiude tutte le scene aperte ed apre la scena all'indice 1 della lista di build delle scene. //La lista può essere trovata in File>Build Settings SceneManager.LoadScene(1, LoadSceneMode.Single); } } }
using System; using System.Collections.Generic; using System.Configuration; using System.Data; using System.Linq; using System.Threading.Tasks; using System.Windows; using WpfAppAbit2.ViewModels; using WpfAppAbit2.Views; namespace WpfAppAbit2 { /// <summary> /// Логика взаимодействия для App.xaml /// </summary> /// public partial class App : Application { public DisplayRootRegistry displayRootRegistry = new DisplayRootRegistry(); public App() { new MainViewModel(new MainView()); displayRootRegistry.RegisterWindowType<AbitAddViewModel, AbitAddView>(); } } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; namespace Opbot.Utils { public class Cmd { public class CommandResult { public int ExitCode { get; set; } public string Output { get; set; } public string Error { get; set; } } /// <summary> /// http://stackoverflow.com/questions/206323/how-to-execute-command-line-in-c-get-std-out-results /// </summary> /// <param name="filename"></param> /// <param name="arguments"></param> /// <returns></returns> public static CommandResult Run(string filename, string arguments = null, int timeoutInMs = 30000) { var process = new Process(); process.StartInfo.FileName = filename; if (!string.IsNullOrEmpty(arguments)) { process.StartInfo.Arguments = arguments; } process.StartInfo.CreateNoWindow = true; process.StartInfo.WindowStyle = ProcessWindowStyle.Hidden; process.StartInfo.UseShellExecute = false; process.StartInfo.RedirectStandardError = true; process.StartInfo.RedirectStandardOutput = true; var stdOutput = new StringBuilder(); var stdError = new StringBuilder(); process.OutputDataReceived += (sender, args) => stdOutput.AppendLine(args.Data); process.ErrorDataReceived += (sender, args) => stdError.AppendLine(args.Data); try { process.Start(); process.BeginOutputReadLine(); process.BeginErrorReadLine(); if (!process.WaitForExit(timeoutInMs)) process.Kill(); } catch (Exception e) { throw new Exception("OS error while executing " + Format(filename, arguments) + ": " + e.Message, e); } return new CommandResult() { ExitCode = process.ExitCode, Output = stdOutput.ToString(), Error=stdError.ToString() }; //if (process.ExitCode == 0) //{ // return new CommandResult() { ExitCode = process.ExitCode, Output = stdOutput.ToString() }; //} //else //{ //var message = new StringBuilder(); //if (!string.IsNullOrEmpty(stdError)) //{ // message.AppendLine(stdError); //} //if (stdOutput.Length != 0) //{ // message.AppendLine("Std output:"); // message.AppendLine(stdOutput.ToString()); //} //throw new Exception(Format(filename, arguments) + " finished with exit code = " + process.ExitCode + ": " + message); //} } private static string Format(string filename, string arguments) { return "'" + filename + ((string.IsNullOrEmpty(arguments)) ? string.Empty : " " + arguments) + "'"; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace WebStock_Net.Controllers { public class CadastroController : Controller { // GET: Cadastro public ActionResult Cli() { return View(); } public ActionResult Products() { return View(); } public ActionResult MarcaProd() { return View(); } public ActionResult Med() { return View(); } public ActionResult Forn() { return View(); } public ActionResult Cat() { return View(); } public ActionResult Scat() { return View(); } public ActionResult Cit() { return View(); } public ActionResult St() { return View(); } public ActionResult Count() { return View(); } public ActionResult Prof() { return View(); } public ActionResult Users() { return View(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace N2.Configuration { public enum SearchIndexType { Database, Lucene } }
using System; using System.Collections.Generic; using System.Windows.Forms; using Grimoire.Botting.Commands.Map; using Grimoire.Game; namespace Grimoire.UI.BotForms { public partial class MapTab : Form { public static MapTab Instance { get; } = new MapTab(); private readonly Dictionary<string, string> _defaultText = new Dictionary<string, string> { {nameof(txtJoin), "battleon-1e99"}, {nameof(txtJoinCell), "Enter"}, {nameof(txtJoinPad), "Spawn"}, {nameof(txtCell), "Cell"}, {nameof(txtPad), "Pad"} }; private MapTab() { InitializeComponent(); TopLevel = false; } private void btnJoin_Click(object sender, EventArgs e) { string map = txtJoin.Text, cell = string.IsNullOrEmpty(txtJoinCell.Text) ? "Enter" : txtJoinCell.Text, pad = string.IsNullOrEmpty(txtJoinPad.Text) ? "Spawn" : txtJoinPad.Text; if (map.Length > 0) BotManagerForm.Instance.AddCommand(new CmdJoin { Map = map, Cell = cell, Pad = pad }); } private void btnCellSwap_Click(object sender, EventArgs e) { txtJoinCell.Text = txtCell.Text; txtJoinPad.Text = txtPad.Text; } private void btnCurrCell_Click(object sender, EventArgs e) { txtCell.Text = Player.Cell; txtPad.Text = Player.Pad; } private void btnJump_Click(object sender, EventArgs e) { string cell = string.IsNullOrEmpty(txtCell.Text) ? "Enter" : txtCell.Text, pad = string.IsNullOrEmpty(txtPad.Text) ? "Spawn" : txtPad.Text; BotManagerForm.Instance.AddCommand(new CmdMoveToCell { Cell = cell, Pad = pad }); } private void btnWalk_Click(object sender, EventArgs e) { string x = numWalkX.Value.ToString(), y = numWalkY.Value.ToString(); BotManagerForm.Instance.AddCommand(new CmdWalk { X = x, Y = y }); } private void btnWalkCur_Click(object sender, EventArgs e) { float[] pos = Player.Position; numWalkX.Value = (decimal)pos[0]; numWalkY.Value = (decimal)pos[1]; } private void TextboxEnter(object sender, EventArgs e) { TextBox t = (TextBox)sender; if (_defaultText[t.Name] == t.Text) t.Clear(); } private void TextboxLeave(object sender, EventArgs e) { TextBox t = (TextBox)sender; if (string.IsNullOrEmpty(t.Text)) t.Text = _defaultText[t.Name]; } } }
using UnityEngine; using UnityEngine.UI; using System.Collections; public class PhotographyDisplayManager : IDisplayManager { public const string NAME_PHOTO_A = "tPhotoA"; public const string NAME_PHOTO_B = "tPhotoB"; public Texture[] photos; public RawImage photoContainer; public Texture transitionTexture; public float switchTime = 3f; public float mixRatioModifier = 0.5f; public RawImage auxPhoto; private string _lastUsedPhoto; private int _currentPictureIndex = 0; private float _lastSwitch; private bool _switchedPhoto; private bool _timeSwitchingEnabled; private bool _initialized = false; public override void InitializeDisplay (int displayId) { _initialized = false; _displayId = displayId; photos = Preloader.instance.GetPhotos (Preloader.instance.GetRunningDisplay()); _currentPictureIndex = 0; cycleTime = photos.Length * switchTime; _timeSwitchingEnabled = true; _switchedPhoto = false; photoContainer.material.SetFloat("mixRatio", 1f); mixRatioModifier = Mathf.Abs(mixRatioModifier); CalculateMixRatio(); if (!auxPhoto.gameObject.activeSelf) { SetTransitionPicture(NAME_PHOTO_A); SetNextPicture(NAME_PHOTO_B); } else { photoContainer.material.SetTexture(NAME_PHOTO_A, photos[_currentPictureIndex]); SetNextPicture(NAME_PHOTO_B); } _lastSwitch = Time.time - switchTime; _initialized = true; } public void Update() { if (!_initialized) return; if (_timeSwitchingEnabled) { float mixRatio = photoContainer.material.GetFloat ("mixRatio"); if ((mixRatio == 1f || mixRatio == 0f)) { if (!_switchedPhoto) { Destroy(auxPhoto.texture); auxPhoto.gameObject.SetActive(false); if (_lastUsedPhoto == NAME_PHOTO_A) { SetNextPicture (NAME_PHOTO_B); } else { SetNextPicture (NAME_PHOTO_A); } } if (Time.time - _lastSwitch > switchTime) { _lastSwitch = Time.time; mixRatioModifier *= -1; CalculateMixRatio(); _switchedPhoto = false; } } else { CalculateMixRatio(); } } else { CalculateMixRatio(); _displayOutFinished = photoContainer.material.GetFloat ("mixRatio") == 1 || photoContainer.material.GetFloat ("mixRatio") == 0; } } private void CalculateMixRatio() { float mixRatio = photoContainer.material.GetFloat ("mixRatio"); mixRatio = Mathf.Clamp(mixRatio + (mixRatioModifier * Time.deltaTime), 0f, 1f); photoContainer.material.SetFloat ("mixRatio", mixRatio); } public override void DisplayOut () { base.DisplayOut (); _displayOutFinished = false; auxPhoto.texture = photos[_currentPictureIndex]; _currentPictureIndex = --_currentPictureIndex < 0 ? photos.Length - 1 : _currentPictureIndex; _timeSwitchingEnabled = false; _switchedPhoto = false; if (_lastUsedPhoto == NAME_PHOTO_A) { SetTransitionPicture (NAME_PHOTO_A); } else { SetTransitionPicture (NAME_PHOTO_B); } mixRatioModifier *= -1; } public override void FinalizeDisplay () { foreach (Texture2D texture in photos) { if (texture != auxPhoto.texture) { Destroy(texture); } } System.GC.Collect(); _initialized = false; } private void SetNextPicture(string container) { photoContainer.material.SetTexture (container, photos[_currentPictureIndex]); _lastUsedPhoto = container; _currentPictureIndex = ++_currentPictureIndex == photos.Length ? 0 : _currentPictureIndex; _switchedPhoto = true; } private void SetTransitionPicture(string container) { photoContainer.material.SetTexture (container, transitionTexture); } public void SetAuxPhoto() { auxPhoto.gameObject.SetActive(true); } }
using Assets.blackwhite_side_scroller.Scripts; using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.Events; public class SteepGroundEndTrigger : GameTrigger { public UnityEvent OnPlayerEnter; // Start is called before the first frame update protected override void Start() { base.Start(); if (OnPlayerEnter == null) OnPlayerEnter = new UnityEvent(); } private void OnTriggerEnter2D(Collider2D collision) { if (collision.gameObject.tag == Constants.TagPlayer) { OnPlayerEnter.Invoke(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace LinkedList { class ListNode<T> { public T Data { get; set; } public ListNode<T> Next { get; set; } } }
// Konner Marak 113423502 using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace SalesTotal_Konner_Marak { class Program { static void Main(string[] args) { const double taxRate = 0.085; Console.WriteLine("What is the name of the product you are purchasing?"); string product = Console.ReadLine(); Console.WriteLine("How many " + product + " do you want to buy?"); int productAmount = Convert.ToInt16(Console.ReadLine()); Console.WriteLine("What is the price for each " + product + "?"); double price = Convert.ToDouble(Console.ReadLine()); double subTotal = price * productAmount; double salesTax = price * productAmount * taxRate; double total = subTotal + salesTax; string subTotalAsstring = subTotal.ToString("C2"); string salesTaxAsstring = salesTax.ToString("C2"); string totalAsstring = total.ToString("C2"); Console.WriteLine("Your subtotal for your bill is " + subTotalAsstring); Console.WriteLine("Your sales tax for your bill is " + salesTaxAsstring); Console.WriteLine("Your total for your bill is " +totalAsstring ); Console.ReadKey(); } } }
using SharpILMixins.Annotations; namespace SharpILMixins.Processor.Workspace.Processor.Actions { public interface IBaseMixinActionProcessor { public MixinWorkspace Workspace { get; set; } void ProcessAction(MixinAction action, BaseMixinAttribute attribute); } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace apiInovaPP.Models { public class Empresa { public int id { get; set; } public string nome { get; set; } public string cnpj { get; set; } public string endereco { get; set; } public string bairro { get; set; } public string cep { get; set; } public int cidadeId { get; set; } public string complemento { get; set; } public string telefone1 { get; set; } public string telefone2 { get; set; } public DateTime DataCad { get; set; } public int usuarioId { get; set; } public Empresa(string Nome, DateTime DataCad, int Id, string Cnpj, string Endereco, string Bairro, string Cep, int CidadeId, string Complemento, string Telefone1, string Telefone2, int UsuarioId) { this.id = Id; this.nome = Nome; this.cnpj = Cnpj; this.endereco = Endereco; this.bairro = Bairro; this.cep = Cep; this.cidadeId = CidadeId; this.complemento = Complemento; this.telefone1 = Telefone1; this.telefone2 = Telefone2; this.DataCad = DataCad; this.usuarioId = UsuarioId; } public Empresa() { } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using KarzPlus.Business; using KarzPlus.Controls; using Telerik.Web.UI; using KarzPlus.Base; namespace KarzPlus.Admin { public partial class ManageLocation : BasePage { protected void Page_Load(object sender, EventArgs e) { } protected void grdLocation_NeedDataSource(object sender, GridNeedDataSourceEventArgs e) { if (!e.IsFromDetailTable) { grdLocation.DataSource = LocationManager.LoadAll().ToList(); } } protected void grdLocation_ItemDataBound(object sender, GridItemEventArgs e) { if (e.Item is GridEditableItem && e.Item.IsInEditMode) { GridEditableItem item = e.Item as GridEditableItem; LocationConfiguration userControl = item.FindControl(GridEditFormItem.EditFormUserControlID) as LocationConfiguration; if (userControl != null) { if (!(item is GridEditFormInsertItem)) { int locationId = (int)item.GetDataKeyValue("LocationId"); userControl.LocationId = locationId; userControl.EditOption = true; } userControl.ReloadControl(); } } } protected void grdLocation_UpdateCommand(object sender, GridCommandEventArgs e) { if (e.Item is GridEditableItem && e.Item.IsInEditMode) { GridEditableItem item = e.Item as GridEditableItem; LocationConfiguration userControl = item.FindControl(GridEditFormItem.EditFormUserControlID) as LocationConfiguration; if (userControl != null) { e.Canceled = !userControl.SaveControl(); } } } protected void grdLocation_DeleteCommand(object sender, GridCommandEventArgs e) { GridDataItem item = (e.Item as GridDataItem); int locationId = (int)item.GetDataKeyValue("LocationId"); lblmessage.Text = string.Empty; if (InventoryManager.IsValidToRemove(locationId)) { LocationManager.Delete(locationId); } else { lblmessage.Text = "There is active inventory items. Please remove inventory before removing Location."; } } protected void grdInventory_UpdateCommand(object sender, GridCommandEventArgs e) { if (e.Item is GridEditableItem && e.Item.IsInEditMode) { GridEditableItem item = e.Item as GridEditableItem; KarzPlus.Controls.InventoryConfiguration userControl = item.FindControl(GridEditFormItem.EditFormUserControlID) as KarzPlus.Controls.InventoryConfiguration; if (userControl != null) { userControl.SaveControl(); } } } protected void grdInventory_DeleteCommand(object sender, GridCommandEventArgs e) { GridDataItem item = (e.Item as GridDataItem); int id = (int)item.GetDataKeyValue("InventoryId"); InventoryManager.Delete(id); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Threading; namespace _07.UseTimer { class MainProg { static void Main() { int ticks = 10; int interval = 2000;// milliseconds TimerDelegate timerElapsed = new TimerDelegate(ShowTicksLeft); Timer timer = new Timer(ticks, interval, timerElapsed); Console.WriteLine("Timer started for {0} ticks, a tick occurring once every {1} second(s).", ticks, interval / 1000); Thread timerThread = new Thread(new ThreadStart(timer.Run)); timerThread.Start(); } static void ShowTicksLeft(int ticksLeft) { Console.WriteLine("Timer interval has elapsed. Ticks left: {0}.", ticksLeft); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using Telerik.Web.Mvc; using Proyek_Informatika.Models; using System.IO; using System.Text; using System.Web.Script.Serialization; namespace Proyek_Informatika.Controllers.Koordinator { public class NilaiController : Controller { // // GET: /Nilai/ SkripsiAutoContainer db = new SkripsiAutoContainer(); public ActionResult Index() { return PartialView(); } public ActionResult Report() { return PartialView(); } public ActionResult NilaiReport() { return PartialView(); } public ActionResult IndexMahasiswa() { EnumSemesterSkripsiContainer semes = new EnumSemesterSkripsiContainer(); var result = from jn in db.jenis_skripsi select (new { id = jn.id, nama_jenis = jn.nama_jenis }); List<jenis_skripsi> temp = new List<jenis_skripsi>(); foreach (var x in result) { temp.Add(new jenis_skripsi { id = x.id, nama_jenis = x.nama_jenis }); } semes.jenis_skripsi = temp; List<semester> temp2 = new List<semester>(); var result2 = from si in db.semesters select (new { id = si.id, nama = si.periode_semester, curr = si.isCurrent }); foreach (var x in result2) { temp2.Add(new semester { id = x.id, periode_semester = x.nama, isCurrent = x.curr }); if (x.curr == 1) { semes.selected_value = x.id; } } semes.jenis_semester = temp2; return PartialView(semes); } [HttpPost] public ActionResult ListMahasiswa(int periode=0, int jenis_skripsi=0) { ViewBag.periode = periode; ViewBag.jenis_skripsi = jenis_skripsi; return PartialView(); } [GridAction] public ActionResult SelectNilai(int periode, int jenis_skripsi) { return bindingNilai(periode, jenis_skripsi); } protected ViewResult bindingNilai(int periode, int jenis_skripsi) { var result = from si in db.nilais where si.skripsi.jenis == jenis_skripsi && si.skripsi.id_semester_pengambilan == periode && si.kategori_nilai.kategori == "nilaiAkhir" select new KoordinatorNilaiMahasiswa() { id = si.skripsi.id, judul = si.skripsi.topik.judul, namaDosen = si.skripsi.dosen.nama, namaMahasiswa = si.skripsi.mahasiswa.nama, nikDosen = si.skripsi.dosen.NIK, npmMahasiswa = si.skripsi.mahasiswa.NPM, periode = si.skripsi.semester.periode_semester, pengambilanke = si.skripsi.pengambilan_ke, tipe = si.skripsi.jenis_skripsi.nama_jenis, nilai = si.angka }; List<KoordinatorNilaiMahasiswa> temp = result.ToList(); foreach (var x in temp) { x.status = getStatusNilai(x.id); } return View(new GridModel<KoordinatorNilaiMahasiswa> { Data = temp }); } public ActionResult DetailNilai(int id=0) { skripsi result = db.skripsis.Where(x => x.id == id).Single<skripsi>(); if (result.jenis == 1) { return NilaiSkripsi1(id); } else { return NilaiSkripsi2(id); } } public ActionResult NilaiSkripsi1(int id=0) { var result = db.skripsis.Where(x => x.id == id).Single(); ViewBag.id = id; ViewBag.NPM = result.NPM_mahasiswa; ViewBag.nama = result.mahasiswa.nama; ViewBag.judul = result.topik.judul; ViewBag.pembimbing = result.dosen.nama; var resultNilai = db.nilais.Where(x => x.id_skripsi == id && x.kategori_nilai.tipe == "general").OrderBy(x => x.kategori_nilai.urutan); List<Tuple<string, int, int, double>> listNilai = new List<Tuple<string, int, int, double>>(); foreach (var item in resultNilai) { listNilai.Add(new Tuple<string, int, int, double>(item.kategori_nilai.kategori, item.kategori, item.kategori_nilai.bobot, item.angka)); } ViewData["nilai"] = listNilai; var resultTotal = db.nilais.Where(x => x.id_skripsi == id && x.kategori_nilai.kategori == "nilaiAkhir").Single(); ViewBag.total = resultTotal.angka; return PartialView(); } [HttpPost] public ActionResult NilaiSkripsi2(int id) { ViewBag.id = id; return PartialView(); } public ActionResult TabSkripsi2(int id) { ViewBag.id = id; return PartialView(); } public int ChangeStatus(int id, byte status) { var result = db.nilais.Where(x => x.id_skripsi == id); foreach (var item in result) { item.submitted = status; if (item.kategori_nilai.tipe == "final" && status == 2) { changeSkripsiTable(item.id_skripsi, item.angka); } } try { db.SaveChanges(); return 1; } catch { return 0; } } public int ChangeAllStatus(int periode, int jenis, byte status) { var result = db.nilais.Where(x => x.skripsi.id_semester_pengambilan == periode && x.skripsi.jenis == jenis); foreach (var item in result) { item.submitted = status; if (item.kategori_nilai.tipe == "final" && status == 2) { changeSkripsiTable(item.id_skripsi, item.angka); } } try { db.SaveChanges(); return 1; } catch { return 0; } } public int ChangeAllSubmitedStatus(int periode, int jenis, byte status) { var result = db.nilais.Where(x => x.skripsi.id_semester_pengambilan == periode && x.skripsi.jenis == jenis && x.submitted == 1); foreach (var item in result) { item.submitted = status; if (item.kategori_nilai.tipe == "final" && status == 2) { changeSkripsiTable(item.id_skripsi, item.angka); } } try { db.SaveChanges(); return 1; } catch { return 0; } } private int changeSkripsiTable(int id, double angka) { var result = db.skripsis.Where(x => x.id == id).Single(); if (angka > 80) { result.nilai_akhir = "A"; } else if( angka > 70) { result.nilai_akhir = "B"; } else if (angka > 60) { result.nilai_akhir = "C"; } else { result.nilai_akhir = "E"; } try { db.SaveChanges(); return 1; } catch { return 0; } } private string getStatusNilai(int id) { byte countNilai = db.nilais.Where(x => x.id_skripsi == id && x.kategori_nilai.kategori.Equals( "nilaiAkhir")).SingleOrDefault().submitted; if (countNilai== 0) { return "Not Submitted"; } else if (countNilai == 1) { return "Submited"; } else { return "Finalized"; } } private string getNik(int id) { string nik = db.skripsis.Where(x => x.id == id).Single().NIK_dosen_pembimbing; return nik; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Text.RegularExpressions; using GalaSoft.MvvmLight; using Grisaia.Json; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using TriggersTools.SharpUtils.Collections; namespace Grisaia.Categories { /// <summary> /// A list of settings defining how character infos should display their name. /// </summary> public sealed class CharacterNamingScheme : ObservableObject { #region Constants /// <summary> /// The regex used to identify tokens to replace with a special name. /// </summary> private static readonly Regex TokenRegex = new Regex(@"\$(?:(?'other'\w+):)?(?'token'\w+)\$"); #endregion #region Fields /// <summary> /// True if all naming rules should be ignored and the Id should be used instead. /// </summary> [JsonIgnore] private bool onlyId = false; /// <summary> /// True if the Id is appended to the end of the name when <see cref="IdOnly"/> is false. /// </summary> [JsonIgnore] private bool appendId = false; /// <summary> /// How a character's first and last name are displayed. /// </summary> [JsonIgnore] private CharacterRealNameType realName = CharacterRealNameType.FirstLast; /// <summary> /// The order used to determine which character naming method goes first. /// </summary> [JsonIgnore] private CharacterNamingOrder order = new CharacterNamingOrder(); #endregion #region Properties /// <summary> /// Gets or sets if all naming rules should be ignored and the Id should be used instead. /// </summary> [JsonProperty("id_only")] public bool IdOnly { get => onlyId; set => Set(ref onlyId, value); } /// <summary> /// Gets or sets if the Id is appended to the end of the name when <see cref="IdOnly"/> is false. /// </summary> [JsonProperty("append_id")] public bool AppendId { get => appendId; set => Set(ref appendId, value); } /// <summary> /// Gets how a character's first and last name are displayed. /// </summary> [JsonProperty("real_name")] public CharacterRealNameType RealName { get => realName; set { if (!Enum.IsDefined(typeof(CharacterRealNameType), value)) throw new ArgumentException($"{nameof(CharacterRealNameType)} {value} is undefined!", nameof(RealName)); Set(ref realName, value); } } /// <summary> /// Gets the order used to determine which character naming method goes first. /// </summary> [JsonProperty("order")] public CharacterNamingOrder Order { get => order; set { if (value == null) throw new ArgumentNullException(nameof(Order)); Set(ref order, value); } } #endregion #region GetName /// <summary> /// Formats the name of the specified character info using the naming scheme settings. /// </summary> /// <param name="character">The character with the name to format.</param> /// <returns>The character's name with the naming scheme applied.</returns> /// /// <exception cref="ArgumentNullException"> /// <paramref name="character"/> is null. /// </exception> /// <exception cref="InvalidOperationException"> /// A name token is invalid or a token character does not have a name for the specified token. /// </exception> public string GetName(CharacterInfo character) { if (character == null) throw new ArgumentNullException(nameof(character)); if (IdOnly) return character.Id; StringBuilder str = new StringBuilder(); foreach (CharacterNameType type in Order) { switch (type) { case CharacterNameType.RealName: str.Append(GetRealFullName(character)); break; case CharacterNameType.Nickname: str.Append(character.Nickname); break; case CharacterNameType.Title: str.Append(character.Title); break; } if (str.Length != 0) break; // We've found a naming method with an existing name to use. } if (str.Length != 0) { if (character.Label != null) str.Append($" ({character.Label})"); // Apply tokens here: MatchCollection matches = TokenRegex.Matches(str.ToString()); foreach (Match match in matches.Cast<Match>().Reverse()) { string other = match.Groups["other"].Value; string token = match.Groups["token"].Value; CharacterInfo tokenCharacter; switch (other) { case "": tokenCharacter = character; break; case "PARENT": tokenCharacter = character.Parent ?? throw new InvalidOperationException($"Character \"{character.Id}\" does not have parent!"); break; case "RELATION": tokenCharacter = character.Relation ?? throw new InvalidOperationException($"Character \"{character.Id}\" does not have relation!"); break; default: throw new InvalidOperationException($"Unknown other character token \"{match.Value}\"!"); } string newValue = GetTokenName(tokenCharacter, token); str.Remove(match.Index, match.Length); str.Insert(match.Index, newValue); } // Append the Id if requested. if (AppendId) str.Append($" \"{character.Id}\""); return str.ToString(); } // Last resort, we should not have to end up here. return character.Id; } /// <summary> /// Formats the full name of the specified character info using the naming scheme settings. /// </summary> /// <param name="character">The character with the name to format.</param> /// <returns> /// The character's full name with the first/last naming scheme applied.<para/> /// Returns null if the character does not have a first or last name. /// </returns> /// /// <exception cref="ArgumentNullException"> /// <paramref name="character"/> is null. /// </exception> public string GetRealFullName(CharacterInfo character) { if (character == null) throw new ArgumentNullException(nameof(character)); if (character.FirstName == null) { if (character.LastName == null) return null; return character.LastName; } else if (character.LastName == null) { return character.FirstName; } switch (RealName) { case CharacterRealNameType.First: return character.FirstName; case CharacterRealNameType.FirstLast: return $"{character.FirstName} {character.LastName}"; case CharacterRealNameType.LastFirst: return $"{character.LastName} {character.FirstName}"; default: throw new ArgumentException($"Invalid {nameof(RealName)}!"); } } /// <summary> /// Formats the single name of the specified character info using the naming scheme settings. /// </summary> /// <param name="character">The character with the name to format.</param> /// <returns> /// The character's single name with the first/last naming scheme applied.<para/> /// Returns null if the character does not have a first or last name. /// </returns> /// /// <exception cref="ArgumentNullException"> /// <paramref name="character"/> is null. /// </exception> public string GetRealName(CharacterInfo character) { if (character == null) throw new ArgumentNullException(nameof(character)); if (character.FirstName == null) { if (character.LastName == null) return null; return character.LastName; } else if (character.LastName == null) { return character.FirstName; } switch (RealName) { case CharacterRealNameType.First: case CharacterRealNameType.FirstLast: return character.FirstName; case CharacterRealNameType.LastFirst: return character.LastName; default: throw new ArgumentException($"Invalid {nameof(RealName)}!"); } } /// <summary> /// Gets the token name for a specific character. /// </summary> /// <param name="c">The character to get the name of.</param> /// <param name="token">The token for the type of name to get.</param> /// <returns>The character's name based on the token.</returns> /// /// <exception cref="InvalidOperationException"> /// <paramref name="token"/> is invalid or <paramref name="c"/> does not have a name for the specified token. /// </exception> private string GetTokenName(CharacterInfo c, string token) { string value; switch (token) { case "NAME": case "FULLNAME": value = (token == "NAME" ? GetRealName(c) : GetRealFullName(c)); if (value == null) throw new InvalidOperationException($"Character \"{c.Id}\" does not have a first or last name!"); break; case "NICK": value = c.Nickname; if (value == null) throw new InvalidOperationException($"Character \"{c.Id}\" does not have a nickname!"); break; case "TITLE": value = c.Title; if (value == null) throw new InvalidOperationException($"Character \"{c.Id}\" does not have a title!"); break; default: throw new InvalidOperationException($"Unknown token type \"${token}$\"!"); } return value; } #endregion #region Clone /// <summary> /// Creates a deep clone of this character naming scheme. /// </summary> /// <returns>The clone of this character naming scheme.</returns> public CharacterNamingScheme Clone() { return new CharacterNamingScheme { IdOnly = IdOnly, AppendId = AppendId, RealName = RealName, Order = Order.Clone(), }; } #endregion } /// <summary> /// An enumeration deciding how character's first and last names are displayed. /// </summary> [JsonConverter(typeof(JsonStringEnumConverter))] public enum CharacterRealNameType { /// <summary>Only the character's first name will be displayed.</summary> [JsonProperty("first")] [Name("First")] First, /// <summary>The character's first then last name will be displayed.</summary> [JsonProperty("first_last")] [Name("First Last")] FirstLast, /// <summary>The character's last then first name will be displayed.</summary> [JsonProperty("last_first")] [Name("Last First")] LastFirst, } /// <summary> /// An enum used in <see cref="CharacterNamingOrder"/> to determine what type of naming method goes first. /// </summary> [JsonConverter(typeof(JsonStringEnumConverter))] public enum CharacterNameType { /// <summary>Character's real name.</summary> [JsonProperty("real_name")] [Name("Real Name")] RealName, /// <summary>Character's nickname.</summary> [JsonProperty("nickname")] [Name("Nickname")] Nickname, /// <summary>Character's title.</summary> [JsonProperty("title")] [Name("Title")] Title, } /// <summary> /// The order used to determine which character naming method goes first. /// </summary> [JsonConverter(typeof(JsonCharacterNamingOrderConverter))] public sealed class CharacterNamingOrder : ObservableArray<CharacterNameType> { #region Converters private class JsonCharacterNamingOrderConverter : JsonConverter { public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { JToken token = JToken.Load(reader); if (token.Type == JTokenType.Array) { return new CharacterNamingOrder(token.ToObject<CharacterNameType[]>()); } throw new InvalidOperationException("Value must be an array!"); } public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { CharacterNamingOrder order = (CharacterNamingOrder) value; value = order.ToArray(); serializer.Serialize(writer, value); } public override bool CanConvert(Type objectType) => (objectType == typeof(CharacterNamingOrder)); public override bool CanWrite => true; } #endregion #region Constructors /// <summary> /// Constructs the character naming order using the default order of Nickname, FirstLast, then Title. /// </summary> public CharacterNamingOrder() : base(new[] { // Default order CharacterNameType.Nickname, CharacterNameType.RealName, CharacterNameType.Title, }) { } /// <summary> /// Constructs the character naming order using an existing order. /// </summary> /// <param name="order">The existing order to copy.</param> internal CharacterNamingOrder(IReadOnlyList<CharacterNameType> order) : base(order) { // Make sure someone didn't fudge the config file HashSet<CharacterNameType> used = new HashSet<CharacterNameType>(); foreach (CharacterNameType type in order) { if (!used.Add(type)) throw new ArgumentException($"Character name type \"{type}\" is already contained in array!"); } } #endregion #region Mutators public void Swap(CharacterNameType typeA, CharacterNameType typeB) { if (!Enum.IsDefined(typeof(CharacterNameType), typeA)) throw new ArgumentException($"{nameof(CharacterNameType)} {typeA} is invalid!", nameof(typeA)); if (!Enum.IsDefined(typeof(CharacterNameType), typeB)) throw new ArgumentException($"{nameof(CharacterNameType)} {typeB} is invalid!", nameof(typeB)); Swap(IndexOf(typeA), IndexOf(typeB)); } public void MoveUp(CharacterNameType type) { if (!Enum.IsDefined(typeof(CharacterNameType), type)) throw new ArgumentException($"{nameof(CharacterNameType)} {type} is invalid!", nameof(type)); MoveUp(IndexOf(type)); } public void MoveDown(CharacterNameType type) { if (!Enum.IsDefined(typeof(CharacterNameType), type)) throw new ArgumentException($"{nameof(CharacterNameType)} {type} is invalid!", nameof(type)); MoveDown(IndexOf(type)); } public void Swap(int indexA, int indexB) { if (indexA < 0 || indexA >= Count) throw new ArgumentOutOfRangeException(nameof(indexA)); if (indexB < 0 || indexB >= Count) throw new ArgumentOutOfRangeException(nameof(indexB)); if (indexA == indexB) return; // Do nothing CharacterNameType orderSwap = this[indexA]; this[indexA] = this[indexB]; this[indexB] = orderSwap; } public void MoveUp(int index) { if (index < 0 || index >= Count) throw new ArgumentOutOfRangeException(nameof(index)); if (index == 0) return; // Do nothing Swap(index, index - 1); } public void MoveDown(int index) { if (index < 0 || index >= Count) throw new ArgumentOutOfRangeException(nameof(index)); if (index + 1 >= Count) return; // Do nothing Swap(index, index + 1); } #endregion #region Accessors /*public int IndexOf(CharacterNameType type) { if (!Enum.IsDefined(typeof(CharacterNameType), type)) throw new ArgumentException($"{nameof(CharacterNameType)} {type} is undefined!", nameof(type)); return ((IEnumerable<CharacterNameType>) this).IndexOf(type); }*/ #endregion #region Clone /// <summary> /// Creates a deep clone of this character naming order. /// </summary> /// <returns>The clone of this character naming order.</returns> public CharacterNamingOrder Clone() => new CharacterNamingOrder(this); #endregion /*#region IReadOnlyList Implementation /// <summary> /// Gets the character naming type at the specified index in the order. /// </summary> /// <param name="index">The index of the character naming type.</param> /// <returns>The character naming type at the specified index.</returns> /// /// <exception cref="IndexOutOfRangeException"> /// <paramref name="index"/> is outside the bounds of the order. /// </exception> public CharacterNameType this[int index] => order[index]; /// <summary> /// Gets the number of naming types in the order. /// </summary> public int Count => order.Count; /// <summary> /// Gets the enumerator for the character naming types. /// </summary> /// <returns>The order's character naming type enumerator.</returns> public IEnumerator<CharacterNameType> GetEnumerator() => order.GetEnumerator(); IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); #endregion*/ } /*/// <summary> /// The settings for how a character's first and last name should be displayed. /// </summary> public sealed class FirstLastNamingScheme { #region Fields /// <summary> /// Gets or sets if the last name should be displayed only. /// </summary> [JsonProperty("last_name_first")] public bool LastNameFirst { get; set; } = false; /// <summary> /// Gets or sets if the name after the first listed name should not be displayed. /// </summary> [JsonProperty("no_second_name")] public bool NoSecondName { get; set; } = false; #endregion #region Clone /// <summary> /// Creates a deep clone of this character naming scheme. /// </summary> /// <returns>The clone of this character naming scheme.</returns> public FirstLastNamingScheme Clone() { return new FirstLastNamingScheme { LastNameFirst = LastNameFirst, NoSecondName = NoSecondName, }; } #endregion #region GetName /// <summary> /// Formats the full name of the specified character info using the naming scheme settings. /// </summary> /// <param name="character">The character with the name to format.</param> /// <returns> /// The character's full name with the first/last naming scheme applied.<para/> /// Returns null if the character does not have a first or last name. /// </returns> /// /// <exception cref="ArgumentNullException"> /// <paramref name="character"/> is null. /// </exception> public string GetFullName(CharacterInfo character) { if (character == null) throw new ArgumentNullException(nameof(character)); if (character.FirstName == null) { if (character.LastName == null) return null; return character.LastName; } else if (character.LastName == null) { return character.FirstName; } else if (LastNameFirst) { if (NoSecondName) return character.LastName; return $"{character.LastName} {character.FirstName}"; } else { if (NoSecondName) return character.FirstName; return $"{character.FirstName} {character.LastName}"; } } /// <summary> /// Formats the single name of the specified character info using the naming scheme settings. /// </summary> /// <param name="character">The character with the name to format.</param> /// <returns> /// The character's single name with the first/last naming scheme applied.<para/> /// Returns null if the character does not have a first or last name. /// </returns> /// /// <exception cref="ArgumentNullException"> /// <paramref name="character"/> is null. /// </exception> public string GetName(CharacterInfo character) { if (character == null) throw new ArgumentNullException(nameof(character)); if (character.FirstName == null) { if (character.LastName == null) return null; return character.LastName; } else if (character.LastName == null) { return character.FirstName; } else if (LastNameFirst) { return character.LastName; } else { return character.FirstName; } } #endregion }*/ }
using Microsoft.EntityFrameworkCore; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using MyMedicine.Models.Post; namespace MyMedicine.Context.Medicine { public partial class MedicineContext { public IEnumerable<Separation> GetAllVisitations() => Separations .Include(x => x.DoctorList) .ThenInclude(x => x.VisitationList) .AsEnumerable(); public async Task<List<Separation>> GetSeparationsListAsync() => await Separations.ToListAsync(); public async Task<List<Doctor>> GetDoctorsListAsync(int separationId) => await ( from s in Separations join d in Doctors on s.SeparationId equals d.SeparationId where s.SeparationId == separationId select d ).ToListAsync(); public async Task<List<Visitation>> GetVisitorsListAsync(int doctorId) => await ( from d in Doctors join v in Visitations on d.DoctorId equals v.DoctorId where d.DoctorId == doctorId select v ).ToListAsync(); /// <summary> /// </summary> /// <param name="posts"></param> /// <param name="type">0 - add new, 1 - edit, 2 - skip</param> /// <returns></returns> public async ValueTask<bool> ImportSeparationListAsync(List<Separation> separations, int type) { List<Separation> contextSeparations = null; if (type != 0) contextSeparations = await GetSeparationsByIds(separations); switch (type) { case 0: // TODO: AddNewSeparationsRange(separations); break; case 1: // TODO: AddOrEditSeparationsRange(separations, contextSeparations); break; case 2: // TODO: AddOrSkipExistensSeparationsRange(separations, contextSeparations); break; default: break; } await SaveChangesAsync(); return true; } // TODO private void AddNewSeparationsRange(List<Separation> separations) { separations = separations .Where(sep => !String.IsNullOrEmpty(sep.Address)) .Select(sep => { sep.SeparationId = 0; sep.DoctorList = sep.DoctorList .Where(doc => !String.IsNullOrEmpty(doc.FirstName) && !String.IsNullOrEmpty(doc.SecondName) ) .Select(doc => { doc.SeparationId = 0; doc.DoctorId = 0; doc.VisitationList = doc.VisitationList .Where(vis => !DateTime.Equals(vis.Date, DateTime.MinValue)) .Select(vis => { vis.DoctorId = 0; vis.VisitationId = 0; return vis; }) .ToList(); return doc; }) .ToList(); return sep; }) .ToList(); // check on ref to client/user/children from Visitation Separations.AddRange(separations.AsEnumerable()); } // TODO private void AddOrEditSeparationsRange(ICollection<Separation> separations, ICollection<Separation> contextSeparations) { void AddOrEditDoctorsRange() { } void AddOrEditVisitorsRange() { } foreach (var separation in separations) { if (String.IsNullOrEmpty(separation.Address)) continue; var item = contextSeparations.FirstOrDefault(x => x.SeparationId == separation.SeparationId); if (item != null) { item.Address = separation.Address; // TODO } else { var newSeparation = new Separation() { Address = separation.Address, DoctorList = new List<Doctor>() }; } } } // TODO private void AddOrSkipExistensSeparationsRange(ICollection<Separation> separations, ICollection<Separation> contextSeparations) { foreach (var separation in separations) if (!contextSeparations.Contains(separation)) { separation.SeparationId = 0; Separations.Add(separation); } } private async Task<List<Separation>> GetSeparationsByIds(ICollection<Separation> separations) { var separationsIds = Separations .Select(x => x.SeparationId) .ToList(); return await Separations .Where(x => separationsIds.Contains(x.SeparationId)) .ToListAsync(); } private async Task<List<Doctor>> GetDoctorsByIds(ICollection<Doctor> doctors) { var doctorsIds = Doctors .Select(x => x.DoctorId) .AsEnumerable(); return await Doctors .Where(x => doctorsIds.Contains(x.DoctorId)) .ToListAsync(); } public async ValueTask<bool> AddNewSeparationAsync(Separation separation) { try { Separations.Add(new Separation() { Address = separation.Address }); await SaveChangesAsync(); } catch { return false; } return true; } public async ValueTask<bool> AddNewDoctorAsync(int separationId, Doctor doctor) { try { var sep = await Separations .Where(s => s.SeparationId == separationId) .FirstOrDefaultAsync(); if (sep == null) { return false; } sep.DoctorList.Add(doctor); await SaveChangesAsync(); } catch { return false; } return true; } public async ValueTask<bool> AddNewVisitorAsync(int doctorId, Visitation visitor) { try { var doc = await Doctors .Where(d => d.DoctorId == doctorId) .FirstOrDefaultAsync(); if (doc == null) { return false; } doc.VisitationList.Add(visitor); await SaveChangesAsync(); } catch { return false; } return true; } } }
using Xamarin.Forms; namespace SampleTracker.Assets.Styles { public static class CollectionViewStyle { public static TCollectionView VerticalListStyle<TCollectionView>(this TCollectionView collection) where TCollectionView : CollectionView { collection.ItemsLayout = new LinearItemsLayout(ItemsLayoutOrientation.Vertical) { ItemSpacing = 5, }; collection.ItemsUpdatingScrollMode = ItemsUpdatingScrollMode.KeepLastItemInView; return collection; } } }
// Copyright 2021 Google LLC. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using NtApiDotNet.Utilities.Memory; using System; namespace NtApiDotNet.Net.Firewall { /// <summary> /// Base security association class. /// </summary> public class IPsecSecurityAssociationParameter { /// <summary> /// Index of the security parameter (SPI). /// </summary> public uint Index { get; } /// <summary> /// Transform type. /// </summary> public IPsecTransformType TransformType { get; } private protected IPsecSecurityAssociationParameter(IPSEC_SA0 sa) { Index = sa.spi; TransformType = sa.saTransformType; } internal static IPsecSecurityAssociationParameter Create(IPSEC_SA0 sa) { switch (sa.saTransformType) { case IPsecTransformType.AH: case IPsecTransformType.EspAuth: case IPsecTransformType.EspAuthFw: return new IPsecSecurityAssociationAuthInformation(sa); case IPsecTransformType.EspCipher: return new IPsecSecurityAssociationCipherInformation(sa); case IPsecTransformType.EspAuthAndCipher: return new IPsecSecurityAssociationAuthCipherInformation(sa); } return new IPsecSecurityAssociationParameter(sa); } } /// <summary> /// IPsec SA authentication information. /// </summary> public sealed class IPsecSecurityAssociationAuthInformation : IPsecSecurityAssociationParameter { /// <summary> /// Type of authentication. /// </summary> public IPsecAuthType Type { get; } /// <summary> /// Authentication configuration. /// </summary> public IPsecAuthConfig Config { get; } /// <summary> /// Module ID for the crypto. /// </summary> public Guid? CryptoModuleId { get; } /// <summary> /// Authentication key. /// </summary> public byte[] Key { get; } internal IPsecSecurityAssociationAuthInformation(IPSEC_SA0 sa) : base(sa) { var auth_info = sa.ptr.ReadStruct<IPSEC_SA_AUTH_INFORMATION0>(); Key = auth_info.authKey.ToArray(); CryptoModuleId = auth_info.authTransform.cryptoModuleId.ReadGuid(); Type = auth_info.authTransform.authTransformId.authType; Config = auth_info.authTransform.authTransformId.authConfig; } } /// <summary> /// IPsec SA authentication information. /// </summary> public sealed class IPsecSecurityAssociationCipherInformation : IPsecSecurityAssociationParameter { /// <summary> /// Type of cipher. /// </summary> public IPsecCipherType Type { get; } /// <summary> /// Cipher configuration. /// </summary> public IPsecCipherConfig Config { get; } /// <summary> /// Module ID for the crypto. /// </summary> public Guid? CryptoModuleId { get; } /// <summary> /// Cipher key. /// </summary> public byte[] Key { get; } internal IPsecSecurityAssociationCipherInformation(IPSEC_SA0 sa) : base(sa) { var cipher_info = sa.ptr.ReadStruct<IPSEC_SA_CIPHER_INFORMATION0>(); Key = cipher_info.cipherKey.ToArray(); CryptoModuleId = cipher_info.cipherTransform.cryptoModuleId.ReadGuid(); Type = cipher_info.cipherTransform.cipherTransformId.cipherType; Config = cipher_info.cipherTransform.cipherTransformId.cipherConfig; } } /// <summary> /// IPsec SA authentication information. /// </summary> public sealed class IPsecSecurityAssociationAuthCipherInformation : IPsecSecurityAssociationParameter { /// <summary> /// Type of authentication. /// </summary> public IPsecAuthType AuthType { get; } /// <summary> /// Authentication configuration. /// </summary> public IPsecAuthConfig AuthConfig { get; } /// <summary> /// Modify ID for the crypto. /// </summary> public Guid? AuthCryptoModuleId { get; } /// <summary> /// Authentication key. /// </summary> public byte[] AuthKey { get; } /// <summary> /// Type of cipher. /// </summary> public IPsecCipherType CipherType { get; } /// <summary> /// Cipher configuration. /// </summary> public IPsecCipherConfig CipherConfig { get; } /// <summary> /// Module ID for the crypto. /// </summary> public Guid? CipherCryptoModuleId { get; } /// <summary> /// Cipher key. /// </summary> public byte[] CipherKey { get; } internal IPsecSecurityAssociationAuthCipherInformation(IPSEC_SA0 sa) : base(sa) { var auth_and_cipher_info = sa.ptr.ReadStruct<IPSEC_SA_AUTH_AND_CIPHER_INFORMATION0>(); var auth_info = auth_and_cipher_info.saAuthInformation; AuthKey = auth_info.authKey.ToArray(); AuthCryptoModuleId = auth_info.authTransform.cryptoModuleId.ReadGuid(); AuthType = auth_info.authTransform.authTransformId.authType; AuthConfig = auth_info.authTransform.authTransformId.authConfig; var cipher_info = auth_and_cipher_info.saCipherInformation; CipherKey = cipher_info.cipherKey.ToArray(); CipherCryptoModuleId = cipher_info.cipherTransform.cryptoModuleId.ReadGuid(); CipherType = cipher_info.cipherTransform.cipherTransformId.cipherType; CipherConfig = cipher_info.cipherTransform.cipherTransformId.cipherConfig; } } }
using System; using UnityEngine; using UnityEngine.Events; using UnityEngine.UI; namespace RenderHeads.Media.AVProVideo { [AddComponentMenu("AVPro Video/Subtitles uGUI", 201)] public class SubtitlesUGUI : MonoBehaviour { [SerializeField] private MediaPlayer _mediaPlayer; [SerializeField] private Text _text; private void Start() { this.ChangeMediaPlayer(this._mediaPlayer); } private void OnDestroy() { this.ChangeMediaPlayer(null); } public void ChangeMediaPlayer(MediaPlayer newPlayer) { if (this._mediaPlayer != null) { this._mediaPlayer.Events.RemoveListener(new UnityAction<MediaPlayer, MediaPlayerEvent.EventType, ErrorCode>(this.OnMediaPlayerEvent)); this._mediaPlayer = null; } this._mediaPlayer = newPlayer; if (this._mediaPlayer != null) { this._mediaPlayer.Events.AddListener(new UnityAction<MediaPlayer, MediaPlayerEvent.EventType, ErrorCode>(this.OnMediaPlayerEvent)); } } private void OnMediaPlayerEvent(MediaPlayer mp, MediaPlayerEvent.EventType et, ErrorCode errorCode) { if (et == MediaPlayerEvent.EventType.SubtitleChange) { string text = this._mediaPlayer.Subtitles.GetSubtitleText(); text = text.Replace("<font color=", "<color="); text = text.Replace("</font>", "</color>"); text = text.Replace("<u>", string.Empty); text = text.Replace("</u>", string.Empty); this._text.set_text(text); } } } }
namespace WissAppEF.Migrations { using System; using System.Data.Entity.Migrations; public partial class WissApp_v101 : DbMigration { public override void Up() { AlterColumn("dbo.Users", "E-Mail", c => c.String(nullable: false, maxLength: 200)); } public override void Down() { AlterColumn("dbo.Users", "E-Mail", c => c.Binary(nullable: false, maxLength: 200)); } } }
using System; using System.Collections.Generic; using System.Text; namespace Flyweight { class FlyweightFactory { private List<IFlyweight> flyweights = new List<IFlyweight>(); private int conteo = 0; public int Conteo { get => conteo; set => conteo = value; } public int Adicionar(string nombre) { bool existe = false; foreach (IFlyweight flyweight in flyweights) { if (flyweight.ObtenerNombre() == nombre) { existe = true; } } if (existe) { Console.WriteLine("El objeto ya existe, no se ha adicionado"); return -1; } else { Receta receta = new Receta(); receta.ColocarNombre(nombre); flyweights.Add(receta); conteo = flyweights.Count; return conteo - 1; } } public IFlyweight this[int index] { get { return flyweights[index]; } } } }
using System; using System.Collections.Generic; using System.Text; using System.Data; using System.Data; namespace DAL.SYSTEM { public class UserDAL { DBUtility.DBOperator db = DBUtility.DALFactory.GetDBOperator(DBUtility.DALFactory.strConnection0); #region 获取用户数据列表 /// <summary> /// 获取数据列表 /// </summary> /// <param name="PageNo">第几页</param> /// <param name="PageSize">每页显示数</param> /// <param name="strWhere">条件</param> /// <returns></returns> public DataSet GetList(int PageNo, int PageSize, string strWhere) { StringBuilder strSql = new StringBuilder(); strSql.Append("select count(users.userID) from Users inner join UserRelationShip on Users.userID=UserRelationShip.userID where delflag=0 " + strWhere); strSql.Append("select top " + PageSize + " userID,[UserName],[usercode],[logincode],[userpwd],[sex],[bLead],[sort] "); strSql.Append(" from ("); strSql.Append("select row_number()over(order by sort asc) rowNumber,* from ("); strSql.Append("select top " + PageNo * PageSize + " Users.userID,[UserName],[usercode],[logincode],[userpwd],[sex],[bLead],[sort] "); strSql.Append(" FROM Users inner join UserRelationShip on Users.userID=UserRelationShip.userID "); strSql.Append(" where delflag=0 " + strWhere); strSql.Append("order by sort asc"); strSql.Append(")t"); strSql.Append(")tt"); strSql.Append(" where rowNumber>" + (PageNo - 1) * PageSize); strSql.Append("order by sort asc;"); return db.ExecuteSQLDataSet(strSql.ToString(), false); } #endregion #region 判断是否存在 public bool Exist(string LoginCode) { string sql = "select count(0) from Users where logincode ='" + LoginCode + "'"; if (Convert.ToInt32(db.ExecuteScalarSQL(sql)) > 0) { return true; } else { return false; } } public bool Exist(string LoginCode, string UserID) { string sql = "select count(0) from Users where logincode ='" + LoginCode + "' and UserID !=" + UserID; if (Convert.ToInt32(db.ExecuteScalarSQL(sql)) > 0) { return true; } else { return false; } } #endregion #region 添加用户信息 /// <summary> /// 添加用户信息 /// </summary> /// <param name="model"></param> /// <param name="deptids">使用部门范围</param> /// <returns></returns> public int Insert(MODEL.SYSTEM.UserModel model) { object[] obj = new object[11]; obj[0] = "add"; obj[1] = DBUtility.MAXIDCreator.CreateMaxIntID("Users", DBUtility.DALFactory.strConnection0); obj[2] = model.Usercode; obj[3] = model.UserName; obj[4] = model.Logincode; obj[5] = model.Userpwd; obj[6] = model.Mobile; obj[7] = model.Sort; obj[8] = model.BLogin; obj[9] = model.Sex; obj[10] = model.DeptID; int i = db.ExecuteNonQueryPRO("pt_EditUser", obj); return i; } #endregion #region 修改人员信息 /// <summary> /// 修改人员信息 /// </summary> /// <param name="model"></param> /// <param name="deptids"></param> /// <returns></returns> public int Update(MODEL.SYSTEM.UserModel model) { object[] obj = new object[11]; obj[0] = "update"; obj[1] = model.UserID; obj[2] = model.Usercode; obj[3] = model.UserName; obj[4] = model.Logincode; obj[5] = model.Userpwd; obj[6] = model.Mobile; obj[7] = model.Sort; obj[8] = model.BLogin; obj[9] = model.Sex; obj[10] = model.DeptID; int i = db.ExecuteNonQueryPRO("pt_EditUser", obj); return i; } #endregion #region 返回用户信息 /// <summary> /// 返回用户信息 /// </summary> /// <param name="userid"></param> /// <returns></returns> public DataSet GetDataSet(string userid) { string sql = " select *,(select deptname from dbo.department where department.deptid=r.deptid) as deptname "; sql += " from dbo.users as u inner join dbo.UserRelationShip as r on u.userid=r.userid and PRIMARYDEPT=1 and u.userid='" + userid + "' "; sql += " select *,(select deptname from dbo.department where department.deptid=r.deptid) as deptname "; sql += " from dbo.UserRelationShip as r where userid='" + userid + "' and PRIMARYDEPT=0 "; return db.ExecuteSQLDataSet(sql, false); } #endregion #region 根据用户ID查询用户信息 /// <summary> /// 根据用户ID查询用户信息, /// </summary> /// <param name="userid"></param> /// <returns></returns> public DataTable GetDataTable(string userid) { string sql = "select email,emailpwd,mobile,telephone,photourl,UserName,userpwd from dbo.users where userid='" + userid + "' "; return db.ExecuteSQLDataTable(sql, false); } #endregion #region 修改所有人密码 /// <summary> /// 修改所有人密码 /// </summary> /// <param name="pwd"></param> /// <returns></returns> public int Update(string pwd) { string sql = " update users set userpwd='" + pwd + "' "; return db.ExecuteNonQuerySQL(sql); } #endregion #region 根据指定的删除条件删除对应的记录 /// <summary> /// 根据指定的删除条件删除对应的记录 /// </summary> /// <param name="condition">删除条件</param> public int Delete(string condition) { string sql = " update Users set delflag=1 where userID in ('" + condition.Replace(",", "','") + "') "; //sql += "delete from UserRelationShip where userID in ('" + condition.Replace(",", "','") + "') "; return db.ExecuteNonQuerySQL(sql.ToString()); } #endregion #region 返回用户信息列表 /// <summary> /// 返回用户信息列表 /// </summary> /// <returns></returns> public DataTable GetDataTable() { string sql = " select dsort,usort,levelcode,userid,logincode,username,photourl,telephone,deptid,deptname,UserName,bOnline from dbo.View_UsersLogin where blogin=1 order by levelcode "; return db.ExecuteSQLDataTable(sql, false); } #endregion #region 返回用户信息列表 /// <summary> /// 返回用户信息列表 /// </summary> /// <returns></returns> public DataTable GetDataTableByDept() { string sql = " select dsort,usort,levelcode,userid,logincode,username,deptid,deptname,UserName from dbo.View_UsersLogin where blogin=1 "; sql += " union all "; sql += " select distinct d.sort,'0' as usort,d.levelCode,'' as userid,'' as logincode,'' as username,u.deptid,d.deptname,'' as username from UserRelationShip as u inner join department as d on u.deptId=d.deptID "; sql += " where dbo.pt_HasChildDeptByID(u.deptId)>0 and primaryDept=0 "; return db.ExecuteSQLDataTable(sql, false); } #endregion #region 根据用户ID获取相关信息 public DataTable GetDataTableByUserID(int userID) { string sql = string.Format("select userid,username,deptid,deptname from dbo.View_UsersLogin where userid='{0}' ", userID); return db.ExecuteSQLDataTable(sql, false); } #endregion #region 根据条件获取相关信息 public DataTable GetDataTableByWhere(string where) { string sql = string.Format("select userid,username,deptid,deptname,telephone from dbo.View_UsersLogin where 1=1 {0}", where); return db.ExecuteSQLDataTable(sql, false); } #endregion #region 根据用户ID获取人事信息 public DataTable GetDataTableDossier(int UserID) { string sql = "select birthday,notion,indentification,maritalstatus,politicalstatus,place,homeplace,educational,school,professional,workTime,homeTelephone,address, teacherBack,resume from dbo.Users where UserID=" + UserID; return db.ExecuteSQLDataTable(sql, false); } #endregion #region 修改人事信息 public int UpdateDossier(MODEL.SYSTEM.UserModel model) { StringBuilder sql = new StringBuilder(); sql.Append("UPDATE Users SET "); sql.Append("birthday='" + model.Birthday.ToString() + "',"); sql.Append("notion='" + model.Notion.ToString() + "',"); sql.Append("indentification='" + model.Indentification.ToString() + "',"); sql.Append("maritalstatus='" + model.Maritalstatus.ToString() + "',"); sql.Append("politicalstatus='" + model.Politicalstatus.ToString() + "',"); sql.Append("place='" + model.Place.ToString() + "',"); sql.Append("homeplace='" + model.Homeplace.ToString() + "',"); sql.Append("educational='" + model.Educational.ToString() + "',"); sql.Append("school='" + model.School.ToString() + "',"); sql.Append("professional='" + model.Professional.ToString() + "',"); sql.Append("workTime='" + model.WorkTime.ToString() + "',"); sql.Append("homeTelephone='" + model.HomeTelephone.ToString() + "',"); sql.Append("address='" + model.Address.ToString() + "',"); sql.Append("teacherBack='" + model.TeacherBack.ToString() + "',"); sql.Append("resume='" + model.Resume.ToString() + "',"); sql.Remove(sql.ToString().LastIndexOf(","), 1); sql.Append(" WHERE userID=" + model.UserID.ToString()); return db.ExecuteNonQuerySQL(sql.ToString()); } #endregion #region 取出所有删除的用户数据 /// <summary> /// 取出所有删除的用户数据 /// <param name="pageno"></param> /// <param name="pagesize"></param> /// <param name="swhere"></param> /// <returns></returns> public DataSet GetAllData(int pageno, int pagesize, string swhere, string selectcolumns) { StringBuilder strSql = new StringBuilder(); strSql.Append(" select count(userID) from users where delflag=1 " + swhere); strSql.Append("select top " + pagesize + " userid," + selectcolumns); strSql.Append(" from ("); strSql.Append("select row_number()over(order by UserName asc) rowNumber,* from ("); strSql.Append("select top " + pageno * pagesize + " userid," + selectcolumns); strSql.Append(" FROM dbo.users "); strSql.Append(" where delflag=1 " + swhere); strSql.Append(" order by UserName asc "); strSql.Append(")t"); strSql.Append(")tt"); strSql.Append(" where rowNumber>" + (pageno - 1) * pagesize); strSql.Append(" order by UserName asc;"); return db.ExecuteSQLDataSet(strSql.ToString(), false); } #endregion #region 彻底的删除数据 /// <summary> /// 彻底的删除数据 /// </summary> /// <param name="ids"></param> /// <returns></returns> public int DeleteUser(string ids) { ids = "'" + ids.Replace(",", "','") + "'"; string sql = "delete from users where delflag=1 and userid in (" + ids + ") "; sql += " delete from UserRelationShip where userid in (" + ids + ") "; if (ids == "All") { sql = " delete from users where delflag=1 "; sql += " delete from UserRelationShip where userid in (select userid from users where delflag=1) "; } return db.ExecuteNonQuerySQL(sql); } #endregion #region 恢复删除的用户 /// <summary> /// 恢复删除的用户 /// </summary> /// <param name="ids"></param> /// <returns></returns> public int Restore(string ids) { ids = "'" + ids.Replace(",", "','") + "'"; string sql = " update Users set delflag=0 where userid in (" + ids + ")"; return db.ExecuteNonQuerySQL(sql); } #endregion } }
namespace Newtonsoft.Json { using Newtonsoft.Json.Serialization; using ns16; using ns20; using System; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.IO; using System.Runtime.Serialization; using System.Runtime.Serialization.Formatters; using System.Threading; public class JsonSerializer { private bool bool_0; private bool bool_1; internal ConstructorHandling constructorHandling_0 = ConstructorHandling.Default; private CultureInfo cultureInfo_0 = JsonSerializerSettings.cultureInfo_0; internal DefaultValueHandling defaultValueHandling_0 = DefaultValueHandling.Include; internal FormatterAssemblyStyle formatterAssemblyStyle_0; internal IContractResolver icontractResolver_0 = DefaultContractResolver.IContractResolver_0; private IReferenceResolver ireferenceResolver_0; internal ITraceWriter itraceWriter_0; internal JsonConverterCollection jsonConverterCollection_0; internal MissingMemberHandling missingMemberHandling_0 = MissingMemberHandling.Ignore; private Formatting? nullable_0; private DateFormatHandling? nullable_1; private DateTimeZoneHandling? nullable_2; private DateParseHandling? nullable_3; private FloatFormatHandling? nullable_4; private FloatParseHandling? nullable_5; private StringEscapeHandling? nullable_6; private int? nullable_7; private bool? nullable_8; internal NullValueHandling nullValueHandling_0 = NullValueHandling.Include; internal ObjectCreationHandling objectCreationHandling_0 = ObjectCreationHandling.Auto; internal PreserveReferencesHandling preserveReferencesHandling_0 = PreserveReferencesHandling.None; internal ReferenceLoopHandling referenceLoopHandling_0 = ReferenceLoopHandling.Error; internal SerializationBinder serializationBinder_0 = DefaultSerializationBinder.defaultSerializationBinder_0; internal StreamingContext streamingContext_0 = JsonSerializerSettings.streamingContext_0; private string string_0; internal TypeNameHandling typeNameHandling_0 = TypeNameHandling.None; public event EventHandler<Newtonsoft.Json.Serialization.ErrorEventArgs> Event_0; public static JsonSerializer Create() { return new JsonSerializer(); } public static JsonSerializer Create(JsonSerializerSettings settings) { JsonSerializer serializer = Create(); if (settings != null) { smethod_0(serializer, settings); } return serializer; } public static JsonSerializer CreateDefault() { Func<JsonSerializerSettings> defaultSettings = JsonConvert.DefaultSettings; JsonSerializerSettings settings = (defaultSettings != null) ? defaultSettings() : null; return Create(settings); } public static JsonSerializer CreateDefault(JsonSerializerSettings settings) { JsonSerializer serializer = CreateDefault(); if (settings != null) { smethod_0(serializer, settings); } return serializer; } public object Deserialize(JsonReader reader) { return this.Deserialize(reader, null); } public T Deserialize<T>(JsonReader reader) { return (T) this.Deserialize(reader, typeof(T)); } public object Deserialize(JsonReader reader, Type objectType) { return this.Newtonsoft.Json.JsonSerializer.‍‪‬‫‮‮‍‌‫‌‫‏‌‭‬‌‬‭‏‬‏​‎‮(reader, objectType); } public object Deserialize(TextReader reader, Type objectType) { return this.Deserialize(new JsonTextReader(reader), objectType); } internal bool method_0() { return this.nullable_8.HasValue; } internal IReferenceResolver method_1() { if (this.ireferenceResolver_0 == null) { this.ireferenceResolver_0 = new Class90(); } return this.ireferenceResolver_0; } internal JsonConverter method_2(Type type_0) { return smethod_1(this.jsonConverterCollection_0, type_0); } internal void method_3(Newtonsoft.Json.Serialization.ErrorEventArgs errorEventArgs_0) { EventHandler<Newtonsoft.Json.Serialization.ErrorEventArgs> handler = this.eventHandler_0; if (handler != null) { handler(this, errorEventArgs_0); } } internal virtual object Newtonsoft.Json.JsonSerializer.‍‪‬‫‮‮‍‌‫‌‫‏‌‭‬‌‬‭‏‬‏​‎‮(JsonReader jsonReader_0, Type type_0) { Class203.smethod_2(jsonReader_0, "reader"); CultureInfo culture = null; if ((this.cultureInfo_0 != null) && !this.cultureInfo_0.Equals(jsonReader_0.Culture)) { culture = jsonReader_0.Culture; jsonReader_0.Culture = this.cultureInfo_0; } DateTimeZoneHandling? nullable = null; if (this.nullable_2.HasValue) { if (jsonReader_0.DateTimeZoneHandling != ((DateTimeZoneHandling) this.nullable_2)) { nullable = new DateTimeZoneHandling?(jsonReader_0.DateTimeZoneHandling); jsonReader_0.DateTimeZoneHandling = this.nullable_2.Value; } } DateParseHandling? nullable2 = null; if (this.nullable_3.HasValue) { if (jsonReader_0.DateParseHandling != ((DateParseHandling) this.nullable_3)) { nullable2 = new DateParseHandling?(jsonReader_0.DateParseHandling); jsonReader_0.DateParseHandling = this.nullable_3.Value; } } FloatParseHandling? nullable3 = null; if (this.nullable_5.HasValue) { if (jsonReader_0.FloatParseHandling != ((FloatParseHandling) this.nullable_5)) { nullable3 = new FloatParseHandling?(jsonReader_0.FloatParseHandling); jsonReader_0.FloatParseHandling = this.nullable_5.Value; } } int? maxDepth = null; if (this.bool_0 && (jsonReader_0.MaxDepth != this.nullable_7)) { maxDepth = jsonReader_0.MaxDepth; jsonReader_0.MaxDepth = this.nullable_7; } Class68 class2 = ((this.ITraceWriter_0 == null) || (this.ITraceWriter_0.LevelFilter < TraceLevel.Verbose)) ? null : new Class68(jsonReader_0); object obj2 = new Class136(this).method_5(class2 ?? jsonReader_0, type_0, this.Boolean_0); if (class2 != null) { this.ITraceWriter_0.Trace(TraceLevel.Verbose, "Deserialized JSON: " + Environment.NewLine + class2.method_14(), null); } if (culture != null) { jsonReader_0.Culture = culture; } if (nullable.HasValue) { jsonReader_0.DateTimeZoneHandling = nullable.Value; } if (nullable2.HasValue) { jsonReader_0.DateParseHandling = nullable2.Value; } if (nullable3.HasValue) { jsonReader_0.FloatParseHandling = nullable3.Value; } if (this.bool_0) { jsonReader_0.MaxDepth = maxDepth; } return obj2; } internal virtual void Newtonsoft.Json.JsonSerializer.‫‭‭‫‭‎‭‎​​‬‌‏‫‌‫‬‌‪‎‮‏‪‭‭‫‎‮(JsonWriter jsonWriter_0, object object_0, Type type_0) { Class203.smethod_2(jsonWriter_0, "jsonWriter"); Formatting? nullable = null; if (this.nullable_0.HasValue) { if (jsonWriter_0.Formatting != ((Formatting) this.nullable_0)) { nullable = new Formatting?(jsonWriter_0.Formatting); jsonWriter_0.Formatting = this.nullable_0.Value; } } DateFormatHandling? nullable2 = null; if (this.nullable_1.HasValue) { if (jsonWriter_0.DateFormatHandling != ((DateFormatHandling) this.nullable_1)) { nullable2 = new DateFormatHandling?(jsonWriter_0.DateFormatHandling); jsonWriter_0.DateFormatHandling = this.nullable_1.Value; } } DateTimeZoneHandling? nullable3 = null; if (this.nullable_2.HasValue) { if (jsonWriter_0.DateTimeZoneHandling != ((DateTimeZoneHandling) this.nullable_2)) { nullable3 = new DateTimeZoneHandling?(jsonWriter_0.DateTimeZoneHandling); jsonWriter_0.DateTimeZoneHandling = this.nullable_2.Value; } } FloatFormatHandling? nullable4 = null; if (this.nullable_4.HasValue) { if (jsonWriter_0.FloatFormatHandling != ((FloatFormatHandling) this.nullable_4)) { nullable4 = new FloatFormatHandling?(jsonWriter_0.FloatFormatHandling); jsonWriter_0.FloatFormatHandling = this.nullable_4.Value; } } StringEscapeHandling? nullable5 = null; if (this.nullable_6.HasValue) { if (jsonWriter_0.StringEscapeHandling != ((StringEscapeHandling) this.nullable_6)) { nullable5 = new StringEscapeHandling?(jsonWriter_0.StringEscapeHandling); jsonWriter_0.StringEscapeHandling = this.nullable_6.Value; } } CultureInfo culture = null; if ((this.cultureInfo_0 != null) && !this.cultureInfo_0.Equals(jsonWriter_0.Culture)) { culture = jsonWriter_0.Culture; jsonWriter_0.Culture = this.cultureInfo_0; } string dateFormatString = null; if (this.bool_1 && (jsonWriter_0.DateFormatString != this.string_0)) { dateFormatString = jsonWriter_0.DateFormatString; jsonWriter_0.DateFormatString = this.string_0; } Class78 class2 = ((this.ITraceWriter_0 == null) || (this.ITraceWriter_0.LevelFilter < TraceLevel.Verbose)) ? null : new Class78(jsonWriter_0); new Class137(this).method_3(class2 ?? jsonWriter_0, object_0, type_0); if (class2 != null) { this.ITraceWriter_0.Trace(TraceLevel.Verbose, "Serialized JSON: " + Environment.NewLine + class2.method_20(), null); } if (nullable.HasValue) { jsonWriter_0.Formatting = nullable.Value; } if (nullable2.HasValue) { jsonWriter_0.DateFormatHandling = nullable2.Value; } if (nullable3.HasValue) { jsonWriter_0.DateTimeZoneHandling = nullable3.Value; } if (nullable4.HasValue) { jsonWriter_0.FloatFormatHandling = nullable4.Value; } if (nullable5.HasValue) { jsonWriter_0.StringEscapeHandling = nullable5.Value; } if (this.bool_1) { jsonWriter_0.DateFormatString = dateFormatString; } if (culture != null) { jsonWriter_0.Culture = culture; } } internal virtual void Newtonsoft.Json.JsonSerializer.‍​‍​‪‍‎‪‏‍‭‬‬‬​‏‎‌‎‌‬‮(JsonReader jsonReader_0, object object_0) { Class203.smethod_2(jsonReader_0, "reader"); Class203.smethod_2(object_0, "target"); new Class136(this).method_3(jsonReader_0, object_0); } public void Populate(JsonReader reader, object target) { this.Newtonsoft.Json.JsonSerializer.‍​‍​‪‍‎‪‏‍‭‬‬‬​‏‎‌‎‌‬‮(reader, target); } public void Populate(TextReader reader, object target) { this.Populate(new JsonTextReader(reader), target); } public void Serialize(JsonWriter jsonWriter, object value) { this.Newtonsoft.Json.JsonSerializer.‫‭‭‫‭‎‭‎​​‬‌‏‫‌‫‬‌‪‎‮‏‪‭‭‫‎‮(jsonWriter, value, null); } public void Serialize(TextWriter textWriter, object value) { this.Serialize(new JsonTextWriter(textWriter), value); } public void Serialize(JsonWriter jsonWriter, object value, Type objectType) { this.Newtonsoft.Json.JsonSerializer.‫‭‭‫‭‎‭‎​​‬‌‏‫‌‫‬‌‪‎‮‏‪‭‭‫‎‮(jsonWriter, value, objectType); } public void Serialize(TextWriter textWriter, object value, Type objectType) { this.Serialize(new JsonTextWriter(textWriter), value, objectType); } private static void smethod_0(JsonSerializer jsonSerializer_0, JsonSerializerSettings jsonSerializerSettings_0) { if (!Class191.smethod_0<JsonConverter>(jsonSerializerSettings_0.Converters)) { for (int i = 0; i < jsonSerializerSettings_0.Converters.Count; i++) { jsonSerializer_0.JsonConverterCollection_0.Insert(i, jsonSerializerSettings_0.Converters[i]); } } if (jsonSerializerSettings_0.nullable_18.HasValue) { jsonSerializer_0.TypeNameHandling_0 = jsonSerializerSettings_0.TypeNameHandling; } if (jsonSerializerSettings_0.nullable_9.HasValue) { jsonSerializer_0.FormatterAssemblyStyle_0 = jsonSerializerSettings_0.TypeNameAssemblyFormat; } if (jsonSerializerSettings_0.nullable_11.HasValue) { jsonSerializer_0.PreserveReferencesHandling_0 = jsonSerializerSettings_0.PreserveReferencesHandling; } if (jsonSerializerSettings_0.nullable_15.HasValue) { jsonSerializer_0.ReferenceLoopHandling_0 = jsonSerializerSettings_0.ReferenceLoopHandling; } if (jsonSerializerSettings_0.nullable_14.HasValue) { jsonSerializer_0.MissingMemberHandling_0 = jsonSerializerSettings_0.MissingMemberHandling; } if (jsonSerializerSettings_0.nullable_13.HasValue) { jsonSerializer_0.ObjectCreationHandling_0 = jsonSerializerSettings_0.ObjectCreationHandling; } if (jsonSerializerSettings_0.nullable_12.HasValue) { jsonSerializer_0.NullValueHandling_0 = jsonSerializerSettings_0.NullValueHandling; } if (jsonSerializerSettings_0.nullable_10.HasValue) { jsonSerializer_0.DefaultValueHandling_0 = jsonSerializerSettings_0.DefaultValueHandling; } if (jsonSerializerSettings_0.nullable_17.HasValue) { jsonSerializer_0.ConstructorHandling_0 = jsonSerializerSettings_0.ConstructorHandling; } if (jsonSerializerSettings_0.nullable_16.HasValue) { jsonSerializer_0.StreamingContext_0 = jsonSerializerSettings_0.Context; } if (jsonSerializerSettings_0.nullable_7.HasValue) { jsonSerializer_0.nullable_8 = jsonSerializerSettings_0.nullable_7; } if (jsonSerializerSettings_0.Error != null) { jsonSerializer_0.Event_0 += jsonSerializerSettings_0.Error; } if (jsonSerializerSettings_0.ContractResolver != null) { jsonSerializer_0.IContractResolver_0 = jsonSerializerSettings_0.ContractResolver; } if (jsonSerializerSettings_0.ReferenceResolver != null) { jsonSerializer_0.IReferenceResolver_0 = jsonSerializerSettings_0.ReferenceResolver; } if (jsonSerializerSettings_0.TraceWriter != null) { jsonSerializer_0.ITraceWriter_0 = jsonSerializerSettings_0.TraceWriter; } if (jsonSerializerSettings_0.Binder != null) { jsonSerializer_0.SerializationBinder_0 = jsonSerializerSettings_0.Binder; } if (jsonSerializerSettings_0.nullable_0.HasValue) { jsonSerializer_0.nullable_0 = jsonSerializerSettings_0.nullable_0; } if (jsonSerializerSettings_0.nullable_1.HasValue) { jsonSerializer_0.nullable_1 = jsonSerializerSettings_0.nullable_1; } if (jsonSerializerSettings_0.nullable_2.HasValue) { jsonSerializer_0.nullable_2 = jsonSerializerSettings_0.nullable_2; } if (jsonSerializerSettings_0.nullable_3.HasValue) { jsonSerializer_0.nullable_3 = jsonSerializerSettings_0.nullable_3; } if (jsonSerializerSettings_0.bool_2) { jsonSerializer_0.string_0 = jsonSerializerSettings_0.string_1; jsonSerializer_0.bool_1 = jsonSerializerSettings_0.bool_2; } if (jsonSerializerSettings_0.nullable_4.HasValue) { jsonSerializer_0.nullable_4 = jsonSerializerSettings_0.nullable_4; } if (jsonSerializerSettings_0.nullable_5.HasValue) { jsonSerializer_0.nullable_5 = jsonSerializerSettings_0.nullable_5; } if (jsonSerializerSettings_0.nullable_6.HasValue) { jsonSerializer_0.nullable_6 = jsonSerializerSettings_0.nullable_6; } if (jsonSerializerSettings_0.cultureInfo_1 != null) { jsonSerializer_0.cultureInfo_0 = jsonSerializerSettings_0.cultureInfo_1; } if (jsonSerializerSettings_0.bool_1) { jsonSerializer_0.nullable_7 = jsonSerializerSettings_0.nullable_8; jsonSerializer_0.bool_0 = jsonSerializerSettings_0.bool_1; } } internal static JsonConverter smethod_1(IList<JsonConverter> ilist_0, Type type_0) { if (ilist_0 != null) { for (int i = 0; i < ilist_0.Count; i++) { JsonConverter converter = ilist_0[i]; if (converter.CanConvert(type_0)) { return converter; } } } return null; } public virtual bool Boolean_0 { get { bool? nullable = this.nullable_8; if (!nullable.HasValue) { return false; } return nullable.GetValueOrDefault(); } set { this.nullable_8 = new bool?(value); } } public virtual ConstructorHandling ConstructorHandling_0 { get { return this.constructorHandling_0; } set { if ((value < ConstructorHandling.Default) || (value > ConstructorHandling.AllowNonPublicDefaultConstructor)) { throw new ArgumentOutOfRangeException("value"); } this.constructorHandling_0 = value; } } public virtual CultureInfo CultureInfo_0 { get { return (this.cultureInfo_0 ?? JsonSerializerSettings.cultureInfo_0); } set { this.cultureInfo_0 = value; } } public virtual DateFormatHandling DateFormatHandling_0 { get { DateFormatHandling? nullable = this.nullable_1; if (!nullable.HasValue) { return DateFormatHandling.IsoDateFormat; } return nullable.GetValueOrDefault(); } set { this.nullable_1 = new DateFormatHandling?(value); } } public virtual DateParseHandling DateParseHandling_0 { get { DateParseHandling? nullable = this.nullable_3; if (!nullable.HasValue) { return DateParseHandling.DateTime; } return nullable.GetValueOrDefault(); } set { this.nullable_3 = new DateParseHandling?(value); } } public virtual DateTimeZoneHandling DateTimeZoneHandling_0 { get { DateTimeZoneHandling? nullable = this.nullable_2; if (!nullable.HasValue) { return DateTimeZoneHandling.RoundtripKind; } return nullable.GetValueOrDefault(); } set { this.nullable_2 = new DateTimeZoneHandling?(value); } } public virtual DefaultValueHandling DefaultValueHandling_0 { get { return this.defaultValueHandling_0; } set { if ((value < DefaultValueHandling.Include) || (value > DefaultValueHandling.IgnoreAndPopulate)) { throw new ArgumentOutOfRangeException("value"); } this.defaultValueHandling_0 = value; } } public virtual FloatFormatHandling FloatFormatHandling_0 { get { FloatFormatHandling? nullable = this.nullable_4; if (!nullable.HasValue) { return FloatFormatHandling.String; } return nullable.GetValueOrDefault(); } set { this.nullable_4 = new FloatFormatHandling?(value); } } public virtual FloatParseHandling FloatParseHandling_0 { get { FloatParseHandling? nullable = this.nullable_5; if (!nullable.HasValue) { return FloatParseHandling.Double; } return nullable.GetValueOrDefault(); } set { this.nullable_5 = new FloatParseHandling?(value); } } public virtual FormatterAssemblyStyle FormatterAssemblyStyle_0 { get { return this.formatterAssemblyStyle_0; } set { if ((value < FormatterAssemblyStyle.Simple) || (value > FormatterAssemblyStyle.Full)) { throw new ArgumentOutOfRangeException("value"); } this.formatterAssemblyStyle_0 = value; } } public virtual Formatting Formatting_0 { get { Formatting? nullable = this.nullable_0; if (!nullable.HasValue) { return Formatting.None; } return nullable.GetValueOrDefault(); } set { this.nullable_0 = new Formatting?(value); } } public virtual IContractResolver IContractResolver_0 { get { return this.icontractResolver_0; } set { this.icontractResolver_0 = value ?? DefaultContractResolver.IContractResolver_0; } } public virtual IReferenceResolver IReferenceResolver_0 { get { return this.method_1(); } set { if (value == null) { throw new ArgumentNullException("value", "Reference resolver cannot be null."); } this.ireferenceResolver_0 = value; } } public virtual ITraceWriter ITraceWriter_0 { get { return this.itraceWriter_0; } set { this.itraceWriter_0 = value; } } public virtual JsonConverterCollection JsonConverterCollection_0 { get { if (this.jsonConverterCollection_0 == null) { this.jsonConverterCollection_0 = new JsonConverterCollection(); } return this.jsonConverterCollection_0; } } public virtual MissingMemberHandling MissingMemberHandling_0 { get { return this.missingMemberHandling_0; } set { if ((value < MissingMemberHandling.Ignore) || (value > MissingMemberHandling.Error)) { throw new ArgumentOutOfRangeException("value"); } this.missingMemberHandling_0 = value; } } public virtual NullValueHandling NullValueHandling_0 { get { return this.nullValueHandling_0; } set { if ((value < NullValueHandling.Include) || (value > NullValueHandling.Ignore)) { throw new ArgumentOutOfRangeException("value"); } this.nullValueHandling_0 = value; } } public virtual ObjectCreationHandling ObjectCreationHandling_0 { get { return this.objectCreationHandling_0; } set { if ((value < ObjectCreationHandling.Auto) || (value > ObjectCreationHandling.Replace)) { throw new ArgumentOutOfRangeException("value"); } this.objectCreationHandling_0 = value; } } public virtual PreserveReferencesHandling PreserveReferencesHandling_0 { get { return this.preserveReferencesHandling_0; } set { if ((value < PreserveReferencesHandling.None) || (value > PreserveReferencesHandling.All)) { throw new ArgumentOutOfRangeException("value"); } this.preserveReferencesHandling_0 = value; } } public virtual int? Prop_0 { get { return this.nullable_7; } set { if (value <= 0) { throw new ArgumentException("Value must be positive.", "value"); } this.nullable_7 = value; this.bool_0 = true; } } public virtual ReferenceLoopHandling ReferenceLoopHandling_0 { get { return this.referenceLoopHandling_0; } set { if ((value < ReferenceLoopHandling.Error) || (value > ReferenceLoopHandling.Serialize)) { throw new ArgumentOutOfRangeException("value"); } this.referenceLoopHandling_0 = value; } } public virtual SerializationBinder SerializationBinder_0 { get { return this.serializationBinder_0; } set { if (value == null) { throw new ArgumentNullException("value", "Serialization binder cannot be null."); } this.serializationBinder_0 = value; } } public virtual StreamingContext StreamingContext_0 { get { return this.streamingContext_0; } set { this.streamingContext_0 = value; } } public virtual string String_0 { get { return (this.string_0 ?? "yyyy'-'MM'-'dd'T'HH':'mm':'ss.FFFFFFFK"); } set { this.string_0 = value; this.bool_1 = true; } } public virtual StringEscapeHandling StringEscapeHandling_0 { get { StringEscapeHandling? nullable = this.nullable_6; if (!nullable.HasValue) { return StringEscapeHandling.Default; } return nullable.GetValueOrDefault(); } set { this.nullable_6 = new StringEscapeHandling?(value); } } public virtual TypeNameHandling TypeNameHandling_0 { get { return this.typeNameHandling_0; } set { if ((value < TypeNameHandling.None) || (value > TypeNameHandling.Auto)) { throw new ArgumentOutOfRangeException("value"); } this.typeNameHandling_0 = value; } } } }
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="Task3.cs" company=""> // // </copyright> // <summary> // The task 3. // </summary> // -------------------------------------------------------------------------------------------------------------------- namespace XMLProcessing.Tasks { using System; using System.Collections; using System.Xml; /// <summary> /// The task 3. /// </summary> public static class Task3 { /// <summary> /// The extract artists x path. /// </summary> /// <param name="xmlFile"> /// The xml file. /// </param> public static void ExtractArtistsXPath(string xmlFile) { // XPath // Write program that extracts all different artists which are found in the catalog.xml. // For each author you should print the number of albums in the catalogue. // Use the DOM parser and a hash-table. var doc = new XmlDocument(); doc.Load(xmlFile); var xPathQuery = "/catalogue/album/artist"; var artists = new Hashtable(); var artistList = doc.SelectNodes(xPathQuery); if (artistList != null) { foreach (XmlNode artistNode in artistList) { var artist = artistNode.InnerText; if (!artists.ContainsKey(artist)) { artists.Add(artist, 1); } else { var numAlbums = (int)artists[artist]; artists[artist] = ++numAlbums; } } } foreach (DictionaryEntry artist in artists) { Console.WriteLine("Artist {0} has {1} album(s)", artist.Key, artists[artist.Key]); } } } }
namespace CloneDeploy_Entities.DTOs.ImageSchemaFE { public class LogicalVolume { public bool Active { get; set; } public string CustomSize { get; set; } public string CustomSizeUnit { get; set; } public bool ForceFixedSize { get; set; } public string FsType { get; set; } public string Name { get; set; } public string Size { get; set; } public string Type { get; set; } public string UsedMb { get; set; } public string Uuid { get; set; } public string VolumeGroup { get; set; } public string VolumeSize { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.HttpsPolicy; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; using Microsoft.EntityFrameworkCore; using GraphQL; using GraphQL.Types; using GraphiQl; using GraphQL.DataLoader; using GraphQL.Http; using Newtonsoft.Json; namespace app { public class Startup { public Startup(IConfiguration configuration) { Configuration = configuration; } public IConfiguration Configuration { get; } // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { var connection = @"Server=localhost,1433;Database=dotnetgraphql;User=sa; Password=Password1"; services.AddDbContext<ApplicationDbContext>(options => options.UseSqlServer(connection), ServiceLifetime.Transient); services.AddControllers(); services.AddScoped<IDocumentWriter, DocumentWriter>(); services.AddScoped<IDocumentExecuter, DocumentExecuter>(); services.AddScoped<BaseGraphQLQuery>(); services.AddScoped<GraphQLQuery>(); services.AddScoped<ISchema, GraphQLSchema>(); services.AddScoped<IDataLoaderContextAccessor, DataLoaderContextAccessor>(); services.AddScoped<DataLoaderDocumentListener>(); services.AddScoped<IGetDataService, GetDataService>(); services.AddScoped<AuthorType>(); services.AddScoped<BookType>(); services.AddScoped<SalesInvoiceType>(); // var sp = services.BuildServiceProvider(); // services.AddSingleton<ISchema>(new GraphQLSchema(new FuncDependencyResolver(type => sp.GetService(type)))); // fix - https://stackoverflow.com/a/58084628 services.AddMvc(option => option.EnableEndpointRouting = false) .SetCompatibilityVersion(CompatibilityVersion.Version_3_0) .AddNewtonsoftJson(opt => opt.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore); services.AddCors(options => options.AddPolicy("AllowAll", p => p.AllowAnyOrigin() .AllowAnyMethod() .AllowAnyHeader())); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { app.UseGraphiQl("/graphql", "/graphql"); if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.UseHttpsRedirection(); app.UseRouting(); app.UseCors("AllowAll"); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapControllers(); }); } } }
using System; using System.Collections.Generic; using System.Text; namespace rsnug_5.Complexidade { class AppointmentIf { public readonly bool IsAllDay; public readonly bool IsRecurrent; public readonly bool HasConflict; public readonly bool HasAdjactentMeeting; public readonly bool IsSafityMinimalDuraton; public readonly bool IsSatifyMinimalParticipantNumber; public readonly bool IsEvent; public AppointmentIf(bool isAllDay, bool isRecurrent, bool hasConflict, bool hasAdjactentMeeting, bool isSafityMinimalDuraton, bool isSatifyMinimalParticipantNumber, bool isEvent) { IsAllDay = isAllDay; IsRecurrent = isRecurrent; HasConflict = hasConflict; HasAdjactentMeeting = hasAdjactentMeeting; IsSafityMinimalDuraton = isSafityMinimalDuraton; IsSatifyMinimalParticipantNumber = isSatifyMinimalParticipantNumber; IsEvent = isEvent; } // Regras para agendar uma reunião // -- Não permitir reuniões menores de 40 minutos // -- Não permitir reuniões com menos de 5 pessoas // -- As reuniões não podem ter conflitos // -- As reuniões não podem ser recorrentes // -- As reuniões não podem ser de dia inteiro // -- Quando for um evento então permitir agendamento com menos de 5 pessoas public bool Decide() { if (!IsAllDay) { if (!IsRecurrent) { if (!HasConflict) { if (IsSafityMinimalDuraton) { if (!IsSatifyMinimalParticipantNumber) { if (IsEvent) { if (IsEvent) { return AccepMeeting(); } return DeclineMeeting(); } return DeclineMeeting(); } return AccepMeeting(); } return DeclineMeeting(); } return DeclineMeeting(); } return DeclineMeeting(); } return DeclineMeeting(); } static bool AccepMeeting() => throw new NotImplementedException(); static bool DeclineMeeting() => throw new NotImplementedException(); } }
namespace Sallaries { using System.Collections.Generic; internal class Employee { public int Id { get; set; } public long Sallary { get; set; } public List<Employee> Employees { get; set; } public Employee(int id) { this.Id = id; this.Employees = new List<Employee>(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.IO; using System.Threading; using System.Diagnostics; using System.Timers; namespace TestYourReflexes { public class ReflexesGame { //Game time public static System.Timers.Timer gameTime; public static char[] distractorSym = {'@', '#', '$', '%', '&', '!', '?', '+', '*', '-'}; public static bool GameOver = false; public static void TimeIsUp(Object source, ElapsedEventArgs e) { Console.Clear(); SideBar(); Console.SetCursorPosition(width - 40, height - 13); Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine("Time is up!"); Console.SetCursorPosition(width - 40, height - 12); Console.WriteLine("Your overall score from this game is: {0}", overallResult); gameTime.Stop(); GameOver = true; string[] highScore = new string[5]; StreamReader readScore = new StreamReader("../../../../../textFiles/HighScores.txt"); using (readScore) { int i = 0; for (string line; (line = readScore.ReadLine()) != null; i++) { highScore[i] = line; } } if (Convert.ToInt32(highScore[1]) < overallResult) { highScore[1] = overallResult.ToString(); StreamWriter newscore = new StreamWriter("../../../../../textFiles/HighScores.txt"); using (newscore) { for (int i = 0; i < highScore.Length; i++) { newscore.WriteLine(highScore[i]); } } } } // struct symbol:IEquatable<symbol> { public int x; public int y; public char c; public ConsoleColor color; public bool Equals(symbol position) { if (x == position.x && y == position.y) { return true; } return false; } } static void PrintAnPosition(int x, int y, char c, ConsoleColor color = ConsoleColor.Green) { Console.SetCursorPosition(x, y); Console.ForegroundColor = color; Console.Write(c); } public const int width = 60; public const int height = 23; public static int counter = 0; public static int timeBonus = 0; public static int overallResult; public static Random randomNum = new Random(); //Side Bar static void SideBar() { for (int i = 0; i <= height + 1; i++) { Console.SetCursorPosition(width, i); Console.ForegroundColor = ConsoleColor.DarkRed; Console.Write("█"); int infoRow = 2; Console.SetCursorPosition(width + 2, infoRow++); infoRow++; Console.ForegroundColor = ConsoleColor.White; Console.Write("Test Your Reflexes"); Console.SetCursorPosition(width + 2, infoRow++); infoRow++; Console.ForegroundColor = ConsoleColor.Green; Console.Write("Score:"); Console.ForegroundColor = ConsoleColor.Green; Console.SetCursorPosition(width + 2, infoRow++); Console.Write(counter); Console.SetCursorPosition(width + 2, infoRow++); Console.SetCursorPosition(width + 2, infoRow++); infoRow++; Console.ForegroundColor = ConsoleColor.Magenta; Console.Write("Time Bonus:"); Console.ForegroundColor = ConsoleColor.Magenta; Console.SetCursorPosition(width + 2, infoRow++); Console.Write(timeBonus); Console.SetCursorPosition(width + 2, infoRow++); Console.SetCursorPosition(width + 2, infoRow++); infoRow++; Console.ForegroundColor = ConsoleColor.Red; Console.Write("Overall result:"); Console.ForegroundColor = ConsoleColor.Red; Console.SetCursorPosition(width + 2, infoRow++); Console.Write(overallResult); Console.SetCursorPosition(width + 2, infoRow += 2); infoRow++; Console.ForegroundColor = ConsoleColor.White; } } // static void GameRules() { Console.SetCursorPosition(0, 3); Console.ForegroundColor = ConsoleColor.DarkRed; Console.Write(new string('█', width)); Console.SetCursorPosition(3, 5); Console.ForegroundColor = ConsoleColor.Magenta; Console.Write("Letters will appear on random places on the game field."); Console.SetCursorPosition(10, 6); Console.Write("Type the letters as fast as you can."); Console.SetCursorPosition(7, 7); Console.Write("You get a bonus if you do it fast enough!"); Console.SetCursorPosition(3, 8); Console.Write("Be careful, there are other symbols to distract you!"); Console.SetCursorPosition(12, 10); Console.Write("Press any key to start playing."); Console.SetCursorPosition(0, 22); Console.ForegroundColor = ConsoleColor.DarkRed; Console.Write(new string('█', width)); SideBar(); Console.ReadKey(); return; } static void YouAreWrong() { Console.BackgroundColor = ConsoleColor.Red; Console.Clear(); Thread.Sleep(20); Console.BackgroundColor = ConsoleColor.Black; Console.Clear(); } public static void Play() { Console.CursorVisible = false; Console.BufferWidth = Console.WindowWidth = 100; Console.BufferHeight = Console.WindowHeight = 25; //distractor List<symbol> distractors = new List<symbol>(); int iteration = 0; int distractorsCount = 0; GameRules(); Console.Clear(); //game timer gameTime = new System.Timers.Timer(60000); gameTime.Elapsed += new ElapsedEventHandler(TimeIsUp); gameTime.Enabled = true; //reading the symbols from a file StreamReader reader = new StreamReader(@"../../../../../textFiles/input_symbols.txt", System.Text.Encoding.UTF8); string contents = reader.ReadToEnd(); char[] symbols = new char[contents.Length]; reader.Close(); int len = contents.Length; //create a char array with the chars in the txt file for (int i = 0; i < len; i++) { symbols[i] = contents[i]; } SideBar(); //game logic while (true) { if (GameOver == true) { return; } Console.BackgroundColor = ConsoleColor.Black; //printing distractors if (iteration <= 10) { distractorsCount = iteration; } else { distractorsCount = 10; } distractors.Clear(); for (int i = 0; i < distractorsCount; i++) { symbol distractor = new symbol(); do { distractor.color = ConsoleColor.Magenta; distractor.x = randomNum.Next(width); distractor.y = randomNum.Next(height); distractor.c = distractorSym[randomNum.Next(0, distractorSym.Length)]; } while (distractors.Contains(distractor) == true); distractors.Add(distractor); } for (int i = 0; i < distractors.Count; i++) { PrintAnPosition(distractors[i].x, distractors[i].y, distractors[i].c, distractors[i].color); } // //printing letters symbol symbol = new symbol(); symbol.color = ConsoleColor.Green; symbol.x = randomNum.Next(width); symbol.y = randomNum.Next(height); symbol.c = symbols[randomNum.Next(0, symbols.Length)]; PrintAnPosition(symbol.x, symbol.y, symbol.c, symbol.color); // Stopwatch stopWatch = new Stopwatch(); stopWatch.Start(); if (symbol.c == Console.ReadKey(true).KeyChar) { stopWatch.Stop(); TimeSpan ts = stopWatch.Elapsed; counter++; if (ts.Milliseconds < 200) { timeBonus+=10; } overallResult = counter + timeBonus; Console.Clear(); SideBar(); } else { YouAreWrong(); Console.Clear(); SideBar(); } iteration++; } } static void Main() { Play(); } } }
using BPiaoBao.AppServices.DataContracts; using BPiaoBao.AppServices.DataContracts.SystemSetting; using BPiaoBao.AppServices.StationContracts.StationMap; using BPiaoBao.AppServices.StationContracts.SystemSetting; using BPiaoBao.AppServices.StationContracts.SystemSetting.SystemMap; using BPiaoBao.Cashbag.Domain.Services; using BPiaoBao.Common; using BPiaoBao.Common.Enums; using BPiaoBao.DomesticTicket.Domain.Models.CustomerInfo; using BPiaoBao.SystemSetting.Domain.Models.Businessmen; using BPiaoBao.SystemSetting.Domain.Services; using JoveZhao.Framework; using JoveZhao.Framework.DDD; using JoveZhao.Framework.Expand; using StructureMap; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Text.RegularExpressions; namespace BPiaoBao.AppServices.SystemSetting { public partial class BusinessmanService : IStationBusinessmanService { IAccountClientProxy accountClientProxy = ObjectFactory.GetInstance<IAccountClientProxy>(); public void AddBussinessmen(BPiaoBao.AppServices.StationContracts.SystemSetting.SystemMap.RequestCarrier carrier) { if (carrier == null) throw new CustomException(501, "输入信息不完整"); var curentUser = AuthManager.GetCurrentUser(); var isexist = this.businessmanRepository.FindAll(p => p.Code == carrier.Code).Count() > 0; if (isexist) throw new CustomException(500, string.Format("{0}已存在", carrier.Code)); var builder = AggregationFactory.CreateBuiler<BusinessmanBuilder>(); var carrierModel = builder.CreateCarrier(AutoMapper.Mapper.Map<BPiaoBao.AppServices.StationContracts.SystemSetting.SystemMap.RequestCarrier, Carrier>(carrier)); carrierModel.CheckRule(); var cashbagModel = accountClientProxy.AddCompany(curentUser.CashbagCode, curentUser.CashbagKey, new BPiaoBao.Cashbag.Domain.Models.CashCompanyInfo { ClientAccount = carrier.Code, Contact = carrier.ContactWay.Contact, CpyName = carrier.Name, Moblie = carrier.ContactWay.Tel, Province = carrier.ContactWay.Province, City = carrier.ContactWay.City, Address = carrier.ContactWay.Address }); try { carrierModel.CashbagCode = cashbagModel.PayAccount; carrierModel.CashbagKey = cashbagModel.Token; this.unitOfWorkRepository.PersistCreationOf(carrierModel); this.unitOfWork.Commit(); } catch (Exception e) { if (cashbagModel != null) accountClientProxy.DeleteCashBagBusinessman(curentUser.CashbagCode, cashbagModel.PayAccount, curentUser.CashbagKey); Logger.WriteLog(LogType.ERROR, "添加商户发生异常", e); throw new CustomException(500, "添加商户发生异常"); } } //public void AddSupplier(BPiaoBao.AppServices.StationContracts.SystemSetting.SystemMap.STRequestSupplier supplier) //{ // if (supplier == null) // throw new CustomException(501, "输入信息不完整"); // var curentUser = AuthManager.GetCurrentUser(); // var isexist = this.businessmanRepository.FindAll(p => p.Code == supplier.Code).Count() > 0; // if (isexist) // throw new CustomException(500, string.Format("{0}已存在", supplier.Code)); // var builder = AggregationFactory.CreateBuiler<BusinessmanBuilder>(); // var carrierModel = builder.CreateSupplier(AutoMapper.Mapper.Map<BPiaoBao.AppServices.StationContracts.SystemSetting.SystemMap.STRequestSupplier, Supplier>(supplier)); // carrierModel.CheckRule(); // var cashbagModel = accountClientProxy.AddCompany(curentUser.CashbagCode, curentUser.CashbagKey, new BPiaoBao.Cashbag.Domain.Models.CashCompanyInfo // { // ClientAccount = supplier.Code, // Contact = supplier.ContactWay.Contact, // CpyName = supplier.Name, // Moblie = supplier.ContactWay.Tel, // Province = supplier.ContactWay.Province, // City = supplier.ContactWay.City, // Address = supplier.ContactWay.Address // }); // try // { // carrierModel.CashbagCode = cashbagModel.PayAccount; // carrierModel.CashbagKey = cashbagModel.Token; // this.unitOfWorkRepository.PersistCreationOf(carrierModel); // this.unitOfWork.Commit(); // } // catch (Exception e) // { // if (cashbagModel != null) // accountClientProxy.DeleteCashBagBusinessman(curentUser.CashbagCode, cashbagModel.PayAccount, curentUser.CashbagKey); // Logger.WriteLog(LogType.ERROR, "添加商户发生异常", e); // throw new CustomException(500, "添加商户发生异常"); // } //} public bool IsExistCarrier(string code) { if (string.IsNullOrEmpty(code)) throw new CustomException(500, "商户号不能为空"); return this.businessmanRepository.FindAll(x => x.Code == code).Count() > 0; } public PagedList<BPiaoBao.AppServices.StationContracts.SystemSetting.SystemMap.ResponseListCarrierOrSupplier> FindCarrierOrSupplier(string name, string code, string cashbagCode, DateTime? startTime, DateTime? endTime, int startIndex, int count,int type) { var query = this.businessmanRepository.FindAll(); if (type == 0) query = query.Where(x=>(x is Carrier)); if( type ==1) query = query.Where(x => (x is Supplier)); if (!string.IsNullOrEmpty(name) && !string.IsNullOrEmpty(name.Trim())) query = query.Where(p => p.Name.Contains(name.Trim())); if (!string.IsNullOrEmpty(code) && !string.IsNullOrEmpty(code.Trim())) query = query.Where(p => p.Code == code.Trim()); if (!string.IsNullOrEmpty(cashbagCode) && !string.IsNullOrEmpty(cashbagCode.Trim())) query = query.Where(p => p.CashbagCode == cashbagCode.Trim()); if (startTime.HasValue) query = query.Where(p => p.CreateTime >= startTime.Value); if (endTime.HasValue) query = query.Where(p => p.CreateTime <= endTime.Value); var list = query.OrderByDescending(p => p.CreateTime).Skip(startIndex).Take(count).Select(p => new BPiaoBao.AppServices.StationContracts.SystemSetting.SystemMap.ResponseListCarrierOrSupplier { Code = p.Code, Address = p.ContactWay.Address, CashbagCode = p.CashbagCode, CashbagKey = p.CashbagKey, Contact = p.ContactWay.Contact, CreateTime = p.CreateTime, IsEnable = p.IsEnable, Name = p.Name, Tel = p.ContactWay.Tel }).ToList(); return new PagedList<StationContracts.SystemSetting.SystemMap.ResponseListCarrierOrSupplier> { Total = query.Count(), Rows = list }; } public ResponseDetailCarrier GetCarrierByCode(string code) { if (string.IsNullOrEmpty(code)) throw new CustomException(500, "商户号不能空"); var carrierModel = this.businessmanRepository.FindAll(p => p.Code == code).OfType<Carrier>().FirstOrDefault(); if (carrierModel != null) { ResponseDetailCarrier response = AutoMapper.Mapper.Map<Carrier, ResponseDetailCarrier>(carrierModel); var user = AuthManager.GetCurrentUser(); var info = _customerInfoDomainService.GetCustomerInfo(false, code); #region 对象转换 if (info != null) { response.CustomPhone = info.CustomPhone; if (info.AdvisoryQQ != null) { foreach (var data in info.AdvisoryQQ) { response.AdvisoryQQ += data.Description + "QQ:" + data.QQ + "、"; } } if (info.HotlinePhone != null) { foreach (var data in info.HotlinePhone) { response.HotlinePhone += data.Description + "电话:" + data.Phone + "、"; } } } #endregion return response; } throw new CustomException(500, "不是运营类型"); } public StationContracts.SystemSetting.SystemMap.ResponseDetailSupplier GetSupplierByCode(string code) { if (string.IsNullOrEmpty(code)) throw new CustomException(500, "商户号不能空"); var carrierModel = this.businessmanRepository.FindAll(p => p.Code == code).FirstOrDefault(); if (carrierModel is Supplier) { var response = AutoMapper.Mapper.Map<Supplier, BPiaoBao.AppServices.StationContracts.SystemSetting.SystemMap.ResponseDetailSupplier>(carrierModel as Supplier); return response; } throw new CustomException(500, "不是供应商类型"); } public void ModifyCarrier(StationContracts.SystemSetting.SystemMap.RequestCarrier carrier) { if (carrier == null) throw new CustomException(501, "输入信息不完整"); var carrierModel = this.businessmanRepository.FindAll(p => p.Code == carrier.Code).Select(p => p as Carrier).FirstOrDefault(); if (carrierModel == null) throw new CustomException(500, "查找商户不存在"); var curentUser = AuthManager.GetCurrentUser(); accountClientProxy.UpdateCompany(curentUser.CashbagCode, curentUser.CashbagKey, new BPiaoBao.Cashbag.Domain.Models.CashCompanyInfo { ClientAccount = carrier.Code, CpyName = carrier.Name, Contact = carrier.ContactWay.Contact, Moblie = carrier.ContactWay.Tel, Province = carrier.ContactWay.Province, City = carrier.ContactWay.City, Address = carrier.ContactWay.Address, PayAccount = carrierModel.CashbagCode }); carrierModel.ContactWay = AutoMapper.Mapper.Map<BPiaoBao.AppServices.StationContracts.SystemSetting.SystemMap.ContactWayDataObject, ContactWay>(carrier.ContactWay); carrierModel.Pids.Clear(); if (carrier.Pids != null && carrier.Pids.Count > 0) { carrier.Pids.ForEach(p => { carrierModel.Pids.Add(AutoMapper.Mapper.Map<BPiaoBao.AppServices.StationContracts.SystemSetting.SystemMap.PIDDataObject, PID>(p)); }); } carrierModel.Rate = carrier.Rate; carrierModel.RemoteRate = carrier.RemoteRate; carrierModel.LocalPolicySwitch = carrier.LocalPolicySwitch; carrierModel.InterfacePolicySwitch = carrier.InterfacePolicySwitch; carrierModel.ShowLocalCSCSwich = carrier.ShowLocalCSCSwich; carrierModel.ForeignRemotePolicySwich = carrier.ForeignRemotePolicySwich; carrierModel.BuyerRemotoPolicySwich = carrier.BuyerRemotoPolicySwich; unitOfWorkRepository.PersistUpdateOf(carrierModel); unitOfWork.Commit(); } public void ModifySupplier(StationContracts.SystemSetting.SystemMap.STRequestSupplier supplier) { if (supplier == null) throw new CustomException(501, "输入信息不完整"); var carrierModel = this.businessmanRepository.FindAll(p => p.Code == supplier.Code).Select(p => p as Supplier).FirstOrDefault(); if (carrierModel == null) throw new CustomException(500, "查找商户不存在"); var curentUser = AuthManager.GetCurrentUser(); accountClientProxy.UpdateCompany(curentUser.CashbagCode, curentUser.CashbagKey, new BPiaoBao.Cashbag.Domain.Models.CashCompanyInfo { ClientAccount = supplier.Code, CpyName = supplier.Name, Contact = supplier.ContactWay.Contact, Moblie = supplier.ContactWay.Tel, Province = supplier.ContactWay.Province, City = supplier.ContactWay.City, Address = supplier.ContactWay.Address, PayAccount = carrierModel.CashbagCode }); carrierModel.ContactWay = AutoMapper.Mapper.Map<BPiaoBao.AppServices.StationContracts.SystemSetting.SystemMap.ContactWayDataObject, ContactWay>(supplier.ContactWay); carrierModel.SupPids.Clear(); if (supplier.Pids != null && supplier.Pids.Count > 0) { supplier.Pids.ForEach(p => { carrierModel.SupPids.Add(AutoMapper.Mapper.Map<BPiaoBao.AppServices.StationContracts.SystemSetting.SystemMap.PIDDataObject, PID>(p)); }); } carrierModel.SupRate = supplier.SupRate; carrierModel.SupRemoteRate = supplier.SupRemoteRate; carrierModel.SupLocalPolicySwitch = supplier.SupLocalPolicySwitch; carrierModel.SupRemotePolicySwitch = supplier.SupRemotePolicySwitch; unitOfWorkRepository.PersistUpdateOf(carrierModel); unitOfWork.Commit(); } public void ResetAdminPassword(string code) { var Model = businessmanRepository.FindAll(p => p.Code == code).FirstOrDefault(); if (Model == null) throw new CustomException(404, "操作的商户号不存在!"); var op = Model.Operators.Where(p => p.IsAdmin == true).FirstOrDefault(); if (op == null) throw new CustomException(404, "未找到该商户号的管理员!"); op.Password = "123456".Md5(); unitOfWorkRepository.PersistUpdateOf(Model); unitOfWork.Commit(); } public void EnableAndDisable(string code) { var carrierModel = businessmanRepository.FindAll(p => p.Code == code).FirstOrDefault(); if (carrierModel == null) throw new CustomException(404, "操作的商户号不存在!"); carrierModel.IsEnable = !carrierModel.IsEnable; unitOfWorkRepository.PersistUpdateOf(carrierModel); unitOfWork.Commit(); } public void SendMessage(string jsonStr, string contentTemplate) { try { if (string.IsNullOrEmpty(jsonStr)) return; MatchCollection matchs = Regex.Matches(contentTemplate, @"(\[(?<val>.*?)\])+"); List<string> properties = new List<string>(); foreach (Match item in matchs) { properties.Add(item.Groups["val"].Value); } Newtonsoft.Json.Linq.JArray objList = Newtonsoft.Json.Linq.JArray.Parse(jsonStr); foreach (var item in objList) { string contentMessage = contentTemplate; foreach (string propertyName in properties) { contentMessage = contentMessage.Replace(string.Format("[{0}]", propertyName), item[propertyName].ToString()); } MessagePushManager.SendMsgByBuyerCodes(new string[] { item["Code"].ToString() }, (EnumPushCommands)Convert.ToInt32(item["command"]), contentMessage, true); } } catch (Exception e) { Logger.WriteLog(LogType.ERROR, "发送消息异常", e); } } public ResponseBusinessman GetBusinessmanByCashBagCode(string code) { var model = this.businessmanRepository.FindAll(p => p.CashbagCode == code).FirstOrDefault(); if (model == null) throw new CustomException(500, "查找商户不存在"); ResponseBusinessman rb = new ResponseBusinessman(); rb.Code = model.Code; rb.ContactName = model.ContactName; rb.Name = model.Name; rb.Phone = model.Phone; if (model.ContactWay != null) rb.ContactWay = new ContactWayDataObject { Address = model.ContactWay.Address, Contact = model.ContactWay.Contact, Tel = model.ContactWay.Tel }; return rb; } public PagedList<ResponseListBuyer> FindBuyerList(string code, string carriercode, string cashbagCode, string tel, DateTime? startTime, DateTime? endTime, int startIndex, int count) { var pagedlist = new PagedList<ResponseListBuyer>(); var query = this.businessmanRepository.FindAll(p => p is Buyer).Select(p => p as Buyer); if (!string.IsNullOrEmpty(carriercode) && !string.IsNullOrEmpty(carriercode.Trim())) query = query.Where(x => x.CarrierCode == carriercode.Trim()); if (!string.IsNullOrEmpty(code) && !string.IsNullOrEmpty(code.Trim())) query = query.Where(x => x.Code == code.Trim()); if (!string.IsNullOrEmpty(cashbagCode) && !string.IsNullOrEmpty(cashbagCode.Trim())) query = query.Where(x => x.CashbagCode == cashbagCode.Trim()); if (!string.IsNullOrWhiteSpace(tel)) query = query.Where(x => x.ContactWay.Tel == tel.Trim()); if (startTime.HasValue) query = query.Where(x => x.CreateTime >= startTime.Value); if (endTime.HasValue) query = query.Where(x => x.CreateTime <= endTime.Value); pagedlist.Total = query.Count(); query = query.OrderByDescending(x => x.CreateTime).Skip(startIndex).Take(count); pagedlist.Rows = query.ToList() .Select(x => new ResponseListBuyer { Address = x.ContactWay.Address, Code = x.Code, CarrierCode = x.CarrierCode, Contact = x.ContactWay.Contact, CreateTime = x.CreateTime, Name = x.Name, RemainCount = x.SMS.RemainCount, SendCount = x.SMS.SendCount, Tel = x.ContactWay.Tel, CashbagCode = x.CashbagCode, CashbagKey = x.CashbagKey, IsEnable = x.IsEnable, ContactName = x.ContactName, Phone = x.Phone, Plane = x.Plane }) .ToList(); return pagedlist; } #region 短信汇总报表 public PagedList<ResponseSMSSum> GetSMSSum(string code, string businessName, DateTime? startTime, DateTime? endTime, int startIndex, int count) { var query = this.businessmanRepository.FindAll(); if (!string.IsNullOrWhiteSpace(code)) query = query.Where(p => p.Code == code); if (!string.IsNullOrWhiteSpace(businessName)) query = query.Where(p => p.Name == businessName); if (startTime.HasValue) query = query.Where(p => p.BuyDetails.Where(w => w.BuyTime > startTime).Count() > 0 && p.SendDetails.Where(s => s.SendTime > startTime).Count() > 0); if (endTime.HasValue) query = query.Where(p => p.BuyDetails.Where(w => w.BuyTime <= endTime).Count() > 0 && p.SendDetails.Where(s => s.SendTime <= endTime).Count() > 0); List<ResponseSMSSum> list = new List<ResponseSMSSum>(); query.Select(p => new { p.SendDetails, p.BuyDetails, p.Name, p.Code, p.SMS.RemainCount }).ToList().AsParallel().ForEach(x => { var querysend = x.SendDetails.AsQueryable().Where(p => p.SendState == true); var querybuy = x.BuyDetails.AsQueryable().Where(p => p.BuyState == EnumPayStatus.OK); if (startTime.HasValue) { querysend = querysend.Where(p => p.SendTime > startTime); querybuy = querybuy.Where(p => p.BuyTime > startTime); } if (endTime.HasValue) { querysend = querysend.Where(p => p.SendTime <= endTime); querybuy = querybuy.Where(p => p.BuyTime <= endTime); } list.Add(new ResponseSMSSum() { Code = x.Code, BusinessName = x.Name, BuyCount = querybuy.Sum(p => p.Count), BuyMoney = querybuy.Sum(p => p.PayAmount), BuyTimes = querybuy.Count(), UseCount = querysend.Sum(p => p.SendCount), RemainCount = x.RemainCount }); }); list.Add(new ResponseSMSSum() { Code = "", BusinessName = "合计:", BuyCount = list.Sum(p => p.BuyCount), BuyMoney = list.Sum(p => p.BuyMoney), BuyTimes = list.Sum(p => p.BuyTimes), UseCount = list.Sum(p => p.UseCount), RemainCount = list.Sum(p => p.RemainCount) }); return new PagedList<ResponseSMSSum>() { Total = list.Count(), Rows = list.OrderByDescending(p => p.BuyCount).Skip(startIndex).Take(count).ToList() }; } public List<ResponseSMSSendSum> GetSMSSendSum(DateTime? startTime, DateTime? endTime) { var query = this.businessmanRepository.FindAll(); if (startTime.HasValue) query = query.Where(p => p.SendDetails.Where(s => s.SendTime > startTime).Count() > 0); if (endTime.HasValue) query = query.Where(p => p.SendDetails.Where(s => s.SendTime <= endTime).Count() > 0); List<ResponseSMSSendSum> list = new List<ResponseSMSSendSum>(); query.Select(p => new { p.SendDetails }).ToList().AsParallel().ForEach(x => { var querysend = x.SendDetails.AsQueryable().Where(p => p.SendState == true); if (startTime.HasValue) querysend = querysend.Where(p => p.SendTime > startTime); if (endTime.HasValue) querysend = querysend.Where(p => p.SendTime <= endTime); foreach (var item in querysend.ToLookup(q => q.SendTime.ToString("yyyy-MM-dd")).ToList()) { list.Add(new ResponseSMSSendSum() { Count = item.Sum(ss => ss.SendCount), DateTime = item.Key }); } }); List<ResponseSMSSendSum> listsum = new List<ResponseSMSSendSum>(); foreach (var item in list.OrderByDescending(o => o.DateTime).ToLookup(g => g.DateTime)) { listsum.Add(new ResponseSMSSendSum() { Count = item.Sum(ss => ss.Count), DateTime = item.Key }); } return listsum; } public List<ResponseSMSSaleSum> GetSMSSaleSum(DateTime? startTime, DateTime? endTime) { var query = this.businessmanRepository.FindAll(); if (startTime.HasValue) query = query.Where(p => p.BuyDetails.Where(s => s.BuyTime > startTime).Count() > 0); if (endTime.HasValue) query = query.Where(p => p.BuyDetails.Where(s => s.BuyTime <= endTime).Count() > 0); List<ResponseSMSSaleSum> list = new List<ResponseSMSSaleSum>(); query.Select(p => new { p.BuyDetails }).ToList().AsParallel().ForEach(x => { var querysend = x.BuyDetails.AsQueryable().Where(p => p.BuyState == EnumPayStatus.OK); if (startTime.HasValue) querysend = querysend.Where(p => p.BuyTime > startTime); if (endTime.HasValue) querysend = querysend.Where(p => p.BuyTime <= endTime); foreach (var item in querysend.ToLookup(q => q.BuyTime.ToString("yyyy-MM-dd")).ToList().AsParallel()) { list.Add(new ResponseSMSSaleSum() { DateTime = item.Key, AccountMoney = item.Where(w => w.PayWay == EnumPayMethod.Account).Sum(s => s.PayAmount), AccountPoundage = item.Where(w => w.PayWay == EnumPayMethod.Account).Sum(s => s.PayFee), CreditMoney = item.Where(w => w.PayWay == EnumPayMethod.Credit).Sum(s => s.PayAmount), CreditPoundage = item.Where(w => w.PayWay == EnumPayMethod.Credit).Sum(s => s.PayFee), TenPayMoney = item.Where(w => w.PayWay == EnumPayMethod.Bank || w.PayWay == EnumPayMethod.TenPay).Sum(s => s.PayAmount), TenPayPoundage = item.Where(w => w.PayWay == EnumPayMethod.Bank || w.PayWay == EnumPayMethod.TenPay).Sum(s => s.PayFee), AliPayMoney = item.Where(w => w.PayWay == EnumPayMethod.AliPay).Sum(s => s.PayAmount), AliPayPoundage = item.Where(w => w.PayWay == EnumPayMethod.AliPay).Sum(s => s.PayFee), TotalMoney = item.Sum(s => s.PayAmount), TotalPoundage = item.Sum(s => s.PayFee) }); } }); List<ResponseSMSSaleSum> listsum = new List<ResponseSMSSaleSum>(); foreach (var item in list.OrderByDescending(o => o.DateTime).ToLookup(g => g.DateTime)) { listsum.Add(new ResponseSMSSaleSum() { DateTime = item.Key, AccountMoney = item.Sum(s => s.AccountMoney), AccountPoundage = item.Sum(s => s.AccountPoundage), CreditMoney = item.Sum(s => s.CreditMoney), CreditPoundage = item.Sum(s => s.CreditPoundage), AliPayMoney = item.Sum(s => s.AliPayMoney), AliPayPoundage = item.Sum(s => s.AliPayPoundage), TenPayMoney = item.Sum(s => s.TenPayMoney), TenPayPoundage = item.Sum(s => s.TenPayPoundage), TotalMoney = item.Sum(s => s.TotalMoney), TotalPoundage = item.Sum(s => s.TotalPoundage) }); } listsum.Add(new ResponseSMSSaleSum() { DateTime = "合计:", AccountMoney = listsum.Sum(s => s.AccountMoney), AccountPoundage = listsum.Sum(s => s.AccountPoundage), CreditMoney = listsum.Sum(s => s.CreditMoney), CreditPoundage = listsum.Sum(s => s.CreditPoundage), AliPayMoney = listsum.Sum(s => s.AliPayMoney), AliPayPoundage = listsum.Sum(s => s.AliPayPoundage), TenPayMoney = listsum.Sum(s => s.TenPayMoney), TenPayPoundage = listsum.Sum(s => s.TenPayPoundage), TotalMoney = listsum.Sum(s => s.TotalMoney), TotalPoundage = listsum.Sum(s => s.TotalPoundage) }); return listsum; } #endregion #region OPEN票扫描信息 public PagedList<ResponseOPENScan> GetOpenScanList(int startIndex, int count) { var currentuser = AuthManager.GetCurrentUser(); var query = openScanRepository.FindAllNoTracking().Where(p => p.Operator == currentuser.OperatorAccount); var list = query.OrderByDescending(o => o.CreateTime).Skip((startIndex - 1) * count).Take(count).ToList(); return new PagedList<ResponseOPENScan>() { Total = list.Count(), Rows = AutoMapper.Mapper.Map<List<OPENScan>, List<ResponseOPENScan> >(list) }; } public void AddOpenScanInfo(RequestOPENScan OpenScan) { var model = AutoMapper.Mapper.Map<RequestOPENScan, OPENScan>(OpenScan); model.CreateTime = DateTime.Now; model.Operator = AuthManager.GetCurrentUser().OperatorAccount; model.State = EnumOPEN.NoScan; this.unitOfWorkRepository.PersistCreationOf(model); this.unitOfWork.Commit(); } public PIDDataObject GetCarrierPid(string code) { if (string.IsNullOrEmpty(code)) throw new CustomException(500, "商户号不能空"); var carrierModel = this.businessmanRepository.FindAll(p => p.Code == code && p is Carrier).FirstOrDefault(); return AutoMapper.Mapper.Map<PID, PIDDataObject>((carrierModel as Carrier).Pids.FirstOrDefault()); } #endregion public Tuple<string, byte[]> DownloadOpenFileByName(string fileName) { string path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Export", fileName); if (!File.Exists(path)) return Tuple.Create<string, byte[]>("文件不存在", null); StreamReader sr = new StreamReader(path); Stream stream = sr.BaseStream; byte[] resultStream = new byte[stream.Length]; stream.Read(resultStream, 0, resultStream.Length); stream.Seek(0, SeekOrigin.Begin); sr.Close(); return Tuple.Create<string, byte[]>(string.Empty, resultStream); } [ExtOperationInterceptor("控台修改客服中心")] public void SetCustomerInfo(CustomerDto customerInfo) { if (customerInfo == null) { throw new CustomException(30001, "客服中心信息不可为空。"); } //if (!customerInfo.CustomPhone.IsMatch(StringExpend.PhonePattern)) //{ // throw new CustomException(30001, customerInfo.HotlinePhone + "不是合法的电话。"); //} //if (customerInfo.AdvisoryQQ.Count(c => string.IsNullOrWhiteSpace(c.Key) || string.IsNullOrWhiteSpace(c.Value)) > 0) // throw new CustomException(30001, "QQ及QQ描述均必须填写。"); //if (customerInfo.HotlinePhone.Count(c => string.IsNullOrWhiteSpace(c.Key) || string.IsNullOrWhiteSpace(c.Value)) > 0) // throw new CustomException(30001, "电话及电话描述均必须填写。"); CustomerInfo info = new CustomerInfo(); info.AdvisoryQQ = new List<QQInfo>(); info.HotlinePhone = new List<PhoneInfo>(); info.CustomPhone = customerInfo.CustomPhone; if (customerInfo.AdvisoryQQ != null) { foreach (var data in customerInfo.AdvisoryQQ) { info.AdvisoryQQ.Add(new QQInfo { Description = data.Key, QQ = data.Value }); } } if (customerInfo.HotlinePhone != null) { foreach (var data in customerInfo.HotlinePhone) { info.HotlinePhone.Add(new PhoneInfo { Description = data.Key, Phone = data.Value }); } } _customerInfoDomainService.SetStationCustomerInfo(info); } [ExtOperationInterceptor("控台获取客服中心")] public CustomerDto GetStationCustomerInfo() { var user = AuthManager.GetCurrentUser(); var info = _customerInfoDomainService.GetCustomerInfo(false, null); #region 对象转换 CustomerDto customerDto = new CustomerDto(); customerDto.AdvisoryQQ = new List<KeyAndValueDto>(); customerDto.HotlinePhone = new List<KeyAndValueDto>(); if (info != null) { customerDto.CustomPhone = info.CustomPhone; if (info.AdvisoryQQ != null) { foreach (var data in info.AdvisoryQQ) { customerDto.AdvisoryQQ.Add(new KeyAndValueDto { Key = data.Description, Value = data.QQ }); } } if (info.HotlinePhone != null) { foreach (var data in info.HotlinePhone) { customerDto.HotlinePhone.Add(new KeyAndValueDto { Key = data.Description, Value = data.Phone }); } } } #endregion return customerDto; } public PagedList<SupplierDataObj> FindSupplier(string code, string carriercode, DateTime? startTime, DateTime? endTime, int startIndex, int count) { //var query = this.businessmanRepository.FindAll(p => (p is Supplier)); //if (!string.IsNullOrEmpty(code) && !string.IsNullOrEmpty(code.Trim())) // query = query.Where(p => p.Code == code.Trim()); //if (!string.IsNullOrEmpty(carriercode) && !string.IsNullOrEmpty(carriercode.Trim())) // query = query.Where(p => p.CashbagCode == carriercode.Trim()); //if (startTime.HasValue) // query = query.Where(p => p.CreateTime >= startTime.Value); //if (endTime.HasValue) // query = query.Where(p => p.CreateTime <= endTime.Value); //var list = query.OrderByDescending(p => p.CreateTime).Skip(startIndex).Take(count).Select(p => new BPiaoBao.AppServices.StationContracts.SystemSetting.SystemMap.ResponseListCarrier //{ // Code = p.Code, // Rate = p.ra // Address = p.ContactWay.Address, // CashbagCode = p.CashbagCode, // CashbagKey = p.CashbagKey, // Contact = p.ContactWay.Contact, // CreateTime = p.CreateTime, // IsEnable = p.IsEnable, // Name = p.Name, // Tel = p.ContactWay.Tel //}).ToList(); //return new PagedList<StationContracts.SystemSetting.SystemMap.ResponseListCarrier> //{ // Total = query.Count(), // Rows = list //}; throw new NotImplementedException(); } public void ModifySupplierSwitch(SupplierDataObj supplierDto) { throw new NotImplementedException(); } public SupplierDataObj FindSupplierInfoByCode(string code) { throw new NotImplementedException(); } public IList<StationBuyerGroupDto> SearchStationBuyerGroups() { var datas = _stationBuyGroupDomainService.QueryStationBuyGroups().ToList(); IList<StationBuyerGroupDto> records = new List<StationBuyerGroupDto>(); foreach (var data in datas) { StationBuyerGroupDto record = new StationBuyerGroupDto(); record.ID = data.ID; record.GroupName = data.GroupName; record.Description = data.Description; record.Color = data.Color; record.LastOperatorUser = data.LastOperatorUser; record.LastOperatTime = data.LastOperatTime; records.Add(record); } return records; } public void SetBuyerToStationBuyerGroup(SetBuyerToStationBuyerGroupRequest request) { _stationBuyGroupDomainService.SetBuyerToGroup(request.BuyerCode, request.GroupID); } public void DeleteStationBuyreGroup(string groupId) { _stationBuyGroupDomainService.DeleteStationBuyGroup(groupId); } public void SetStationBuyerGroupInfo(SetStationBuyerGroupInfoRequest dto) { StationBuyGroup group = new StationBuyGroup(); group.ID = dto.ID; group.GroupName = dto.GroupName; group.Description = dto.Description; group.Color = dto.Color; _stationBuyGroupDomainService.UpdateStationBuyGroup(group, AuthManager.GetCurrentUser().OperatorAccount); //_stationBuyGroupDomainService.UpdateStationBuyGroup() } public void AddStationBuyerGroup(AddStationBuyerGroupRequest request) { StationBuyGroup group = new StationBuyGroup(); group.GroupName = request.GroupName; group.Description = request.Description; group.Color = request.Color; _stationBuyGroupDomainService.AddStationBuyGroup(group, AuthManager.GetCurrentUser().OperatorAccount); } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using DevExpress.XtraEditors; using TLF.Framework.Config; using TLF.Framework.Authentication; using TLF.Framework.Localization; namespace TLF.Framework.BaseFrame { /// <summary> /// /// </summary> /// <remarks> /// 2009-04-27 최초생성 : 황준혁 /// 변경내역 /// /// </remarks> public partial class PopupFrame : DevExpress.XtraEditors.XtraForm { /////////////////////////////////////////////////////////////////////////////////////////////// // Constructor & Global Instance /////////////////////////////////////////////////////////////////////////////////////////////// #region :: 생성자 :: /// <summary> /// 생성자 /// </summary> public PopupFrame() { InitializeComponent(); } #endregion /////////////////////////////////////////////////////////////////////////////////////////////// // Properties /////////////////////////////////////////////////////////////////////////////////////////////// #region :: CurrentUser :: 현재 사용자의 정보를 설정합니다. /// <summary> /// 현재 사용자의 정보를 설정합니다. /// </summary> [Category(AppConfig.CONTROLCATEGORY)] [Description("현재 사용자의 정보를 설정합니다."), Browsable(false)] public UserInformation CurrentUser { get { return (Owner as MainFrame).CurrentUser; } } #endregion #region :: localizer :: 다국어 지원에 사용할 Localizer /// <summary> /// 다국어 지원에 사용할 Localizer /// </summary> [Category(AppConfig.CONTROLCATEGORY)] [Description("다국어 지원에 사용할 Localizer"), Browsable(false)] public Localizer localizer { get { return (Owner as MainFrame).localizer; } } #endregion } }
using System; using System.Collections.Generic; using System.Text; namespace FixMyShip.Test.Exeptions { public class AnswerNotFoundException : Exception { public string Messages = "Answer Not Found"; public AnswerNotFoundException(string message) { Messages = message; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Channel.Mine.IMDB.Parsers { public class ReleaseDateParser : Abstraction.BaseFileParser<Collections.MediaCollection> { public ReleaseDateParser(params String[] fileNames) : base(fileNames) { } public override void DoAction(Collections.MediaCollection item) { throw new NotImplementedException(); } } }
using System; using System.Collections.Generic; namespace userDashboard.Models { public class Message : BaseEntity { public int MessageId {get;set;} public string MessageData {get;set;} public DateTime Date {get;set;} public int UserId {get;set;} public User User {get;set;} public List<Comment> Comments{get;set;} public Message() { Comments = new List<Comment>(); } } }
using System; using Tsu.CLI.Commands; using Microsoft.CodeAnalysis; namespace Tsu.CLI.SourceGenerator.CommandManager { public class CommonSymbols { /// <summary> /// The <see cref="CommandAttribute" /> type symbol. /// </summary> public INamedTypeSymbol Tsu_CLI_Commands_CommandAttribute { get; } /// <summary> /// The <see cref="HelpDescriptionAttribute" /> type symbol. /// </summary> public INamedTypeSymbol Tsu_CLI_Commands_HelpDescriptionAttribute { get; } /// <summary> /// The <see cref="HelpExampleAttribute" /> type symbol. /// </summary> public INamedTypeSymbol Tsu_CLI_Commands_HelpExampleAttribute { get; } /// <summary> /// The <see cref="JoinRestOfArgumentsAttribute" /> type symbol. /// </summary> public INamedTypeSymbol Tsu_CLI_Commands_JoinRestOfArgumentsAttribute { get; } /// <summary> /// The <see cref="RawInputAttribute" /> type symbol. /// </summary> public INamedTypeSymbol Tsu_CLI_Commands_RawInputAttribute { get; } /// <summary> /// The <see cref="Type" /> type symbol. /// </summary> public INamedTypeSymbol System_Type { get; } /// <summary> /// The <see cref="String" /> type symbol. /// </summary> public INamedTypeSymbol System_String { get; } /// <summary> /// The <see cref="String.IsNullOrWhiteSpace(String)" /> method symbol. /// </summary> public IMethodSymbol System_String__IsNullOrWhiteSpaceString { get; } /// <summary> /// The <see cref="String.Trim()" /> method symbol. /// </summary> public IMethodSymbol System_String__Trim { get; } /// <summary> /// The <see cref="String.IndexOf(Char)" /> method symbol. /// </summary> public IMethodSymbol System_String__IndexOfChar { get; } /// <summary> /// The <see cref="String.IndexOf(Char, Int32)" /> method symbol. /// </summary> public IMethodSymbol System_String__IndexOfCharInt32 { get; } /// <summary> /// The <see cref="String.Substring(Int32, Int32)" /> method symbol. /// </summary> public IMethodSymbol System_String__SubstringInt32Int32 { get; } /// <summary> /// The <see cref="Enum" /> type symbol. /// </summary> public INamedTypeSymbol System_Enum { get; } /// <summary> /// The <see cref="Enum.Parse(Type, String)" /> method symbol. /// </summary> public IMethodSymbol System_Enum__ParseTypeString { get; } /// <summary> /// The <see cref="Int32" /> type symbol. /// </summary> public INamedTypeSymbol System_Int32 { get; } public CommonSymbols ( Compilation compilation ) { this.Tsu_CLI_Commands_CommandAttribute = getSymbol ( typeof ( CommandAttribute ) ); this.Tsu_CLI_Commands_HelpDescriptionAttribute = getSymbol ( typeof ( HelpDescriptionAttribute ) ); this.Tsu_CLI_Commands_HelpExampleAttribute = getSymbol ( typeof ( HelpExampleAttribute ) ); #pragma warning disable CS0618 // Type or member is obsolete this.Tsu_CLI_Commands_JoinRestOfArgumentsAttribute = getSymbol ( typeof ( JoinRestOfArgumentsAttribute ) ); #pragma warning restore CS0618 // Type or member is obsolete this.Tsu_CLI_Commands_RawInputAttribute = getSymbol ( typeof ( RawInputAttribute ) ); this.System_Type = getSymbol ( typeof ( Type ) ); this.System_String = compilation.GetSpecialType ( SpecialType.System_String ); this.System_String__IsNullOrWhiteSpaceString = getMethodSymbol ( this.System_String, nameof ( String.IsNullOrWhiteSpace ), true, this.System_String ); this.System_String__Trim = getMethodSymbol ( this.System_String, nameof ( String.Trim ), false ); this.System_String__IndexOfChar = getMethodSymbol ( this.System_String, nameof ( String.IndexOf ), false, SpecialType.System_Char ); this.System_String__IndexOfCharInt32 = getMethodSymbol ( this.System_String, nameof ( String.IndexOf ), false, SpecialType.System_Char, this.System_Int32 ); this.System_String__SubstringInt32Int32 = getMethodSymbol ( this.System_String, nameof ( String.Substring ), false, this.System_Int32, this.System_Int32 ); this.System_Enum = compilation.GetSpecialType ( SpecialType.System_Enum ); this.System_Enum__ParseTypeString = getMethodSymbol ( this.System_Enum, "Parse", true, this.System_Type, this.System_String ); this.System_Int32 = compilation.GetSpecialType ( SpecialType.System_Int32 ); INamedTypeSymbol getSymbol ( Type type ) => compilation.GetTypeByMetadataName ( type.FullName ) ?? throw new InvalidOperationException ( $"{type.FullName} type symbol not found." ); static IMethodSymbol getMethodSymbol ( ITypeSymbol typeSymbol, String name, Boolean isStatic, params Object[] paramsTypes ) => Utilities.GetMethodSymbol ( typeSymbol, name, isStatic, paramsTypes ) ?? throw new InvalidOperationException ( $"{typeSymbol.ToDisplayString ( SymbolDisplayFormat.CSharpErrorMessageFormat )}.{name} method symbol not found." ); } } }
using System; using System.Windows.Forms; using Grimoire.Networking; namespace Grimoire.UI { public partial class PacketTampererForm : Form { public static PacketTampererForm Instance { get; } = new PacketTampererForm(); private PacketTampererForm() { InitializeComponent(); MainForm.Instance.SizeChanged += Root_SizeChanged; MainForm.Instance.VisibleChanged += Root_VisibleChanged; } private void Root_SizeChanged(object sender, EventArgs e) { FormWindowState state = ((Form)sender).WindowState; if (state != FormWindowState.Maximized) WindowState = state; } private void Root_VisibleChanged(object sender, EventArgs e) { Visible = ((Form)sender).Visible; } private void PacketTamperer_FormClosing(object sender, FormClosingEventArgs e) { if (e.CloseReason == CloseReason.UserClosing) { e.Cancel = true; Hide(); } } private void chkFromServer_CheckedChanged(object sender, EventArgs e) { if (chkFromServer.Checked) Proxy.Instance.ReceivedFromServer += ReceivedFromServer; else Proxy.Instance.ReceivedFromServer -= ReceivedFromServer; } private void chkFromClient_CheckedChanged(object sender, EventArgs e) { if (chkFromClient.Checked) Proxy.Instance.ReceivedFromClient += ReceivedFromClient; else Proxy.Instance.ReceivedFromClient -= ReceivedFromClient; } private async void btnToClient_Click(object sender, EventArgs e) { if (!string.IsNullOrEmpty(txtSend.Text)) { btnToClient.Enabled = false; await Proxy.Instance.SendToClientTask(txtSend.Text); btnToClient.Enabled = true; } } private async void btnToServer_Click(object sender, EventArgs e) { if (!string.IsNullOrEmpty(txtSend.Text)) { btnToServer.Enabled = false; await Proxy.Instance.SendToServerTask(txtSend.Text); btnToServer.Enabled = true; } } private void ReceivedFromClient(Networking.Message message) { txtSend.Invoke(new Action(() => Append("From client: " + message.RawContent))); } private void ReceivedFromServer(Networking.Message message) { txtSend.Invoke(new Action(() => Append("From server: " + message.RawContent))); } private void Append(string text) { txtReceive.AppendText(text + Environment.NewLine + Environment.NewLine); } } }
using Docker.DotNet.Models; using MarsQA_1.Pages; using OpenQA.Selenium; using OpenQA.Selenium.Chrome; using System; using System.Collections.Generic; using System.Text; using TechTalk.SpecFlow; namespace MarsQA_1.StepDefination { [Binding] public sealed class Login { Mars_Login _Login = new Mars_Login(); [When(@"Click on the Login button")] public void WhenClickOnTheLoginButton() { _Login.ClickIn(); } [Then(@"I should be able to login successfully with valid credenatial")] public void ThenIShouldBeAbleToLoginSuccessfullyWithValidCredenatial() { _Login.SignIn(); } //[When(@"Click on Login button")] //public void WhenClickOnLoginButton() //{ // Mars_Login _login = new Mars_Login(); // _login.ClickIn(driver); //} //[Then(@"I should be able to login succesfully with valid creadential")] //public void ThenIShouldBeAbleToLoginSuccesfullyWithValidCreadential() //{ // Mars_Login _login = new Mars_Login(); // _login.SignIn(driver); //} } }
using System; using System.Windows.Input; using System.Windows.Threading; using Caliburn.Micro; using Frontend.Core.Model.Interfaces; using Action = System.Action; namespace Frontend.Core.Commands { /// <summary> /// Base class for various commands /// </summary> public abstract class CommandBase : DispatcherObject, ICommand { /// <summary> /// Initializes a new instance of the <see cref="CommandBase" /> class. /// </summary> /// <param name="eventAggregator">The event aggregator</param> protected CommandBase(IEventAggregator eventAggregator) : this(eventAggregator, null) { } /// <summary> /// Initializes a new instance of the <see cref="CommandBase" /> class. /// </summary> /// <param name="eventAggregator">The event aggregator</param> /// <param name="options">The object holding all converter preferences set by the user</param> protected CommandBase(IEventAggregator eventAggregator, IConverterOptions options) { EventAggregator = eventAggregator; Options = options; } protected IEventAggregator EventAggregator { get; private set; } protected IConverterOptions Options { get; private set; } /// <summary> /// Occurs when changes occur that affect whether or not the command should execute. /// <remarks> /// A quite inconvenient canexecute handler, as it tends to trigger several canexecute checks a second. Not /// enough to cause performance problems, but hardly optimal /// </remarks> /// </summary> public event EventHandler CanExecuteChanged { add { CommandManager.RequerySuggested += value; } remove { CommandManager.RequerySuggested -= value; } } /// <summary> /// Defines the method that determines whether the command can execute in its current state. /// </summary> /// <param name="parameter"> /// Data used by the command. If the command does not require data to be passed, this object can /// be set to null. /// </param> /// <returns> /// true if this command can be executed; otherwise, false. /// </returns> public bool CanExecute(object parameter) { return OnCanExecute(parameter); } /// <summary> /// Defines the method to be called when the command is invoked. /// </summary> /// <param name="parameter"> /// Data used by the command. If the command does not require data to be passed, this object can /// be set to null. /// </param> public void Execute(object parameter) { OnExecute(parameter); } /// <summary> /// Called when [can execute]. /// </summary> /// <param name="parameter">The parameter.</param> /// <returns></returns> protected virtual bool OnCanExecute(object parameter) { return true; } /// <summary> /// Called when [execute]. /// </summary> /// <param name="parameter">The parameter.</param> protected virtual void OnExecute(object parameter) { } /// <summary> /// Method used to marshall actions over to the UI thread if they're on a different thread to begin with. Required if /// the action updates UI controls /// </summary> /// <param name="action">The action.</param> /// <param name="priority">The priority.</param> protected void MarshallMethod(Action action, DispatcherPriority priority) { if (!Dispatcher.CheckAccess()) { Dispatcher.Invoke(action, priority); return; } action(); } } }
using MooshakPP.Models.Entities; namespace MooshakPP.Models.ViewModels { public class DescriptionViewModel { public Milestone milestone { get; set; } public IndexViewModel indexView { get; set; } } }
using UnityEngine; using UnityEngine.UI; using UnityEngine.SceneManagement; using System.Collections; public class EndGameScript : MonoBehaviour { private bool playerInfoSet; private Vector3 destination; private Camera cam; private GameObject player; public float speed; private bool moving; private float playerSpeed; public Scores scores; public Canvas scoreCanvas; public DisplayScores displayScoresScript; //the rate the player will move faster than the camera; public float playerSpeedIncrement; void Start(){ Messenger.AddListener<Scores,GameObject> ("gameOver", gameOver); } void gameOver(Scores score, GameObject player){ PlayEndGame (player); setScore (score); } void Update(){ if (moving) { playerSpeed += playerSpeedIncrement; player.transform.position = Vector3.MoveTowards(player.transform.position, destination,playerSpeed); cam.transform.position = Vector3.MoveTowards(cam.transform.position, destination,speed); Bounds bounds = CameraExtensions.OrthographicBounds (cam); if (cam.transform.position.y + bounds.size.y + 10f < player.transform.position.y) { moving = false; displayScores (); } } } private void PlayEndGame(GameObject player){ playerSpeed = speed; this.player = player; Collider2D[] colliders = GameObject.FindObjectsOfType<Collider2D> (); foreach (Collider2D collider2d in colliders) { collider2d.enabled = false; } player.GetComponent<Rigidbody2D> ().isKinematic = true; cam = Camera.main; destination = new Vector3 (player.transform.position.x, player.transform.position.y + 100, -10); moving = true; } private void setScore(Scores scores){ this.scores = scores; } private void displayScores(){ displayScoresScript.setInfo (scores); scoreCanvas.gameObject.SetActive (true); displayScoresScript.showLine (); } public void onClick (){ SceneManager.LoadScene (0); } }
using CSharpFunctionalExtensions; using EnsureThat; using L7.Domain; using MediatR; namespace L7.Business { public class EditShoppingCartCommandHandler : RequestHandler<EditShoppingCartCommand, Result> { private readonly IShopingCartRepository repository; public EditShoppingCartCommandHandler(IShopingCartRepository repository) { EnsureArg.IsNotNull(repository); this.repository = repository; } protected override Result Handle(EditShoppingCartCommand request) { EnsureArg.IsNotNull(request); var existingShoppingCartOrNothing = repository.GetById(request.Id); return existingShoppingCartOrNothing.ToResult(ErrorMessages.ShoppingCartNotFound) .OnSuccess(s => UpdateShoppingCart(s, request)); } private void UpdateShoppingCart(Domain.ShoppingCart shoppingCart, EditShoppingCartCommand request) { shoppingCart.Update(request.Model.Description); repository.Update(shoppingCart); repository.Save(); } } }
using UnityEngine; using UnityEngine.Tilemaps; using System.Collections.Generic; public class AttackRange : MonoBehaviour { [SerializeField] Tilemap _attackRange; [SerializeField] TileBase _attackbleTile; private GameObject[] _playerObjects; private PlayerBehaviour _playerBehave; private List<PlayerBehaviour> _players; private GameObject[] _enemyObjects; private EnemyBehaviour _enemyBehave; private List<EnemyBehaviour> _enemys; void Start() { _playerObjects = GameObject.FindGameObjectsWithTag("Player"); _players = new List<PlayerBehaviour>(); foreach(var player in _playerObjects) { _players.Add(player.GetComponent<PlayerBehaviour>()); } _enemyObjects = GameObject.FindGameObjectsWithTag("Enemy"); _enemys = new List<EnemyBehaviour>(); foreach (var enemy in _enemyObjects) { _enemys.Add(enemy.GetComponent<EnemyBehaviour>()); } } void Update() { foreach(var player in _players) { foreach (var enemy in _enemys) { Vector3Int tempPlayerPos = FloorToPosition(player.transform.position); Vector3Int tempEnemyPos = FloorToPosition(enemy.transform.position); tempEnemyPos.z = tempPlayerPos.z; ShowAtackbleTile(tempPlayerPos, tempEnemyPos, player.attackRange); } } } //攻撃可能のマスの可視化 void ShowAtackbleTile(Vector3Int unitPos,Vector3Int enemyPos, int maxStep) { CheckAtackble(unitPos, enemyPos, maxStep + 1); } //攻撃できるかのチェック void CheckAtackble(Vector3Int pos, Vector3Int epos, int remainStep) { foreach (var player in _players) { if (player.GetAttackFlag) { if (epos == pos)//攻撃範囲に敵がいるかどうか { _attackRange.SetTile(pos, _attackbleTile);//攻撃可能範囲表示 } --remainStep; if (remainStep == 0) return; } else { _attackRange.SetTile(pos, null);//攻撃可能範囲非表示 --remainStep; if (remainStep == 0) return; } //再帰してremainStep分チェック&表示or非表示 CheckAtackble(pos + Vector3Int.up, epos, remainStep); CheckAtackble(pos + Vector3Int.left, epos, remainStep); CheckAtackble(pos + Vector3Int.right, epos, remainStep); CheckAtackble(pos + Vector3Int.down, epos, remainStep); } } //float型の小数点以下を切り捨て、int(整数)型に private Vector3Int FloorToPosition(Vector3 position) { Vector3Int afterPosition = new Vector3Int( Mathf.FloorToInt(position.x), Mathf.FloorToInt(position.y), Mathf.FloorToInt(position.z)); return afterPosition; } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace NoNameTask.Models { public class MenyItem { public MenyItem() { MenyItemIns =new HashSet<MenyItemIn>(); } public int Id { get; set; } public string Name { get; set; } public string PagePath { get; set; } public ICollection<MenyItemIn> MenyItemIns { get; set; } } }
using KPITV.Models; using KPITV.Models.AccountViewModels; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Mvc; using System.Threading.Tasks; namespace KPITV.Controllers { [Authorize] public class AccountController : Controller { readonly UserManager<ApplicationUser> userManager; readonly SignInManager<ApplicationUser> signInManager; public AccountController( UserManager<ApplicationUser> userManager, SignInManager<ApplicationUser> signInManager) { this.userManager = userManager; this.signInManager = signInManager; } [HttpGet] [AllowAnonymous] public IActionResult LogIn() { return View(); } [HttpGet] [AllowAnonymous] public IActionResult Register() { return View(); } [HttpPost] [AllowAnonymous] [ValidateAntiForgeryToken] public async Task<IActionResult> Register(RegisterViewModel model) { if (ModelState.IsValid) { var user = new ApplicationUser { UserName = model.Email, Email = model.Email }; var result = await userManager.CreateAsync(user, model.Password); if (result.Succeeded) { await signInManager.SignInAsync(user, isPersistent: true); return RedirectToAction(nameof(HomeController.Index), "Home"); } } return View(model); } [HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> LogOff() { await signInManager.SignOutAsync(); return RedirectToAction(nameof(HomeController.Index), "Home"); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class Spawner : MonoBehaviour { //asteroid = 0, spacecapsule = 1 public GameObject[] prefabList = new GameObject[2]; private List<GameObject> asteroidsAndCapsules = new List<GameObject>(); public static float radius = 12f; public float velocityScale = 1f; public float respawnTime = 3f; // Start is called before the first frame update void Start() { StartCoroutine(wave()); } // Update is called once per frame void Update() { //if(Input.GetMouseButtonDown(0)) //{ // SpawnRandomObject(); //} //List<GameObject> temp = new List<GameObject>(asteroidsAndCapsules); //asteroidsAndCapsules.Clear(); //while(temp.Count > 0) //{ // GameObject obj = temp[0]; // temp.RemoveAt(0); // else // { // asteroidsAndCapsules.Add(obj); // } //} } void SpawnRandomObject() { float randomAngle = Random.Range(0f, 2* Mathf.PI); //float shiftX = Random.Range(-6f, 2f); //shiftX = shiftX > -2f ? shiftX + 4f : shiftX; //float shiftY = Random.Range(-3f, 1f); //shiftY = shiftY > -1f ? shiftY + 2f : shiftY; float randomX = Mathf.Cos(randomAngle) * radius; float randomY = Mathf.Sin(randomAngle) * radius; Vector3 randomPos = new Vector3(randomX, randomY, 0); Vector3 randomDestination = Random.insideUnitCircle * 4f; GameObject instanciatedObject; float rand = Random.Range(0f, 1f); if(rand < 0.9f) { //asteroid instanciatedObject = Instantiate(prefabList[0], randomPos, Quaternion.identity); //instanciatedObject.transform.localScale *= Random.Range(0.5f, 1.5f); } else { //capsule instanciatedObject = Instantiate(prefabList[1], randomPos, Quaternion.identity); } //asteroidsAndCapsules.Add(instanciatedObject); Rigidbody2D rb = instanciatedObject.GetComponent<Rigidbody2D>(); rb.angularVelocity = Random.Range(-45f, 45f); rb.velocity = (randomDestination - randomPos) / (randomDestination - randomPos).magnitude * (velocityScale + Random.Range(0f,1f)); } private void OnDrawGizmos() { Gizmos.color = Color.magenta; Gizmos.DrawWireSphere(this.transform.position, radius); } IEnumerator wave() { while(true) { yield return new WaitForSeconds(respawnTime); SpawnRandomObject(); } } }
/* * Copyright 2019 Adobe * All Rights Reserved. * * NOTICE: Adobe permits you to use, modify, and distribute this file in * accordance with the terms of the Adobe license agreement accompanying * it. If you have received this file from a source other than Adobe, * then your use, modification, or distribution of it requires the prior * written permission of Adobe. */ using System; using System.IO; using log4net.Repository; using log4net; using log4net.Config; using System.Reflection; using Adobe.PDFServicesSDK; using Adobe.PDFServicesSDK.auth; using Adobe.PDFServicesSDK.pdfops; using Adobe.PDFServicesSDK.io; using Adobe.PDFServicesSDK.options; using Adobe.PDFServicesSDK.exception; /// <summary> /// This sample illustrates how to combine specific pages of multiple PDF files into a single PDF file. /// <para/> /// Note that the SDK supports combining upto 20 files in one operation. /// <para/> /// Refer to README.md for instructions on how to run the samples. /// </summary> namespace CombinePDFWithPageRanges { class Program { private static readonly ILog log = LogManager.GetLogger(typeof(Program)); static void Main() { //Configure the logging ConfigureLogging(); try { // Initial setup, create credentials instance. Credentials credentials = Credentials.ServicePrincipalCredentialsBuilder() .WithClientId(Environment.GetEnvironmentVariable("PDF_SERVICES_CLIENT_ID")) .WithClientSecret(Environment.GetEnvironmentVariable("PDF_SERVICES_CLIENT_SECRET")) .Build(); //Create an ExecutionContext using credentials and create a new operation instance. ExecutionContext executionContext = ExecutionContext.Create(credentials); CombineFilesOperation combineFilesOperation = CombineFilesOperation.CreateNew(); // Create a FileRef instance from a local file. FileRef firstFileToCombine = FileRef.CreateFromLocalFile(@"combineFileWithPageRangeInput1.pdf"); PageRanges pageRangesForFirstFile = GetPageRangeForFirstFile(); // Add the first file as input to the operation, along with its page range. combineFilesOperation.AddInput(firstFileToCombine, pageRangesForFirstFile); // Create a second FileRef instance using a local file. FileRef secondFileToCombine = FileRef.CreateFromLocalFile(@"combineFileWithPageRangeInput2.pdf"); PageRanges pageRangesForSecondFile = GetPageRangeForSecondFile(); // Add the second file as input to the operation, along with its page range. combineFilesOperation.AddInput(secondFileToCombine, pageRangesForSecondFile); // Execute the operation. FileRef result = combineFilesOperation.Execute(executionContext); //Generating a file name String outputFilePath = CreateOutputFilePath(); // Save the result to the specified location. result.SaveAs(Directory.GetCurrentDirectory() + outputFilePath); } catch (ServiceUsageException ex) { log.Error("Exception encountered while executing operation", ex); } catch (ServiceApiException ex) { log.Error("Exception encountered while executing operation", ex); } catch(SDKException ex) { log.Error("Exception encountered while executing operation", ex); } catch(IOException ex) { log.Error("Exception encountered while executing operation", ex); } catch(Exception ex) { log.Error("Exception encountered while executing operation", ex); } } private static PageRanges GetPageRangeForSecondFile() { // Specify which pages of the second file are to be included in the combined file. PageRanges pageRangesForSecondFile = new PageRanges(); // Add all pages including and after page 5. pageRangesForSecondFile.AddAllFrom(5); return pageRangesForSecondFile; } private static PageRanges GetPageRangeForFirstFile() { // Specify which pages of the first file are to be included in the combined file. PageRanges pageRangesForFirstFile = new PageRanges(); // Add page 2. pageRangesForFirstFile.AddSinglePage(2); // Add page 3. pageRangesForFirstFile.AddSinglePage(3); // Add pages 5 to 7. pageRangesForFirstFile.AddRange(5, 7); return pageRangesForFirstFile; } static void ConfigureLogging() { ILoggerRepository logRepository = LogManager.GetRepository(Assembly.GetEntryAssembly()); XmlConfigurator.Configure(logRepository, new FileInfo("log4net.config")); } //Generates a string containing a directory structure and file name for the output file. public static string CreateOutputFilePath() { String timeStamp = DateTime.Now.ToString("yyyy'-'MM'-'dd'T'HH'-'mm'-'ss"); return ("/output/combine" + timeStamp + ".pdf"); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace HealthCloud.DBModel { /// <summary> /// 模版参数 /// </summary> public class TemplateInfo { public string templateId { get; set; } public string templateName { get; set; } public string docotorMID { get; set; } public string teamMID { get; set; } public string templateMemo { get; set; } //public int templateType { get; set; } public int applicationType { get; set; } public String createName { get; set; } public DateTime? createTime { get; set; } public DateTime? updateTime { get; set; } public List<TemplateDetail> templateDetailList { get; set; } } /// <summary> /// 患者模版信息 /// </summary> public class PatientTemplateInfo { public string templateId { get; set; } public string templateName { get; set; } public string docotorName { get; set; } public string templateMemo { get; set; } /// <summary> /// 模版类型 /// </summary> public int applicationType { get; set; } public List<TemplateDetail> templateDetailList { get; set; } } //返回的模版信息 public class TemplateRetuInfo { public string templateId { get; set; } public string templateName { get; set; } public string docotorMID { get; set; } public string teamMID { get; set; } public string templateMemo { get; set; } public int applicationType { get; set; } public String createName { get; set; } public DateTime? createTime { get; set; } public DateTime? updateTime { get; set; } } //返回的模版信息 public class AdminTemplateRetuInfo { public string templateId { get; set; } public string templateName { get; set; } public string templateMemo { get; set; } public int applicationType { get; set; } public String createName { get; set; } public DateTime? createTime { get; set; } public DateTime? updateTime { get; set; } } /// <summary> /// Stage对象 /// </summary> public class StageInfo { //public string stageID { get; set; } //public string targetGID { get; set; } public int stageIndex { get; set; } public int fromData { get; set; } public int toData { get; set; } public string valueData { get; set; } } /// <summary> /// 模版详情 /// </summary> public class TemplateDetail { public string templateDetailId { get; set; } //public string templateId { get; set; } public string actionId { get; set; } public string actionName { get; set; } public int actionType { get; set; } public int statisticalType { get; set; } public string actionImages { get; set; } public List<StageInfo> targetList { get; set; } } /// <summary> /// 动作表 /// </summary> public class ActionInfo { public string actionGID { get; set; } public string actionName { get; set; } public string actionImages { get; set; } public string actionVideos { get; set; } public string actionMemo { get; set; } public int actionType { get; set; } public int StatisticalType { get; set; } } public class ActionInfoParam { public string ActionGID { get; set; } public string ActionName { get; set; } public string ActionImages { get; set; } public string ActionVideos { get; set; } public string ActionMemo { get; set; } public int ActionType { get; set; } public int StatisticalType { get; set; } } }
using System.Text; using System; using System.Collections.Generic; using Newtonsoft.Json.Converters; using Newtonsoft.Json; using System.Net.Http; using System.Drawing; using System.Collections.ObjectModel; using System.Xml; using System.ComponentModel; using System.Reflection; namespace LinnworksAPI { public class ProcessOrderByOrderIdOrReferenceResponse { public OrderProcessedState ProcessedState; public String Message; public Object Response; public Guid OrderId; public OrderSummary OrderSummary; public List<OrderItem> Items; public List<StockItemBatch> BatchInformation; } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; /* Сохранить дерево каталогов и файлов * по заданному пути в текстовый файл — с рекурсией и без. */ namespace l5p { class l5p4 { public static void CatalogTree() { string start_catalog = @"C:\Users\user\source\repos\hwles1\lesson5"; ReadCatalog(start_catalog); } public static void ReadCatalog(string start_catalog) { string filename = "catalog.txt"; if (Directory.Exists(start_catalog)) { string[] files = Directory.GetFiles(start_catalog); DirectoryInfo di = new DirectoryInfo(start_catalog); File.AppendAllText(filename, $"\n \nФайлы каталога: {di.Name}"); for (int i = 0; i < files.Length; i++) { File.AppendAllText(filename, $"\n{Path.GetFileName(files[i])}"); } string[] direct = Directory.GetDirectories(start_catalog); File.AppendAllText(filename, $"\n \nПодкаталоги каталога: {di.Name}"); for (int i = 0; i < direct.Length; i++) { di = new DirectoryInfo(direct[i]); File.AppendAllText(filename, $"\n{di.Name}"); } for(int i = 0; i < direct.Length; i++) { ReadCatalog(direct[i]); } } else { Console.WriteLine("Указанный каталог не найден."); } } } }
 using UnityEngine; using System.Collections; using System; using System.Text; using System.Net; using System.Net.Sockets; using System.Threading; using System.Collections.Generic; public enum FeatureType { None, Motor, Color, Float, Hue_Bulb, Debug } [System.Serializable] public class FixtureFeature { public String Name; public int Channel; public FeatureType Type; public GameObject SourceObject; public int Index; public float DebugValue; public Vector4 MotorRange = new Vector4(); public bool IsActive = true; public bool DebugOutput = false; public float FloatMult = 1f; // Variables for Motor type private Transform sourceTransform; // Variables for Color type private Material colorMat; // Variables for Float type private Transform sourceScaleReference; // Variables for Hue_Bulb type private Hue_LightColor hueLightColor; private bool hasInit = false; public void Init() { if (DebugOutput) Debug.Log("Initializing " + Name + " " + Type.ToString() + " " + SourceObject.name); if (Type == FeatureType.Motor) { sourceTransform = SourceObject.transform; } else if (Type == FeatureType.Color) { hueLightColor = SourceObject.GetComponent<Hue_LightColor>(); } else if (Type == FeatureType.Float) { sourceScaleReference = SourceObject.transform; } else if (Type == FeatureType.Hue_Bulb) { hueLightColor = SourceObject.GetComponent<Hue_LightColor>(); } hasInit = true; } public void Update() { /*if (!hasInit) { Init(); }*/ } public string GetData(int startChannel) { string result = (Channel + startChannel - 1).ToString(); if (Type == FeatureType.Motor) { float compensatedRot = sourceTransform.localEulerAngles[Index]; if (compensatedRot < 0f) { compensatedRot = 360f + compensatedRot; } if (DebugOutput) { Debug.Log(sourceTransform.localEulerAngles[Index].ToString() + " becomes " + compensatedRot.Remap(MotorRange[0], MotorRange[1], MotorRange[3], MotorRange[2]).ToString()); } result += ",motor," + Mathf.Clamp( compensatedRot.Remap(MotorRange[0], MotorRange[1], MotorRange[3], MotorRange[2]), 0f, 255f ).ToString(); } else if (Type == FeatureType.Color) { result += ",color," + (hueLightColor.LightColor.r * 255).ToString() + "," + (hueLightColor.LightColor.g * 255).ToString() + "," + (hueLightColor.LightColor.b * 255).ToString(); } else if (Type == FeatureType.Float) { result += ",float," + Mathf.Clamp(sourceScaleReference.localScale[0] * 255 * FloatMult, 0f, 255f).ToString(); } else if (Type == FeatureType.Hue_Bulb) { result += ",hueBulb," + (hueLightColor.LightColor.r * 255).ToString() + "," + (hueLightColor.LightColor.g * 255).ToString() + "," + (hueLightColor.LightColor.b * 255).ToString() + "," + (Mathf.Clamp( hueLightColor.LightColor.a * 254, 1f, 254f)).ToString() + "," + Name; } else if (Type == FeatureType.Debug) { result += ",motor," + DebugValue.ToString(); } if (DebugOutput) Debug.Log("Sending: " + result); return result; } } [ExecuteAlways] public class UDP_DMXFixture : MonoBehaviour { public List<FixtureFeature> Features = new List<FixtureFeature>(); public string IP = "127.0.0.1"; public int Port = 8051; public int StartChannel = 1; public float SendRate = 1f; protected IPEndPoint remoteEndPoint; protected UdpClient client; public bool PlayInEditor = false; // Start is called before the first frame update void Start() { foreach (FixtureFeature f in Features) { f.Init(); } remoteEndPoint = new IPEndPoint(IPAddress.Parse(IP), Port); client = new UdpClient(); InvokeRepeating("SendAllData", UnityEngine.Random.Range(0f, 3f), SendRate); } private void SendAllData() { if (!Application.IsPlaying(gameObject) && !PlayInEditor) { return; } foreach (FixtureFeature f in Features) { if (f.IsActive) { SendData(f); } } } public void SendData(FixtureFeature feature) { //byte[] data = Encoding.UTF8.GetBytes(SourceObject.rotation.eulerAngles.y.ToString()); string compiledString = StartChannel.ToString() + "," + feature.GetData(StartChannel); byte[] data = Encoding.UTF8.GetBytes(compiledString); client.Send(data, data.Length, remoteEndPoint); } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class ExperienceBar : MonoBehaviour { public float CurrentExp { get; set; } public float MaxExp { get; set; } private Slider experienceBar; public float FillSpeed = 0.2f; private float targetProgress = 0; private void Awake() { experienceBar = gameObject.GetComponent<Slider>(); } // Start is called before the first frame update void Start() { MaxExp = 0f; // Resets Experience to full on game load CurrentExp = MaxExp; experienceBar.value = CalculateExp(); } // Update is called once per frame void Update() { if (experienceBar.value < targetProgress) experienceBar.value += FillSpeed * Time.deltaTime; if (Input.GetKeyDown(KeyCode.X)) IncrementProgress(0.10f); } void DealExp(float ExpValue) { // Deduct the Experience gain from the character's enemy kill CurrentExp -= ExpValue; experienceBar.value = CalculateExp(); // If the character is full of experience, level up! if (CurrentExp >= 1) LevelUp(); } // Add progress to the bar public void IncrementProgress(float newProgress) { targetProgress = experienceBar.value + newProgress; } float CalculateExp() { return CurrentExp / MaxExp; } void LevelUp() { CurrentExp = 1; Debug.Log("Livellato bro"); } }
using Microsoft.Extensions.DependencyInjection; using System; using System.Drawing; using System.Windows.Forms; using TQVaultAE.Domain.Contracts.Providers; using TQVaultAE.Domain.Contracts.Services; using TQVaultAE.Domain.Entities; using TQVaultAE.Domain.Helpers; using TQVaultAE.GUI.Helpers; using TQVaultAE.GUI.Models; using TQVaultAE.GUI.Tooltip; using TQVaultAE.Presentation; namespace TQVaultAE.GUI.Components; public partial class ForgePanel : UserControl { #region Internal Types private enum ItemPropertyType { Base, Prefix, Suffix, Relic1, Relic2, } private class ForgeComboItem { public ItemPropertyType Value; public string Text; public override string ToString() => Text; } #endregion private readonly ISoundService SoundService; private readonly IUIService UIService; private readonly IFontService FontService; private readonly ITranslationService TranslationService; private readonly IItemProvider ItemProvider; internal Action CancelAction; internal Action ForgeAction; private Item BaseItem; private SackCollection BaseSack; private Item PrefixItem; private SackCollection PrefixSack; private Item SuffixItem; private SackCollection SuffixSack; private Item Relic1Item; private SackCollection Relic1Sack; private Item Relic2Item; private SackCollection Relic2Sack; private ScalingRadioButton lastMode; private static RecordId SoundStricMode = @"Sounds\MONSTERS\GREECE\G_TELKINE\TELEKINEVOICE01.WAV"; private static RecordId SoundRelaxMode = @"Sounds\MONSTERS\GREECE\G_TELKINE\TELEKINEVOICE02.WAV"; private static RecordId SoundGameMode = @"Sounds\MONSTERS\GREECE\G_TELKINE\TELEKINEVOICE03.WAV"; private static RecordId SoundGodMode = @"Sounds\AMBIENCE\RANDOMEVENT\TYPHONLAUGHDISTANCE.WAV"; /// <summary> /// Gets or sets the dragInfo instance of any items being dragged. /// </summary> protected ItemDragInfo DragInfo; private readonly IServiceProvider ServiceProvider; private Bitmap dragingBmp; private Item lastDragedItem; private bool IsGodMode => scalingRadioButtonGod.Checked; private bool IsRelaxMode => scalingRadioButtonRelax.Checked; private bool IsStrictMode => scalingRadioButtonStrict.Checked; private bool IsGameMode => scalingRadioButtonGame.Checked; bool IsDraging => DragInfo != null && DragInfo.IsActive; private Point CurrentDragPicturePosition { get { var cursorPos = PointToClient(Cursor.Position); return new Point( cursorPos.X - (pictureBoxDragDrop.Size.Width / 2) , cursorPos.Y - pictureBoxDragDrop.Size.Height / 2 ); } } private readonly string OfTheTinkererTranslation; private readonly Color PictureBoxBaseColor = Color.FromArgb(32 * 7, 46, 41, 31); Item _PreviewItem = null; internal bool HardcoreMode; private Item PreviewItem { get { if (BaseItem is null) return null; if (_PreviewItem is null) { _PreviewItem = BaseItem.Clone(); if (SuffixItem is not null || PrefixItem is not null || Relic1Item is not null || Relic2Item is not null) { MergeItemProperties(_PreviewItem); this.ItemProvider.GetDBData(_PreviewItem); } } return _PreviewItem; } } public ForgePanel() { InitializeComponent(); } public ForgePanel(ItemDragInfo dragInfo, IServiceProvider serviceProvider) { InitializeComponent(); DoubleBuffered = true; DragInfo = dragInfo; ServiceProvider = serviceProvider; SetStyle(ControlStyles.OptimizedDoubleBuffer | ControlStyles.AllPaintingInWmPaint | ControlStyles.SupportsTransparentBackColor, true); SoundService = serviceProvider.GetService<ISoundService>(); UIService = serviceProvider.GetService<IUIService>(); FontService = serviceProvider.GetService<IFontService>(); TranslationService = serviceProvider.GetService<ITranslationService>(); ItemProvider = serviceProvider.GetService<IItemProvider>(); #region Font, Scaling, Translate, BackGround BackgroundImageLayout = ImageLayout.Stretch; BackgroundImage = Resources.caravan_bg; tableLayoutPanelForge.BackgroundImageLayout = ImageLayout.Stretch; tableLayoutPanelForge.BackgroundImage = Resources.StashPanel; scalingCheckBoxHardcore.Font = scalingRadioButtonGame.Font = scalingRadioButtonGod.Font = scalingRadioButtonRelax.Font = scalingRadioButtonStrict.Font = FontService.GetFont(10F, FontStyle.Regular, UIService.Scale); scalingLabelBaseItem.Font = scalingLabelPrefix.Font = scalingLabelRelic1.Font = scalingLabelRelic2.Font = scalingLabelSuffix.Font = FontService.GetFont(11F, FontStyle.Bold, UIService.Scale); scalingLabelBaseItem.ForeColor = scalingLabelPrefix.ForeColor = scalingLabelRelic1.ForeColor = scalingLabelRelic2.ForeColor = scalingLabelSuffix.ForeColor = TQColor.Yellow.Color(); // Scalling var size = TextRenderer.MeasureText(scalingLabelBaseItem.Text, scalingLabelBaseItem.Font); scalingLabelBaseItem.Height = scalingLabelPrefix.Height = scalingLabelRelic1.Height = scalingLabelRelic2.Height = scalingLabelSuffix.Height = size.Height; ForgeButton.Font = FontService.GetFontLight(12F); ResetButton.Font = FontService.GetFontLight(12F); CancelButton.Font = FontService.GetFontLight(12F); scalingRadioButtonGod.Text = Resources.ForgeGodMode; toolTip.SetToolTip(scalingRadioButtonGod, Resources.ForgeGodModeTT); scalingRadioButtonGod.ForeColor = TQColor.Indigo.Color(); OfTheTinkererTranslation = TranslationService.TranslateXTag("x3tagSuffix01"); scalingRadioButtonRelax.Text = Resources.ForgeRelaxMode; toolTip.SetToolTip(scalingRadioButtonRelax, string.Format(Resources.ForgeRelaxModeTT, OfTheTinkererTranslation)); scalingRadioButtonRelax.ForeColor = TQColor.Aqua.Color(); scalingRadioButtonStrict.Text = Resources.ForgeStrictMode; toolTip.SetToolTip(scalingRadioButtonStrict, Resources.ForgeStrictModeTT); scalingRadioButtonStrict.ForeColor = TQColor.Yellow.Color(); scalingRadioButtonGame.Text = Resources.ForgeGameMode; toolTip.SetToolTip(scalingRadioButtonGame, Resources.ForgeGameModeTT); scalingRadioButtonGame.ForeColor = TQColor.Green.Color(); scalingCheckBoxHardcore.Text = Resources.GlobalHardcore; toolTip.SetToolTip(scalingCheckBoxHardcore, Resources.ForgeHardcoreTT); scalingCheckBoxHardcore.ForeColor = TQColor.Red.Color(); #endregion HideGodModeRows(); // Everything in the Forge must respond this.ProcessAllControls(c => { c.MouseEnter += ForgePanel_MouseEnter; c.MouseMove += pictureBoxDragDrop_MouseMove; }); ResetSelection(); } private void HideGodModeRows() { comboBoxPrefix.Visible = comboBoxRelic1.Visible = comboBoxRelic2.Visible = comboBoxSuffix.Visible = false; } private void InvalidateItemCacheAll(params Item[] items) { ItemTooltip.InvalidateCache(items); BagButtonTooltip.InvalidateCache(items); ItemProvider.InvalidateFriendlyNamesCache(items); } private void HardcoreDeleteMaterialItems() { if (this.HardcoreMode) { if (PrefixSack is not null) { PrefixSack.RemoveItem(PrefixItem); InvalidateItemCacheAll(PrefixItem); } if (SuffixSack is not null) { SuffixSack.RemoveItem(SuffixItem); InvalidateItemCacheAll(SuffixItem); } if (Relic1Sack is not null) { Relic1Sack.RemoveItem(Relic1Item); InvalidateItemCacheAll(Relic1Item); } if (Relic2Sack is not null) { Relic2Sack.RemoveItem(Relic2Item); InvalidateItemCacheAll(Relic2Item); } } this.FindForm().Refresh(); } private void ShowGodModeRows() { comboBoxPrefix.SelectedIndex = comboBoxRelic1.SelectedIndex = comboBoxRelic2.SelectedIndex = comboBoxSuffix.SelectedIndex = -1; comboBoxPrefix.Visible = comboBoxRelic1.Visible = comboBoxRelic2.Visible = comboBoxSuffix.Visible = true; } private void MergeItemProperties(Item itm) { if (PrefixItem is not null) { itm.prefixInfo = null; if (!IsGodMode) itm.prefixID = PrefixItem.prefixID; else { // God Mode var selectedPropreties = comboBoxPrefix.SelectedItem as ForgeComboItem; if (selectedPropreties is not null) { switch (selectedPropreties.Value) { case ItemPropertyType.Prefix: itm.prefixID = PrefixItem.prefixID; break; case ItemPropertyType.Suffix: itm.prefixID = PrefixItem.suffixID; break; case ItemPropertyType.Relic1: itm.prefixID = PrefixItem.relicID; break; case ItemPropertyType.Relic2: itm.prefixID = PrefixItem.relic2ID; break; case ItemPropertyType.Base: default: itm.prefixID = PrefixItem.BaseItemId; break; } } } } if (SuffixItem is not null) { itm.suffixInfo = null; if (!IsGodMode) itm.suffixID = SuffixItem.suffixID; else { // God Mode var selectedPropreties = comboBoxSuffix.SelectedItem as ForgeComboItem; if (selectedPropreties is not null) { switch (selectedPropreties.Value) { case ItemPropertyType.Prefix: itm.suffixID = SuffixItem.prefixID; break; case ItemPropertyType.Suffix: itm.suffixID = SuffixItem.suffixID; break; case ItemPropertyType.Relic1: itm.suffixID = SuffixItem.relicID; break; case ItemPropertyType.Relic2: itm.suffixID = SuffixItem.relic2ID; break; case ItemPropertyType.Base: default: itm.suffixID = SuffixItem.BaseItemId; break; } } } } if (Relic1Item is not null) { itm.RelicInfo = itm.RelicBonusInfo = null; if (!IsGodMode) { if (Relic1Item.IsRelicOrCharm) { itm.relicID = Relic1Item.BaseItemId; itm.RelicBonusId = Relic1Item.RelicBonusId; itm.Var1 = Relic1Item.Var1; } else { itm.relicID = Relic1Item.relicID; itm.RelicBonusId = Relic1Item.RelicBonusId; itm.Var1 = Relic1Item.Var1; } } else { // God Mode var selectedPropreties = comboBoxRelic1.SelectedItem as ForgeComboItem; if (selectedPropreties is not null) { switch (selectedPropreties.Value) { case ItemPropertyType.Prefix: itm.relicID = Relic1Item.prefixID; itm.RelicBonusId = null; itm.Var1 = 1; break; case ItemPropertyType.Suffix: itm.relicID = Relic1Item.suffixID; itm.RelicBonusId = null; itm.Var1 = 1; break; case ItemPropertyType.Relic1: itm.relicID = Relic1Item.relicID; itm.RelicBonusId = Relic1Item.RelicBonusId; itm.Var1 = Relic1Item.Var1; break; case ItemPropertyType.Relic2: itm.relicID = Relic1Item.relic2ID; itm.RelicBonusId = Relic1Item.RelicBonus2Id; itm.Var1 = Relic1Item.Var2; break; case ItemPropertyType.Base: default: itm.relicID = Relic1Item.BaseItemId; itm.RelicBonusId = Relic1Item.RelicBonusId; itm.Var1 = Relic1Item.Var1; break; } } } } if (Relic2Item is not null) { itm.Relic2Info = itm.RelicBonus2Info = null; if (!IsGodMode) { if (Relic2Item.IsRelicOrCharm) { itm.relic2ID = Relic2Item.BaseItemId; itm.RelicBonus2Id = Relic2Item.RelicBonusId; itm.Var2 = Relic2Item.Var1; } else { itm.relic2ID = Relic2Item.relicID; itm.RelicBonus2Id = Relic2Item.RelicBonusId; itm.Var2 = Relic2Item.Var1; } } else { // God Mode var selectedPropreties = comboBoxRelic2.SelectedItem as ForgeComboItem; if (selectedPropreties is not null) { switch (selectedPropreties.Value) { case ItemPropertyType.Prefix: itm.relic2ID = Relic2Item.prefixID; itm.RelicBonus2Id = null; itm.Var2 = 1; break; case ItemPropertyType.Suffix: itm.relic2ID = Relic2Item.suffixID; itm.RelicBonus2Id = null; itm.Var2 = 1; break; case ItemPropertyType.Relic1: itm.relic2ID = Relic2Item.relicID; itm.RelicBonus2Id = Relic2Item.RelicBonusId; itm.Var2 = Relic2Item.Var1; break; case ItemPropertyType.Relic2: itm.relic2ID = Relic2Item.relic2ID; itm.RelicBonus2Id = Relic2Item.RelicBonus2Id; itm.Var2 = Relic2Item.Var2; break; case ItemPropertyType.Base: default: itm.relic2ID = Relic2Item.BaseItemId; itm.RelicBonus2Id = Relic2Item.RelicBonusId; itm.Var2 = Relic2Item.Var1; break; } } } } } private void ResetSelection() { pictureBoxBaseItem.Image = pictureBoxPrefix.Image = pictureBoxRelic1.Image = pictureBoxRelic2.Image = pictureBoxSuffix.Image = null; pictureBoxBaseItem.BackColor = pictureBoxPrefix.BackColor = pictureBoxRelic1.BackColor = pictureBoxRelic2.BackColor = pictureBoxSuffix.BackColor = PictureBoxBaseColor; BaseItem = PrefixItem = Relic1Item = Relic2Item = SuffixItem = null; BaseSack = null; comboBoxPrefix.Items.Clear(); comboBoxSuffix.Items.Clear(); comboBoxRelic1.Items.Clear(); comboBoxRelic2.Items.Clear(); ResetPreviewItem(); } private void ResetPreviewItem() { if (_PreviewItem is not null) ItemTooltip.InvalidateCache(_PreviewItem);// Invalide old preview item _PreviewItem = null; } private void CancelButton_Click(object sender, EventArgs e) { ResetSelection(); if (CancelAction is not null) CancelAction(); } private void ForgeButton_Click(object sender, EventArgs e) { ForgeItem(); } private void ForgeItem() { if (MustSelectBaseItem()) return; if (MustSelectAtLeastAnotherItem()) return; // Merge item properties into Base item var itm = BaseItem; MergeItemProperties(itm); ItemProvider.GetDBData(itm); BaseSack.IsModified = itm.IsModified = true; HardcoreDeleteMaterialItems(); ItemTooltip.InvalidateCache(itm); ItemProvider.InvalidateFriendlyNamesCache(itm); ResetSelection(); // Sound if (IsGodMode) SoundService.PlayLevelUp(); else SoundService.PlayRandomMetalHit(); // External Code if (ForgeAction is not null) ForgeAction(); } private void ForgeMode_Clicked(object sender, EventArgs e) { if (IsGameMode) { SoundService.PlaySound(SoundGameMode); // Reset on Mode downgrade if (lastMode == scalingRadioButtonGod || lastMode == scalingRadioButtonRelax || lastMode == scalingRadioButtonStrict) ResetSelection(); HideGodModeRows(); lastMode = scalingRadioButtonGame; return; } if (IsStrictMode) { SoundService.PlaySound(SoundStricMode); // Reset on Mode downgrade if (lastMode == scalingRadioButtonGod || lastMode == scalingRadioButtonRelax) ResetSelection(); HideGodModeRows(); lastMode = scalingRadioButtonStrict; return; } if (IsRelaxMode) { SoundService.PlaySound(SoundRelaxMode); // Reset on Mode downgrade if (lastMode == scalingRadioButtonGod) ResetSelection(); HideGodModeRows(); lastMode = scalingRadioButtonRelax; return; } if (IsGodMode) { SoundService.PlaySound(SoundGodMode); ShowGodModeRows(); lastMode = scalingRadioButtonGod; } } private void ForgePanel_MouseEnter(object sender, EventArgs e) { // Enforce first autosize display if (MaximumSize == Size.Empty) MaximumSize = new Size(Size.Width, Size.Height + 50); if (lastDragedItem != DragInfo.Item)// Item Switching { lastDragedItem = DragInfo.Item; dragingBmp = null; } if (IsDraging && dragingBmp is null) // First time with this item { dragingBmp = UIService.LoadBitmap(DragInfo.Item.TexImageResourceId); pictureBoxDragDrop.Location = CurrentDragPicturePosition; pictureBoxDragDrop.Size = dragingBmp.Size; // TODO try to make transparency work with a picturebox with an overrided Paint() event https://stackoverflow.com/questions/34673496/override-picturbox-onpaint-event-to-rotate-the-image-create-custom-picturebox //pictureBoxDragDrop.BackColor = Color.FromArgb(46, 41, 31);// Not pretty but Transparent doesn't work pictureBoxDragDrop.Image = dragingBmp; pictureBoxDragDrop.BringToFront(); pictureBoxDragDrop.Visible = true; // seek for mouse out of panel SubscribeExternalMouseMove(); } } private void SubscribeExternalMouseMove() { // tout le form sauf ce control this.FindForm().ProcessAllControlsWithExclusion(c => { if (c == this) return true;// Exclude myself and my children c.MouseMove += Parent_MouseMove; return false; }); } private void UnsubscribeExternalMouseMove() { // tout le form sauf ce control this.FindForm().ProcessAllControlsWithExclusion(c => { if (c == this) return true;// Exclude myself and my children c.MouseMove -= Parent_MouseMove; return false; } ); } private void Parent_MouseMove(object sender, EventArgs e) { // Out of Panel if (pictureBoxDragDrop.Visible) { UnsubscribeExternalMouseMove(); pictureBoxDragDrop.Image = dragingBmp = null; pictureBoxDragDrop.Visible = false; } } private void pictureBoxDragDrop_MouseMove(object sender, MouseEventArgs e) { if (IsDraging) { pictureBoxDragDrop.Location = CurrentDragPicturePosition; } } /// <summary> /// Drop <see cref="pictureBoxDragDrop"/> /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void pictureBoxDragDrop_Click(object sender, EventArgs e) { if (ItemMustBeInsideASack()) return; if (IsAlreadyPlaced(DragInfo.Item)) return; pictureBoxDragDrop.Visible = false; var found = tableLayoutPanelForge.GetChildAtPoint( tableLayoutPanelForge.PointToClient(Cursor.Position) , GetChildAtPointSkip.Invisible | GetChildAtPointSkip.Transparent ) as PictureBox; var drgItm = DragInfo.Item; var drgSack = DragInfo.Sack; if (found == pictureBoxBaseItem) { if (GameModePrefixSuffixMustBeSameBaseItem(found, drgItm)) return; if (GameModePrefixSuffixMustHaveLevelRequirementLowerThanEqualThanBaseItem(found, drgItm)) return; if (StrictModeNoEpicLegendaryItem(drgItm)) return; if (StrictModePrefixSuffixMustBeSameType(found, drgItm)) return; if (StrictModeCantUsePrefixSuffixOfHigherLevelThanBaseItem(found, drgItm)) return; // Strict reset relic 2 if non Tinkered forge result if ((IsStrictMode || IsGameMode) && Relic2Item is not null && SuffixItem is not null && !SuffixItem.AcceptExtraRelic && drgItm.AcceptExtraRelic ) { ResetRelic2(); } // Strict/Relax reset relic 1 & 2 if non allowed gear type if (!IsGodMode) { if (Relic1Item is not null && ( (Relic1Item.IsRelicOrCharm && !drgItm.IsRelicAllowed(Relic1Item)) || (Relic1Item.HasRelicOrCharmSlot1 && !drgItm.IsRelicAllowed(Relic1Item.relicID)) ) ) { ResetRelic1(); } if (Relic2Item is not null && ( (Relic2Item.IsRelicOrCharm && !drgItm.IsRelicAllowed(Relic2Item)) || (Relic2Item.HasRelicOrCharmSlot1 && !drgItm.IsRelicAllowed(Relic2Item.relicID)) ) ) { ResetRelic2(); } } // Only Weapon/Armor/Jewellery allowed if (drgItm.IsWeaponShield || drgItm.IsArmor || drgItm.IsJewellery || IsGodMode) { BaseItem = drgItm; BaseSack = drgSack; pictureBoxBaseItem.Image = UIService.LoadBitmap(BaseItem.TexImageResourceId); pictureBoxBaseItem.BackColor = Color.FromArgb(127, ControlPaint.Dark(drgItm.ItemStyle.Color())); DragInfo.Cancel(); SoundService.PlayRandomItemDrop(); ResetPreviewItem(); return; } // Not good item class this.UIService.NotifyUser(Resources.ForgeMustSelectArmorOrWeaponOrJewellery, TQColor.Red); SoundService.PlayRandomCancel(); } if (found == pictureBoxPrefix) { if (BaseItemFirst()) return; if (GameModePrefixSuffixMustBeSameBaseItem(found, drgItm)) return; if (GameModePrefixSuffixMustHaveLevelRequirementLowerThanEqualThanBaseItem(found, drgItm)) return; if (StrictModeNoEpicLegendaryItem(drgItm)) return; if (StrictModePrefixSuffixMustBeSameType(found, drgItm)) return; if (StrictModeCantUsePrefixSuffixOfHigherLevelThanBaseItem(found, drgItm)) return; // Strict & Relax mode need item having prefix if (!IsGodMode && !drgItm.HasPrefix) { pictureBoxDragDrop.Visible = true; this.UIService.NotifyUser(Resources.ForgeMustHavePrefixOutsideOfGodMode, TQColor.Red); SoundService.PlayRandomCancel(); return; } // Only Weapon/Armor/Jewellery allowed if (drgItm.IsWeaponShield || drgItm.IsArmor || drgItm.IsJewellery || IsGodMode) { PrefixItem = drgItm; PrefixSack = drgSack; pictureBoxPrefix.Image = UIService.LoadBitmap(PrefixItem.TexImageResourceId); pictureBoxPrefix.BackColor = Color.FromArgb(127, ControlPaint.Dark(drgItm.ItemStyle.Color())); DragInfo.Cancel(); AdjustComboBox(comboBoxPrefix); SoundService.PlayRandomItemDrop(); ResetPreviewItem(); return; } // Not good item class this.UIService.NotifyUser(Resources.ForgeMustSelectArmorOrWeaponOrJewellery, TQColor.Red); SoundService.PlayRandomCancel(); } if (found == pictureBoxSuffix) { if (BaseItemFirst()) return; if (GameModePrefixSuffixMustBeSameBaseItem(found, drgItm)) return; if (GameModePrefixSuffixMustHaveLevelRequirementLowerThanEqualThanBaseItem(found, drgItm)) return; if (StrictModeNoEpicLegendaryItem(drgItm)) return; if (StrictModePrefixSuffixMustBeSameType(found, drgItm)) return; if (StrictModeCantUsePrefixSuffixOfHigherLevelThanBaseItem(found, drgItm)) return; // Strict mode : reset relic 2 if non Tinkered forge result if ((IsStrictMode || IsGameMode) && Relic2Item is not null && !drgItm.AcceptExtraRelic ) { ResetRelic2(); } // Strict & Relax mode need item having suffix if (!IsGodMode && !drgItm.HasSuffix) { pictureBoxDragDrop.Visible = true; this.UIService.NotifyUser(Resources.ForgeMustHaveSuffixOutsideOfGodMode, TQColor.Red); SoundService.PlayRandomCancel(); return; } // Only Weapon/Armor/Jewellery allowed if (drgItm.IsWeaponShield || drgItm.IsArmor || drgItm.IsJewellery || IsGodMode) { SuffixItem = drgItm; SuffixSack = drgSack; pictureBoxSuffix.Image = UIService.LoadBitmap(SuffixItem.TexImageResourceId); pictureBoxSuffix.BackColor = Color.FromArgb(127, ControlPaint.Dark(drgItm.ItemStyle.Color())); DragInfo.Cancel(); AdjustComboBox(comboBoxSuffix); SoundService.PlayRandomItemDrop(); ResetPreviewItem(); return; } // Not good item class this.UIService.NotifyUser(Resources.ForgeMustSelectArmorOrWeaponOrJewellery, TQColor.Red); SoundService.PlayRandomCancel(); } if (found == pictureBoxRelic1) { if (BaseItemFirst()) return; // Strict mode need relic if (StrictModeMustBeRelic(drgItm)) return; // Relax mode need item having relic or a relic if (RelaxModeMustHaveRelic(drgItm)) return; if (StrictRelaxEnforceRelicGearConstraint(drgItm)) return; // Only Weapon/Armor/Jewellery with relic allowed or a relic item if ( IsGodMode || ( (drgItm.IsWeaponShield && drgItm.HasRelicOrCharmSlot1) || (drgItm.IsArmor && drgItm.HasRelicOrCharmSlot1) || (drgItm.IsJewellery && drgItm.HasRelicOrCharmSlot1) || drgItm.IsRelicOrCharm ) ) { Relic1Item = drgItm; Relic1Sack = drgSack; pictureBoxRelic1.Image = UIService.LoadBitmap(Relic1Item.TexImageResourceId); pictureBoxRelic1.BackColor = Color.FromArgb(127, ControlPaint.Dark(drgItm.ItemStyle.Color())); DragInfo.Cancel(); AdjustComboBox(comboBoxRelic1); SoundService.PlayRandomItemDrop(); ResetPreviewItem(); return; } // Not good item class this.UIService.NotifyUser(Resources.ForgeMustSelectRelicOrItemWithRelic, TQColor.Red); SoundService.PlayRandomCancel(); } if (found == pictureBoxRelic2) { if (BaseItemFirst()) return; // Strict mode need relic if (StrictModeMustBeRelic(drgItm)) return; // Relax mode need item having relic or a relic if (RelaxModeMustHaveRelic(drgItm)) return; if (StrictRelaxEnforceRelicGearConstraint(drgItm)) return; // Strict Mode only allowed on BaseItem "of the Tinkered" if ((IsStrictMode || IsGameMode) && !( // No Suffix Item && BaseItem of Tinkerer (SuffixItem is null && BaseItem.AcceptExtraRelic) // Or Suffix Item of Tinkerer || (SuffixItem is not null && SuffixItem.AcceptExtraRelic) ) ) { pictureBoxDragDrop.Visible = true; this.UIService.NotifyUser(string.Format(Resources.ForgeMustHaveTinkeredSuffix, OfTheTinkererTranslation), TQColor.Red); SoundService.PlayRandomCancel(); return; } // Only Weapon/Armor/Jewellery with relic allowed or a relic item if ( IsGodMode || ( (drgItm.IsWeaponShield && drgItm.HasRelicOrCharmSlot1) || (drgItm.IsArmor && drgItm.HasRelicOrCharmSlot1) || (drgItm.IsJewellery && drgItm.HasRelicOrCharmSlot1) || drgItm.IsRelicOrCharm ) ) { Relic2Item = drgItm; Relic2Sack = drgSack; pictureBoxRelic2.Image = UIService.LoadBitmap(Relic2Item.TexImageResourceId); pictureBoxRelic2.BackColor = Color.FromArgb(127, ControlPaint.Dark(drgItm.ItemStyle.Color())); DragInfo.Cancel(); AdjustComboBox(comboBoxRelic2); SoundService.PlayRandomItemDrop(); ResetPreviewItem(); return; } // Not good item class this.UIService.NotifyUser(Resources.ForgeMustSelectRelicOrItemWithRelic, TQColor.Red); SoundService.PlayRandomCancel(); } pictureBoxDragDrop.Visible = true; } #region Validate private bool ItemMustBeInsideASack() { // Happen when i copy an item without droping it in a sack first if (DragInfo.Sack is null) { this.UIService.NotifyUser(Resources.ForgeItemMustBeStoredFirst, TQColor.Red); SoundService.PlayRandomCancel(); return true; } return false; } /// <summary> /// Strict/Relax : Enforce relic gear constraint /// </summary> /// <param name="drgItm"></param> /// <returns></returns> private bool StrictRelaxEnforceRelicGearConstraint(Item drgItm) { if (!IsGodMode && ( (drgItm.IsRelicOrCharm && !BaseItem.IsRelicAllowed(drgItm)) || (drgItm.HasRelicOrCharmSlot1 && !BaseItem.IsRelicAllowed(drgItm.relicID)) ) ) { pictureBoxDragDrop.Visible = true; this.UIService.NotifyUser(Resources.ForgeRelicNotAllowed, TQColor.Red); SoundService.PlayRandomCancel(); return true; } return false; } /// <summary> /// Relax mode need item having relic or a relic /// </summary> /// <param name="drgItm"></param> /// <returns></returns> private bool RelaxModeMustHaveRelic(Item drgItm) { // Relax mode need item having relic if (IsRelaxMode && !(drgItm.IsRelicOrCharm || drgItm.HasRelicOrCharmSlot1) ) { pictureBoxDragDrop.Visible = true; this.UIService.NotifyUser(Resources.ForgeMustHaveRelicInRelaxMode, TQColor.Red); SoundService.PlayRandomCancel(); return true; } return false; } /// <summary> /// Strict mode need relic /// </summary> /// <param name="drgItm"></param> /// <returns></returns> private bool StrictModeMustBeRelic(Item drgItm) { // Strict mode need relic if ((IsStrictMode || IsGameMode) && !drgItm.IsRelicOrCharm ) { pictureBoxDragDrop.Visible = true; this.UIService.NotifyUser(Resources.ForgeMustBeRelicInStrictMode, TQColor.Red); SoundService.PlayRandomCancel(); return true; } return false; } private void ResetRelic1() { Relic1Item = null; pictureBoxRelic1.Image = null; pictureBoxRelic1.BackColor = PictureBoxBaseColor; comboBoxRelic1.Items.Clear(); } private void ResetRelic2() { Relic2Item = null; pictureBoxRelic2.Image = null; pictureBoxRelic2.BackColor = PictureBoxBaseColor; comboBoxRelic2.Items.Clear(); } private bool IsAlreadyPlaced(Item item) => BaseItem == item || SuffixItem == item || PrefixItem == item || Relic2Item == item || Relic1Item == item; private bool MustSelectAtLeastAnotherItem() { // Must select at least another item if (PrefixItem is null && SuffixItem is null && Relic1Item is null && Relic2Item is null) { this.UIService.NotifyUser(Resources.ForgeMustSelectItemToMerge, TQColor.Red); SoundService.PlayRandomCancel(); return true; } return false; } private bool MustSelectBaseItem() { // Must select Base Item if (BaseItem is null) { this.UIService.NotifyUser(Resources.ForgeMustSelectBaseItem, TQColor.Red); SoundService.PlayRandomCancel(); return true; } return false; } private bool GameModePrefixSuffixMustHaveLevelRequirementLowerThanEqualThanBaseItem(PictureBox from, Item drgItm) { if (IsGameMode) { int drgLvl = 0, baseLvl = 0; var reqs = ItemProvider.GetRequirementVariables(drgItm); if (reqs.TryGetValue(Variable.KEY_LEVELREQ, out var varLvl)) drgLvl = varLvl.GetInt32(0); if (BaseItem is not null) { reqs = ItemProvider.GetRequirementVariables(BaseItem); if (reqs.TryGetValue(Variable.KEY_LEVELREQ, out varLvl)) baseLvl = varLvl.GetInt32(0); } if (from == pictureBoxBaseItem && BaseItem is not null && drgLvl > baseLvl ) { Notify(true);// Reset & Notify } if ((from == pictureBoxSuffix || from == pictureBoxPrefix) && drgLvl > baseLvl ) { return Notify(false);// Notify & Prevent Drop } } return false; bool Notify(bool reset) { pictureBoxDragDrop.Visible = true; this.UIService.NotifyUser(Resources.ForgeCantUsePrefixSuffixHavingGreaterReqLevelThanBaseItem, TQColor.Red); SoundService.PlayRandomCancel(); if (reset) ResetPrefixSuffix(); return true; } } private bool GameModePrefixSuffixMustBeSameBaseItem(PictureBox from, Item drgItm) { if (IsGameMode) { var baseId = RecordId.IsNullOrEmpty(BaseItem?.BaseItemId) ? RecordId.Empty : BaseItem.BaseItemId; var drgItmBaseId = RecordId.IsNullOrEmpty(drgItm?.BaseItemId) ? RecordId.Empty : drgItm.BaseItemId; if (from == pictureBoxBaseItem && BaseItem is not null && drgItmBaseId != baseId ) { Notify(true);// Reset & Notify } if ((from == pictureBoxSuffix || from == pictureBoxPrefix) && drgItmBaseId != baseId ) { return Notify(false);// Notify & Prevent Drop } } return false; bool Notify(bool reset) { pictureBoxDragDrop.Visible = true; this.UIService.NotifyUser(Resources.ForgeCantUsePrefixSuffixOfAnotherBaseItem, TQColor.Red); SoundService.PlayRandomCancel(); if (reset) ResetPrefixSuffix(); return true; } } /// <summary> /// Strict Mode Can't use Prefix/Suffix of another type /// </summary> /// <param name="from"></param> /// <param name="drgItm"></param> /// <returns></returns> private bool StrictModePrefixSuffixMustBeSameType(PictureBox from, Item drgItm) { if (IsStrictMode || IsGameMode) { var baseClass = string.IsNullOrWhiteSpace(BaseItem?.ItemClass) ? "NoClass" : BaseItem.ItemClass; var drgItmClass = string.IsNullOrWhiteSpace(drgItm?.ItemClass) ? "NoClass" : drgItm.ItemClass; if (from == pictureBoxBaseItem && BaseItem is not null && drgItmClass != baseClass ) { Notify(true);// Reset & Notify } if ((from == pictureBoxSuffix || from == pictureBoxPrefix) && drgItmClass != baseClass ) { return Notify(false);// Notify & Prevent Drop } } return false; bool Notify(bool reset) { pictureBoxDragDrop.Visible = true; this.UIService.NotifyUser(Resources.ForgeCantUsePrefixSuffixOfAnotherGearType, TQColor.Red); SoundService.PlayRandomCancel(); if (reset) ResetPrefixSuffix(); return true; } } /// <summary> /// Strict Mode Can't use Prefix/Suffix of higher level than baseitem /// </summary> /// <param name="from"></param> /// <param name="drgItm"></param> /// <returns></returns> private bool StrictModeCantUsePrefixSuffixOfHigherLevelThanBaseItem(PictureBox from, Item drgItm) { if (IsStrictMode || IsGameMode) { if (from == pictureBoxBaseItem && BaseItem is not null && ( ((PrefixItem?.Rarity ?? 0) > drgItm.Rarity) || ((SuffixItem?.Rarity ?? 0) > drgItm.Rarity) ) ) { Notify(true);// Reset & Notify } if ((from == pictureBoxPrefix || from == pictureBoxSuffix) && (BaseItem.Rarity < drgItm.Rarity) ) { return Notify(false);// Notify & Prevent Drop } } return false; bool Notify(bool reset) { pictureBoxDragDrop.Visible = true; this.UIService.NotifyUser(Resources.ForgeCantUsePrefixSuffixBetterThanBase, TQColor.Red); SoundService.PlayRandomCancel(); if (reset) ResetPrefixSuffix(); return true; } } private void ResetPrefixSuffix() { SuffixItem = PrefixItem = null; pictureBoxSuffix.Image = pictureBoxPrefix.Image = null; pictureBoxSuffix.BackColor = pictureBoxPrefix.BackColor = PictureBoxBaseColor; comboBoxPrefix.Items.Clear(); comboBoxSuffix.Items.Clear(); } private bool BaseItemFirst() { // BaseItem First if (BaseItem is null) { pictureBoxDragDrop.Visible = true; this.UIService.NotifyUser(Resources.ForgeMustSelectBaseItemFirst, TQColor.Red); SoundService.PlayRandomCancel(); return true; } return false; } /// <summary> /// No Epic/Legendary item in Strict Mode /// </summary> /// <param name="drgItm"></param> /// <returns></returns> private bool StrictModeNoEpicLegendaryItem(Item drgItm) { if ((IsStrictMode || IsGameMode) && (drgItm.Rarity > Rarity.Rare) ) { pictureBoxDragDrop.Visible = true; this.UIService.NotifyUser(Resources.ForgeNoEpicLegendaryAllowed, TQColor.Red); SoundService.PlayRandomCancel(); return true; } return false; } #endregion private void AdjustComboBox(ComboBox comboBox) { Item current = null; if (comboBox == comboBoxPrefix) current = PrefixItem; if (comboBox == comboBoxSuffix) current = SuffixItem; if (comboBox == comboBoxRelic1) current = Relic1Item; if (comboBox == comboBoxRelic2) current = Relic2Item; comboBox.Items.Clear(); comboBox.Items.Add(new ForgeComboItem { Value = ItemPropertyType.Base, Text = Resources.ForgeUseBase, }); if (current.HasPrefix) comboBox.Items.Add(new ForgeComboItem { Value = ItemPropertyType.Prefix, Text = Resources.ForgeUsePrefix, }); if (current.HasSuffix) comboBox.Items.Add(new ForgeComboItem { Value = ItemPropertyType.Suffix, Text = Resources.ForgeUseSuffix, }); if (current.HasRelicOrCharmSlot1) comboBox.Items.Add(new ForgeComboItem { Value = ItemPropertyType.Relic1, Text = Resources.ForgeUseRelic1, }); if (current.HasRelicOrCharmSlot2) comboBox.Items.Add(new ForgeComboItem { Value = ItemPropertyType.Relic2, Text = Resources.ForgeUseRelic2, }); comboBox.SelectedIndex = 0;// default on Base } private void scalingButtonReset_Click(object sender, EventArgs e) => ResetSelection(); private void pictureBox_MouseEnter(object sender, EventArgs e) { var picbox = sender as PictureBox; Item itm = null; if (picbox == pictureBoxPrefix) itm = PrefixItem; if (picbox == pictureBoxSuffix) itm = SuffixItem; if (picbox == pictureBoxRelic1) itm = Relic1Item; if (picbox == pictureBoxRelic2) itm = Relic2Item; if (picbox == pictureBoxBaseItem) itm = PreviewItem; if (itm is null) return; ItemTooltip.ShowTooltip(ServiceProvider, itm, picbox, true); } private void pictureBox_MouseLeave(object sender, EventArgs e) { ItemTooltip.HideTooltip(); } private void comboBox_SelectedIndexChanged(object sender, EventArgs e) { var combo = sender as ComboBox; ResetPreviewItem(); } private void scalingCheckBoxHardcore_CheckedChanged(object sender, EventArgs e) { this.HardcoreMode = scalingCheckBoxHardcore.Checked; } }
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.Linq; using System.Reflection; using System.Resources; using System.Text; using System.Text.RegularExpressions; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Media; using System.Windows.Media.Imaging; namespace Swiddler.Converters { public class CrispImageConverter : IMultiValueConverter { public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture) => throw new NotSupportedException(); public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture) { if (values is null) throw new ArgumentNullException(nameof(values)); if (values.Length != 4) return null; var width = (double)values[0]; var height = (double)values[1]; var name = (string)values[2]; var dpi = (double)values[3]; if (dpi == 0) dpi = 96; return GetImage(name, new Size(width, height), dpi); } static Size Round(Size size) => new Size(Math.Round(size.Width), Math.Round(size.Height)); public BitmapSource GetImage(string name, Size size, double dpi) { if (name is null) return null; if (double.IsNaN(size.Width) || double.IsNaN(size.Height)) return null; var physicalSize = Round(new Size(size.Width * dpi / 96, size.Height * dpi / 96)); if (physicalSize.Width == 0 || physicalSize.Height == 0) return null; ImageSourceInfo[] infos = null; if (imageResources?.TryGetValue(name, out infos) != true) return null; var infoList = new List<ImageSourceInfo>(infos); infoList.Sort((a, b) => { if (a.Size == b.Size) return 0; // Try exact size first if ((a.Size == physicalSize) != (b.Size == physicalSize)) return a.Size == physicalSize ? -1 : 1; // Try any-size (xaml images) if ((a.Size == ImageSourceInfo.AnySize) != (b.Size == ImageSourceInfo.AnySize)) return a.Size == ImageSourceInfo.AnySize ? -1 : 1; // Closest size (using height) if (a.Size.Height >= physicalSize.Height) { if (b.Size.Height < physicalSize.Height) return -1; return a.Size.Height.CompareTo(b.Size.Height); } else { if (b.Size.Height >= physicalSize.Height) return 1; return b.Size.Height.CompareTo(a.Size.Height); } }); foreach (var info in infoList) { var bitmapSource = TryGetImage(info, physicalSize); if (!(bitmapSource is null)) return bitmapSource; } return null; } static readonly Dictionary<ImageKey, BitmapSource> imageCache = new Dictionary<ImageKey, BitmapSource>(); static BitmapSource TryGetImage(ImageSourceInfo img, Size size) { if (img is null) return null; var key = new ImageKey(img.Uri, size); BitmapSource image; if (imageCache.TryGetValue(key, out var bmp)) return bmp; image = TryLoadImage(img, size); if (image is null) return null; imageCache[key] = image; return image; } struct ImageKey { private string uriString; private Size size; public ImageKey(string uriString, Size size) { this.uriString = uriString; this.size = size; } public override int GetHashCode() { return uriString.GetHashCode() ^ size.GetHashCode(); } public override bool Equals(object obj) { if (obj == null) return false; var other = (ImageKey)obj; return size.Equals(other.size) && uriString.Equals(other.uriString); } public override string ToString() { return $"{uriString} ({size})"; } } static BitmapSource TryLoadImage(ImageSourceInfo img, Size size) { try { var uri = new Uri(img.Uri, UriKind.RelativeOrAbsolute); var info = Application.GetResourceStream(uri); if (info.ContentType.Equals("application/xaml+xml", StringComparison.OrdinalIgnoreCase) || info.ContentType.Equals("application/baml+xml", StringComparison.OrdinalIgnoreCase)) { var component = Application.LoadComponent(uri); if (component is FrameworkElement elem) return ResizeElement(elem, size); return null; } else if (info.ContentType.StartsWith("image/", StringComparison.OrdinalIgnoreCase)) { var decoder = BitmapDecoder.Create(info.Stream, BitmapCreateOptions.None, BitmapCacheOption.OnDemand); if (decoder.Frames.Count == 0) return null; return ResizeImage(decoder.Frames[0], size); } else return null; } catch { return null; } } static BitmapSource ResizeElement(FrameworkElement elem, Size physicalSize) { elem.Width = physicalSize.Width; elem.Height = physicalSize.Height; elem.Measure(physicalSize); elem.Arrange(new Rect(physicalSize)); var dv = new DrawingVisual(); using (var dc = dv.RenderOpen()) { var brush = new VisualBrush(elem) { Stretch = Stretch.Uniform }; dc.DrawRectangle(brush, null, new Rect(physicalSize)); } Debug.Assert((int)physicalSize.Width == physicalSize.Width); Debug.Assert((int)physicalSize.Height == physicalSize.Height); var renderBmp = new RenderTargetBitmap((int)physicalSize.Width, (int)physicalSize.Height, 96, 96, PixelFormats.Pbgra32); renderBmp.Render(dv); return new FormatConvertedBitmap(renderBmp, PixelFormats.Bgra32, null, 0); } static BitmapSource ResizeImage(BitmapSource bitmapImage, Size physicalSize) { if (bitmapImage.PixelWidth == physicalSize.Width && bitmapImage.PixelHeight == physicalSize.Height) return bitmapImage; var image = new Image { Source = bitmapImage }; RenderOptions.SetBitmapScalingMode(image, BitmapScalingMode.HighQuality); return ResizeElement(image, physicalSize); } static CrispImageConverter() { InitResources(); } class ImageSourceInfo { /// <summary> /// Any size /// </summary> public static readonly Size AnySize = new Size(0, 0); /// <summary> /// URI of image /// </summary> public string Uri { get; set; } /// <summary> /// Size of image in pixels or <see cref="AnySize"/> /// </summary> public Size Size { get; set; } } static Dictionary<string, ImageSourceInfo[]> imageResources; static void InitResources() { var asm = typeof(CrispImageConverter).Assembly; string resName = asm.GetName().Name + ".g.resources"; using (var stream = asm.GetManifestResourceStream(resName)) { if (stream == null) return; // design time using (var reader = new System.Resources.ResourceReader(stream)) { imageResources = reader.Cast<DictionaryEntry>() .Select(x => (string)x.Key) .Where(key => key.StartsWith("images/", StringComparison.OrdinalIgnoreCase)) .Select(uri => new { Source = new ImageSourceInfo() { Uri = "/Swiddler;component/" + FixXamlExtension(uri), Size = GetImageSize(uri, out var nameKey) }, Key = nameKey, }) .ToLookup(x => x.Key, x => x.Source) .ToDictionary(x => x.Key, x => x.ToArray(), StringComparer.OrdinalIgnoreCase); } } } static string FixXamlExtension(string uri) { if (uri.EndsWith(".baml")) return uri.Substring(0, uri.Length - 4) + "xaml"; return uri; } static readonly Regex sizeRegex = new Regex(@"(.+)_(\d+)x$"); static Size GetImageSize(string name, out string nameKey) { name = name.Split('/').Last(); nameKey = name.Substring(0, name.LastIndexOf('.')); var match = sizeRegex.Match(nameKey); if (!match.Success) return ImageSourceInfo.AnySize; nameKey = match.Groups[1].Value; int.TryParse(match.Groups[2].Value, out int sz); return new Size(sz, sz); } } }
using System; using DomainNotificationHelper; using DomainNotificationHelper.Events; using EP.CrudModalDDD.Domain.Commands.Inputs; using EP.CrudModalDDD.Domain.Commands.Results; using EP.CrudModalDDD.Domain.Entities; using EP.CrudModalDDD.Domain.Interfaces; using EP.CrudModalDDD.Domain.Interfaces.Repository; using EP.CrudModalDDD.Domain.Scopes.Commands; using EP.CrudModalDDD.Domain.Scopes.ValueObjects; using EP.CrudModalDDD.Domain.ValueObjects; namespace EP.CrudModalDDD.Domain.Commands.Handlers { public class ClienteCommandHandler : CommandHandler, ICommandHandler<AdicionaNovoClienteCommand>, ICommandHandler<AtualizaClienteCommand>, ICommandHandler<RemoveClienteCommand> { private readonly IClienteRepository _clienteRepository; public ClienteCommandHandler(IUnitOfWork uow, IHandler<DomainNotification> notifications, IClienteRepository clienteRepository) : base(uow, notifications) { _clienteRepository = clienteRepository; } public ICommandResult Handle(AdicionaNovoClienteCommand command) { //Gera os Value Objects var cpf = new CPF(command.CpfNumero); var emailAddress = new EmailAddress(command.EmailAddress); //Valida propriedades que não buscam de repositório if (!(cpf.IsValid() & emailAddress.IsValid() & command.EhMaiorDeIdade() & command.PossuiEnderecoInformado())) { return new ClienteCommandResult(); } //Valida propriedades que buscam de repositório if (!(command.PossuiCpfUnico(_clienteRepository) & command.PossuiEmailUnico(_clienteRepository))) { return new ClienteCommandResult(); } //Gera a entidade cliente var cliente = new Cliente(command.ClienteId, command.Nome, emailAddress, cpf, command.DataNascimento, command.Ativo); //Gera as foreach (var clienteEnderecoCommand in command.Enderecos) { var endereco = new Endereco(clienteEnderecoCommand.Logradouro, clienteEnderecoCommand.Numero, clienteEnderecoCommand.Complemento, clienteEnderecoCommand.Bairro, clienteEnderecoCommand.CEP, clienteEnderecoCommand.Cidade, clienteEnderecoCommand.Estado); cliente.AdicionarEndereco(endereco); } //Adiciona a entidade ao repositório _clienteRepository.Adicionar(cliente); return new ClienteCommandResult(); } public ICommandResult Handle(AtualizaClienteCommand command) { //Gera os Value Objects var cpf = new CPF(command.CpfNumero); var emailAddress = new EmailAddress(command.EmailAddress); //Valida propriedades que não buscam de repositório if (!(cpf.IsValid() & emailAddress.IsValid() & command.EhMaiorDeIdade())) { return new ClienteCommandResult(); } //Valida propriedades que buscam de repositório if (!(command.PossuiCpfUnico(_clienteRepository) & command.PossuiEmailUnico(_clienteRepository))) { return new ClienteCommandResult(); } //Gera a entidade cliente var cliente = new Cliente(command.ClienteId, command.Nome, emailAddress, cpf, command.DataNascimento, command.Ativo); //Atualiza a entidade junto ao repositório _clienteRepository.Atualizar(cliente); return new ClienteCommandResult(); } public ICommandResult Handle(RemoveClienteCommand command) { if (!command.PossuiEnderecoInformado(_clienteRepository)) { return new ClienteCommandResult(); } _clienteRepository.Remover(command.ClienteId); return new ClienteCommandResult(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace CakeShop.ViewModels { public class AboutUsViewModel { public List<Member> Members { get; set; } /// <summary> /// Hàm khởi tạo mặc định đối tượng /// </summary> public AboutUsViewModel() { Members = new List<Member>(); var member1 = new Member { Name = "Nguyễn Hoàng Khang", AvatarImage = "../Data/Images/0039.jpg", Job = "Student", Position = "PM & Designer", Gmail = "nhk25022016", Facebook = "nhkitusk18" }; var member2 = new Member { Name = "Bùi Huỳnh Trung Tín", AvatarImage = "../Data/Images/0092.jpg", Job = "Student", Position = "Tester", Gmail = "bhtt190800", Facebook = "bhtt190800" }; var member3 = new Member { Name = "Trương Đại Triều", AvatarImage = "../Data/Images/0096.jpg", Job = "Student", Position = "Dev & Designer", Gmail = "truongdaitrieu2109", Facebook = "truong.daitrieu.5" }; AddMember(member1); AddMember(member2); AddMember(member3); } /// <summary> /// Hàm thêm thành viên mới vào team /// </summary> /// <param name="member"></param> public void AddMember(Member member) { Members.Add(member); member.Id = Members.Count.ToString(); } } public class Member { public string Id { get; set; } public string Name { get; set; } public string AvatarImage { get; set; } public string Job { get; set; } public string Position { get; set; } public string Gmail { get; set; } public string Facebook { get; set; } public Member() { } } }
using admin.Models; using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Data.Entity; namespace admin.Models { public class Db:DbContext { public Db(): base("name=database") { } public DbSet<UserLogIn> UserLogIns { get; set; } public DbSet<UserLogIn2> UserLogIn2s { get; set; } public DbSet<UserLog> UserLogs { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using VindiniumCore.GameTypes; namespace VindiniumCore.Bot { /// <summary> /// I did it for the puns. /// </summary> public interface IRobot { Directions GetHeroMove(GameState gameState); } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; namespace SC601_Semana01.Views { public partial class Customers : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { GetCustormers(); } } private void GetCustormers() { List<DataAccess.customers> customers = new List<DataAccess.customers>(); customers = BusinessModel.Customers.GetCustomers(); grvClientes.DataSource = customers; grvClientes.DataBind(); } /*Este metodo nos permite cambiar el index del grid esto quiere decir que si me muevo entre tabas se posiciona en la primera fila del tab.*/ protected void grvClientes_PageIndexChanging(object sender, GridViewPageEventArgs e) { grvClientes.PageIndex = e.NewPageIndex; grvClientes.DataBind(); this.GetCustormers(); } /*Este metodo me permite habilitar los campos para ser editados*/ protected void grvClientes_RowEditing(object sender, GridViewEditEventArgs e) { grvClientes.EditIndex = e.NewEditIndex; this.GetCustormers(); } /*Este metodo se encagara de realizar el update del registro*/ protected void grvClientes_RowUpdating(object sender, GridViewUpdateEventArgs e) { GridViewRow row = grvClientes.Rows[e.RowIndex]; int customer_id = Convert.ToInt32(grvClientes.DataKeys[e.RowIndex].Values[0]); string firstName = (row.FindControl("txtfirst_name") as TextBox).Text; string lastName = (row.FindControl("txtlast_name") as TextBox).Text; string phone = (row.FindControl("txtphone") as TextBox).Text; string email = (row.FindControl("txtemail") as TextBox).Text; string street = (row.FindControl("txtstreet") as TextBox).Text; string city = (row.FindControl("txtcity") as TextBox).Text; string state = (row.FindControl("txtstate") as TextBox).Text; string zip_code = (row.FindControl("txtzip_code") as TextBox).Text; var customers = new DataAccess.customers { customer_id = customer_id, first_name = firstName, last_name = lastName, phone = phone, email = email, street = street, city = city, state = state, zip_code = zip_code }; BusinessModel.Customers.UpdateCustomers(customers); grvClientes.EditIndex = -1; this.GetCustormers(); } protected void grvClientes_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e) { grvClientes.EditIndex = -1; this.GetCustormers(); } /*Este metodo valida si estoy seguro de si quiero eliminar un fila*/ protected void grvClientes_RowDataBound(object sender, GridViewRowEventArgs e) { if (e.Row.RowType == DataControlRowType.DataRow && e.Row.RowIndex != grvClientes.EditIndex) { (e.Row.Cells[9].Controls[2] as LinkButton).Attributes["onclick"] = "return confirm('Do you want to delete this row?');"; } } protected void grvClientes_RowDeleting(object sender, GridViewDeleteEventArgs e) { int customer_id = Convert.ToInt32(grvClientes.DataKeys[e.RowIndex].Values[0]); BusinessModel.Customers.DeleteCustomers(customer_id); this.GetCustormers(); } protected void btnAdd_Click(object sender, EventArgs e) { Response.Redirect("CustomersAdd.aspx"); } } }
using System; using System.Collections.Generic; using System.Data; using System.Data.Entity; using System.Linq; using System.Net; using System.Web; using System.Web.Mvc; using DiabeticsHelper; namespace DiabeticsHelper.Controllers { public class Insulin_DosageController : Controller { private Diabetes_Helper_Entities db = new Diabetes_Helper_Entities(); // GET: Insulin_Dosage public ActionResult Index() { var insulin_Dosage = db.Insulin_Dosage.Include(i => i.Blood_Sugar_Range).Include(i => i.User); return View(insulin_Dosage.ToList()); } // GET: Insulin_Dosage/Details/5 public ActionResult Details(long? id) { if (id == null) { return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } Insulin_Dosage insulin_Dosage = db.Insulin_Dosage.Find(id); if (insulin_Dosage == null) { return HttpNotFound(); } return View(insulin_Dosage); } // GET: Insulin_Dosage/Create public ActionResult Create() { ViewBag.Blood_Sugar_Range_ID = new SelectList(db.Blood_Sugar_Range, "Blood_Sugar_Range_ID", "Blood_Sugar_Range_ID"); ViewBag.User_ID = new SelectList(db.Users, "User_ID", "First_Name"); return View(); } // POST: Insulin_Dosage/Create // To protect from overposting attacks, please enable the specific properties you want to bind to, for // more details see http://go.microsoft.com/fwlink/?LinkId=317598. [HttpPost] [ValidateAntiForgeryToken] public ActionResult Create([Bind(Include = "Dosage_ID,User_ID,Blood_Sugar_Range_ID,Insulin_Dosage1")] Insulin_Dosage insulin_Dosage) { if (ModelState.IsValid) { db.Insulin_Dosage.Add(insulin_Dosage); db.SaveChanges(); return RedirectToAction("Index"); } ViewBag.Blood_Sugar_Range_ID = new SelectList(db.Blood_Sugar_Range, "Blood_Sugar_Range_ID", "Blood_Sugar_Range_ID", insulin_Dosage.Blood_Sugar_Range_ID); ViewBag.User_ID = new SelectList(db.Users, "User_ID", "First_Name", insulin_Dosage.User_ID); return View(insulin_Dosage); } // GET: Insulin_Dosage/Edit/5 public ActionResult Edit(long? id) { if (id == null) { return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } Insulin_Dosage insulin_Dosage = db.Insulin_Dosage.Find(id); if (insulin_Dosage == null) { return HttpNotFound(); } ViewBag.Blood_Sugar_Range_ID = new SelectList(db.Blood_Sugar_Range, "Blood_Sugar_Range_ID", "Blood_Sugar_Range_ID", insulin_Dosage.Blood_Sugar_Range_ID); ViewBag.User_ID = new SelectList(db.Users, "User_ID", "First_Name", insulin_Dosage.User_ID); return View(insulin_Dosage); } // POST: Insulin_Dosage/Edit/5 // To protect from overposting attacks, please enable the specific properties you want to bind to, for // more details see http://go.microsoft.com/fwlink/?LinkId=317598. [HttpPost] [ValidateAntiForgeryToken] public ActionResult Edit([Bind(Include = "Dosage_ID,User_ID,Blood_Sugar_Range_ID,Insulin_Dosage1")] Insulin_Dosage insulin_Dosage) { if (ModelState.IsValid) { db.Entry(insulin_Dosage).State = EntityState.Modified; db.SaveChanges(); return RedirectToAction("Index"); } ViewBag.Blood_Sugar_Range_ID = new SelectList(db.Blood_Sugar_Range, "Blood_Sugar_Range_ID", "Blood_Sugar_Range_ID", insulin_Dosage.Blood_Sugar_Range_ID); ViewBag.User_ID = new SelectList(db.Users, "User_ID", "First_Name", insulin_Dosage.User_ID); return View(insulin_Dosage); } // GET: Insulin_Dosage/Delete/5 public ActionResult Delete(long? id) { if (id == null) { return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } Insulin_Dosage insulin_Dosage = db.Insulin_Dosage.Find(id); if (insulin_Dosage == null) { return HttpNotFound(); } return View(insulin_Dosage); } // POST: Insulin_Dosage/Delete/5 [HttpPost, ActionName("Delete")] [ValidateAntiForgeryToken] public ActionResult DeleteConfirmed(long id) { Insulin_Dosage insulin_Dosage = db.Insulin_Dosage.Find(id); db.Insulin_Dosage.Remove(insulin_Dosage); db.SaveChanges(); return RedirectToAction("Index"); } protected override void Dispose(bool disposing) { if (disposing) { db.Dispose(); } base.Dispose(disposing); } } }
using System; using System.Collections.Generic; namespace nguoiduado.Models { public class ListModel<T> where T : class { public Decimal TotalRecord { get; set; } public int PageSize { get; set; } public int PageNumber { get; set; } public IEnumerable<T> ListDiplay { get; set; } public Decimal MaNoiDung { get; set; } //Dùng để tìm kiếm public DateTime TuNgay { get; set; } public DateTime DenNgay { get; set; } //Dùng cho Văn Bản public int ID { get; set; } public IEnumerable<T> ListDiplayVanBan { get; set; } public string TenVanBan { get; set; } public string TenMenu { get; set; } } }
namespace SGDE.Domain.Converters { #region Using using System.Collections.Generic; using System.Linq; using Entities; using ViewModels; #endregion public class TypeClientConverter { public static TypeClientViewModel Convert(TypeClient typeClient) { if (typeClient == null) return null; var typeClientViewModel = new TypeClientViewModel { id = typeClient.Id, addedDate = typeClient.AddedDate, modifiedDate = typeClient.ModifiedDate, iPAddress = typeClient.IPAddress, name = typeClient.Name, description = typeClient.Description }; return typeClientViewModel; } public static List<TypeClientViewModel> ConvertList(IEnumerable<TypeClient> typeClients) { return typeClients?.Select(typeClient => { var model = new TypeClientViewModel { id = typeClient.Id, addedDate = typeClient.AddedDate, modifiedDate = typeClient.ModifiedDate, iPAddress = typeClient.IPAddress, name = typeClient.Name, description = typeClient.Description }; return model; }) .ToList(); } } }
using System; using Logs.Models; namespace Logs.Factories { public interface INutritionFactory { Nutrition CreateNutrition(int calories, int protein, int carbs, int fats, double water, int fiber, int sugar, string notes, string userId, DateTime date); } }
using System; using System.Collections.Generic; using System.Data.Entity.Infrastructure; using System.Data.Entity.Validation; using System.Linq; using System.Web; namespace Project_NotesDeFrais.Models.Reposirery { public class TvasRepositery { NotesDeFraisEntities e; public TvasRepositery() { e = new NotesDeFraisEntities(); } public void AddTva(Tvas tva) { using (new NotesDeFraisEntities()) { e.Tvas.Add(tva); e.SaveChanges(); } } public void updateTvas(Tvas tva, String name, double value) { using (new NotesDeFraisEntities()) { tva.Name = name; tva.Value = value; e.SaveChanges(); } } public IQueryable<Tvas> allTvas() { using (new NotesDeFraisEntities()) { var tvas = e.Tvas.OrderBy(r => r.TVA_ID); return tvas; } } public Tvas tvasById(Guid Id) { using (new NotesDeFraisEntities()) { var tvas = (from t in e.Tvas where t.TVA_ID == Id select t).FirstOrDefault(); ; return tvas; } } public IQueryable<Tvas> getSerachingTvas(String query) { using (new NotesDeFraisEntities()) { var tvas = (from s in e.Tvas where s.Name.Contains(query) select s).OrderBy(r => r.TVA_ID); return tvas; } } public void delete(Tvas tva) { using (new NotesDeFraisEntities()) { e.Tvas.Remove(tva); } } public void Save() { try { e.SaveChanges(); } catch (DbEntityValidationException ex) { foreach (DbEntityValidationResult item in ex.EntityValidationErrors) { // Get entry DbEntityEntry entry = item.Entry; string entityTypeName = entry.Entity.GetType().Name; // Display or log error messages foreach (DbValidationError subItem in item.ValidationErrors) { string message = string.Format("Error '{0}' occurred in {1} at {2}", subItem.ErrorMessage, entityTypeName, subItem.PropertyName); Console.WriteLine(message); } } } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Windows; using System.Windows.Controls; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Animation; using System.Windows.Shapes; using PhuThuyDuaThu.Codes; using System.Security.Cryptography; using System.Text; using System.Windows.Browser; namespace PhuThuyDuaThu.Controls { public partial class GameOver : UserControl { GameServices.GameServicesSoapClient service = new PhuThuyDuaThu.GameServices.GameServicesSoapClient(); string securityKey = "ahgnuocgnudgnouhpuhtaudyuhtuhp"; bool _isSubmitting = false; MapNumbersToImages ctrlNumber; public GameOver() { InitializeComponent(); this.Loaded += new RoutedEventHandler(GameOver_Loaded); } void GameOver_Loaded(object sender, RoutedEventArgs e) { service.GetChallengeIDCompleted += new EventHandler<PhuThuyDuaThu.GameServices.GetChallengeIDCompletedEventArgs>(service_GetChallengeIDCompleted); service.UpdateScoreCompleted += new EventHandler<PhuThuyDuaThu.GameServices.UpdateScoreCompletedEventArgs>(service_UpdateScoreCompleted); ctrlNumber = new MapNumbersToImages(GlobalVarialble.Points, Constants.YellowNumber, 30, 30, true); ctrlNumber.SetValue(Canvas.LeftProperty, (double)200); ctrlNumber.SetValue(Canvas.TopProperty, (double)240); this.canvasGameOver.Children.Add(ctrlNumber); } #region Save Point void service_UpdateScoreCompleted(object sender, PhuThuyDuaThu.GameServices.UpdateScoreCompletedEventArgs e) { int point = e.Result; if (point > -1) MessageBox.Show("Đã lưu điểm cao nhất của bạn! Bạn được thưởng " + point + " kẹo!"); else MessageBox.Show("Có lỗi xảy ra!"); _isSubmitting = false; HtmlPage.Document.GetElementById("silverlightLoading").SetStyleAttribute("display", "none"); HtmlPage.Document.GetElementById("silverlightMask").SetStyleAttribute("display", "none"); this.ReplayGame(); } void service_GetChallengeIDCompleted(object sender, PhuThuyDuaThu.GameServices.GetChallengeIDCompletedEventArgs e) { int challengeID = e.Result; string hash = CalculateHash(GlobalVarialble.Points, securityKey); service.UpdateScoreAsync(hash, challengeID, GlobalVarialble.Points); } string CalculateHash(int score, string securityKey) { string str = score + "Secux" + securityKey + "ite"; SHA256Managed sha = new SHA256Managed(); Encoding encoding = Encoding.UTF8; return Convert.ToBase64String(sha.ComputeHash(encoding.GetBytes(str))); } #endregion private void hplReplay_MouseEnter(object sender, MouseEventArgs e) { this.imgBtnReplay.Visibility = Visibility.Collapsed; this.imgBtnReplaySelected.Visibility = Visibility.Visible; } private void hplReplay_MouseLeave(object sender, MouseEventArgs e) { this.imgBtnReplay.Visibility = Visibility.Visible; this.imgBtnReplaySelected.Visibility = Visibility.Collapsed; } private void hplReplay_Click(object sender, RoutedEventArgs e) { this.ReplayGame(); } private void hplSavePoint_MouseEnter(object sender, MouseEventArgs e) { this.imgBtnSavePoint.Visibility = Visibility.Collapsed; this.imgBtnSavePointSelected.Visibility = Visibility.Visible; } private void hplSavePoint_MouseLeave(object sender, MouseEventArgs e) { this.imgBtnSavePoint.Visibility = Visibility.Visible; this.imgBtnSavePointSelected.Visibility = Visibility.Collapsed; } private void hplSavePoint_Click(object sender, RoutedEventArgs e) { //Lưu điểm if (!_isSubmitting) { _isSubmitting = true; HtmlPage.Document.GetElementById("silverlightMask").SetStyleAttribute("display", "block"); HtmlPage.Document.GetElementById("silverlightLoading").SetStyleAttribute("display", "block"); service.GetChallengeIDAsync(GlobalVarialble.GameID); } } private void ReplayGame() { this.canvasGameOver.Children.Clear(); this.canvasGameOver.Children.Add(new Home()); } } }
using Contoso.Forms.Configuration.DataForm; using Contoso.XPlatform.ViewModels.Validatables; using System; using System.Collections.Generic; using System.Collections.ObjectModel; namespace Contoso.XPlatform.Services { public interface IEntityUpdater { TModel ToModelObject<TModel>(ObservableCollection<IValidatable> modifiedProperties, List<FormItemSettingsDescriptor> fieldSettings, TModel? destination = null) where TModel : class; object ToModelObject(Type modelType, ObservableCollection<IValidatable> modifiedProperties, List<FormItemSettingsDescriptor> fieldSettings, object? destination = null); } }
// // 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.Collections.Generic; using Dnn.PersonaBar.Library.Model; namespace Dnn.PersonaBar.Library.Controllers { public interface IExtensionController { string GetPath(PersonaBarExtension extension); bool Visible(PersonaBarExtension extension); IDictionary<string, object> GetSettings(PersonaBarExtension extension); } }
using Prism.Modularity; using Prism.Regions; using System; using System.ComponentModel.Composition; using Prism.Mef.Modularity; using Infrastructure; namespace ModuleB { [ModuleExport(typeof(ModuleBModule), InitializationMode = InitializationMode.WhenAvailable)] public class ModuleBModule : IModule { IRegionManager _regionManager; [ImportingConstructor] public ModuleBModule(IRegionManager regionManager) { _regionManager = regionManager; } public void Initialize() { _regionManager.RegisterViewWithRegion(RegionNames.ToolRegion, typeof(MenuViewModel)); } } }
using UnityEngine; using System.Collections; public class Car : MonoBehaviour { public Transform derechaR; public Transform izquierdaR; public float potencia = 200f; public float anguloMaxGiro = 30f; private float aceleracion = 0f; private float gasto=0f; public float consumo=0.01f; /* void Start() { rigidbody.centerOfMass=Vector3.zero; }*/ void FixedUpdate () { //hacia adelante y hacia atras Desplazamiento(); //giro Giro(); Fin(); if(aceleracion==0) { GameMaster.acelerando=false; } else { GameMaster.acelerando=true; } } void Desplazamiento() { if(GameMaster.combustible>0) { if(aceleracion>=0) { aceleracion= Input.GetAxis("Vertical")*potencia*10; rigidbody.AddRelativeForce(new Vector3(0,0,aceleracion)); gasto=Mathf.Abs(aceleracion)*consumo; GameMaster.combustible-=gasto; } else if(aceleracion<=0) { aceleracion= Input.GetAxis("Vertical")*(potencia/2)*10; rigidbody.AddRelativeForce(new Vector3(0,0,aceleracion)); gasto=Mathf.Abs(aceleracion)*consumo; GameMaster.combustible-=gasto; } } else{ aceleracion=0; } } void Giro() { float rotacion=Input.GetAxis("Horizontal")*anguloMaxGiro; if(aceleracion>0) { derechaR.localEulerAngles=new Vector3(0,rotacion*-1,0); izquierdaR.localEulerAngles=new Vector3(0,rotacion*-1,0); this.transform.eulerAngles=new Vector3(0,this.transform.eulerAngles.y+Input.GetAxis("Horizontal"),0); } else { derechaR.localEulerAngles=new Vector3(0,rotacion*-1,0); izquierdaR.localEulerAngles=new Vector3(0,rotacion*-1,0); } } void Fin() { if(GameMaster.vida<=0) { Application.LoadLevel("vehiculoDestroy"); GameMaster.combustible=1000; GameMaster.vida=100; GameMaster.muertes=0; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using WebApplication.Core.IRepository; namespace WebApplication.Repository { public class UserRepository : IUserRepository { public string Welcome() { return "Hai"; } } }
using System; using System.Collections.Generic; using PropOhGate.Data; using PropOhGate.Message; using PropOhGate.Send; using Fleck; namespace PropOhGate.WebSockets.Send { public class WebSocketSendListener : SendListener { private WebSocketServer _server; private readonly Dictionary<Guid, WebSocketSender> _clients = new Dictionary<Guid, WebSocketSender>(); public WebSocketSendListener(Repository repository) : base(repository) { } public void Start(string uri) { _server = new WebSocketServer(uri); _server.Start(socket => { socket.OnOpen = () => OnOpen(socket); socket.OnClose = () => OnClose(socket); socket.OnBinary = data => OnBinary(socket, data); socket.OnError = ex => OnError(socket, ex); }); } public void Stop() { if (_server != null) { _server.Dispose(); } } private void OnOpen(IWebSocketConnection connection) { lock (_clients) { var sender = new WebSocketSender(connection, Repository.GetRepositoryHash()); _clients[connection.ConnectionInfo.Id] = sender; } } private void OnBinary(IWebSocketConnection connection, byte[] data) { lock (_clients) { WebSocketSender sender; if (_clients.TryGetValue(connection.ConnectionInfo.Id, out sender)) { if (data.IsSubscribe()) { DoSubscribe(sender); } else if (data.IsUnsubscribe()) { DoUnsubscribe(connection); } } } } private void OnClose(IWebSocketConnection connection) { lock (_clients) { DoUnsubscribe(connection); } } private void OnError(IWebSocketConnection connection, Exception ex) { Console.WriteLine("There was an error: {0}", ex.Message); OnClose(connection); } private void DoSubscribe(WebSocketSender sender) { if (sender.Subscription == null) { sender.Subscription = Subscribe(sender); } } private void DoUnsubscribe(IWebSocketConnection connection) { lock (_clients) { WebSocketSender sender; if (_clients.TryGetValue(connection.ConnectionInfo.Id, out sender)) { if (sender.Subscription != null) { sender.Subscription.Dispose(); } _clients.Remove(connection.ConnectionInfo.Id); connection.Close(); } } } } }
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; namespace MacroWeb.Models { public class Comment { [Key] public int CommentId {get; set;} // one to many user public int UserId {get; set;} public User Creator {get; set;} // one to many massage public int MessageId {get; set;} public Message OfMessage {get; set;} [Required(ErrorMessage="This field is required")] [MinLength(5, ErrorMessage="{0} must be at least {1} characters")] public string CommentContent {get; set;} [DisplayFormat(DataFormatString = "{0:MM/dd/yyyy)")] public DateTime CreatedAt {get; set;} = DateTime.Now; [DisplayFormat(DataFormatString = "{0:MM/dd/yyyy)")] public DateTime UpdatedAt {get; set;} = DateTime.Now; // many to many users public List<LikedComment> UserLikedThisComment{get; set;} } }
using System; using System.Collections.Generic; using System.Linq; using System.Runtime.InteropServices.ComTypes; using System.Text; using System.Web; using System.Web.Mvc; using workshop4.Models; namespace workshop4.Controllers { public class DemoController : Controller { // GET: Demo public ActionResult Index() { return View(); } [HttpPost()] public JsonResult GetTestData(string testString) { return Json(testString + "ajax"); } [HttpPost()] public JsonResult GetDropDownListData() { List<string> tempData = new List<string>(); tempData.Add("item 1"); tempData.Add("item 1"); tempData.Add("item 1"); return Json(tempData); } [HttpPost()] public JsonResult GetGridListData() { List<Models.Demo> tempData = new List<Demo>(); tempData.Add(new Demo("1","eric")); tempData.Add(new Demo("1", "eric")); tempData.Add(new Demo("1", "eric")); return Json(tempData); } [HttpPost()] public JsonResult GetAutoCompleteData() { List<string> tempData = new List<string>(); tempData.Add("資料庫設計"); tempData.Add("資料庫a"); tempData.Add("資料庫b"); tempData.Add("演算法"); return Json(tempData); } } }
using DAL; using Entidades; using System; using System.Collections.Generic; using System.Data.Entity; using System.Linq; using System.Text; using System.Threading.Tasks; namespace BLL { public class RepositorioCompras : RepositorioBase<Compras> { internal Contexto db; public override bool Guardar(Compras entity) { bool paso = false; db = new Contexto(); RepositorioBase<Agricultores> dbA = new RepositorioBase<Agricultores>(); Contexto dbP = new Contexto(); try { Agricultores agriculto = dbA.Buscar(entity.IdAgricultor); agriculto.Balance += entity.Total; dbA.Modificar(agriculto); db.Compra.Add(entity); paso = db.SaveChanges() > 0; var producto = dbP.Producto.Where(P=> P.Descripcion.Equals("Arroz Cascara")).FirstOrDefault<Productos>(); if(producto != null) { producto.Existencia += entity.CantidadSacos; dbP.Entry(producto).State = EntityState.Modified; dbP.SaveChanges(); } } catch (Exception) { throw; } return paso; } public override bool Modificar(Compras entity) { bool paso = false; db = new Contexto(); Contexto db2 = new Contexto(); Contexto dbP = new Contexto(); RepositorioBase<Agricultores> dbA = new RepositorioBase<Agricultores>(); try { var anterior = db2.Compra.Find(entity.IdCompra); var producto = dbP.Producto.Where(P => P.Descripcion.Equals("Arroz Cascara")).FirstOrDefault<Productos>(); if (producto != null) { producto.Existencia -= anterior.CantidadSacos; producto.Existencia += entity.CantidadSacos; dbP.Entry(producto).State = EntityState.Modified; dbP.SaveChanges(); } Agricultores agriculto = dbA.Buscar(entity.IdAgricultor); agriculto.Balance -= anterior.Total; agriculto.Balance += entity.Total; dbA.Modificar(agriculto); db.Entry(entity).State = EntityState.Modified; paso = db.SaveChanges() > 0; } catch (Exception) { throw; } return paso; } public override bool Elimimar(int id) { db = new Contexto(); Contexto dbP = new Contexto(); RepositorioBase<Agricultores> dbA = new RepositorioBase<Agricultores>(); bool paso = false; try { var eliminar = db.Compra.Find(id); var agricultor = dbA.Buscar(eliminar.IdAgricultor); agricultor.Balance -= eliminar.Total; dbA.Modificar(agricultor); var producto = dbP.Producto.Where(P => P.Descripcion.Equals("Arroz Cascara")).FirstOrDefault<Productos>(); if (producto != null) { producto.Existencia -= eliminar.CantidadSacos; dbP.Entry(producto).State = EntityState.Modified; dbP.SaveChanges(); } db.Entry(eliminar).State = EntityState.Modified; paso = db.SaveChanges() > 0; } catch(Exception) { throw; } return paso; } } }