text stringlengths 13 6.01M |
|---|
// Skeleton written by Joe Zachary for CS 3500, January 2015
// Revised by Joe Zachary, January 2016
// JLZ Repaired pair of mistakes, January 23, 2016
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
namespace Formulas
{
/// <summary>
/// Represents formulas written in standard infix notation using standard precedence
/// rules. Provides a means to evaluate Formulas. Formulas can be composed of
/// non-negative floating-point numbers, variables, left and right parentheses, and
/// the four binary operator symbols +, -, *, and /. (The unary operators + and -
/// are not allowed.)
/// </summary>
public struct Formula
{
private const string lpPattern = @"\(";
private const string rpPattern = @"\)";
private const string opPattern = @"^[\+\-*/]$";
private const string varPattern = @"[a-zA-Z][0-9]+";
private const string doublePattern = @"(?: \d+\.\d* | \d*\.\d+ | \d+ ) (?: e[\+-]?\d+)?";
private const string spacePattern = @"\s+";
private List<string> _tokens;
private Validator _validator;
/// <summary>
/// Creates a Formula from a string that consists of a standard infix expression composed
/// from non-negative floating-point numbers (using C#-like syntax for double/int literals),
/// variable symbols (a letter followed by zero or more letters and/or digits), left and right
/// parentheses, and the four binary operator symbols +, -, *, and /. White space is
/// permitted between tokens, but is not required.
///
/// Examples of a valid parameter to this constructor are:
/// "2.5e9 + x5 / 17"
/// "(5 * 2) + 8"
/// "x*y-2+35/9"
///
/// Examples of invalid parameters are:
/// "_"
/// "-5.3"
/// "2 5 + 3"
///
/// If the formula is syntacticaly invalid, throws a FormulaFormatException with an
/// explanatory Message.
/// </summary>
public Formula(string formula)
{
List<string> tokens = GetTokens(formula).ToList();
_tokens = tokens;
_validator = null;
}
/// <summary>
/// Creates a formula with a Normalizer and Validator.
/// The purpose of a Normalizer is to convert variables into a canonical form.
/// The purpose of a Validator is to impose extra restrictions on the validity of a variable,
/// beyond the ones already built into the Formula definition.
/// </summary>
public Formula(string formula, Normalizer normalizer, Validator validator) : this()
{
List<string> tokens = GetTokens(formula, normalizer).ToList();
_validator = validator;
_tokens = tokens;
}
public void ValidateFormula()
{
if (_tokens.Count <= 0) throw new FormulaFormatException("Formula must contain at least one token.");
ValidateTokens(_tokens, _validator);
ValidateParentheses(_tokens);
ValidateOrderOfOperations(_tokens);
}
/// <summary>
/// Tests the order of operations in a list of tokens from a formula.
/// </summary>
/// <param name="tokens">List of strings (tokens) to check.</param>
private static void ValidateOrderOfOperations(List<string> tokens)
{
//The first token of a formula must be a number, a variable, or an opening parenthesis.
if (!Regex.IsMatch(tokens[0], $"({doublePattern}) | ({varPattern}) | ({lpPattern})",
RegexOptions.IgnorePatternWhitespace))
{
throw new FormulaFormatException(
"The first token of a formula must be a number, a variable, or an opening parenthesis.");
}
//The last token of a formula must be a number, a variable, or a closing parenthesis.
if (
!Regex.IsMatch(tokens.Last(), $"({doublePattern}) | ({varPattern}) | ({rpPattern})",
RegexOptions.IgnorePatternWhitespace))
{
throw new FormulaFormatException(
"The last token of a formula must be a number, a variable, or a closing parenthesis.");
}
for (int i = 0; i < tokens.Count - 1; i++)
{
// Any token that immediately follows a number, a variable, or a closing parenthesis must be either an operator or a closing parenthesis.
if (Regex.IsMatch(tokens[i], $"({doublePattern}) | ({varPattern}) | ({rpPattern})",
RegexOptions.IgnorePatternWhitespace))
{
if (
!Regex.IsMatch(tokens[i + 1], $"({opPattern}) | ({rpPattern})",
RegexOptions.IgnorePatternWhitespace))
{
throw new FormulaFormatException(
"Any token that immediately follows a number, a variable, or a closing parenthesis must be either an operator or a closing parenthesis.");
}
}
// Any token that immediately follows an opening parenthesis or an operator must be either a number, a variable, or an opening parenthesis.
if (Regex.IsMatch(tokens[i], $"({lpPattern}) | ({opPattern})", RegexOptions.IgnorePatternWhitespace))
{
if (
!Regex.IsMatch(tokens[i + 1], $"({doublePattern}) | ({varPattern}) | ({lpPattern})",
RegexOptions.IgnorePatternWhitespace))
{
throw new FormulaFormatException(
"Any token that immediately follows an opening parenthesis or an operator must be either a number, a variable, or an opening parenthesis.");
}
}
}
}
/// <summary>
/// Validates all tokens in a formula that they match one of the patterns.
/// Also validates against a given validator.
/// </summary>
private void ValidateTokens(List<string> tokens, Validator validator)
{
ValidateTokens(tokens);
foreach (var token in tokens.Where(token => Regex.IsMatch(token, $"^{varPattern}$")))
{
if (validator != null && !validator.Invoke(token))
{
throw new FormulaFormatException($"Validator caught an invalid token '{token}'.");
}
}
}
/// <summary>
/// Validates all tokens in a formula that they match one of the patterns.
/// </summary>
private static void ValidateTokens(List<string> tokens)
{
string pattern = $"({lpPattern}) | ({rpPattern}) | ({opPattern}) | ({varPattern}) | ({doublePattern})";
foreach (string token in tokens)
{
if (!Regex.IsMatch(token, pattern, RegexOptions.IgnorePatternWhitespace))
{
throw new FormulaFormatException($"Invalid token in formula: \"{token}\"");
}
}
}
/// <summary>
/// Checks that the number of opening parantheses is equal to the number of closing parantheses.
/// Checks that the number of closing parentheses when read from left to right is never greater than
/// the number of opening perentheses seen so far.
/// </summary>
/// <param name="tokens">List of strings (tokens) to check.</param>
/// <returns></returns>
private static void ValidateParentheses(List<string> tokens)
{
int right;
var left = right = 0;
foreach (var token in tokens)
{
if (token == "(") left++;
if (token == ")") right++;
if (right > left) throw new FormulaFormatException("Invalid order of parentheses.");
}
if (left != right) throw new FormulaFormatException("Invalid number of parentheses.");
}
/// <summary>
/// Evaluates this Formula, using the Lookup delegate to determine the values of variables. (The
/// delegate takes a variable name as a parameter and returns its value (if it has one) or throws
/// an UndefinedVariableException (otherwise). Uses the standard precedence rules when doing the evaluation.
///
/// If no undefined variables or divisions by zero are encountered when evaluating
/// this Formula, its value is returned. Otherwise, throws a FormulaEvaluationException
/// with an explanatory Message.
/// </summary>
public double Evaluate(Lookup lookup)
{
Stack<object> operatorStack = new Stack<object>();
Stack<double> valueStack = new Stack<double>();
if (_tokens == null) _tokens = new List<string> {"0"};
try
{
ValidateFormula();
}
catch (Exception e)
{
throw new FormulaEvaluationException(e.Message);
}
foreach (var token in _tokens)
{
// If it is a variable.
if (Regex.IsMatch(token, $"^{varPattern}$", RegexOptions.IgnorePatternWhitespace))
{
HandleVariable(lookup, token, operatorStack, valueStack);
}
// If it is a double.
if (Regex.IsMatch(token, $"^{doublePattern}$", RegexOptions.IgnorePatternWhitespace))
{
HandleDouble(token, operatorStack, valueStack);
}
// If it is a operator or a '('.
if (Regex.IsMatch(token, $"({opPattern}) | ({lpPattern})", RegexOptions.IgnorePatternWhitespace))
{
HandleOpAndLp(token, operatorStack, valueStack);
}
//If it is a ')'.
if (Regex.IsMatch(token, rpPattern, RegexOptions.IgnorePatternWhitespace))
{
HandleRightParenthesis(operatorStack, valueStack);
}
}
if (operatorStack.Count > 0)
{
return Operate(operatorStack.Pop(), valueStack.Pop(), valueStack.Pop());
}
return valueStack.Pop();
}
/// <summary>
/// If + or - is at the top of the operator stack, pop the value stack twice and the
/// operator stack once. Apply the popped operator to the popped numbers.
/// Push the result onto the value stack.
/// </summary>
private static void HandleOpAndLp(string token, Stack<object> operatorStack, Stack<double> valueStack)
{
if (token == "+" || token == "-")
{
if (operatorStack.Count >= 1 && new[] {"+", "-"}.Contains(operatorStack.Peek()))
{
valueStack.Push(Operate(operatorStack.Pop(), valueStack.Pop(), valueStack.Pop()));
}
}
//push token onto the operator stack no matter what.
operatorStack.Push(token);
}
/// <summary>
/// If * or / is at the top of the operator stack, pop the value stack, pop the operator stack,
/// and apply the popped operator to t and the popped number. Push the result onto the value stack.
/// Otherwise, push t onto the value stack
/// </summary>
private static void HandleDouble(string token, Stack<object> operatorStack, Stack<double> valueStack)
{
double value = double.Parse(token);
if (operatorStack.Count > 0 && new[] {"/", "*"}.Contains(operatorStack.Peek()))
{
valueStack.Push(Operate(operatorStack.Pop(), value, valueStack.Pop()));
}
else
{
valueStack.Push(value);
}
}
/// <summary>
/// If * or / is at the top of the operator stack, pop the value stack, pop the operator stack,
/// and apply the popped operator to t and the popped number.Push the result onto the value stack.
/// Otherwise, push t onto the value stack
/// </summary>
private static void HandleVariable(Lookup lookup, string token, Stack<object> operatorStack, Stack<double> valueStack)
{
double value;
try
{
value = lookup(token);
}
catch (CircularException e)
{
throw new FormulaEvaluationException(e.Message);
}
catch (UndefinedVariableException e)
{
throw new FormulaEvaluationException(e.Message);
}
if (double.IsNaN(value))
{
throw new UndefinedVariableException($"Could not find value for variable: {token}.");
}
if (operatorStack.Count > 0 && new[] {"/", "*"}.Contains(operatorStack.Peek()))
{
valueStack.Push(Operate(operatorStack.Pop(), value, valueStack.Pop()));
}
else
{
valueStack.Push(value);
}
}
/// <summary>
/// If + or - is at the top of the operator stack, pop the value stack twice and the operator stack once.
/// Apply the popped operator to the popped numbers.Push the result onto the value stack.
///
/// Whether or not you did the first step, the top of the operator stack will be a (. Pop it.
///
/// After you have completed the previous step, if *or / is at the top of the operator stack,
/// pop the value stack twice and the operator stack once. Apply the popped operator to the
/// popped numbers. Push the result onto the value stack.
/// </summary>
private static void HandleRightParenthesis(Stack<object> operatorStack, Stack<double> valueStack)
{
if (operatorStack.Count > 0 && new[] {"+", "-"}.Contains(operatorStack.Peek()))
{
valueStack.Push(Operate(operatorStack.Pop(), valueStack.Pop(), valueStack.Pop()));
}
operatorStack.Pop();
if (operatorStack.Count > 0 && new[] {"*", "/"}.Contains(operatorStack.Peek()))
{
valueStack.Push(Operate(operatorStack.Pop(), valueStack.Pop(), valueStack.Pop()));
}
}
/// <summary>
/// Applies the operator between two doubles.
/// </summary>
/// <param name="op">The operator to apply.</param>
/// <returns></returns>
public static double Operate(object op, double num1, double num2)
{
switch (op.ToString())
{
case "+": return num2 + num1;
case "-": return num2 - num1;
case "*": return num2 * num1;
case "/":
if (num1 == 0) throw new FormulaEvaluationException("Divide by zero.");
return num2 / num1;
case "%": return num2 % num1;
default: throw new FormulaFormatException($"Invalid operation: {op}");
}
}
/// <summary>
/// Given a formula, enumerates the tokens that compose it. Tokens are left paren,
/// right paren, one of the four operator symbols, a string consisting of a letter followed by
/// zero or more digits and/or letters, a double literal, and anything that doesn't
/// match one of those patterns. There are no empty tokens, and no token contains white space.
/// </summary>
private static IEnumerable<string> GetTokens(string formula, Normalizer normalizer = null)
{
string pattern = $"({lpPattern}) | ({rpPattern}) | ({opPattern}) | ({varPattern}) | ({doublePattern}) | ({spacePattern})";
// Enumerate matching tokens that don't consist solely of white space.
foreach (string s in Regex.Split(formula, pattern, RegexOptions.IgnorePatternWhitespace))
{
if (!Regex.IsMatch(s, @"^\s*$", RegexOptions.Singleline))
{
if (normalizer != null && Regex.IsMatch(s, $"^{varPattern}$")) yield return normalizer.Invoke(s);
else yield return s;
}
}
}
/// <summary>
/// Returns the original formula as it was entered to begin with.
/// </summary>
public override string ToString()
{
if (_tokens == null) _tokens = new List<string> { "0" };
string result = _tokens.Aggregate("", (current, token) => current + token + " ");
return result.Trim();
}
public ISet<string> GetVariables()
{
if (_tokens == null) _tokens = new List<string>{ "0" };
return new HashSet<string>(_tokens.Where(token => Regex.IsMatch(token, $"^{varPattern}$")));
}
}
/// <summary>
/// A Lookup method is one that maps some strings to double values. Given a string,
/// such a function can either return a double (meaning that the string maps to the
/// double) or throw an UndefinedVariableException (meaning that the string is unmapped
/// to a value. Exactly how a Lookup method decides which strings map to doubles and which
/// don't is up to the implementation of the method.
/// </summary>
public delegate double Lookup(string s);
public delegate string Normalizer(string s);
public delegate bool Validator(string s);
/// <summary>
/// Used to report that a Lookup delegate is unable to determine the value
/// of a variable.
/// </summary>
public class UndefinedVariableException : Exception
{
/// <summary>
/// Constructs an UndefinedVariableException containing whose message is the
/// undefined variable.
/// </summary>
/// <param name="variable"></param>
public UndefinedVariableException(String variable)
: base(variable)
{
}
}
/// <summary>
/// Thrown to indicate that a change to a cell will cause a circular dependency.
/// </summary>
public class CircularException : Exception
{
/// <summary>
/// Creates the exception with a message
/// </summary>
public CircularException(string msg)
: base(msg)
{
}
}
/// <summary>
/// Used to report syntactic errors in the parameter to the Formula constructor.
/// </summary>
public class FormulaFormatException : Exception
{
/// <summary>
/// Constructs a FormulaFormatException containing the explanatory message.
/// </summary>
public FormulaFormatException(String message) : base(message)
{
}
}
/// <summary>
/// Used to report errors that occur when evaluating a Formula.
/// </summary>
public class FormulaEvaluationException : Exception
{
/// <summary>
/// Constructs a FormulaEvaluationException containing the explanatory message.
/// </summary>
public FormulaEvaluationException(String message) : base(message)
{
}
}
}
|
namespace gView.Framework.Data
{
public interface IOID
{
/// <summary>
/// The object ID of the object.
/// </summary>
int OID { get; }
}
/*
public interface IFeatureBuffer
{
IFeature CreateFeature();
bool Store();
}
*/
}
|
using Alabo.Domains.Entities.Core;
namespace Alabo.Datas.Stores.Column {
public interface IColumnStore<TEntity, in TKey> where TEntity : class, IKey<TKey>, IVersion, IEntity {
object GetFieldValue(object id, string field);
}
} |
using System;
namespace Task_03
{
class Program
{
static void Generate(int[] array)
{
Random random = new Random();
for (int i = 0; i < array.Length; i++)
{
array[i] = random.Next(-10, 11);
}
}
static void Swap(int[] array)
{
int[] newArray1 = Array.FindAll(array, i => i >= 0);
int[] newArray2 = Array.FindAll(array, i => i < 0);
for (int i = 0; i < array.Length; i++)
{
if (i < newArray1.Length)
{
array[i] = newArray1[i];
}
else
{
array[i] = newArray2[i - newArray1.Length];
}
}
}
static void Main(string[] args)
{
int[] myArray = new int[int.Parse(Console.ReadLine())];
Generate(myArray);
Swap(myArray);
Array.ForEach(myArray, i => Console.Write($" {i}"));
}
}
}
|
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using DesafioTecGraf.Domain.Domain;
using DesafioTecGraf.Domain.Service;
namespace DesafioTecGraf.Console
{
public class Program
{
private static void Main(string[] args)
{
var filename = "";
var path = "";
var matriculaService = new MatriculaService();
var solutionpath = Path.GetDirectoryName(Path.GetDirectoryName(System.IO.Directory.GetCurrentDirectory()));
filename = "matriculasSemDV.txt";
path = $@"{solutionpath}\Arquivos\{filename}";
System.Console.WriteLine($"Lendo o Arquivo {filename}");
var matriculasSemDv = matriculaService.LerArquivo(path);
System.Console.WriteLine($"Calculando as matrículas com DV");
var matriculasComDv = (from matricula in matriculasSemDv
where !matricula.Key.Equals("")
select matriculaService.CalcularDigito(matricula.Key)
into matriculas select matriculas.MatriculaDigito)
.ToList();
filename = "matriculasComDV.txt";
System.Console.WriteLine($"Criando o Arquivo {filename}");
matriculaService.CriarTxt(matriculasComDv, filename);
filename = "matriculasParaVerificar.txt";
path = $@"{solutionpath}\Arquivos\{filename}";
System.Console.WriteLine($"Lendo o Arquivo {filename}");
var matriculasValidar = matriculaService.LerArquivo(path);
System.Console.WriteLine($"Validando as matrículas com DV");
var validarMatriculas = (from matricula in matriculasValidar
where !matricula.Key.Equals("")
select matriculaService.ValidatMatriculas
(matricula.Key)
into matriculas
select matriculas.ToString())
.ToList();
filename = "matriculasVerificadas.txt";
System.Console.WriteLine($"Criando o Arquivo {filename}");
matriculaService.CriarTxt(validarMatriculas, filename);
System.Console.ReadKey();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace GerenciadorDespesas.Models
{
public class Meses
{
public int MesId { get; set; }
public string Nome { get; set; }
#region propriedades navegacionais
public ICollection<Despesas> Despesas { get; set; }
public Salarios Salarios { get; set; }
#endregion
}
}
|
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Update;
using Moq;
using RiverPuzzle1.Controllers;
using RiverPuzzle1.Models;
using RiverPuzzle1.Services;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Xunit;
namespace RiverPuzzle1.Tests.Controllers
{
public class GamesControllerTests
{
[Fact]
public void GetGames_ReturnsListOfGames()
{
// Arrange
var gameService = new Mock<IGameService>();
gameService.Setup(s => s.GetGames()).Returns(new List<Game>());
var contoller = new GamesController(gameService.Object);
// Act
var result = contoller.GetGames();
// Assert
Assert.IsAssignableFrom<IEnumerable<Game>>(result);
Assert.Empty(result);
}
[Fact]
public void GetGame_WhenModelStateIsInvalid_ReturnsBadRequest()
{
// Arrange
var gameService = new Mock<IGameService>();
var contoller = new GamesController(gameService.Object);
contoller.ModelState.AddModelError("test", "test");
// Act
var result = contoller.GetGame(1).Result;
// Assert
Assert.IsType<BadRequestObjectResult>(result);
}
[Fact]
public async Task GetGame_WhenModelStateIsValidAndGameDoesNotExist_ReturnNotFound()
{
// Arrange
var game = new Game
{
ID = 1,
StartTime = new DateTime(2018, 01, 01, 00, 00, 00)
};
var gameService = new Mock<IGameService>();
gameService.Setup(s => s.GetGame(1)).Returns(Task.FromResult<Game>(null));
var controller = new GamesController(gameService.Object);
// Act
var result = await controller.GetGame(1);
// Assert
var apiResult = Assert.IsType<NotFoundResult>(result);
}
[Fact]
public async Task GetGame_WhenModelStateIsValidAndGameExists_ReturnGame()
{
// Arrange
var game = new Game
{
ID = 1,
StartTime = new DateTime(2018, 01, 01, 00, 00, 00)
};
var gameService = new Mock<IGameService>();
gameService.Setup(s => s.GetGame(1)).ReturnsAsync(game);
var controller = new GamesController(gameService.Object);
// Act
var result = await controller.GetGame(1);
// Assert
var apiResult = Assert.IsType<OkObjectResult>(result);
var returnedGame = (Game)apiResult.Value;
Assert.Equal(1, returnedGame.ID);
}
[Fact]
public async Task PostGame_WhenCalled_ReturnsNewGame()
{
// Arrange
var gameService = new Mock<IGameService>();
gameService.Setup(s => s.CreateAsync()).ReturnsAsync(new Game { ID = 1 });
var controller = new GamesController(gameService.Object);
// Act
var result = await controller.PostGame();
// Assert
var createdResult = Assert.IsType<CreatedAtActionResult>(result);
Assert.IsType<Game>(createdResult.Value);
}
[Fact]
public async Task PutGame_WhenModelStateIsInvalid_ReturnsBadRequest()
{
// Arrange
var gameService = new Mock<IGameService>();
var controller = new GamesController(gameService.Object);
controller.ModelState.AddModelError("test", "test");
// Act
var result = await controller.PutGame(1, new Game());
// Assert
Assert.IsType<BadRequestObjectResult>(result);
}
[Fact]
public async Task PutGame_WhenModelStateIsValidAndNoExceptionISThrown_ReturnsOk()
{
// Arrange
var game = new Game { ID = 1 };
var gameService = new Mock<IGameService>();
gameService.Setup(
s => s.UpdateAsync(It.Is<Game>(k => k.ID == 1))
).ReturnsAsync(game);
var controller = new GamesController(gameService.Object);
// Act
var result = await controller.PutGame(1, game);
// Assert
var okObjectResult = Assert.IsType<OkObjectResult>(result);
Assert.IsType<Game>(okObjectResult.Value);
}
[Fact]
public async Task PutGame_WhenModelStateIsValidAndServiceReturnsNull_ReturnsNoBadRequest()
{
// Arrange
var game = new Game { ID = 1 };
var gameService = new Mock<IGameService>();
gameService.Setup(
s => s.UpdateAsync(It.Is<Game>(k => k.ID == 1))
).Returns(Task.FromResult<Game>(null));
var controller = new GamesController(gameService.Object);
// Act
var result = await controller.PutGame(1, game);
// Assert
Assert.IsType<BadRequestResult>(result);
}
[Fact]
public async Task PutGame_WhenModelStateIsValidAndInvalidOperationIsRaised_ReturnsBadRequest()
{
// Arrange
var game = new Game { ID = 1 };
var gameService = new Mock<IGameService>();
gameService.Setup(
s => s.UpdateAsync(It.Is<Game>(k => k.ID == 1))
).Throws(new InvalidOperationException("invalid"));
var controller = new GamesController(gameService.Object);
// Act
var result = await controller.PutGame(1, game);
// Assert
var badRequestObjectResult = Assert.IsType<BadRequestObjectResult>(result);
Assert.Equal("invalid", badRequestObjectResult.Value);
}
[Fact]
public async Task PutGame_WhenModelStateIsValidAndDbUpdateConcurrencyExceptionIsRaised_ReturnsInternalServerError()
{
// Arrange
var updateEntry = new Mock<IUpdateEntry>();
IReadOnlyList<IUpdateEntry> entries = new List<IUpdateEntry>
{
updateEntry.Object
};
var game = new Game { ID = 1 };
var gameService = new Mock<IGameService>();
gameService.Setup(
s => s.UpdateAsync(It.Is<Game>(k => k.ID == 1))
).Throws(new DbUpdateConcurrencyException("invalid", entries));
var controller = new GamesController(gameService.Object);
// Act
var result = await controller.PutGame(1, game);
// Assert
var statusCodeResult = Assert.IsType<StatusCodeResult>(result);
Assert.Equal(500, statusCodeResult.StatusCode);
}
}
}
|
using System;
using System.Collections.Generic;
using Pe.Stracon.SGC.Infraestructura.QueryModel.Contractual;
using Pe.Stracon.SGC.Aplicacion.TransferObject.Response.Contractual;
using Pe.Stracon.SGC.Infraestructura.CommandModel.Contractual;
using Pe.Stracon.SGC.Aplicacion.TransferObject.Request.Contractual;
using System.Linq;
using Pe.Stracon.SGC.Infraestructura.Core.Context;
using Pe.Stracon.Politicas.Aplicacion.TransferObject.Response.General;
namespace Pe.Stracon.SGC.Aplicacion.Adapter.Contractual
{
/// <summary>
/// Implementacion del adaptador de Variable
/// </summary>
public sealed class VariableAdapter
{
/// <summary>
/// Realiza la adaptación de campos logic a response
/// </summary>
/// <param name="variableLogic">Lista de variables tipo Logic</param>
/// <returns>Lista de variables tipo response</returns>
public static VariableResponse ObtenerVariable(VariableLogic variableLogic, List<PlantillaResponse> plantilla, List<CodigoValorResponse> tipoVariable)
{
var variableResponse = new VariableResponse();
string sPlantilla = null;
string sTipos = null;
if (plantilla != null)
{
var listaPlantilla = plantilla.Where(n => n.CodigoPlantilla.ToString() == variableLogic.CodigoPlantilla.ToString()).FirstOrDefault();
sPlantilla = (listaPlantilla == null) ? null : listaPlantilla.Descripcion.ToString();
}
if (tipoVariable != null)
{
var tipos = tipoVariable.Where(t => variableLogic.CodigoTipo.Equals(t.Codigo)).FirstOrDefault();
sTipos = tipos.Valor.ToString();
}
variableResponse.CodigoVariable = variableLogic.CodigoVariable;
variableResponse.CodigoPlantilla = variableLogic.CodigoPlantilla;
variableResponse.DescripcionCodigoPlantilla = sPlantilla;
variableResponse.Identificador = variableLogic.Identificador;
variableResponse.IdentificadorSinAlmohadilla = variableLogic.Identificador.Replace(DatosConstantes.IdentificadorVariable.Almohadilla, string.Empty);
variableResponse.Nombre = variableLogic.Nombre;
variableResponse.CodigoTipo = variableLogic.CodigoTipo;
variableResponse.DescripcionCodigoTipo = sTipos;
variableResponse.DescripcionTipoVariable = variableLogic.DescripcionTipoVariable;
variableResponse.IndicadorGlobal = variableLogic.IndicadorGlobal;
variableResponse.IndicadorVariableSistema = variableLogic.IndicadorVariableSistema;
variableResponse.Descripcion = variableLogic.Descripcion;
return variableResponse;
}
/// <summary>
/// Realiza la adaptación de los campos del request al entity de variable
/// </summary>
/// <param name="variableRequest">Request de Variable</param>
/// <returns>Entity de Variable</returns>
public static VariableEntity ObtenerVariableEntityDesdeVariableRequest(VariableRequest variableRequest)
{
var variableEntity = new VariableEntity();
variableEntity.CodigoVariable = variableRequest.CodigoVariable != null ? new Guid(variableRequest.CodigoVariable) : Guid.NewGuid();
variableEntity.CodigoPlantilla = !Convert.ToBoolean(variableRequest.IndicadorGlobal) ? (variableRequest.CodigoPlantilla != null ? new Guid(variableRequest.CodigoPlantilla) : Guid.Empty) : (Guid?) null;
variableEntity.Identificador = variableRequest.Identificador;
variableEntity.Nombre = variableRequest.Nombre;
variableEntity.CodigoTipo = variableRequest.CodigoTipo;
variableEntity.IndicadorGlobal = Convert.ToBoolean(variableRequest.IndicadorGlobal);
variableEntity.IndicadorVariableSistema = Convert.ToBoolean(variableRequest.IndicadorVariableSistema);
variableEntity.Descripcion = variableRequest.Descripcion;
return variableEntity;
}
/// <summary>
/// Adaptador de Campo de Variable
/// </summary>
/// <param name="variableCampoLogic">Entidad Lógica de Campo de Variable</param>
/// <returns>Entidad Response de Campo de Variable</returns>
public static VariableCampoResponse ObtenerVariableCampo(VariableCampoLogic variableCampoLogic, List<CodigoValorResponse> listaTipoAlineamiento)
{
var tipoAlineamiento = listaTipoAlineamiento.Where(ta => ta.Codigo.Equals(variableCampoLogic.TipoAlineamiento)).FirstOrDefault();
var descripcionTipoAlineamiento = tipoAlineamiento == null ? "" : tipoAlineamiento.Valor.ToString();
return new VariableCampoResponse()
{
CodigoVariableCampo = variableCampoLogic.CodigoVariableCampo,
CodigoVariable = variableCampoLogic.CodigoVariable,
Nombre = variableCampoLogic.Nombre,
Orden = variableCampoLogic.Orden,
TipoAlineamiento = variableCampoLogic.TipoAlineamiento,
DescripcionTipoAlineamiento = descripcionTipoAlineamiento,
Tamanio = variableCampoLogic.Tamanio
};
}
/// <summary>
/// Obtiene la entidad de Campo de Variable
/// </summary>
/// <param name="variableCampoRequest">Request de Campo de Variable</param>
/// <returns>Entidad de Campo de Variable</returns>
public static VariableCampoEntity ObtenerVariableCampoEntity(VariableCampoRequest variableCampoRequest)
{
return new VariableCampoEntity()
{
CodigoVariableCampo = (variableCampoRequest.CodigoVariableCampo == null || variableCampoRequest.CodigoVariableCampo == "" || variableCampoRequest.CodigoVariableCampo == "00000000-0000-0000-0000-000000000000" ? Guid.NewGuid() : new Guid(variableCampoRequest.CodigoVariableCampo)),
CodigoVariable = new Guid(variableCampoRequest.CodigoVariable),
Orden = (byte)variableCampoRequest.Orden,
Nombre = variableCampoRequest.Nombre,
Tamanio = variableCampoRequest.Tamanio.Value,
TipoAlineamiento = variableCampoRequest.TipoAlineamiento
};
}
/// <summary>
/// Adaptador de Lista de Variable
/// </summary>
/// <param name="variableListaLogic">Entidad Lógica de Lista de Variable</param>
/// <returns>Entidad Response de Lista de Variable</returns>
public static VariableListaResponse ObtenerVariableLista(VariableListaLogic variableListaLogic)
{
return new VariableListaResponse()
{
CodigoVariableLista = variableListaLogic.CodigoVariableLista,
CodigoVariable = variableListaLogic.CodigoVariable,
Nombre = variableListaLogic.Nombre,
Descripcion = variableListaLogic.Descripcion
};
}
/// <summary>
/// Obtiene la entidad de Campo de Variable
/// </summary>
/// <param name="variableCampoRequest">Request de Campo de Variable</param>
/// <returns>Entidad de Campo de Variable</returns>
public static VariableListaEntity ObtenerVariableListaEntity(VariableListaRequest variableListaRequest)
{
return new VariableListaEntity()
{
CodigoVariableLista = (variableListaRequest.CodigoVariableLista == null || variableListaRequest.CodigoVariableLista == "" || variableListaRequest.CodigoVariableLista == "00000000-0000-0000-0000-000000000000" ? Guid.NewGuid() : new Guid(variableListaRequest.CodigoVariableLista)),
CodigoVariable = new Guid(variableListaRequest.CodigoVariable),
Nombre = variableListaRequest.Nombre,
Descripcion = variableListaRequest.Descripcion
};
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using AutoMapper;
using Microsoft.EntityFrameworkCore;
using BookLibrary.Data;
using BookLibrary.Models;
using BookLibrary.ViewModels;
namespace BookLibrary.Services
{
public class BooksService : BaseService
{
public BooksService(ApplicationDbContext db, IMapper mapper)
: base(db, mapper)
{
}
public async Task<BookViewModel> GetBookDetails(int? id)
{
Book book = await GetBookById(id);
return _mapper.Map<BookViewModel>(book);
}
public async Task<IEnumerable<BookViewModel>> GetBooksCollection()
{
IEnumerable<Book> booksList = await _db.Books
.Include(b => b.Rentals)
.ToListAsync();
return _mapper.Map<IEnumerable<BookViewModel>>(booksList);
}
public async Task<int> CreateBook(BookViewModel bookViewModel)
{
bookViewModel.Id = 0;
Book book = _mapper.Map<Book>(bookViewModel);
_db.Add(book);
await _db.SaveChangesAsync();
return book.Id;
}
public async Task<int> EditBook(BookViewModel bookViewModel)
{
Book book = await GetBookById(bookViewModel.Id);
try
{
_mapper.Map(bookViewModel, book);
_db.Update(book);
await _db.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException)
{
if (!BookExists(book.Id))
{
throw new ArgumentException("Entity does not exist.");
}
else
{
throw;
}
}
return book.Id;
}
public async Task<bool> DeleteBook(int id)
{
Book book = await GetBookById(id);
_db.Books.Remove(book);
await _db.SaveChangesAsync();
return true;
}
public void Dispose()
{
_db.Dispose();
}
}
}
|
// Copyright © 2020 Void-Intelligence All Rights Reserved.
namespace Vortex.Metrics.Utility
{
public enum EMetricType
{
CategoricalAccuracy,
CategoricalArgMaxAccuracy,
CategoricalF1Score,
CategoricalPrecision,
CategoricalRecall,
RegressionCosineSimilarity,
RegressionRMSE,
RegressionRMSLE,
RegressionRSquared
}
}
|
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Text;
using Microsoft.EntityFrameworkCore.Metadata.Internal;
using System.ComponentModel.DataAnnotations;
namespace DataAccessLayer.dbDTO
{
public class MarkPost
{
public int id { get; set; }
public int posts_id { get; set; }
public int marking_type_id { get; set; }
public DateTime creation_date { get; set; }
}
}
|
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Formatting;
using Microsoft.CodeAnalysis.MSBuild;
using Microsoft.CSharp;
using System;
using System.CodeDom;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
namespace DartVS.DartAnalysis.JsonBuilder
{
public class CSharpFileBuilder
{
readonly string @namespace;
readonly List<CSharpClass> classes = new List<CSharpClass>();
public CSharpFileBuilder(string @namespace)
{
this.@namespace = @namespace;
}
public CSharpClass AddClass(string name, string docComment)
{
var @class = new CSharpClass(name, docComment);
classes.Add(@class);
return @class;
}
public string GetContents()
{
var document =
SyntaxFactory
.NamespaceDeclaration(SyntaxFactory.IdentifierName(@namespace))
.WithMembers(GetClasses());
var workspace = MSBuildWorkspace.Create();
var options = workspace.Options.WithChangedOption(FormattingOptions.UseTabs, LanguageNames.CSharp, true);
var formattedResult = Formatter.Format(document, workspace, options);
var output = new StringBuilder();
using (var sw = new StringWriter(output))
formattedResult.WriteTo(sw);
return output.ToString();
}
SyntaxList<MemberDeclarationSyntax> GetClasses()
{
return SyntaxFactory.List(
classes.Select(c => c.GetClass())
);
}
}
public class CSharpClass
{
readonly string name;
readonly string docComment;
readonly List<CSharpProperty> properties = new List<CSharpProperty>();
public CSharpClass(string name, string docComment)
{
this.name = name;
this.docComment = docComment;
}
public void AddProperty<T>(string name, string docComment)
{
properties.Add(new CSharpProperty(typeof(T), name, docComment));
}
public MemberDeclarationSyntax GetClass()
{
return SyntaxFactory
.ClassDeclaration(name)
.AddModifiers(SyntaxFactory.Token(SyntaxKind.PublicKeyword))
.WithXmlComment(docComment)
.WithMembers(GetProperties());
}
SyntaxList<MemberDeclarationSyntax> GetProperties()
{
return SyntaxFactory.List<MemberDeclarationSyntax>(
properties.Select(p => p.GetProperty())
);
}
}
public class CSharpProperty
{
readonly Type type;
readonly string name;
readonly string docComment;
static CSharpCodeProvider csharp = new CSharpCodeProvider();
public CSharpProperty(Type type, string name, string docComment)
{
this.type = type;
this.name = name;
this.docComment = docComment;
}
public PropertyDeclarationSyntax GetProperty()
{
return
SyntaxFactory.PropertyDeclaration(
SyntaxFactory.ParseTypeName(csharp.GetTypeOutput(new CodeTypeReference(type))),
name
)
.AddModifiers(SyntaxFactory.Token(SyntaxKind.PublicKeyword))
.WithXmlComment(docComment)
.AddAccessorListAccessors(
SyntaxFactory.AccessorDeclaration(SyntaxKind.GetAccessorDeclaration).WithSemicolonToken(SyntaxFactory.Token(SyntaxKind.SemicolonToken)),
SyntaxFactory.AccessorDeclaration(SyntaxKind.SetAccessorDeclaration).WithSemicolonToken(SyntaxFactory.Token(SyntaxKind.SemicolonToken))
);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Microsoft.AspNet.SignalR;
using Microsoft.AspNet.SignalR.Hubs;
using carto.Models;
namespace carto
{
[HubName("cartoHub")]
public class CartoHub : Hub
{
private readonly CmdbRepository _repository;
public CartoHub():this(CmdbRepository.Instance) {}
public CartoHub(CmdbRepository repository)
{
_repository = repository;
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Xlns.BusBook.Core.Repository;
using Xlns.BusBook.Core.Model;
using Xlns.BusBook.Core.DAL;
using Xlns.BusBook.ConfigurationManager;
using Xlns.BusBook.UI.Web.Controllers;
namespace Xlns.BusBook.UI.Web.Models
{
public static class ViaggioHelper
{
private static NLog.Logger logger = NLog.LogManager.GetCurrentClassLogger();
public static ViaggioSearch getViaggioSearchParams(ViaggioSearchView searchViewModelParams)
{
ViaggioSearch searchModelParams = null;
if (searchViewModelParams != null)
{
searchModelParams = new ViaggioSearch()
{
onlyPubblicati = searchViewModelParams.onlyPubblicati,
SearchString = searchViewModelParams.SearchString,
DataPartenzaMin = searchViewModelParams.DataPartenzaMin,
DataPartenzaMax = searchViewModelParams.DataPartenzaMax,
PrezzoMin = searchViewModelParams.PrezzoMin,
PrezzoMax = searchViewModelParams.PrezzoMax,
PassaDa = getGeoLocationModelFromViewModel(searchViewModelParams.PassaDa),
ArrivaA = getGeoLocationModelFromViewModel(searchViewModelParams.ArrivaA),
PassaDaTipoSearch = searchViewModelParams.PassaDaTipoSearch,
ArrivaATipoSearch = searchViewModelParams.ArrivaATipoSearch
};
}
return searchModelParams;
}
public static GeoLocation getGeoLocationModelFromViewModel(GeoLocationView geoView)
{
GeoLocation geoModel = null;
if (geoView != null && !geoView.isEmpty())
{
geoModel = new GeoLocation()
{
CAP = geoView.CAP,
City = geoView.City,
Lat = geoView.Lat,
Lng = geoView.Lng,
Nation = geoView.Nation,
Number = geoView.Number,
Province = geoView.Province,
Region = geoView.Region,
Street = geoView.Street
};
}
return geoModel;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
namespace Draft_FF.Frontend.Entities
{
public class Enums
{
public enum Position
{
QB = 1,
RB = 2,
WR = 3,
TE = 4,
K = 5,
DST = 6,
}
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace TP.Entities.ValueObjects.JobViewModels
{
public class JobAdvEditViewModel
{
[DisplayName("Başlık"), Required, StringLength(50)]
public string adv_title { get; set; }
[DisplayName("İster"), Required, StringLength(4000)]
public string adv_desc { get; set; }
[DisplayName("Ödül Skor"), Required]
public int AwardScoreValue { get; set; }
[DisplayName("Resim")]
public string adv_picturepath { get; set; }
[DisplayName("Yayın Durumu")]
public bool adv_ispublished { get; set; }
[DisplayName("Yayın Tarihi")]
public DateTime adv_publishdate { get; set; }
[DisplayName("Ücret")]
[Required(ErrorMessage = "Price is required")]
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:0.00}")]
public decimal price { get; set; }
public int Id { get; set; }
}
}
|
using Newtonsoft.Json.Linq;
using RestSharp;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace LTIProject2
{
class API
{
public JArray listNodes(string ip)
{
var url = new RestClient("http://"+ip+ "/api/v1/nodes");
var getRequest = new RestRequest("/", Method.GET);
IRestResponse getResponse = url.Execute(getRequest);
Console.WriteLine(getResponse.Content);
JObject content = JObject.Parse(getResponse.Content);
Console.WriteLine(content);
JArray nodes = (JArray)content.SelectToken("items");
/*Console.WriteLine(nodes);
foreach(var node in nodes)
{
Console.WriteLine(node["metadata"]["name"]);
}*/
return nodes;
}
public JArray listNamespaces(string ip)
{
var url = new RestClient("http://" + ip + "/api/v1/namespaces");
var getRequest = new RestRequest("/", Method.GET);
IRestResponse getResponse = url.Execute(getRequest);
Console.WriteLine(getResponse.Content);
JObject content = JObject.Parse(getResponse.Content);
Console.WriteLine(content);
JArray namespaces = (JArray)content.SelectToken("items");
return namespaces;
}
public IRestResponse createNamespaces(string ip, string name)
{
var url = new RestClient("http://" + ip + "/api/v1/namespaces");
var postRequest = new RestRequest("/", Method.POST);
var json = "{\"apiVersion\": \"v1\",\"kind\": \"Namespace\",\"metadata\": {\"name\": \""+name+"\"}}";
postRequest.AddJsonBody(json);
IRestResponse response = url.Execute(postRequest);
Console.WriteLine(response);
return response;
}
public IRestResponse deleteNamespaces(string ip, string namesp)
{
var url = new RestClient("http://" + ip + "/api/v1/namespaces/"+namesp);
var deleteRequest = new RestRequest("/", Method.DELETE);
IRestResponse response = url.Execute(deleteRequest);
Console.WriteLine(response);
return response;
}
public JArray listPods(string ip, string namesp)
{
var url = new RestClient("http://" + ip + "/api/v1/namespaces/"+namesp+"/pods");
var getRequest = new RestRequest("/", Method.GET);
IRestResponse getResponse = url.Execute(getRequest);
Console.WriteLine(getResponse.Content);
JObject content = JObject.Parse(getResponse.Content);
Console.WriteLine(content);
JArray pods = (JArray)content.SelectToken("items");
return pods;
}
public IRestResponse createPods(string ip, string namesp, string podname, string podlabel, string imgname, string img)
{
var url = new RestClient("http://" + ip + "/api/v1/namespaces/" + namesp + "/pods");
var postRequest = new RestRequest("/", Method.POST);
//var json = "{\"apiVersion\": \"v1\",\"kind\": \"Pod\",\"metadata\": {\"name\": \"nginxTeste\"},\"spec\": {\"containers\": [{\"name\": \"nginx\",\"image\": \"nginx:1.7.9\",\"ports\": [{\"containerPort\": 80}]}]}}";
var json = "{\"apiVersion\": \"v1\",\"kind\": \"Pod\",\"metadata\":{\"name\": \""+podname+"\",\"label\":\""+podlabel+"\"},\"spec\":{\"containers\":[{\"name\":\""+imgname+"\",\"image\":\""+img+"\"}]}}";
postRequest.AddJsonBody(json);
IRestResponse response = url.Execute(postRequest);
Console.WriteLine(response);
return response;
}
public IRestResponse deletePods(string ip, string namesp, string podname)
{
var url = new RestClient("http://" + ip + "/api/v1/namespaces/" + namesp + "/pods/"+podname);
var deleteRequest = new RestRequest("/", Method.DELETE);
IRestResponse response = url.Execute(deleteRequest);
Console.WriteLine(response);
return response;
}
public JArray listDeployments(string ip, string namesp)
{
var url = new RestClient("http://" + ip + "/apis/apps/v1/namespaces/"+namesp+ "/deployments");
var getRequest = new RestRequest("/", Method.GET);
IRestResponse getResponse = url.Execute(getRequest);
Console.WriteLine(getResponse.Content);
JObject content = JObject.Parse(getResponse.Content);
Console.WriteLine(content);
JArray deployments = (JArray)content.SelectToken("items");
return deployments;
}
public IRestResponse createDeployments(string ip, string namesp, string deployname, string deploylabel,int replicas, string matchlabel, string cname, string cimage, int port)
{
var url = new RestClient("http://" + ip + "/apis/apps/v1/namespaces/" + namesp + "/deployments");
var postRequest = new RestRequest("/", Method.POST);
var json = "{\"apiVersion\": \"apps/v1\",\"kind\": \"Deployment\",\"metadata\": {\"name\": \""+deployname+"\",\"labels\": {\"app\": \""+deploylabel+"\"}},\"spec\": {\"replicas\": "+replicas+",\"selector\": {\"matchLabels\": {\"app\": \""+matchlabel+"\"}},\"template\": {\"metadata\": {\"labels\": {\"app\": \""+matchlabel+"\"}},\"spec\": {\"containers\": [{\"name\": \""+cname+"\",\"image\": \""+cimage+"\",\"ports\": [{\"containerPort\": "+port+"}]}]}}}}";
postRequest.AddJsonBody(json);
IRestResponse response = url.Execute(postRequest);
Console.WriteLine(response);
return response;
}
public IRestResponse deleteDeployments(string ip, string namesp, string deployname)
{
var url = new RestClient("http://" + ip + "/apis/apps/v1/namespaces/" + namesp + "/deployments/"+deployname);
var deleteRequest = new RestRequest("/", Method.DELETE);
IRestResponse response = url.Execute(deleteRequest);
Console.WriteLine(response);
return response;
}
public JArray listServices(string ip, string namesp)
{
var url = new RestClient("http://" + ip + "/api/v1/namespaces/" + namesp + "/services");
var getRequest = new RestRequest("/", Method.GET);
IRestResponse getResponse = url.Execute(getRequest);
Console.WriteLine(getResponse.Content);
JObject content = JObject.Parse(getResponse.Content);
Console.WriteLine(content);
JArray services = (JArray)content.SelectToken("items");
return services;
}
public IRestResponse createServices(string ip, string namesp, string servicename, string portname, int portorg, int porttarget, string selectorname, string type)
{
var url = new RestClient("http://" + ip + "/api/v1/namespaces/" + namesp + "/services");
var postRequest = new RestRequest("/", Method.POST);
var json = "{\"kind\": \"Service\",\"apiVersion\": \"v1\",\"metadata\": {\"name\": \""+servicename+"\"},\"spec\": {\"ports\": [{\"name\": \""+portname+"\",\"port\": "+portorg+",\"targetPort\": "+porttarget+"}],\"selector\": {\"app\": \""+selectorname+"\"},\"type\": \""+type+"\"}}";
postRequest.AddJsonBody(json);
IRestResponse response = url.Execute(postRequest);
Console.WriteLine(response);
return response;
}
public IRestResponse deleteServices(string ip, string namesp, string servicename)
{
var url = new RestClient("http://" + ip + "/api/v1/namespaces/" + namesp + "/services/"+servicename);
var deleteRequest = new RestRequest("/", Method.DELETE);
IRestResponse response = url.Execute(deleteRequest);
Console.WriteLine(response);
return response;
}
public IRestResponse createAll(string ip, string namesp, string deployname, string deploylabel, int replicas, string matchlabel, string cname, string cimage, int port, string portname,int porttarget,string type, string servicename)
{
//DEPLOY
var url = new RestClient("http://" + ip + "/apis/apps/v1/namespaces/" + namesp + "/deployments");
var postRequest = new RestRequest("/", Method.POST);
var json = "{\"apiVersion\": \"apps/v1\",\"kind\": \"Deployment\",\"metadata\": {\"name\": \"" + deployname + "\",\"labels\": {\"app\": \"" + deploylabel + "\"}},\"spec\": {\"replicas\": " + replicas + ",\"selector\": {\"matchLabels\": {\"app\": \"" + matchlabel + "\"}},\"template\": {\"metadata\": {\"labels\": {\"app\": \"" + matchlabel + "\"}},\"spec\": {\"containers\": [{\"name\": \"" + cname + "\",\"image\": \"" + cimage + "\",\"ports\": [{\"containerPort\": " + port + "}]}]}}}}";
postRequest.AddJsonBody(json);
IRestResponse response = url.Execute(postRequest);
Console.WriteLine(response);
//SERVICE
var url2 = new RestClient("http://" + ip + "/api/v1/namespaces/" + namesp + "/services");
var postRequest2 = new RestRequest("/", Method.POST);
var json2 = "{\"kind\": \"Service\",\"apiVersion\": \"v1\",\"metadata\": {\"name\": \"" + servicename + "\"},\"spec\": {\"ports\": [{\"name\": \"" + portname + "\",\"port\": " + port + ",\"targetPort\": " + porttarget + "}],\"selector\": {\"app\": \"" + deployname + "\"},\"type\": \"" + type + "\"}}";
postRequest2.AddJsonBody(json2);
IRestResponse response2 = url2.Execute(postRequest2);
Console.WriteLine(response2);
return response2;
}
public IRestResponse createPodFile(string ip, string namesp,string json)
{
var url = new RestClient("http://" + ip + "/api/v1/namespaces/" + namesp + "/pods");
var postRequest = new RestRequest("/", Method.POST);
postRequest.AddJsonBody(json);
IRestResponse response = url.Execute(postRequest);
Console.WriteLine(response);
return response;
}
public IRestResponse createDeployFile(string ip, string namesp, string json)
{
var url = new RestClient("http://" + ip + "/apis/apps/v1/namespaces/" + namesp + "/deployments");
var postRequest = new RestRequest("/", Method.POST);
postRequest.AddJsonBody(json);
IRestResponse response = url.Execute(postRequest);
Console.WriteLine(response);
return response;
}
public IRestResponse createServiceFile(string ip, string namesp, string json)
{
var url = new RestClient("http://" + ip + "/api/v1/namespaces/" + namesp + "/services");
var postRequest = new RestRequest("/", Method.POST);
postRequest.AddJsonBody(json);
IRestResponse response = url.Execute(postRequest);
Console.WriteLine(response);
return response;
}
public IRestResponse getPodInfo(string ip, string namesp, string pod)
{
var url = new RestClient("http://" + ip + "/api/v1/namespaces/" + namesp + "/pods/"+pod);
var getRequest = new RestRequest("/", Method.GET);
IRestResponse getResponse = url.Execute(getRequest);
Console.WriteLine(getResponse.Content);
return getResponse;
}
public IRestResponse getDeployInfo(string ip, string namesp, string deploy)
{
var url = new RestClient("http://" + ip + "/apis/apps/v1/namespaces/" + namesp + "/deployments/"+deploy);
var getRequest = new RestRequest("/", Method.GET);
IRestResponse getResponse = url.Execute(getRequest);
Console.WriteLine(getResponse.Content);
return getResponse;
}
public IRestResponse getServiceInfo(string ip, string namesp, string service)
{
var url = new RestClient("http://" + ip + "/api/v1/namespaces/" + namesp + "/services/"+service);
var getRequest = new RestRequest("/", Method.GET);
IRestResponse getResponse = url.Execute(getRequest);
Console.WriteLine(getResponse.Content);
return getResponse;
}
public IRestResponse getNamespaceInfo(string ip, string namesp)
{
var url = new RestClient("http://" + ip + "/api/v1/namespaces/"+namesp);
var getRequest = new RestRequest("/", Method.GET);
IRestResponse getResponse = url.Execute(getRequest);
Console.WriteLine(getResponse.Content);
return getResponse;
}
}
}
|
using System;
using System.Text;
namespace gView.Framework.system
{
public class SimpleScriptInterpreter
{
public SimpleScriptInterpreter(string script)
{
this.Script = script;
}
public string Script { get; set; }
public string Interpret()
{
var script = this.Script.Replace(Environment.NewLine, "\n");
var result = this.Script;
if (script.StartsWith("@@start\n"))
{
var expr_lines = script.Split('\n');
StringBuilder sb = new StringBuilder();
bool interpret = false, useLine = true;
for (int i = 1, to = expr_lines.Length; i < to; i++)
{
var expr_line = expr_lines[i];
if (expr_line == "@@end")
{
interpret = true;
result = sb.ToString();
}
else if (expr_line.StartsWith("@@if("))
{
var commandResult = GetCommand(expr_line);
useLine = CheckCondition(commandResult.arguments);
}
else if (expr_line == "@@endif")
{
useLine = true;
}
else if (interpret == false && useLine)
{
if (sb.Length > 0)
{
sb.Append(Environment.NewLine);
}
sb.Append(expr_line);
}
if (interpret == true)
{
var commandResult = GetCommand(expr_line);
if (commandResult.command != null)
{
switch (commandResult.command)
{
case "replace":
if (commandResult.arguments.Length == 2)
{
result = result.Replace(commandResult.arguments[0], commandResult.arguments[1]);
}
break;
}
}
}
}
}
return result;
}
private (string command, string[] arguments) GetCommand(string line)
{
line = line.Trim();
if (line.StartsWith("@@") && line.EndsWith(")"))
{
var index = line.IndexOf("(");
string command = line.Substring(2, index - 2);
var args = line.Substring(index + 1, line.Length - index - 2).Split(',');
return (command.ToLower(), args);
}
return (null, null);
}
private bool CheckCondition(string[] args)
{
if (args.Length == 1)
{
return !String.IsNullOrWhiteSpace(args[0]);
}
else if (args.Length == 2)
{
return args[0] == args[1];
}
else if (args.Length == 3)
{
switch (args[1]?.ToLower())
{
case "eq":
return args[0] == args[2];
case "not":
return args[0] != args[2];
}
}
return false;
}
public static bool IsSimpleScript(string script)
{
return script.StartsWith("@@start");
}
}
}
|
using System;
using System.Collections.Generic;
namespace WebAPI.MoneyXChange.Models
{
public partial class User
{
public int UspId { get; set; }
public string UspFirstname { get; set; }
public string UspLastname { get; set; }
public string UspEmail { get; set; }
public UserAccount UserAccount { get; set; }
}
}
|
using System;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Migrations;
namespace Assign02_AWS_Movies.Data.Migrations
{
public partial class Migration02_UserReference : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "Category",
columns: table => new
{
CategoryId = table.Column<int>(nullable: false)
.Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn),
CategoryName = table.Column<string>(maxLength: 30, nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Category", x => x.CategoryId);
});
migrationBuilder.CreateTable(
name: "Movie",
columns: table => new
{
MovieId = table.Column<int>(nullable: false)
.Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn),
Title = table.Column<string>(maxLength: 150, nullable: false),
description = table.Column<string>(maxLength: 1000, nullable: true),
UploadDate = table.Column<DateTime>(nullable: true),
FileName = table.Column<string>(maxLength: 100, nullable: false),
Downloads = table.Column<int>(nullable: false),
User = table.Column<string>(maxLength: 256, nullable: true),
CategoryId = table.Column<int>(nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Movie", x => x.MovieId);
table.ForeignKey(
name: "FK_Movie_Category_CategoryId",
column: x => x.CategoryId,
principalTable: "Category",
principalColumn: "CategoryId",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "Comment",
columns: table => new
{
CommentId = table.Column<int>(nullable: false)
.Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn),
User = table.Column<string>(maxLength: 256, nullable: true),
CommentText = table.Column<string>(maxLength: 1000, nullable: false),
value = table.Column<int>(nullable: false),
UserId = table.Column<string>(nullable: true),
MovieId = table.Column<int>(nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Comment", x => x.CommentId);
table.ForeignKey(
name: "FK_Comment_Movie_MovieId",
column: x => x.MovieId,
principalTable: "Movie",
principalColumn: "MovieId",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateIndex(
name: "IX_Comment_MovieId",
table: "Comment",
column: "MovieId");
migrationBuilder.CreateIndex(
name: "IX_Movie_CategoryId",
table: "Movie",
column: "CategoryId");
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "Comment");
migrationBuilder.DropTable(
name: "Movie");
migrationBuilder.DropTable(
name: "Category");
}
}
}
|
using UnityEngine;
using System.Collections;
using System;
public class DogPooActorState : ActorState
{
protected override void OnBegin(AnimatorStateInfo stateInfo)
{
}
protected override void OnUpdate(AnimatorStateInfo stateInfo)
{
}
protected override void OnEnd(AnimatorStateInfo stateInfo)
{
}
}
|
/*
* Interface for player state machine that dictates what actions player can and cannot take
* Copyright (c) Yulo Leake 2016
*/
using Deadwood.Model.Rooms;
namespace Deadwood.Model.PlayerStates
{
interface IPlayerState
{
IPlayerState Act(Player p);
IPlayerState Rehearse(Player p);
IPlayerState Move(Player p, string destination);
IPlayerState Upgrade(Player p, CurrencyType type, int rank);
IPlayerState TakeRole(Player p, string rolename);
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MIDIDotNet;
using NUnit.Framework;
namespace UnitTests
{
class GMOutDeviceTests
{
[Test]
public void SendNoteOn_Simple()
{
MockOutDevice mockOutDevice = new MockOutDevice();
GMOutDevice gmOutDevice = new GMOutDevice(mockOutDevice);
gmOutDevice.SendNoteOn(0, 0, 0);
Assert.AreEqual(mockOutDevice.callsTo("SendShortMsg"), 1);
Assert.AreEqual(mockOutDevice.LastShortMsg, 0x00000090);
mockOutDevice.clearCalls();
gmOutDevice.SendNoteOn(10, 50, 127);
Assert.AreEqual(mockOutDevice.callsTo("SendShortMsg"), 1);
Assert.AreEqual(mockOutDevice.LastShortMsg, 0x007f329a);
}
[Test]
public void SendNoteOn_Invalid()
{
MockOutDevice mockOutDevice = new MockOutDevice();
GMOutDevice gmOutDevice = new GMOutDevice(mockOutDevice);
MIDIException e = Assert.Throws<MIDIException>(delegate { gmOutDevice.SendNoteOn(17, 0, 0); });
Assert.AreEqual(e.ErrorCode, ErrorCode.MDNERR_GM_INVALIDCHANNEL);
e = Assert.Throws<MIDIException>(delegate { gmOutDevice.SendNoteOn(0, 200, 0); });
Assert.AreEqual(e.ErrorCode, ErrorCode.MDNERR_GM_INVALIDNOTE);
e = Assert.Throws<MIDIException>(delegate { gmOutDevice.SendNoteOn(0, 0, 128); });
Assert.AreEqual(e.ErrorCode, ErrorCode.MDNERR_GM_INVALIDVELOCITY);
}
[Test]
public void SendNoteOff_Simple()
{
MockOutDevice mockOutDevice = new MockOutDevice();
GMOutDevice gmOutDevice = new GMOutDevice(mockOutDevice);
gmOutDevice.SendNoteOff(0, 0, 0);
Assert.AreEqual(mockOutDevice.callsTo("SendShortMsg"), 1);
Assert.AreEqual(mockOutDevice.LastShortMsg, 0x00000080);
mockOutDevice.clearCalls();
gmOutDevice.SendNoteOff(10, 50, 127);
Assert.AreEqual(mockOutDevice.callsTo("SendShortMsg"), 1);
Assert.AreEqual(mockOutDevice.LastShortMsg, 0x007f328a);
}
}
}
|
using Foundation;
using System;
using System.CodeDom.Compiler;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using ResidentAppCross.iOS.Views;
using ResidentAppCross.Interfaces;
using ResidentAppCross.ViewModels.Screens;
using UIKit;
namespace ResidentAppCross.iOS
{
public partial class SegmentSelectionSection : SectionViewBase
{
private bool _editable;
public SegmentSelectionSection()
{
}
public SegmentSelectionSection (IntPtr handle) : base (handle)
{
}
public UILabel Label => _headerTitle;
public UISegmentedControl Selector => _segmentSelector;
public override void AwakeFromNib()
{
base.AwakeFromNib();
Label.Font = AppFonts.SectionHeader;
HeightConstraint.Constant = AppTheme.SegmentSectionHeight;
Selector.RemoveAllSegments();
Selector.TintColor = AppTheme.FormControlColor;
}
public void HideTitle(bool hide)
{
_headerHeightConstraint.Constant = hide ? 0 : 30;
HeightConstraint.Constant = hide ? AppTheme.SegmentSectionHeightReduced : AppTheme.SegmentSectionHeight;
_headerTitle.Hidden = hide;
}
public bool Editable
{
get { return _editable; }
set
{
_editable = value;
SegmentSelector.Enabled = value;
}
}
public void BindTo<T>(IList<T> items, Func<T,string> keySelector, Action<T> itemSelected, int startIndex)
{
if (BindingDisposable != null)
{
BindingDisposable.Dispose();
BindingDisposable = null;
}
SegmentSelector.RemoveAllSegments();
var i = 0;
foreach (var item in items)
{
SegmentSelector.InsertSegment(keySelector(item),i++,true);
}
SegmentSelector.SelectedSegment = startIndex;
EventHandler segmentSelectorOnValueChanged = (sender, args) =>
{
itemSelected(items[(int)SegmentSelector.SelectedSegment]);
};
SegmentSelector.ValueChanged += segmentSelectorOnValueChanged;
BindingDisposable = new Disposable(() =>
{
SegmentSelector.ValueChanged -= segmentSelectorOnValueChanged;
});
}
public Disposable BindingDisposable { get; set; }
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class GMScript : MonoBehaviour
{
public Transform kumObj;
void Start()
{
for (float xPos = -3.0f; xPos < 3.08f; xPos = xPos + 0.08f)
{
for (float yPos = 5.0f; yPos > -10.08f; yPos = yPos - 0.08f)
{
if(
((xPos < -2.0f) || (xPos > -1.2f)) ||
((yPos < -0.8f) || (yPos > 0.0f))
)
Instantiate(kumObj, new Vector2(xPos, yPos), kumObj.rotation);
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Pe.Stracon.SGC.Aplicacion.TransferObject.Response.Contractual
{
/// <summary>
/// Representa el objeto response de variable
/// </summary>
/// <remarks>
/// Creación : GMD 20150527 <br />
/// Modificación : <br />
/// </remarks>
public class VariableResponse
{
/// <summary>
/// Código de Variable
/// </summary>
public Guid? CodigoVariable { get; set; }
/// <summary>
/// Código de Plantilla
/// </summary>
public Guid? CodigoPlantilla { get; set; }
/// <summary>
/// Descripción codigo plantilla
/// </summary>
public string DescripcionCodigoPlantilla { get; set; }
/// <summary>
/// Identificador
/// </summary>
public string Identificador { get; set; }
/// <summary>
/// Identificador sin Almohadilla
/// </summary>
public string IdentificadorSinAlmohadilla { get; set; }
/// <summary>
/// Nombre
/// </summary>
public string Nombre { get; set; }
/// <summary>
/// Código de Tipo de Variable
/// </summary>
public string CodigoTipo { get; set; }
/// <summary>
/// Descripcion Codigo Tipo
/// </summary>
public string DescripcionCodigoTipo { get; set; }
/// <summary>
/// Descripción de Tipo de Variable
/// </summary>
public string DescripcionTipoVariable { get; set; }
/// <summary>
/// Indicador de Variable Global
/// </summary>
public bool? IndicadorGlobal { get; set; }
/// <summary>
/// Indicador de Variable de Sistema
/// </summary>
public bool IndicadorVariableSistema { get; set; }
/// <summary>
/// Descripcion
/// </summary>
public string Descripcion { get; set; }
}
}
|
using System;
namespace SymbolicMath {
class Ln : Unaries {
public Ln(Expression value) : base(value) {}
public override string toString() {
return $"ln({value.toString()})";
}
public override double calc() {
return Math.Log(value.calc(), Math.E);
}
}
} |
namespace HTTPServer.core
{
public interface IPathContents
{
string DirectoryPath { get; }
string[] GetFiles(string directoryExtension);
string[] GetDirectories(string directoryExtension);
byte[] GetFileContents(string filePath);
void PostContents(Request request);
void PutContents(Request request);
}
}
|
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Threading;
using System.Threading.Tasks;
using Console = Colorful.Console;
namespace S3.AutoBatcher.Samples.SimpleProducer
{
/// <summary>
/// It processes the batch chunks for the sample.
/// The process consists in joining the numbers in the current batch and printing them on the screen
/// </summary>
class BatchChunkProcessor : IBatchChunkProcessor<int>
{
private int _batchNumber = 0;
public Task Process(IReadOnlyCollection<int> chunkItems, CancellationToken cancellationToken)
{
Console.WriteLine($"Batch #{++_batchNumber}, items processed:",Color.DarkGreen);
//prints the items comma-separated
var current = string.Join(',', chunkItems);
Console.WriteLine(current,Color.Olive);
return Task.CompletedTask;
}
public ErrorResult HandleError(IReadOnlyCollection<int> chunkItems, Exception exception, int currentAttemptNumber)
{
//rethrow;
return ErrorResult.AbortAndRethrow;
//compensate
//explore other options here, like store for later execution,...
//_failedItems.Add(chunkItems);
//return ErrorResult.Continue;
// or retry, together with the parameter currentAttemptNumber
//return ErrorResult.Retry;
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Strategy.Cars
{
public class PorscheCar : ICar
{
public int GetMaxSpeed()
{
return 280;
}
}
}
|
using OpenQA.Selenium;
using OpenQA.Selenium.Support.UI;
using Kliiko.Ui.Tests.Environment;
using System.Threading;
using TechTalk.SpecFlow;
using Kliiko.Ui.Tests.Selenium;
namespace Kliiko.Ui.Tests.WebPages.Login
{
class ForgetPasswordPage : WebPage
{
private static readonly By INPUT_EMAIL = By.XPath("//*[@id='login']//*[@type='email']");
private static readonly By BUTTON_SUBMIT = By.XPath("//*[@id='login']//*[@type='submit']");
private static readonly By ERROR_WRONG_EMAIL = By.XPath("//*[@id='warning-email-password']");
public static void ExpectWebElements()
{
Web.WaitUntil(ExpectedConditions.ElementIsVisible(INPUT_EMAIL));
Web.WaitUntil(ExpectedConditions.ElementIsVisible(BUTTON_SUBMIT));
}
public static void TypeInEmail(object data)
{
string email = WebApplication.GetFieldDataFromDynamicClass(data, "Email");
Web.TypeNewText(INPUT_EMAIL, email);
}
public static void EmailValidation()
{
Web.Validation(ERROR_WRONG_EMAIL);
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.SceneManagement;
public class ResetPlayerPrefs : MonoBehaviour {
void Awake () {
var btn = GetComponent<Button>();
btn.onClick.AddListener(ResetGame);
}
private void ResetGame()
{
LevelSelectButtons.Instance.ResetPrefs();
SceneManager.LoadScene("Main Menu");
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
namespace DistCWebSite.SharePoint.Utility
{
/// <summary>
/// 文件夹路径
/// 如文件/pdrpt/600 CIB/China/East/600CIB_2014_11.txt
/// FolderRelativeUrl为/pdrpt/600 CIB/China/East
/// SiteUrl为pdrpt
/// ListName为600 CIB
/// underListPath为China/East
/// </summary>
class SFolderUrl
{
public SFolderUrl(string siteUrl)
{
SiteUrl = siteUrl;
}
public string SiteUrl { get; set; }
public List<string> GetUrlFamilies(string listName, string underListUrl)
{
List<string> urlFamilies = new List<string>();
var folders = underListUrl.Split("/".ToArray(), StringSplitOptions.RemoveEmptyEntries).ToArray();
for (int i = 1; i <= folders.Count(); i++)
{
var url = string.Format("/{0}/{1}/{2}", SiteUrl, listName, string.Join("/", folders,0,i));
urlFamilies.Add(url);
}
return urlFamilies;
}
public string GetListName(string folderUrl)
{
string listName = "";
var headStr = "/" + SiteUrl;
var index = folderUrl.IndexOf(headStr, StringComparison.Ordinal);
if (index != -1)
{
var otherStr = folderUrl.Substring(headStr.Length);
var strs = otherStr.Split("/".ToArray(), StringSplitOptions.RemoveEmptyEntries);
if (strs.Length >= 1)
{
listName = strs[0];
}
}
return listName;
}
/// <summary>
/// 确定权限是
/// </summary>
/// <param name="folderUrl"></param>
/// <returns></returns>
public string IsGroupOrUser(string folderUrl)
{
string name;
var underListUrl = GetUnderListUrl(folderUrl);
var count = underListUrl.Split("/".ToArray(), StringSplitOptions.RemoveEmptyEntries).Count();
if (count <= 3)
{
name = "Group";
}
else
{
name = "User";
}
return name;
}
private string GetUnderListUrl(string folderUrl)
{
string underListUrl = "";
var headStr = "/" + SiteUrl;
var index = folderUrl.IndexOf(headStr, StringComparison.Ordinal);
if (index != -1)
{
var otherStr = folderUrl.Substring(headStr.Length);
var strs = otherStr.Split("/".ToArray(), StringSplitOptions.RemoveEmptyEntries).ToList();
strs.RemoveAt(0);
underListUrl = string.Join("/", strs.ToArray());
}
return underListUrl;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Algorithms
{
public static class Other
{
public static bool IsPalindrome(string str)
{ //string word = "Noel sees Leon.";
// IsPalindrome(word);
string word = new string(Array.FindAll<char>(str.ToCharArray(), (c => char.IsLetterOrDigit(c)))).ToUpper();
StringBuilder sb = new StringBuilder();
foreach (var item in word.Reverse())
{
sb.Append(item);
}
string wordReverse = sb.ToString();
if (word.Equals(wordReverse))
{
return true;
}
return false;
}
public static int NumberOfWays(int n)
{
int wayStep = n != 0 ? 1 : 0;
int wayOnlyJumping = (n % 2) == 0 ? 1 : 0;
int wayStepJumping = (n * (2.0 / 3.0)) % 2 == 0 ? 2 : 0;
//if (wayOnlyJumping == 0 && n > 2)
// wayStepJumping = 2;//Forward and Backward
return wayStep + wayOnlyJumping + wayStepJumping;
//step 1
//jump 2
}
private static void sum_up(List<int> numbers, int target)
{
sum_up_recursive(numbers, target, new List<int>());
}
private static void sum_up_recursive(List<int> numbers, int target, List<int> partial)
{
int s = 0;
foreach (int x in partial) s += x;
if (s == target)
Console.WriteLine("sum(" + string.Join(",", partial.ToArray()) + ")=" + target);
if (s >= target)
return;
for (int i = 0; i < numbers.Count; i++)
{
List<int> remaining = new List<int>();
int n = numbers[i];
for (int j = i + 1; j < numbers.Count; j++) remaining.Add(numbers[j]);
List<int> partial_rec = new List<int>(partial);
partial_rec.Add(n);
sum_up_recursive(remaining, target, partial_rec);
}
Console.WriteLine("");
}
public static void Clothes()
{
var arr = new int[] { 10, 20, 30 };
Console.WriteLine(arr.All(i => i > 20));
Console.WriteLine(arr.Any(i => i > 20));
Console.WriteLine(arr.Select(i => i / 2).ToList()[0]);
var colours = new[] { "colour - red", "colour - blue", "colour - green", "colour - yellow" };
var cloth = new[] { "cloth - cotton", "cloth - poly", "cloth - silk" };
var type = new[] { "type - full", "type - half" };
var combinations = from c in colours
from cl in cloth
from t in type
select new[] { c, cl, t };
}
}
public class CollectionWrapper
{
private ICollection<Exception> _errors;
private List<int> _data;
//public List<int> _data { get; set; }
public CollectionWrapper()
{
_data = new List<int>();
}
public void AddItem(int item)
{
_data.Add(item);
}
public void AddMany(IEnumerable<int> toAppend)
{
if (toAppend == null)
{
OnExceptionThrown(new ArgumentNullException("toAppend"));
}
_data.AddRange(toAppend);
}
public int GetElement(int index)
{
if (index < _data.Count)
{
return _data[index];
}
else
{
OnExceptionThrown(new IndexOutOfRangeException($"Range{index}"));
}
return 0;
}
public int CalculateSum()
{
return _data.Sum();
}
public IEnumerable<int> GetPage(int pageNumber, int pageSize)
{
return _data.Skip((pageNumber - 1) * pageSize).Take(pageSize);
}
public int CalculateMedian()
{
var currentCount = _data.Count;
if (currentCount == 0)
{
return 0;
}
_data.Sort();
return _data[currentCount / 2];
}
public int GetItemByIndex(int index)
{
return _data[index];
}
public IEnumerable<int> GetItemsWhichSumToLessThan(int sum)
{
int total = 0, i = 0;
foreach (var item in _data)
{
if (total + item >= sum) break;
total += item;
++i;
}
return _data.Take(i);
}
public bool AreItemsUnique()
{
return _data.Distinct().Count() == _data.Count();
}
private void OnExceptionThrown(Exception ex)
{
if (_errors == null)
_errors = new Collection<Exception>();
_errors.Add(ex);
}
}
}
|
using ContestsPortal.Domain.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ContestsPortal.Domain.DataAccess.Providers.Interfaces
{
public interface IUsersProvider
{
Task<IList<UserProfile>> GetAllUsers();
Task<UserProfile> GetUser(int userId);
Task<UserProfile> GetByLogin(string login);
}
}
|
using System.Xml.Serialization;
namespace Witsml.Data.Measures
{
public class Measure
{
[XmlAttribute("uom")] public string Uom { get; set; }
[XmlText] public string Value { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using PCLStorage;
using Xamarin.Forms;
using System.Net.Http;
namespace TestApp
{
public partial class NewProyect : ContentPage
{
public NewProyect()
{
InitializeComponent();
}
public async Task<String> DescargarContenido(String direccion)
{
using (var client = new HttpClient())
{
var url = string.Format(direccion);
var resp = await client.GetAsync(url);
if (resp.IsSuccessStatusCode)
{
return resp.Content.ReadAsStringAsync().Result;
}
else
{
return "Ha habido un problema con la descarga";
}
}
}
public async void new_project(Object sender, EventArgs e)
{
// Get the root directory of the file system for our application.
IFolder rootFolder = FileSystem.Current.LocalStorage;
// Create another folder, if one doesn't already exist.
IFolder projects = await rootFolder.CreateFolderAsync("Projects", CreationCollisionOption.OpenIfExists);
if (newProject.Text == "")
{
await DisplayAlert("Error", "Introduce un nombre valido", "OK");
return;
}
string project = "Projects\\" + newProject.Text;
IFolder projectFolder = await rootFolder.CreateFolderAsync(project, CreationCollisionOption.OpenIfExists);
try
{
IFile file = await projects.CreateFileAsync(newProject.Text + "\\index.html", CreationCollisionOption.FailIfExists);
string web = await DescargarContenido("http://test.jolama.es/Hackaton/index.html");
await file.WriteAllTextAsync(web);
//Abrir editor de codigo
await Navigation.PushAsync(new CodeEditor(newProject.Text));
}
catch
{
await DisplayAlert("Error", "Ya hay un proyecto con ese nombre", "OK");
return;
}
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class TargetMatchBehaviour : StateMachineBehaviour
{
public override void OnStateEnter (Animator animator, AnimatorStateInfo stateInfo, int layerIndex)
{
CharacterTargetMatch ctm = animator.GetComponent<CharacterTargetMatch> ();
ctm.GetComponent<Collider> ().isTrigger = true;
ctm.GetComponent<Rigidbody> ().useGravity = false;
}
override public void OnStateUpdate (Animator animator, AnimatorStateInfo stateInfo, int layerIndex)
{
CharacterTargetMatch ctm = animator.GetComponent<CharacterTargetMatch> ();
CharacterTargetMatch.MatchData data = ctm.CurrentData ( stateInfo.normalizedTime );
if (data == null) return;
animator.MatchTarget ( data.targetPosition, data.targetRotation, data.targetBodyPath, new MatchTargetWeightMask ( data.positionWeight, data.rotationWeight ), data.start, data.end );
}
override public void OnStateExit (Animator animator, AnimatorStateInfo stateInfo, int layerIndex)
{
CharacterTargetMatch ctm = animator.GetComponent<CharacterTargetMatch> ();
ctm.GetComponent<Collider> ().isTrigger = false;
ctm.GetComponent<Rigidbody> ().useGravity = true;
}
}
|
// Copyright (c) 2020, mParticle, Inc
//
// 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
//
// https://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 System;
using System.Collections.Generic;
using System.Text;
using Xunit;
namespace MP.Json.Validation.Test
{
public class LogicTests
{
private MPJson m2 = MPJson.Object(MPJson.Property("multipleOf", 2));
private MPJson m3 = MPJson.Object(MPJson.Property("multipleOf", 3));
private MPJson m5 = MPJson.Object(MPJson.Property("multipleOf", 5));
private MPJson m7 = MPJson.Object(MPJson.Property("multipleOf", 7));
[Fact]
private void LogicKeywordsRequiredNonEmptyArrayTest()
{
Assert.False(SimpleSchema("allOf", true).IsValid);
Assert.False(SimpleSchema("anyOf", true).IsValid);
Assert.False(SimpleSchema("oneOf", true).IsValid);
Assert.False(SimpleSchema("allOf", MPJson.Array()).IsValid);
Assert.False(SimpleSchema("anyOf", MPJson.Array()).IsValid);
Assert.False(SimpleSchema("oneOf", MPJson.Array()).IsValid);
}
[Fact]
public void AllOfTest()
{
var schema = SimpleSchema("allOf", MPJson.Array(m2, m3, m5));
Assert.True(schema.IsValid);
Assert.True(schema.Validate(0));
Assert.False(schema.Validate(1));
Assert.False(schema.Validate(2));
Assert.False(schema.Validate(15));
Assert.False(schema.Validate(21));
Assert.True(schema.Validate(30));
Assert.True(schema.Validate(60));
Assert.True(schema.Validate("Not a number"));
}
[Fact]
public void AnyOfTest()
{
var schema = SimpleSchema("anyOf", MPJson.Array(m2, m3, m5));
Assert.True(schema.IsValid);
Assert.True(schema.Validate(0));
Assert.False(schema.Validate(1));
Assert.True(schema.Validate(2));
Assert.True(schema.Validate(15));
Assert.True(schema.Validate(21));
Assert.True(schema.Validate(30));
Assert.True(schema.Validate(60));
Assert.True(schema.Validate("Not a number"));
}
[Fact]
public void OneOfTest()
{
var schema = SimpleSchema("oneOf", MPJson.Array(m2, m3, m5));
Assert.True(schema.IsValid);
Assert.False(schema.Validate(0));
Assert.False(schema.Validate(1));
Assert.True(schema.Validate(2));
Assert.False(schema.Validate(15));
Assert.True(schema.Validate(21));
Assert.False(schema.Validate(30));
Assert.False(schema.Validate(60));
// Wow! This is surprising but true!!
Assert.False(schema.Validate("Not a number"));
}
[Fact]
public void NotTest()
{
var schema = SimpleSchema("not", m3);
Assert.True(schema.IsValid);
Assert.False(schema.Validate(0));
Assert.True(schema.Validate(1));
Assert.True(schema.Validate(2));
Assert.False(schema.Validate(15));
Assert.False(schema.Validate(21));
Assert.False(schema.Validate(30));
Assert.False(schema.Validate(60));
// Wow! This is surprising but true!!
Assert.False(schema.Validate("Not a number"));
}
[Fact]
public void IfThenElseTest()
{
MPSchema schema = new MPSchema(
MPJson.Object(
MPJson.Property("if", m2),
MPJson.Property("then", m3),
MPJson.Property("else", m5)
));
Assert.True(schema.IsValid);
// if T then T else T
Assert.True(schema.Validate(0));
Assert.True(schema.Validate(30));
Assert.True(schema.Validate(60));
Assert.True(schema.Validate("Not a number"));
// if T then T else F
Assert.True(schema.Validate(6));
// if T then F else T
Assert.False(schema.Validate(10));
// if T then F else F
Assert.False(schema.Validate(2));
// if F then T else T
Assert.True(schema.Validate(15));
// if F then T else F
Assert.False(schema.Validate(21));
// if F then T else F
Assert.False(schema.Validate(3));
// if F then F else F
Assert.False(schema.Validate(1));
}
#region Helpers
MPSchema SimpleSchema(string keyword, MPJson json)
{
return new MPSchema(MPJson.Object(MPJson.Property(keyword, json)));
}
#endregion
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Media;
namespace ViewLib
{
public class SortAdorner : Adorner
{
private static Geometry up = Geometry.Parse("M 0,8 8,8 4,0 0,8");
private static Geometry down = Geometry.Parse("M 0,0 4,8 8,0 0,0");
private Geometry direction;
private static Brush brush = new SolidColorBrush(Color.FromArgb(128, 0, 0, 0));
private static Pen pen =new Pen( new SolidColorBrush(Color.FromArgb(128, 255, 255, 255)),1);
public SortAdorner(GridViewColumnHeader AdornedElement, ListSortDirection SortDirection)
: base(AdornedElement)
{
direction = SortDirection == ListSortDirection.Ascending ? up : down;
}
protected override void OnRender(System.Windows.Media.DrawingContext drawingContext)
{
double x = AdornedElement.RenderSize.Width - 12;
double y = (AdornedElement.RenderSize.Height - 8) / 2;
if (x >= 10)
{
// Right order of the statements is important
drawingContext.PushTransform(new TranslateTransform(x, y));
drawingContext.DrawGeometry(brush, pen, direction);
drawingContext.Pop();
}
}
}
}
|
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using GraphDataStructure.Models;
namespace GraphDataStructure.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class GraphsController : ControllerBase
{
private readonly GraphDSContext _context;
public GraphsController(GraphDSContext context)
{
_context = context;
if (_context.Vertices.Count() == 0)
{
_context.Vertices.Add(new Vertex { Name = "A" });
_context.Vertices.Add(new Vertex { Name = "B" });
_context.Vertices.Add(new Vertex { Name = "C" });
_context.Vertices.Add(new Vertex { Name = "D" });
_context.Vertices.Add(new Vertex { Name = "E" });
_context.Vertices.Add(new Vertex { Name = "F" });
_context.SaveChanges();
}
if (_context.Edges.Count() == 0)
{
var vertexA = _context.Vertices.FirstOrDefault(vertex => vertex.Name == "A");
var vertexB = _context.Vertices.FirstOrDefault(vertex => vertex.Name == "B");
var vertexC = _context.Vertices.FirstOrDefault(vertex => vertex.Name == "C");
var vertexD = _context.Vertices.FirstOrDefault(vertex => vertex.Name == "D");
var vertexE = _context.Vertices.FirstOrDefault(vertex => vertex.Name == "E");
var vertexF = _context.Vertices.FirstOrDefault(vertex => vertex.Name == "F");
// Create a new TodoItem if collection is empty,
// which means you can't delete all TodoItems.
_context.Edges.Add(new Edge { VertexA = vertexA, VertexB = vertexB });
_context.Edges.Add(new Edge { VertexA = vertexA, VertexB = vertexD });
_context.Edges.Add(new Edge { VertexA = vertexB, VertexB = vertexF });
_context.Edges.Add(new Edge { VertexA = vertexC, VertexB = vertexF });
_context.Edges.Add(new Edge { VertexA = vertexC, VertexB = vertexE });
_context.Edges.Add(new Edge { VertexA = vertexF, VertexB = vertexE });
_context.SaveChanges();
}
}
[HttpGet]
public ActionResult<IEnumerable<string>> Get()
{
return new string[] { "value1", "value2" };
}
// GET: api/Todo
// [HttpGet]
// public async Task<ActionResult<IEnumerable<TodoItem>>> GetTodoItems()
// {
// return await _context.TodoItems.ToListAsync();
// }
// // GET: api/Todo/5
// [HttpGet("{id}")]
// public async Task<ActionResult<TodoItem>> GetTodoItem(long id)
// {
// var todoItem = await _context.TodoItems.FindAsync(id);
// if (todoItem == null)
// {
// return NotFound();
// }
// return todoItem;
// }
// // POST: api/Todo
// [HttpPost]
// public async Task<ActionResult<TodoItem>> PostTodoItem(TodoItem item)
// {
// _context.TodoItems.Add(item);
// await _context.SaveChangesAsync();
// return CreatedAtAction(nameof(GetTodoItem), new { id = item.Id }, item);
// }
// // PUT: api/Todo/5
// [HttpPut("{id}")]
// public async Task<IActionResult> PutTodoItem(long id, TodoItem item)
// {
// if (id != item.Id)
// {
// return BadRequest();
// }
// _context.Entry(item).State = EntityState.Modified;
// await _context.SaveChangesAsync();
// return NoContent();
// }
// // DELETE: api/Todo/5
// [HttpDelete("{id}")]
// public async Task<IActionResult> DeleteTodoItem(long id)
// {
// var todoItem = await _context.TodoItems.FindAsync(id);
// if (todoItem == null)
// {
// return NotFound();
// }
// _context.TodoItems.Remove(todoItem);
// await _context.SaveChangesAsync();
// return NoContent();
// }
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text.Json;
using System.Threading.Tasks;
namespace LighterApi
{
public class RepoService
{
private readonly HttpClient _httpClient;
public RepoService(HttpClient client)
{
_httpClient = client;
}
public async Task<IEnumerable<GitHubBranch>> GetRepos()
{
var response = await _httpClient.GetAsync("repos/aspnet/AspNetCore.Docs/branches");
response.EnsureSuccessStatusCode();
using var responseStream = await response.Content.ReadAsStreamAsync();
return await JsonSerializer.DeserializeAsync<IEnumerable<GitHubBranch>>(responseStream);
}
}
}
|
using System;
using System.Drawing;
using System.IO;
using Vanara.InteropServices;
namespace Vanara.PInvoke
{
public static partial class Gdi32
{
Stream dib = null;
byte[] header = null;
public static Bitmap BitmapFromDib(IntPtr dib)
{
var reader = new MarshalingStream(dib, );
int headerSize = reader.ReadInt32();
int pixelSize = (int)dib.Length - headerSize;
int fileSize = 14 + headerSize + pixelSize;
MemoryStream bmp = new MemoryStream(14);
BinaryWriter writer = new BinaryWriter(bmp);
/* Get the palette size
* The Palette size is stored as an int32 at offset 32
* Actually stored as number of colours, so multiply by 4
*/
dib.Position = 32;
int paletteSize = 4 * reader.ReadInt32();
// Get the palette size from the bbp if none was specified
if (paletteSize == 0)
{
/* Get the bits per pixel
* The bits per pixel is store as an int16 at offset 14
*/
dib.Position = 14;
int bpp = reader.ReadInt16();
// Only set the palette size if the bpp < 16
if (bpp < 16)
paletteSize = 4 * (2 << (bpp - 1));
}
// 1. Write Bitmap File Header:
writer.Write((byte)'B');
writer.Write((byte)'M');
writer.Write(fileSize);
writer.Write((int)0);
writer.Write(14 + headerSize + paletteSize);
header = bmp.GetBuffer();
writer.Close();
dib.Position = 0;
}
public override int Read(byte[] buffer, int offset, int count)
{
int dibCount = count;
int dibOffset = offset - 14;
int result = 0;
if (_position & lt; 14){
int headerCount = Math.Min(count + (int)_position, 14);
Array.Copy(header, _position, buffer, offset, headerCount);
dibCount -= headerCount;
_position += headerCount;
result = headerCount;
}
if (_position & gt;= 14 ) {
result += dib.Read(buffer, offset + result, dibCount);
_position = 14 + dib.Position;
}
return (int)result;
}
public override long Length
{
get { return 14 + dib.Length; }
}
private long _position = 0;
public override long Position
{
get { return _position; }
set
{
_position = value;
if (_position > 14)
dib.Position = _position - 14;
}
}
}
} |
using System;
using Fingo.Auth.DbAccess.Models.Statuses;
using Fingo.Auth.DbAccess.Repository.Interfaces;
using Fingo.Auth.Domain.Infrastructure.EventBus.Events.Project;
using Fingo.Auth.Domain.Infrastructure.EventBus.Interfaces;
using Fingo.Auth.Domain.Infrastructure.ExtensionMethods;
using Fingo.Auth.Domain.Projects.Interfaces;
namespace Fingo.Auth.Domain.Projects.Implementation
{
public class DeleteProject : IDeleteProject
{
private readonly IEventBus _eventBus;
private readonly IProjectRepository _repo;
public DeleteProject(IProjectRepository repo , IEventBus eventBus)
{
_repo = repo;
_eventBus = eventBus;
}
public void Invoke(int id)
{
var toRemove = _repo.GetByIdWithAll(id).WithoutStatuses(ProjectStatus.Deleted);
if (toRemove == null)
throw new ArgumentNullException($"Cannot find project with id={id}.");
toRemove.ModificationDate = DateTime.UtcNow;
toRemove.Status = ProjectStatus.Deleted;
toRemove.ProjectCustomData = null;
toRemove.ProjectPolicies = null;
toRemove.ProjectUsers = null;
_repo.Edit(toRemove);
_eventBus.Publish(new ProjectRemoved(toRemove.Id , toRemove.Name));
}
}
} |
using AcoesDotNet.Model;
using System;
using System.Collections.Generic;
using System.Linq.Expressions;
using System.Threading.Tasks;
namespace AcoesDotNet.Dal.Daos
{
public interface IGenericDao<TEntity> where TEntity : class
{
Task DeleteAsync(object id);
Task<IEnumerable<TEntity>> GetAllAsyc(params Expression<Func<TEntity, object>>[] includeProperties);
Task<TEntity> GetById(object id, params Expression<Func<TEntity, object>>[] includeProperties);
Task InsertAsync(TEntity entity);
Task UpdateAsync(TEntity entity);
Task<bool> ExistsAsync(Expression<Func<TEntity, bool>> predicate);
Task<TEntity> GetByExpression(Expression<Func<TEntity, bool>> predicate,
string campoOrdenacao = nameof(BaseModel.Id), bool desc = false, params Expression<Func<TEntity, object>>[] includeProperties);
}
}
|
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace MovieWebSite.Models
{
public class Context : DbContext
{
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseSqlServer("server=LAPTOP-N1UQOJ3H; database=MovieWeb; integrated security=true");
}
public DbSet<Website> Website { get; set; }
public DbSet<Genres> Genres { get; set; }
public DbSet<Choose> Choose { get; set; }
public DbSet<Country> Country { get; set; }
public DbSet<Filter> Filter { get; set; }
public DbSet<AppUser> AppUser { get; set; }
}
}
|
using System;
using System.Collections.Generic;
namespace POSServices.PosMsgModels
{
public partial class JobSynchDetailDownloadStatus
{
public long SynchDetail { get; set; }
public int Rowfatch { get; set; }
public int RowApplied { get; set; }
public int Status { get; set; }
public Guid? Downloadsessionid { get; set; }
}
}
|
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
namespace IotHubSync.Service
{
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Configuration;
using System.IO;
public class Program
{
public static void Main(string[] args)
{
CreateHostBuilder(args).Build().Run();
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureAppConfiguration((hostingContext, config) =>
{
config.SetBasePath(Directory.GetCurrentDirectory());
config.AddJsonFile("appsettings.json", optional: true, reloadOnChange: false);
config.AddJsonFile("appsettings.Development.json", optional: true, reloadOnChange: false);
config.AddEnvironmentVariables();
})
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
});
}
}
|
using UnityEngine;
namespace Sound
{
public class LevelMusicManager : MonoBehaviour
{
[SerializeField] private MusicManager[] _allMusic;
[SerializeField] private int[] _musicThreshold;
private int _playedMusic = -1;
private void Awake()
{
MemoryHandler mem = FindObjectOfType<MemoryHandler>();
mem.OnNewMemoryPickedUp += OnNewMemoryPickedUp;
}
private void Start()
{
OnNewMemoryPickedUp(0);
}
private void OnNewMemoryPickedUp(int nbPickedUp)
{
int lastIdx = -1;
for (int x = 0; x < _musicThreshold.Length; x++)
{
if (_musicThreshold[x] <= nbPickedUp)
lastIdx = x;
}
PlayMusic(lastIdx);
}
private void PlayMusic(int idx)
{
if (_playedMusic != -1)
_allMusic[_playedMusic].Disable(1f);
_playedMusic = idx;
_allMusic[_playedMusic].Enable(1f);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using Data;
using UI.Desktop.Content;
namespace UI.Desktop
{
/// <summary>
/// Interaction logic for ProductBrowser.xaml
/// </summary>
public partial class ProductBrowser : UserControl, ProductCategoryChangedEmitter
{
public enum ProductsViewMode
{
List,
Grid,
Tree,
Start
}
private ProductCategory rootCategory;
private ProductsViewMode viewMode;
private ListView listView;
private GridView gridView;
private TreeView treeView;
private CategoryControl categoryControl;
private Label homeLabel;
public event ProductCategoryChangedHandler PreviewProductCategorySelectionChanged;
public event ProductCategoryChangedHandler ProductCategorySelectionChanged;
public ProductCategory RootCategory
{
get { return rootCategory; }
set { rootCategory = value;
categorySourceUpdated(); }
}
public ProductsViewMode ViewMode
{
get { return viewMode; }
set {
switch (value)
{
case ProductsViewMode.Grid:
//What's that smell?!
((MainWindow)MainWindow.WindowContainer).sortFilterToolBar.Visibility = System.Windows.Visibility.Visible;
itemFrame.Content = gridView;
showCategories();
breadCrumbs.Visibility = System.Windows.Visibility.Visible;
break;
case ProductsViewMode.List:
((MainWindow)MainWindow.WindowContainer).sortFilterToolBar.Visibility = System.Windows.Visibility.Visible;
itemFrame.Content = listView;
showCategories();
breadCrumbs.Visibility = System.Windows.Visibility.Visible;
break;
case ProductsViewMode.Tree:
((MainWindow)MainWindow.WindowContainer).sortFilterToolBar.Visibility = System.Windows.Visibility.Visible;
itemFrame.Content = treeView;
hideCategories();
breadCrumbs.Visibility = System.Windows.Visibility.Visible;
break;
case ProductsViewMode.Start:
((MainWindow)MainWindow.WindowContainer).sortFilterToolBar.Visibility = System.Windows.Visibility.Collapsed;
itemFrame.Content = new StartPage();
showCategories();
breadCrumbs.Visibility = System.Windows.Visibility.Collapsed;
if (PreviewProductCategorySelectionChanged != null)
{
PreviewProductCategorySelectionChanged.Invoke(this, new ProductCategoryChangedEventArgs(null));
}
break;
default:
throw new NotImplementedException();
}
if (homeLabel != null)
{
homeLabel.FontWeight = value == ProductsViewMode.Start ? FontWeights.Bold : FontWeights.Normal;
}
viewMode = value;
}
}
public ProductBrowser()
{
InitializeComponent();
listView = new ListView();
gridView = new GridView();
treeView = new TreeView();
treeView.HorizontalAlignment = System.Windows.HorizontalAlignment.Stretch;
treeView.Width = 500;
ViewMode = ProductsViewMode.Start;
listView.ItemAdded += itemAdded;
//TODO: Implement for grid view and tree view
gridView.ItemAdded += itemAdded;
treeView.ItemAdded += itemAdded;
breadCrumbs.ItemAdded += itemAdded;
}
public void SetCategory(ProductCategory cat)
{
root_ProductCategorySelectionChanged(this, new ProductCategoryChangedEventArgs(cat));
}
private void showCategories()
{
categoryListScrollView.Visibility = System.Windows.Visibility.Visible;
}
private void hideCategories()
{
categoryListScrollView.Visibility = System.Windows.Visibility.Collapsed;
}
private void categorySourceUpdated()
{
container.Children.Clear();
Image image = new Image();
image.Source = (ImageSource)App.Current.Resources["FeatureImage"];
image.Width = 24;
image.Height = 24;
StackPanel sp = new StackPanel();
sp.Orientation = Orientation.Horizontal;
homeLabel = new Label();
homeLabel.Content = "Start";
homeLabel.FontSize = 14;
homeLabel.Cursor = Cursors.Hand;
homeLabel.FontWeight = viewMode == ProductsViewMode.Start ? FontWeights.Bold : FontWeights.Normal;
sp.Children.Add(homeLabel);
sp.Children.Add(image);
container.Children.Add(sp);
categoryControl = new CategoryControl(rootCategory, 1, this);
container.Children.Add(categoryControl);
categoryControl.Expand();
Thickness margin = categoryControl.stackPanel.Margin;
margin.Left = 0;
categoryControl.stackPanel.Margin = margin;
breadCrumbs.DataContext = rootCategory;
listView.DataContext = rootCategory;
gridView.DataContext = rootCategory;
treeView.DataContext = rootCategory;
homeLabel.MouseUp += homeLabel_MouseUp;
categoryControl.ProductCategorySelectionChanged += root_ProductCategorySelectionChanged;
breadCrumbs.ProductCategorySelected += root_ProductCategorySelectionChanged;
Refresh();
}
void homeLabel_MouseUp(object sender, MouseButtonEventArgs e)
{
ViewMode = ProductsViewMode.Start;
}
void root_ProductCategorySelectionChanged(object sender, ProductCategoryChangedEventArgs e)
{
if (viewMode == ProductsViewMode.Start)
{
// TODO: gör så att den sätts till default-ViewModen
ViewMode = ProductBrowser.ProductsViewMode.List;
}
listView.DataContext = gridView.DataContext = breadCrumbs.DataContext = e.Category;
PreviewProductCategorySelectionChanged.Invoke(sender, e);
}
void itemAdded(object sender, CartEventArgs e)
{
if (ItemAdded != null)
{
ItemAdded.Invoke(sender, e);
}
}
public event ShoppingCartChangedHandler ItemAdded;
public void Refresh()
{
categoryControl.Refresh();
}
}
}
|
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Runtime.Remoting.Lifetime;
using System.Security.Permissions;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
//**********************************************************************
//
// 文件名称(File Name):AbstractTask.CS
// 功能描述(Description):
// 作者(Author):Aministrator
// 日期(Create Date): 2017-04-06 10:56:25
//
// 修改记录(Revision History):
// R1:
// 修改作者:
// 修改日期:2017-04-06 10:56:25
// 修改理由:
//**********************************************************************
namespace ND.FluentTaskScheduling.TaskInterface
{
public abstract class AbstractTask : MarshalByRefObject, IDisposable
{
public static event EventHandler<string> OnProcessing;
public static object obj = new object();
/// <summary>
/// 任务的配置信息,类似项目app.config文件配置
/// 测试时需要手工代码填写配置,线上环境需要在任务发布的时候配置
/// </summary>
public TaskAppConfigInfo AppConfig = new TaskAppConfigInfo();
public tb_task TaskDetail = new tb_task();
public tb_taskversion TaskVersionDetail = new tb_taskversion();
private StringBuilder strLog = new StringBuilder();
private string AlarmEmailList = "";
private string AlarmMobileList = "";
#region MyRegion
///// <summary>
///// 线上环境运行入口
///// </summary>
//public RunTaskResult TryRunTask()
//{
// RunTaskResult result = new RunTaskResult() { RunStatus = RunStatus.Failed };
// try
// {
// ShowProcessIngLog("----------------------" + DateTime.Now + ":开始执行任务-----------------------------------------");
// DateTime startTime = DateTime.Now;
// //开始执行任务,上报开始执行日志,并更新任务版本状态为执行中
// Stopwatch sw = new Stopwatch();
// sw.Start();
// try
// {
// result = RunTask();
// }
// catch (Exception ex)
// {
// result = new RunTaskResult() { RunStatus = RunStatus.Exception, Message = ex.Message, Ex = ex };
// ShowProcessIngLog("执行任务异常,异常信息:" + JsonConvert.SerializeObject(ex));
// }
// sw.Stop();
// ShowProcessIngLog("----------------------" + DateTime.Now + ":执行任务完成-----------------------------------------");
// DateTime endTime = DateTime.Now;
// TimeSpan ts = sw.Elapsed;
// long times = sw.ElapsedMilliseconds / 1000;//秒
// //上报任务执行日志和执行结果,并更新最后一次任务状态
// }
// catch (Exception exp)
// {
// ShowProcessIngLog("执行任务异常,异常信息:" + JsonConvert.SerializeObject(exp));
// ShowProcessIngLog("----------------------" + DateTime.Now + ":执行任务完成-----------------------------------------");
// }
// finally
// {
// strLog.Clear();
// }
// return result;
//}
#endregion
public AbstractTask()
{
InitTaskAppConfig();
}
public void ShowProcessIngLog(string content)
{
strLog.AppendLine(content + "<br/>");
if (OnProcessing != null)
{
OnProcessing(this, content);
}
}
public void ClearLog()
{
strLog.Clear();
}
public string GetLog()
{
return strLog.ToString();
}
/// <summary>
/// 运行任务
/// </summary>
/// <returns></returns>
public abstract RunTaskResult RunTask();
/// <summary>
/// 初始化任务配置
/// </summary>
public abstract void InitTaskAppConfig();
/// <summary>
/// 更新是否暂停调度
/// </summary>
public virtual void UpdateTaskPauseStatus(int isPauseSchdule)
{
this.TaskDetail.ispauseschedule = isPauseSchdule;
}
public virtual void SetAlarmList(string emaillist="",string mobilelist="")
{
AlarmEmailList = emaillist;
AlarmMobileList = mobilelist;
}
public string GetAlarmEmailList()
{
return AlarmEmailList ;
}
public string GetAlarmMobileList()
{
return AlarmMobileList;
}
/// <summary>
/// 释放资源
/// </summary>
public virtual void Dispose()
{
this.Dispose();
GC.SuppressFinalize(this);
}
public void TryDispose()
{
try
{
Dispose();
}
catch (Exception ex)
{
ShowProcessIngLog("尝试释放任务资源异常,异常信息:" + JsonConvert.SerializeObject(ex));
}
}
/*忽略默认的对象租用行为,以便“在主机应用程序域运行时始终”将对象保存在内存中.
这种机制将对象锁定到内存中,防止对象被回收,但只能在主机应用程序运行
期间做到这样。*/
[SecurityPermissionAttribute(SecurityAction.Demand,
Flags = SecurityPermissionFlag.Infrastructure)]
public override object InitializeLifetimeService()
{
//return null;
ILease lease = (ILease)base.InitializeLifetimeService();
// Normally, the initial lease time would be much longer.
// It is shortened here for demonstration purposes.
if (lease.CurrentState == LeaseState.Initial)
{
lease.InitialLeaseTime = TimeSpan.Zero;//这里改成0,则是无限期
//lease.SponsorshipTimeout = TimeSpan.FromSeconds(10);
//lease.RenewOnCallTime = TimeSpan.FromSeconds(2);
}
return lease;
}
}
}
|
using Euler_Logic.Helpers;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Euler_Logic.Problems {
public class Problem69 : ProblemBase {
private PrimeSieve _primes;
/*
According to the wiki on euler's totient function (https://en.wikipedia.org/wiki/Euler%27s_totient_function), if the prime factors
of (n) are (p1, p2, p3...pr), then the totient value can be calculated: n(1 - (1/p1))(1 - (1/p2))...(1 - (1/pr)). So what I do
is create a starting fraction for all numbers up to 1000000. Then I loop through all prime numbers, and for each prime number,
I multiply all of its composites by (p - 1)/p. That will give me the totient value for all numbers. I then just loop through them
all to find the highest value for n/t.
*/
public override string ProblemName {
get { return "69: Totient maximum"; }
}
public override string GetAnswer() {
ulong max = 1000000;
_primes = new PrimeSieve(max);
BuildPractions(max);
FindTotiens(max);
return FindHighest(max).ToString();
}
private Dictionary<ulong, Fraction> _fractions = new Dictionary<ulong, Fraction>();
private void BuildPractions(ulong max) {
for (ulong num = 2; num <= max; num++) {
_fractions.Add(num, new Fraction(num, 1));
}
}
private void FindTotiens(ulong max) {
foreach (var prime in _primes.Enumerate) {
for (ulong composite = 2; composite * prime <= max; composite++) {
_fractions[composite * prime].Multiply(prime - 1, prime);
}
}
}
private ulong FindHighest(ulong max) {
ulong highestNum = 0;
decimal highestValue = 0;
for (ulong num = 4; num <= max; num++) {
if (!_primes.IsPrime(num)) {
var fract = _fractions[num];
decimal value = (decimal)num / (decimal)fract.X;
if (value > highestValue) {
highestValue = value;
highestNum = num;
}
}
}
return highestNum;
}
}
}
|
using System.Collections.Generic;
using System.Linq;
using PizzaMore.Data;
using PizzaMore.Utility;
namespace AddPizza
{
class AddPizza
{
public static IDictionary<string, string> RetrieveParameters;
public static Header Header = new Header();
public static Session Session;
static void Main()
{
Session = WebUtil.GetSession();
if (Session == null)
{
Header.Print();
WebUtil.PageNotAllowed();
return;
}
if (WebUtil.IsGet())
{
ShowGetPage();
}
else if (WebUtil.IsPost())
{
RetrieveParameters = WebUtil.RetrievePostParameters();
string title = RetrieveParameters["title"];
string recipe = RetrieveParameters["recipe"];
string url = RetrieveParameters["url"];
using (var pizzaMoreContext = new PizzaMoreContext())
{
var user = pizzaMoreContext.Users.FirstOrDefault(u => u.Id == Session.UserId);
user.Suggestions.Add(new Pizza()
{
ImageUrl = url,
Recipe = recipe,
Title = title,
OwnerId = user.Id,
DownVotes = 0,
UpVotes = 0
});
pizzaMoreContext.SaveChanges();
}
ShowGetPage();
}
}
private static void ShowGetPage()
{
Header.Print();
WebUtil.PrintFileContent(Constants.AddPizzaHtml);
}
}
}
|
namespace WebApi.OData.Controllers
{
// Testing
public class TestController : StandardODataControllerBase<HomeNetDB>
{
[EnableQuery]
public string Get ()
{
return "The OData server is on-line. The time is " + DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss tt") + ".";
}
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class box : MonoBehaviour {
public levelData datalevel;
public Color seleact;
public Renderer m;
Color c;
void Start () {
m = GetComponent<MeshRenderer>();
c = m.material.color;
datalevel = GameObject.FindGameObjectWithTag("level").GetComponent<levelData>();
}
private void OnMouseEnter()
{
m.material.color =Color.red;
}
private void OnMouseExit()
{
m.material.color =c;
}
private void OnMouseDown()
{
Instantiate(datalevel.boxSeleact, transform.position, Quaternion.identity,transform.parent);
Destroy(this.gameObject);
if (datalevel.boxSeleact == null || datalevel.GameOpjactInt ==0) print("i dont have box"); return;
}
// Update is called once per frame
void Update () {
if(datalevel.GameOpjactInt != 0) { datalevel.boxSeleact = datalevel.BoxsLevel[datalevel.GameOpjactInt]; } else { datalevel.boxSeleact = datalevel.BoxsLevel[0]; }
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
namespace ConsoleApp1
{
class Program
{
public static bool Polyndrom(string q) // булевая функция для проверки на полиндромность
{
bool qw = true;
for(int i = 0; i <= q.Length/2; i++) // пробегаемся до середины текста и проверяем первый и последний элемент на сходство
{
if (q[i] != q[q.Length - 1 - i]) // если не равны то текст является не полиндромом, функция возвращает значение false
{
qw = false;
return qw;
}
}
return qw; // если же все элементы равны, то функция возвращает значение true
}
static void Main(string[] args)
{
string file = File.ReadAllText(@"C:\Users\user1\Desktop\PP2\Week 2\Task1\ConsoleApp1\text.txt"); // стринговая переменная file принимает значение текста в данной path
if (Polyndrom(file)) // проверяем текст на полиндромность
{
Console.WriteLine("Yes"); // если полиндром выводим yes, иначе no
}
else Console.WriteLine("No");
Console.ReadKey(); // ЧТОБЫ КОНСОЛЬ НЕ ЗАКРЫЛАСЬ СРАЗУ
}
}
}
|
using System;
using System.Linq;
using System.Text.Json;
using System.Threading.Tasks;
using MeetMuch.Web.Calendar;
using MeetMuch.Web.Graph;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Graph;
using Microsoft.Identity.Web;
namespace MeetMuch.Web.Controllers
{
public class ListController : Controller
{
private readonly ICalendarAccess _calendarAccess;
public ListController(ICalendarAccess calendarAccess)
{
_calendarAccess = calendarAccess;
}
// Minimum permission scope needed for this view
[AuthorizeForScopes(Scopes = new[] { "Calendars.Read" })]
public async Task<IActionResult> Index(int start = 0)
{
DateTime endDate = default;
DateTime startDate = default;
if (start >= 0)
{
startDate = DateTime.Today;
endDate = DateTime.Today.AddDays(start);
}
else
{
startDate = DateTime.Today.AddDays(start);
endDate = DateTime.Today;
}
try
{
var events = await _calendarAccess.GetUserCalendar(User.GetUserGraphTimeZone(), startDate, endDate);
// Return a JSON dump of events
return new ContentResult
{
Content = JsonSerializer.Serialize(events.OrderBy(r => r.Start)),
ContentType = "application/json"
};
}
catch (ServiceException ex)
{
if (ex.InnerException is MicrosoftIdentityWebChallengeUserException)
{
throw;
}
return new ContentResult
{
Content = $"Error getting calendar view: {ex.Message}",
ContentType = "text/plain"
};
}
}
}
} |
using System;
namespace MyLAB1
{
public class CubicOperation
{
//my varibles
private int _numberOne;
private int _numberTwo;
public int NumberOne
{
get
{
return _numberOne;
}
set
{
_numberOne = value;
}
}
public int NumberTwo
{
get
{
return _numberTwo;
}
set
{
_numberTwo = value;
}
}
//methodes
public int Substraction()
{
return (NumberOne - NumberTwo);
}
//cubic operation
public int Cube()
{
return (CubicFunction(Substraction()));
}
//print method
public void Print()
{
Console.Write(_numberOne);
Console.Write(_numberTwo);
}
//print method with a message
public void Print(string message)
{
Console.Write(message);
Console.Write(_numberOne);
Console.Write(_numberTwo);
}
//my exponatial function
private int CubicFunction(int value)
{
return value*value*value;
}
}
}
|
using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
namespace NCWorkpieceModel
{
/// <summary>
/// Control element for browsing voxel models
/// </summary>
public partial class NCWorkpieceWPFView : UserControl
{
WriteableBitmap _wbmp = null; //bitmap for model rendering
ViewportWrapper _vport = new ViewportWrapper(); //data for viewport functions support
VoxelModel _model = null; //current voxel model for browsing
System.Threading.Mutex _modelLockMutex = new System.Threading.Mutex(); //for lock model modifications
bool[,] _pixelsToFilter = null; //array for filtering operations (same resolution as _wbmp)
//camera control parameters
bool _dragging = false; //true if user started to move mouse pointer with left button pressed
Point _mouseStartPoint; //start point of dragging - for mouse move events
float _rotationSensitivity = 1.0f; //rotation sensivity factor
float _scalingSensitivity = 0.1f; //scaling sensivity factor
bool _stopPainting = false; //if true, OnRender will be skipped
//color values
Color _colorBackground = Color.FromRgb(0, 0, 0); //background color
Color _colorAxis = Color.FromRgb(0, 192, 0); //all lines and text color
Color _colorModelRaw = Color.FromRgb(240, 255, 255); //color for raw model surfaces
Color _colorModelProcessed = Color.FromRgb(240, 255, 255); //color for processed model surfaces
//various presentation parameters
float _ambientLightLevel = 0.1f; //level of ambient light
Size _axisLabelSize; //pre-calculated size of axis labels in logical units
Brush _axisBrush = null; //brush for axis color
Brush _backgroundBrush = null; //brush for background
Pen _axisPen = null; //pen for visible lines
Pen _axisPenHidden = null; //pen for invisible lines
double _drawLineWeight = 1.0; //weight of lines in logical units
float _relativeScale = 0.5f; //relative scale (model size / view size)
bool _drawAxis = true; //if true, axis will be drawn
bool _drawGrid = false; //if true, grid for coordinate planes will be drawn
int _gridIntervalCount = 4; //count of grid intervals
bool _multiSourceLighting = true; //if true, several sources of light will be simulated
//constants
public const float MIN_MODEL_SCALE = 20; //min model size in pixels
public const float MAX_OVERSAMPLE = 5; //max pixel size of smallest voxel element
public NCWorkpieceWPFView()
{
InitializeComponent();
SetDefaultModel();
InitRendering();
ResetModelPosition();
this.MouseDown += NCWorkpieceWPFView_MouseDown;
this.MouseUp += NCWorkpieceWPFView_MouseUp;
this.MouseLeave += NCWorkpieceWPFView_MouseLeave;
this.MouseWheel += NCWorkpieceWPFView_MouseWheel;
this.MouseMove += NCWorkpieceWPFView_MouseMove;
this.SizeChanged += NCWorkpieceWPFView_SizeChanged;
ClipToBounds = true;
KeepRelativeScale = false;
RenderingTime = 0;
}
/// <summary>
/// Locks model rendering (for multithreaded operations)
/// </summary>
public void LockModel() => _modelLockMutex.WaitOne();
/// <summary>
/// Unlocks model rendering (for multithreaded operations)
/// </summary>
public void UnlockModel() => _modelLockMutex.ReleaseMutex();
/// <summary>
/// Resets current model to a simple cube with 256^3 resolution
/// </summary>
public void SetDefaultModel()
{
Model = new VoxelModel(new Vector3f(100, 100, 100), 8, null);
Model.CreateDefault();
}
public event EventHandler ViewChange;
public void UpdateView()
{
InvalidateVisual();
ViewChange?.Invoke(null, null);
}
#region InputAndCamera
/// <summary>
/// Sets default model position, scale and orientation
/// </summary>
public void ResetModelPosition()
{
int min_size = W < H ? W : H;
_vport.Scale = min_size / 2;
//set scaling into some reasonable limits
if ((_vport.Scale / (float)Math.Pow(2, Model.Scale)) > MAX_OVERSAMPLE)
_vport.Scale = (float)(0.99 * MAX_OVERSAMPLE * Math.Pow(2, Model.Scale));
else if (_vport.Scale < MIN_MODEL_SCALE)
_vport.Scale = MIN_MODEL_SCALE;
_relativeScale = min_size != 0 ? _vport.Scale / min_size : 0.5f;
_vport.X0 = (W - (int)_vport.Scale) / 2;
_vport.Y0 = H - (H - (int)_vport.Scale) / 2;
_vport.RotationQuaternion = new Quaternion(new Vector3f(1, 0, 0), (float)Math.PI);
UpdateView();
}
/// <summary>
/// Zoom view for defined step count
/// </summary>
public void ZoomView(float steps)
{
float newScale = _vport.Scale * (1 + steps * _scalingSensitivity);
if (newScale > MIN_MODEL_SCALE && newScale / (float)Math.Pow(2, Model.Scale) < MAX_OVERSAMPLE)
{
_vport.Scale = newScale;
int min_size = W < H ? W : H;
_relativeScale = min_size != 0 ? _vport.Scale / min_size : 0.5f;
UpdateView();
}
}
/// <summary>
/// Shift view for defined increments
/// </summary>
public void ShiftView(int dx, int dy)
{
_vport.X0 += dx;
_vport.Y0 += dy;
UpdateView();
}
/// <summary>
/// Rotate view for defined axis vector and angle
/// </summary>
public void RotateView(Vector3f rot_axis, float angle)
{
_vport.RotationQuaternion = new Quaternion(rot_axis, angle) * _vport.RotationQuaternion;
UpdateView();
}
private void NCWorkpieceWPFView_MouseDown(object sender, MouseButtonEventArgs e)
{
if (e.LeftButton == MouseButtonState.Pressed)
{
_mouseStartPoint = e.GetPosition(this);
_dragging = true;
}
else if (e.RightButton == MouseButtonState.Pressed)
{
ResetModelPosition();
}
else if (e.MiddleButton == MouseButtonState.Pressed)
{
_drawAxis = !_drawAxis;
UpdateView();
}
}
private void NCWorkpieceWPFView_MouseUp(object sender, MouseButtonEventArgs e)
{
_dragging = false;
}
private void NCWorkpieceWPFView_MouseLeave(object sender, MouseEventArgs e)
{
_dragging = false;
}
private void NCWorkpieceWPFView_MouseWheel(object sender, MouseWheelEventArgs e)
{
if (e.Delta != 0)
{
//change scale of the view
ZoomView(e.Delta / 120.0f);
}
}
private void NCWorkpieceWPFView_MouseMove(object sender, MouseEventArgs e)
{
if (_dragging)
{
Point pos = e.GetPosition(this);
if (Keyboard.IsKeyDown(Key.LeftCtrl) || Keyboard.IsKeyDown(Key.RightCtrl))
{
//rotate view
Vector3f shift = new Vector3f((float)(pos.X - _mouseStartPoint.X), (float)(pos.Y - _mouseStartPoint.Y), 0);
Vector3f rot_axis = shift.CrossProduct(new Vector3f(0, 0, 1));
rot_axis.Normalize();
float angle = shift.Length() * _rotationSensitivity / _vport.Scale;
RotateView(rot_axis, angle);
}
else
{
//shift view
ShiftView((int)(pos.X - _mouseStartPoint.X), (int)(pos.Y - _mouseStartPoint.Y));
}
_mouseStartPoint = pos;
}
}
private void NCWorkpieceWPFView_SizeChanged(object sender, SizeChangedEventArgs e)
{
if (W > 0 && H > 0)
{
InitRendering();
Quaternion old_q = _vport.RotationQuaternion;
if (!KeepRelativeScale)
{
ResetModelPosition();
}
else
{
float KX = _vport.X0 / _vport.Scale;
float KY = _vport.Y0 / _vport.Scale;
int min_size = W < H ? W : H;
_vport.Scale = _relativeScale * min_size;
//set scaling into limits
if ((_vport.Scale / (float)Math.Pow(2, Model.Scale)) > MAX_OVERSAMPLE)
_vport.Scale = (float)(0.99 * MAX_OVERSAMPLE * Math.Pow(2, Model.Scale));
else if (_vport.Scale < MIN_MODEL_SCALE)
_vport.Scale = MIN_MODEL_SCALE;
_vport.X0 = (int)Math.Round(_vport.Scale * KX);
_vport.Y0 = (int)Math.Round(_vport.Scale * KY);
}
_vport.RotationQuaternion = old_q; //keep current orientation
UpdateView();
}
}
#endregion
#region Rendering
/// <summary>
/// Init all render support things after control init & resize
/// </summary>
private void InitRendering()
{
if (W == 0 || H == 0)
return;
_wbmp = new WriteableBitmap(W, H, 96, 96, PixelFormats.Pbgra32, null);
_pixelsToFilter = new bool[W, H];
_vport.Width = W;
_vport.Height = H;
FontSize = 20;
_drawLineWeight = GetScreenPixelSize();
_axisLabelSize = MeasureString("X");
_axisBrush = new SolidColorBrush(_colorAxis);
_backgroundBrush = new SolidColorBrush(_colorBackground);
_axisPen = new Pen(_axisBrush, _drawLineWeight);
_axisPenHidden = new Pen(_axisBrush, _drawLineWeight);
_axisPenHidden.DashStyle = new DashStyle(new double[] { _drawLineWeight * 3.0F, _drawLineWeight * 6.0F }, 0);
RenderOptions.SetEdgeMode((DependencyObject)this, EdgeMode.Aliased);
RenderOptions.SetBitmapScalingMode(this, BitmapScalingMode.NearestNeighbor);
RenderOptions.ProcessRenderMode = System.Windows.Interop.RenderMode.Default;
}
protected override void OnRender(DrawingContext drawingContext)
{
if (_wbmp == null || _stopPainting)
return;
System.Diagnostics.Stopwatch watch = null;
watch = System.Diagnostics.Stopwatch.StartNew();
//clear background
drawingContext.DrawRectangle(_backgroundBrush, new Pen(), new Rect(0, 0, ActualWidth, ActualHeight));
//Draw lines and text - first phase
DrawAxisAndGrid(drawingContext, false);
//Draw model
RenderModel();
drawingContext.PushOpacityMask(new ImageBrush(_wbmp));
drawingContext.DrawImage(_wbmp, new Rect(0, 0, ActualWidth, ActualHeight));
drawingContext.Pop();
//Draw lines and text - second phase.
//Why 2 phases? Because I don't want to use costly depth buffer in this app, so,
//after model is being drawn, we should redraw erased lines again.
//if a line is not visible, a dashed pattern is used in this phase
DrawAxisAndGrid(drawingContext, true);
watch.Stop();
RenderingTime = watch.ElapsedMilliseconds;
}
/// <summary>
/// Draws axis and grid lines, labels and additional info
/// </summary>
/// <param name="drawingContext">Context to draw</param>
/// <param name="bSecondPhase">Set true, if you use it after model rendering</param>
private void DrawAxisAndGrid(DrawingContext drawingContext, bool bSecondPhase)
{
Vector3f xVector = _vport.RotationMatrix * new Vector3f(_vport.Scale + 30, 0, 0);
Vector3f yVector = _vport.RotationMatrix * new Vector3f(0, _vport.Scale + 30, 0);
Vector3f zVector = _vport.RotationMatrix * new Vector3f(0, 0, _vport.Scale + 30);
if (_drawGrid) //draw grid and info
{
Vector3f gridVX = _vport.RotationMatrix * new Vector3f(_vport.Scale, 0, 0);
Vector3f gridVY = _vport.RotationMatrix * new Vector3f(0, _vport.Scale, 0);
Vector3f gridVZ = _vport.RotationMatrix * new Vector3f(0, 0, _vport.Scale);
float scale_m = _vport.Scale / (_vport.Scale + 30);
for (int i = 0; i <= _gridIntervalCount; i++)
{
//lines perpendicular to X
float xm = _vport.X0 + xVector.X * scale_m * i / _gridIntervalCount;
float ym = _vport.Y0 + xVector.Y * scale_m * i / _gridIntervalCount;
Pen pen = bSecondPhase && zVector.Z < 0 ? _axisPenHidden : _axisPen;
drawingContext.DrawLine(pen, new Point(xm, ym), new Point(xm + gridVY.X, ym + gridVY.Y));
pen = bSecondPhase && yVector.Z < 0 ? _axisPenHidden : _axisPen;
drawingContext.DrawLine(pen, new Point(xm, ym), new Point(xm + gridVZ.X, ym + gridVZ.Y));
//lines perpendicular to Z
xm = _vport.X0 + zVector.X * scale_m * i / _gridIntervalCount;
ym = _vport.Y0 + zVector.Y * scale_m * i / _gridIntervalCount;
pen = bSecondPhase && xVector.Z < 0 ? _axisPenHidden : _axisPen;
drawingContext.DrawLine(pen, new Point(xm, ym), new Point(xm + gridVY.X, ym + gridVY.Y));
pen = bSecondPhase && yVector.Z < 0 ? _axisPenHidden : _axisPen;
drawingContext.DrawLine(pen, new Point(xm, ym), new Point(xm + gridVX.X, ym + gridVX.Y));
//lines perpendicular to Y
xm = _vport.X0 + yVector.X * scale_m * i / _gridIntervalCount;
ym = _vport.Y0 + yVector.Y * scale_m * i / _gridIntervalCount;
pen = bSecondPhase && zVector.Z < 0 ? _axisPenHidden : _axisPen;
drawingContext.DrawLine(pen, new Point(xm, ym), new Point(xm + gridVX.X, ym + gridVX.Y));
pen = bSecondPhase && xVector.Z < 0 ? _axisPenHidden : _axisPen;
drawingContext.DrawLine(pen, new Point(xm, ym), new Point(xm + gridVZ.X, ym + gridVZ.Y));
}
if (_model != null && bSecondPhase)
{
float xm = 20;
float ym = H - 20;
drawingContext.DrawLine(_axisPen, new Point(xm, ym), new Point(xm, ym - 10));
drawingContext.DrawLine(_axisPen, new Point(xm, ym - 5), new Point(xm + _vport.Scale / _gridIntervalCount, ym - 5));
xm = xm + _vport.Scale / _gridIntervalCount;
drawingContext.DrawLine(_axisPen, new Point(xm, ym), new Point(xm, ym - 10));
drawingContext.DrawText(GetFormattedText(_model.MaxSize / _gridIntervalCount + " mm"), new Point(xm + 10, ym - _axisLabelSize.Height * 0.625));
}
}
if (_drawAxis)
{
//draw axis vectors
Pen pen = bSecondPhase && yVector.Z < 0 && zVector.Z < 0 ? _axisPenHidden : _axisPen;
drawingContext.DrawLine(pen, new Point(_vport.X0, _vport.Y0), new Point(_vport.X0 + xVector.X, _vport.Y0 + xVector.Y));
pen = bSecondPhase && xVector.Z < 0 && zVector.Z < 0 ? _axisPenHidden : _axisPen;
drawingContext.DrawLine(pen, new Point(_vport.X0, _vport.Y0), new Point(_vport.X0 + yVector.X, _vport.Y0 + yVector.Y));
pen = bSecondPhase && xVector.Z < 0 && yVector.Z < 0 ? _axisPenHidden : _axisPen;
drawingContext.DrawLine(pen, new Point(_vport.X0, _vport.Y0), new Point(_vport.X0 + zVector.X, _vport.Y0 + zVector.Y));
if (bSecondPhase)
{
//draw text
drawingContext.DrawText(GetFormattedText("X"), GetAxisTextPosition(xVector));
drawingContext.DrawText(GetFormattedText("Y"), GetAxisTextPosition(yVector));
drawingContext.DrawText(GetFormattedText("Z"), GetAxisTextPosition(zVector));
}
}
}
/// <summary>
/// Returns size of a string in logical units
/// </summary>
private Size MeasureString(string str)
{
var formattedText = GetFormattedText(str);
return new Size(formattedText.Width, formattedText.Height);
}
/// <summary>
/// Returns size of the screen pixel in logical units
/// </summary>
private double GetScreenPixelSize()
{
Matrix m = PresentationSource.FromVisual(this).CompositionTarget.TransformToDevice;
return m.M11;
}
/// <summary>
/// Returns formatted text for rendering
/// </summary>
private FormattedText GetFormattedText(string txt)
{
return new FormattedText(txt,
System.Globalization.CultureInfo.CurrentCulture,
FlowDirection.LeftToRight,
new Typeface("Courier New"),
FontSize,
_axisBrush,
new NumberSubstitution(),
1);
}
/// <summary>
/// Returns good-looking axis label position
/// </summary>
/// <param name="axis">Axis vector in viewport coordinate system</param>
private Point GetAxisTextPosition(Vector3f axis)
{
Point p = new Point(_vport.X0 + axis.X + 0.5 * _axisLabelSize.Width, _vport.Y0 + axis.Y - _axisLabelSize.Height * 0.5);
double angle = Math.Atan2(axis.Y, axis.X);
p.X -= (float)(_axisLabelSize.Width * (1.0 - Math.Cos(angle)));
p.Y += (float)(0.625 * _axisLabelSize.Height * Math.Sin(angle));
return p;
}
///Sets alpha channel value to zero for all pixels of model bitmap
private unsafe void WbmpClear()
{
byte* pixel_data = (byte*)_wbmp.BackBuffer.ToPointer();
int width_in_bytes = _wbmp.BackBufferStride;
int width = _wbmp.PixelWidth;
int height = _wbmp.PixelHeight;
System.Threading.Tasks.Parallel.For(0, height, (y_idx) =>
{
int row_start = width_in_bytes * y_idx;
int row_end = row_start + width_in_bytes;
for (int px_alpha_pos = row_start + 3; px_alpha_pos < row_end; px_alpha_pos += 4)
{
pixel_data[px_alpha_pos] = 0;
}
});
}
/// <summary>
/// Renders voxel model to bitmap
/// </summary>
private unsafe void RenderModel()
{
if (_model == null)
return;
_wbmp.Lock();
WbmpClear();
byte* pixel_data = (byte*)_wbmp.BackBuffer.ToPointer();
int width_in_bytes = _wbmp.BackBufferStride;
RayCastingData rd = _vport.RaycastingData;
float R = _colorModelRaw.R;
float G = _colorModelRaw.G;
float B = _colorModelRaw.B;
float Rproc = _colorModelProcessed.R;
float Gproc = _colorModelProcessed.G;
float Bproc = _colorModelProcessed.B;
int x_count = _vport.RaycastingData.x_count;
int y_count = _vport.RaycastingData.y_count;
LockModel();
try
{
//cast rays for all pixels of region containing the model
System.Threading.Tasks.Parallel.For(0, x_count, (x_idx) =>
{
Ray ray;
Vector3f norm = new Vector3f(0, 0, 0);
ray.kx = rd.k.X;
ray.ky = rd.k.Y;
ray.kz = rd.k.Z;
uint color_int;
for (int y_idx = 0; y_idx < y_count; y_idx++)
{
//prepare ray
ray.px = rd.k.X * (rd.p0.X + x_idx * rd.dpx.X + y_idx * rd.dpy.X);
ray.py = rd.k.Y * (rd.p0.Y + x_idx * rd.dpx.Y + y_idx * rd.dpy.Y);
ray.pz = rd.k.Z * (rd.p0.Z + x_idx * rd.dpx.Z + y_idx * rd.dpy.Z);
if (rd.look_v.X > 0.0f)
ray.px = 3.0f * ray.kx - ray.px;
if (rd.look_v.Y > 0.0f)
ray.py = 3.0f * ray.ky - ray.py;
if (rd.look_v.Z > 0.0f)
ray.pz = 3.0f * ray.kz - ray.pz;
//cast the ray and calculate shading coefficient
int result = RayCaster.CastRay(_model, ref ray, ref rd, ref norm);
if (result >= 0)
{
float br = CalculateBrightnessLevel(ref norm);
if (br >= 0.0f)
{
if (result == 2) //processed surface
color_int = ((uint)(Bproc * br)) | (((uint)(Gproc * br)) << 8) | (((uint)(Rproc * br)) << 16) | ((uint)(0xFF000000));
else //raw surface
color_int = ((uint)(B * br)) | (((uint)(G * br)) << 8) | (((uint)(R * br)) << 16) | ((uint)(0xFF000000));
//set color value to the pixel
*((uint*)(pixel_data + (rd.y_start + y_idx) * width_in_bytes + (rd.x_start + x_idx) * 4)) = color_int;
//the pixel is good and shouldn't be filtered
_pixelsToFilter[rd.x_start + x_idx, rd.y_start + y_idx] = false;
}
else //the pixel should be filtered
_pixelsToFilter[rd.x_start + x_idx, rd.y_start + y_idx] = true;
}
else //this pixel belongs to background and shouldn't be filtered
_pixelsToFilter[rd.x_start + x_idx, rd.y_start + y_idx] = false;
}
});
}
catch (AggregateException ae)
{
UnlockModel();
_wbmp.Unlock();
throw ae.InnerException;
}
UnlockModel();
//filter ambigouos pixels (which are located exactly on the edges of voxels)
int start_ix = Math.Max(Math.Min(rd.x_start, 1), _wbmp.PixelWidth - 2);
int end_ix = Math.Max(Math.Min(rd.x_start + x_count, 1), _wbmp.PixelWidth - 2);
int start_iy = Math.Max(Math.Min(rd.y_start, 1), _wbmp.PixelHeight - 2);
int end_iy = Math.Max(Math.Min(rd.y_start + y_count, 1), _wbmp.PixelHeight - 2);
try
{
System.Threading.Tasks.Parallel.For(start_ix, end_ix, (ix) =>
{
uint Rsum, Gsum, Bsum, colorval;
for (int iy = start_iy; iy < end_iy; iy++)
{
if (_pixelsToFilter[ix, iy])
{
Rsum = 0; Gsum = 0; Bsum = 0;
uint sum_count = 0;
//calculate average value in 3x3 area
for (int dx = ix - 1; dx <= ix + 1; dx++)
for (int dy = iy - 1; dy <= iy + 1; dy++)
{
if (!_pixelsToFilter[dx, dy] && !(dx == ix && dy == iy))
{
colorval = *((uint*)(pixel_data + dy * width_in_bytes + dx * 4));
Rsum += (colorval >> 16) & 255;
Gsum += (colorval >> 8) & 255;
Bsum += colorval & 255;
sum_count++;
}
}
if (sum_count > 0)
{
Rsum /= sum_count; Gsum /= sum_count; Bsum /= sum_count;
colorval = (uint)(Bsum | (Gsum << 8) | (Rsum << 16) | (0xFF << 24));
*((uint*)(pixel_data + iy * width_in_bytes + ix * 4)) = colorval;
}
}
}
});
}
catch (AggregateException ae)
{
throw ae.InnerException;
}
finally
{
_wbmp.AddDirtyRect(new Int32Rect(0, 0, _wbmp.PixelWidth, _wbmp.PixelHeight));
_wbmp.Unlock();
}
}
/// <summary>
/// Gets brightness level for model surface point
/// </summary>
/// <param name="norm">Surface normal vector</param>
private float CalculateBrightnessLevel(ref Vector3f norm)
{
RayCastingData rd = _vport.RaycastingData;
float L = -norm * rd.look_v;
if (L >= 0.0f)
{
if (_multiSourceLighting)
{
//hard-coded empirical coefficients
float sk_diff = L; //diffuse coeff.
float sk_refl; //reflection coeff.
//ambient + primary "flashlight" source
L = _ambientLightLevel + 0.05f * sk_diff;
sk_refl = sk_diff * sk_diff;
sk_refl *= sk_refl; sk_refl *= sk_refl; sk_refl *= sk_refl;
L += 0.77f * sk_refl;
//additional light sources
foreach (Vector3f v in _vport.Lights)
{
sk_diff = -norm * v;
if (sk_diff > 0)
{
L += 0.05f * sk_diff;
sk_refl = sk_diff * sk_diff;
sk_refl *= sk_refl; sk_refl *= sk_refl; sk_refl *= sk_refl;
L += 0.82f * sk_refl;
}
}
if (L > 1.0f) L = 1.0f;
}
else
L = _ambientLightLevel + (1.0f - _ambientLightLevel) * L;
}
return L;
}
#endregion
#region Properties
/// <summary>
/// Integer width
/// </summary>
private int W { get => (int)ActualWidth; }
/// <summary>
/// Integer height
/// </summary>
private int H { get => (int)ActualHeight; }
/// <summary>
/// Approximate execution time for last OnRender call.
/// </summary>
public long RenderingTime { get; private set; }
/// <summary>
/// If true, the control is trying to keep model_size/screen_size ratio the same after resize
/// </summary>
public bool KeepRelativeScale { get; set; }
/// <summary>
/// Gets or sets axis drawing option
/// </summary>
public bool DrawAxis
{
get => _drawAxis;
set { _drawAxis = value; UpdateView(); }
}
/// <summary>
/// Gets or sets grid drawing option
/// </summary>
public bool DrawGrid
{
get => _drawGrid;
set { _drawGrid = value; UpdateView(); }
}
/// <summary>
/// Gets or sets count of grid intervals
/// </summary>
public int GridIntervalCount
{
get => _gridIntervalCount;
set { _gridIntervalCount = Math.Min(Math.Max(2, value), 100); UpdateView(); }
}
/// <summary>
/// Gets or sets lighting mode.
/// If true, several light sources and semi-reflective material of the model will be simulated.
/// Otherwise, only one "flashlight" source and diffuse material of the model will be used
/// </summary>
public bool MultiSourceLighting
{
get => _multiSourceLighting;
set { _multiSourceLighting = value; UpdateView(); }
}
/// <summary>
/// Scaling sensivity value
/// </summary>
public int ScalingSensitivity
{
get => (int)(_scalingSensitivity * 500.0f + 0.5f);
set
{ _scalingSensitivity = Math.Min(Math.Max(1, value), 100) / 500.0f; }
}
/// <summary>
/// Rotation sensivity value
/// </summary>
public int RotationSensitivity
{
get => (int)(_rotationSensitivity * 50.0f + 0.5f);
set { _rotationSensitivity = Math.Min(Math.Max(1, value), 100) / 50.0f; }
}
/// <summary>
/// Background color
/// </summary>
public Color ColorBackground
{
get => _colorBackground;
set
{
_colorBackground = value;
_backgroundBrush = new SolidColorBrush(_colorBackground);
UpdateView();
}
}
/// <summary>
/// Gets or sets color for axis and grid
/// </summary>
public Color ColorAxisAndGrid
{
get => _colorAxis;
set
{
_colorAxis = value;
_axisBrush = new SolidColorBrush(_colorAxis);
_axisPen = new Pen(_axisBrush, _drawLineWeight);
_axisPenHidden = new Pen(_axisBrush, _drawLineWeight);
_axisPenHidden.DashStyle = new DashStyle(new double[] { _drawLineWeight * 3.0F, _drawLineWeight * 3.0F }, 0);
UpdateView();
}
}
/// <summary>
/// Gets or sets color for raw surfaces of the model
/// </summary>
public Color ColorModelRaw
{
get => _colorModelRaw;
set { _colorModelRaw = value; UpdateView(); }
}
/// <summary>
/// Gets or sets color for processed surfaces of the model
/// </summary>
public Color ColorModelProcessed
{
get => _colorModelProcessed;
set { _colorModelProcessed = value; UpdateView(); }
}
/// <summary>
/// Gets or sets current voxel model
/// </summary>
public VoxelModel Model
{
get => _model;
set
{
if (value == null)
return;
LockModel();
if (_model != null)
_model.Dispose();
_model = value;
UnlockModel();
ResetModelPosition();
UpdateView();
}
}
/// <summary>
/// Gets or sets level of ambient light [0...20]
/// </summary>
public int AmbientLightLevel
{
get => (int)(_ambientLightLevel * 100.0f + 0.5f);
set
{
_ambientLightLevel = Math.Min(Math.Max(0, value), 20) / 100.0f;
UpdateView();
}
}
/// <summary>
/// Sets value to suspend or resume view update
/// </summary>
public bool StopPainting
{
set
{
_stopPainting = value;
if (!_stopPainting)
UpdateView();
}
}
#endregion
}
}
|
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BOB2
{
abstract class MovingObject : GameObject
{
protected Vector2 hastighet;
protected float scale;
public MovingObject(Texture2D _texture, Vector2 _vector, Vector2 _hastighet, float _scale) : base(_texture, _vector)
{
scale = _scale;
hastighet = _hastighet;
}
public abstract void Update();
}
}
|
using MartianRobotsService.BaseClasses;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace MartianRobotsService.Models
{
public class _2DDirection : DirectionBase
{
private _2DDirection()
{
}
public _2DDirection(uint direction) : base()
{
Direction = new List<uint>(1) { direction % 360 };
}
public override string ToOrientation()
{
string orientation;
switch (Direction[0])
{
case 0:
orientation = "N";
break;
case 90:
orientation = "E";
break;
case 180:
orientation = "S";
break;
case 270:
orientation = "W";
break;
default:
throw new NotImplementedException();
}
return orientation;
}
}
}
|
using Xamarin.Forms;
using Xamarin.Forms.Platform.iOS;
using UIKit;
using XamarinFormsNativeDemo.PlatformSpecifics.iOS;
//[assembly: ExportEffect(typeof(XamarinFormsNativeDemo.iOS.Effects.ClearEntryEffect), "ClearEntryEffect")]
namespace XamarinFormsNativeDemo.iOS.Effects
{
/*
public class ClearEntryEffect : PlatformEffect
{
private UITextFieldViewMode _initialMode;
protected override void OnAttached()
{
ConfigureControl();
}
protected override void OnDetached()
{
ResetControl();
}
private void ConfigureControl()
{
_initialMode = ((UITextField)Control).ClearButtonMode;
((UITextField)Control).ClearButtonMode = UITextFieldViewMode.WhileEditing;
}
private void ResetControl()
{
((UITextField)Control).ClearButtonMode = _initialMode;
}
}
*/
/*
//Platform specifics version of effect
public class ClearEntryEffect : PlatformEffect
{
protected override void OnAttached()
{
ConfigureControl();
}
protected override void OnDetached()
{
}
protected override void OnElementPropertyChanged(System.ComponentModel.PropertyChangedEventArgs args)
{
base.OnElementPropertyChanged(args);
//Trigger at runtime update of the control when attached property changes
if (args.PropertyName == PlatformSpecifics.iOS.ClearEntryPlatformSpecific.IsClearEnabledProperty.PropertyName)
ConfigureControl();
}
private void ConfigureControl()
{
//Use property on xamarin forms element to validate what needs to be done with the native control
if (((Entry)Element).OnThisPlatform().GetIsClearEnabled())
((UITextField)Control).ClearButtonMode = UITextFieldViewMode.WhileEditing;
else
((UITextField)Control).ClearButtonMode = UITextFieldViewMode.Never;
}
}
*/
} |
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.EntityFrameworkCore;
using WziumStars.Data;
using WziumStars.Models;
namespace WziumStars.Areas.Identity.Pages.Account.Manage
{
public partial class IndexModel : PageModel
{
private readonly UserManager<IdentityUser> _userManager;
private readonly SignInManager<IdentityUser> _signInManager;
private readonly ApplicationDbContext _db;
public IndexModel(
UserManager<IdentityUser> userManager,
SignInManager<IdentityUser> signInManager,
ApplicationDbContext db)
{
_userManager = userManager;
_signInManager = signInManager;
_db = db;
}
public string Username { get; set; }
[TempData]
public string StatusMessage { get; set; }
[BindProperty]
public InputModel Input { get; set; }
public class InputModel
{
[Display(Name = "Imię")]
public string FirstName { get; set; }
[Display(Name = "Nazwisko")]
public string LastName { get; set; }
[Display(Name = "Kraj")]
public string Country { get; set; }
[Display(Name = "Stan")]
public string State { get; set; }
[Display(Name = "Miejscowość")]
public string City { get; set; }
[Display(Name = "Ulica i numer budynku")]
public string Street { get; set; }
[Display(Name = "Numer mieszkania")]
public string ApartmentNumber { get; set; }
[Display(Name = "Kod pocztowy")]
public string PostalCode { get; set; }
[Phone(ErrorMessage = "Błędna składnia numeru telefonu")]
[Display(Name = "Telefon")]
public string PhoneNumber { get; set; }
[EmailAddress]
[Display(Name = "Email")]
public string Email { get; set; }
}
private void Load(ApplicationUser user)
{
Input = new InputModel
{
FirstName = user.FirstName,
LastName = user.LastName,
Country = user.Country,
State = user.State,
City = user.City,
Street = user.Street,
ApartmentNumber = user.ApartmentNumber,
PostalCode = user.PostalCode,
PhoneNumber = user.PhoneNumber,
Email = user.Email
};
}
public async Task<IActionResult> OnGetAsync()
{
var claimsIdentity = (ClaimsIdentity)User.Identity;
var claim = claimsIdentity.FindFirst(ClaimTypes.NameIdentifier);
ApplicationUser applicationUser = await _db.ApplicationUser.Where(c => c.Id == claim.Value).FirstOrDefaultAsync();
if (applicationUser == null)
{
return NotFound();
}
Load(applicationUser);
return Page();
}
public async Task<IActionResult> OnPostAsync()
{
if (ModelState.IsValid)
{
var claimsIdentity = (ClaimsIdentity)User.Identity;
var claim = claimsIdentity.FindFirst(ClaimTypes.NameIdentifier);
ApplicationUser applicationUser = await _db.ApplicationUser.Where(c => c.Id == claim.Value).FirstOrDefaultAsync();
applicationUser.FirstName = Input.FirstName;
applicationUser.LastName = Input.LastName;
applicationUser.Country = Input.Country;
applicationUser.State = Input.State;
applicationUser.City = Input.City;
applicationUser.Street = Input.Street;
applicationUser.ApartmentNumber = Input.ApartmentNumber;
applicationUser.PostalCode = Input.PostalCode;
applicationUser.PhoneNumber = Input.PhoneNumber;
await _db.SaveChangesAsync();
StatusMessage = "Pomyślnie zmieniono dane użytkownika.";
return RedirectToPage();
}
StatusMessage = "Error: Wystąpił błąd podczas zapisywania danych profilu.";
return RedirectToPage();
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Cell : MonoBehaviour {
public int XPos;
public int YPos;
public Unit Unit;
private Color _startcolor;
public bool IsRotateTarget = false;
public PlaceManager PlaceManager;
public Map Map;
private void Start()
{
_startcolor = GetComponent<Renderer>().material.color;
}
void OnMouseEnter()
{
if (PlaceManager == null) return;
if(ShowPlacementHighlight()) return;
}
public void Highlight(Color color)
{
GetComponent<Renderer>().material.color = color;
}
public void RemoveHighligh()
{
GetComponent<Renderer>().material.color = _startcolor;
}
private bool ShowPlacementHighlight()
{
if (PlaceManager.ObjectToPlace == null) return false;
Map.HighLightCells(this, PlaceManager.ObjectToPlace);
return true;
}
}
|
using System;
namespace Phenix.Test.使用指南._21._3
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("需事先在本机启动WebAPI服务(启动Bin.Top目录下的Phenix.Services.Host.x86/x64.exe程序)");
Console.WriteLine("如需观察日志,请启动Host后将Debugging功能点亮,测试过程中产生的日志会保存在Host当前目录下的TempDirectory子目录里");
Console.Write("准备好后请点回车继续:");
Console.ReadLine();
DataSecurityTest();
Console.ReadLine();
}
private static async void DataSecurityTest()
{
Console.WriteLine("**** 测试身份认证 ****");
Phenix.Web.Client.Security.UserIdentity userIdentity = new Phenix.Web.Client.Security.UserIdentity("ADMIN", "ADMIN");
using (Phenix.Web.Client.HttpClient client = new Phenix.Web.Client.HttpClient("127.0.0.1", userIdentity))
{
Console.WriteLine("登录ADMIN用户(第二个参数为ADMIN的默认口令,如有被修改过请赋值为当前口令)");
bool succeed = await client.SecurityProxy.LogOnAsync();
Console.WriteLine("是否已登录成功:" + (succeed ? "是 ok" : "否 error"));
Console.WriteLine();
Console.WriteLine("修改ADMIN登录口令(第二个参数为ADMIN的默认口令,如有被修改过请赋值为当前口令)");
succeed = await client.SecurityProxy.ChangePasswordAsync("ADMIN");
Console.WriteLine("是否已修改成功:" + (succeed ? "是 ok" : "否 error"));
Console.WriteLine();
succeed = await client.SecurityProxy.LogOffAsync();
Console.WriteLine("是否已登出成功:" + (succeed ? "是 ok" : "否 error"));
Console.WriteLine();
Console.WriteLine("结束");
Console.ReadLine();
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace KartObjects
{
[Serializable]
public class POSButtonAction:SimpleDbEntity
{
[DBIgnoreReadParam]
[DBIgnoreAutoGenerateParam]
public override string FriendlyName
{
get { return "Кнопка-действие"; }
}
/// <summary>
/// Код кнопки
/// </summary>
public int ButtonCode
{
get;
set;
}
/// <summary>
/// Модификаторы (shift,ctrl,alt)
/// </summary>
public int Modifiers
{
get;
set;
}
[DBIgnoreReadParam]
[DBIgnoreAutoGenerateParam]
public bool CtrlButtonPressed
{
get
{
return (Modifiers & 131072) == 131072;
}
set
{
if (value)
Modifiers |= 131072;
else
if ((Modifiers & 131072) == 131072)
Modifiers ^= 131072;
}
}
[DBIgnoreReadParam]
[DBIgnoreAutoGenerateParam]
public bool AltButtonPressed
{
get
{
return (Modifiers & 262144) == 262144;
}
set
{
if (value)
Modifiers |= 262144;
else
if ((Modifiers & 262144) == 262144)
Modifiers ^= 262144;
}
}
[DBIgnoreReadParam]
[DBIgnoreAutoGenerateParam]
public bool ShiftButtonPressed
{
get
{
return (Modifiers & 65536) == 65536;
}
set
{
if (value)
Modifiers |= 65536;
else
if ((Modifiers & 65536) == 65536)
Modifiers ^= 65536;
}
}
/// <summary>
/// Действие кассового модуля
/// </summary>
//[DBIdAutoGenerateParam]
//[DBIgnoreReadParam]
public POSActionMnemonic MnemonicAction
{
get;
set;
}
/// <summary>
/// Мнемоника действия
/// </summary>
[DBIgnoreReadParam]
[DBIgnoreAutoGenerateParam]
public string MnemAction
{
get { return MnemonicAction.GetDescription(); }
}
/// <summary>
/// дополнительное значение
/// </summary>
public string AddValue
{
get;
set;
}
/// <summary>
/// Идентификатор группы устройств
/// </summary>
public long IdPOSGroup
{
get;
set;
}
/// <summary>
/// Группа устройств
/// </summary>
[DBIgnoreReadParam]
[DBIgnoreAutoGenerateParam]
public POSGroup POSGroup
{
get;
set;
}
}
}
|
/*
* --------------------------------------------------------------------------------
* <copyright file = "Person" Developer: Diogo Rocha @IPCA</copyright>
* <author>Diogo Miguel Correia Rocha</author>
* <email>a18855@alunos.ipca.pt</email>
* <date>26/06/2020</date>
* <description>Esta classe define uma pessoa.</description>
* --------------------------------------------------------------------------------
*/
using System;
namespace Classes
{
/// <summary>
/// Classe Pessoa.Define uma pessoa.
/// </summary>
[Serializable]
public class Pessoa
{
#region Atributos
protected string regiao;
protected int idades;
protected string genero;
protected string nome;
#endregion
#region Construtor
public Pessoa()
{
}
/// <summary>
/// Construtor com dados do exterior
/// </summary>
/// <param name="rRegiao"></param>
/// <param name="iIdade"></param>
/// <param name="gGenero"></param>
public Pessoa(string nNome, string rRegiao, int iIdade, string gGenero)
{
nome = nNome;
regiao = rRegiao;
idades = iIdade;
genero = gGenero;
}
#endregion
#region Propriedades
/// <summary>
/// Manipula atributo "nome"
/// </summary>
public string Nome
{
get { return nome; }
set { if (nome.Length > 10) nome = value; }
}
/// <summary>
/// Manipula atributo "regiao"
/// int regiao;
/// </summary>
public string Regiao
{
get { return regiao; }
set { regiao = value; }
}
/// <summary>
/// Manipula atributo "idade"
/// int idades;
/// </summary>
public int Idades
{
get { return idades; }
set { if (value > 0 && value < 115) idades = value; }
}
/// <summary>
/// Manipula atributo "genero"
/// int genero;
/// </summary>
public string Genero
{
get { return genero; }
set { genero = value; }
}
#endregion
#region Métodos
#endregion
}
}
|
using Senparc.Core.Models;
namespace Senparc.Repository
{
public interface IAdminUserInfoRepository : IBaseClientRepository<AdminUserInfo>
{
}
public class AdminUserInfoRepository : BaseClientRepository<AdminUserInfo>, IAdminUserInfoRepository
{
private readonly ISqlClientFinanceData _sqlClientFinanceData;
public AdminUserInfoRepository(ISqlClientFinanceData sqlClientFinanceData) : base(sqlClientFinanceData)
{
_sqlClientFinanceData = sqlClientFinanceData;
}
}
}
|
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.
using Microsoft.MixedReality.Toolkit;
using UnityEngine;
using UnityEngine.SceneManagement;
public class LoadFirstScene : MonoBehaviour
{
[SerializeField]
private string contentName = string.Empty;
void Start()
{
CoreServices.SceneSystem.LoadContent(contentName, LoadSceneMode.Single);
}
}
|
using System.Collections;
using UnityEngine;
using UnityEngine.UI;
namespace Gamekit2D
{
public class HealthUI : MonoBehaviour
{
public static GameObject healthBarSlider;
public static GameObject healthBarFill;
void Start(){
healthBarSlider = GameObject.Find("healthBarSlider");
healthBarFill = GameObject.Find("healthBarFill");
}
/* AdaScript - I wanted to do this differently
public Damageable representedDamageable;
public GameObject healthIconPrefab;
protected Animator[] m_HealthIconAnimators;
protected readonly int m_HashActivePara = Animator.StringToHash ("Active");
protected readonly int m_HashInactiveState = Animator.StringToHash ("Inactive");
protected const float k_HeartIconAnchorWidth = 0.041f;
IEnumerator Start ()
{
if(representedDamageable == null)
yield break;
yield return null;
m_HealthIconAnimators = new Animator[representedDamageable.startingHealth];
for (int i = 0; i < representedDamageable.startingHealth; i++)
{
GameObject healthIcon = Instantiate (healthIconPrefab);
healthIcon.transform.SetParent (transform);
RectTransform healthIconRect = healthIcon.transform as RectTransform;
healthIconRect.anchoredPosition = Vector2.zero;
healthIconRect.sizeDelta = Vector2.zero;
healthIconRect.anchorMin += new Vector2(k_HeartIconAnchorWidth, 0f) * i;
healthIconRect.anchorMax += new Vector2(k_HeartIconAnchorWidth, 0f) * i;
m_HealthIconAnimators[i] = healthIcon.GetComponent<Animator> ();
if (representedDamageable.CurrentHealth < i + 1)
{
m_HealthIconAnimators[i].Play (m_HashInactiveState);
m_HealthIconAnimators[i].SetBool (m_HashActivePara, false);
}
}
}
public void ChangeHitPointUI (Damageable damageable)
{
if(m_HealthIconAnimators == null)
return;
for (int i = 0; i < m_HealthIconAnimators.Length; i++)
{
m_HealthIconAnimators[i].SetBool(m_HashActivePara, damageable.CurrentHealth >= i + 1);
}
}*/
public static void ChangeHitPointUI (Damageable damageable)
{
healthBarSlider.GetComponent<Slider>().value = damageable.CurrentHealth;
healthBarFill.GetComponent<Text>().text = damageable.CurrentHealth + " / " + damageable.startingHealth;
}
}
} |
using UnityEngine;
using System.Collections;
public class doorcontroll : MonoBehaviour {
Transform player,m_transform;
// Use this for initialization
void Start () {
player = GameObject.FindGameObjectWithTag ("Player").transform;
m_transform=this.transform;
}
// Update is called once per frame
void Update () {
float d = (m_transform.position - player.position).magnitude;
if ((Input.GetKey (KeyCode.Space)) && (d < 1f))
opendoor ();
}
void opendoor(){
m_transform.GetComponent<Animation> ().Play();
}
}
|
using System;
using System.Windows.Input;
using VideoStream.Models;
using VideoStream.ViewModels;
namespace VideoStream.Commands
{
public class Maximize:ICommand
{
public MainPageViewModel MainPageVM { get; set; }
public Maximize(MainPageViewModel mainPage)
{
this.MainPageVM = mainPage;
}
public event EventHandler CanExecuteChanged;
public bool CanExecute(object parameter)
{
return true;
}
public void Execute(object parameter)
{
MainPageVM.PlayerYTranslation = -365;
MainPageVM.IsPlaying = true;
MainPageVM.IsMaximized = true;
if (MainPageVM.IsSecondShowing == true)
{
MainPageVM.tabSelect = TabSelect.second;
}
else if (MainPageVM.IsFirstShowing==true){
MainPageVM.tabSelect = TabSelect.first;
}
MainPageVM.IsSecondShowing = false;
MainPageVM.IsFirstShowing = false;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Data;
using System.Windows.Forms;
using System.Data.OleDb;
using PickBoxTest;
using System.Drawing;
using System.IO;
using project_vniia.Properties;
namespace project_vniia
{
public partial class Form1 : Form
{
DataSet ds = new DataSet();
public int i;
bool flag_filtr = false;
public static string[] cmdText = new string[13] { "SELECT * FROM [CANNote] ORDER BY Номер_КАН ASC",
"SELECT * FROM [БлокиМетро]","SELECT * FROM [Замечания по БД]","SELECT * FROM [КАН]",
"SELECT * FROM [КАНы]","SELECT * FROM [ОперацииМетро]","SELECT * FROM [Проверка]",
"SELECT * FROM [Проверка ФЭУ]","SELECT * FROM [ПроверкаТСРМ61]","SELECT * FROM [Работы по БД]",
"SELECT * FROM [Системы в сборе]","SELECT * FROM [Термокалибровка] ORDER BY Номер_БД ASC",
"SELECT * FROM Блоки ORDER BY [Номер БД] ASC"};// если понадобиться порядок по определённому столбцу
public static string filePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "change_2_rows.txt");
public static string filePath_calibr = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "calibration_check.txt");
Button button_filtr = new Button();
//
// Create an instance of the PickBox class
//
private PickBox pb = new PickBox();
public static string conString;// = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\\Users\\nasty\\Desktop\\_TCPM82_New.mdb";
public static string[] F2 = new string[4];
public static string Log_ways;
public static string Log_ways_peremesti;
public static string Zamech_ways;
public static string Zamech_ways_peremesti;
public static string[] _ways_=new string[4] {"\\log_ways.txt", "\\log_peremesti.txt", "\\zamech_ways.txt", "\\zamech_peremesti.txt" };
public Form1()
{
InitializeComponent();
//this.KeyPreview = true;
for (int t = 4; this.Controls[t] != this.Controls[6]; t++)
{
Control c = this.Controls[t];
pb.WireControl(c);
}
dataGridView1.DataError += new DataGridViewDataErrorEventHandler(DataGridView1_DataError);
dataGridView2.DataError += new DataGridViewDataErrorEventHandler(DataGridView2_DataError);
dataGridView2.RowPrePaint += DataGridView2_RowPrePaint;
dataGridView1.RowPrePaint += DataGridView1_RowPrePaint;
textBox1.KeyUp += TextBox1_KeyUp;
//резервное копирование
//File.Copy(openFileDialog1.FileName, "C:\\Users\\APM\\Desktop\\2.mdb", true);
}
private void TextBox1_KeyUp(object sender, KeyEventArgs e)
{
button_filtr_Click();
}
private void DataGridView1_RowPrePaint(object sender, DataGridViewRowPrePaintEventArgs e)
{
int index = e.RowIndex;
string indexStr = (index + 1).ToString();
object header = this.dataGridView1.Rows[index].HeaderCell.Value;
if (header == null || !header.Equals(indexStr))
this.dataGridView1.Rows[index].HeaderCell.Value = indexStr;
}
private void DataGridView2_RowPrePaint(object sender, DataGridViewRowPrePaintEventArgs e)
{
int index = e.RowIndex;
string indexStr = (index + 1).ToString();
object header = this.dataGridView2.Rows[index].HeaderCell.Value;
if (header == null || !header.Equals(indexStr))
this.dataGridView2.Rows[index].HeaderCell.Value = indexStr;
}
private void DataGridView2_DataError(object sender, DataGridViewDataErrorEventArgs e)
{
e.ThrowException = false;
}
private void DataGridView1_DataError(object sender, DataGridViewDataErrorEventArgs e)
{
//MessageBox.Show("Ошибка");
e.ThrowException = false;
}
private void Form1_Load(object sender, EventArgs e)
{
do
{
conString = Class_zagruz.Try_(conString, openFileDialog1);
}
while (conString == null);
bool[] flag_sysh = new bool[4];
for (int i = 0; i < 4; i++)
{
bool pusto = Class_ways.Pusto_(_ways_[i]);
flag_sysh[i] = Class_ways.Log_pusto(_ways_[i], pusto);
}
int k_tr=0;
foreach (bool f in flag_sysh)
{
if (f) { k_tr++; }
}
try
{
if (k_tr != 4 && k_tr < 4)
{
do
{
F2 = Class_ways.Forma2_();
if (Form2.close_all)
{
Environment.Exit(0);
}
} while (Array.Exists(F2, element => element == "") || Array.Exists(F2, element => element == null));
}
}
catch (Exception p)
{
Console.WriteLine(p.Message);
}
Class_ways.Zap_(_ways_, F2, k_tr);
//
MyDB myDB = new MyDB();
Class_zagruz.Combobox_(conString, comboBox1, ds, myDB, myDBs);
dataGridView1.DataSource = myDBs["[Блоки]"].table.DefaultView;
dataGridView1.Columns["Номер БД"].ReadOnly = true;
Datagrid_columns_delete_blocks();
Datagrid_columns_delete();
//ready and work
Calibr calibr = new Calibr();
calibr.Main_calibr(this);
Zamech_BD zamech_BD = new Zamech_BD();
zamech_BD.Main_Zamech_BD(this);
}
private void dataGridView2_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
}
string[] stolbez = new string[5] { "Номер блока", "Номер КАН", "Номер БД", "Номер изделия", "Номер системы"};
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
dataGridView2.DataSource = myDBs["[" + comboBox1.Text + "]"].table.DefaultView;
for (i = 0; i < 5; i++)
{
if (dataGridView2.Columns.Contains(stolbez[i]))
{
dataGridView2.Columns[stolbez[i]].ReadOnly = true;
break;
}
}
Datagrid_columns_delete();
if (flag_filtr)
button_filtr_Click();
}
public void Datagrid_columns_delete()
{
if (dataGridView2.Columns.Contains("s_ColLineage") == true)
dataGridView2.Columns.Remove("s_ColLineage");
if (dataGridView2.Columns.Contains("s_Generation") == true)
dataGridView2.Columns.Remove("s_Generation");
if (dataGridView2.Columns.Contains("s_GUID") == true)
dataGridView2.Columns.Remove("s_GUID");
if (dataGridView2.Columns.Contains("s_Lineage") == true)
dataGridView2.Columns.Remove("s_Lineage");
}
public void Datagrid_columns_delete_blocks()
{
if (dataGridView1.Columns.Contains("s_ColLineage") == true)
dataGridView1.Columns.Remove("s_ColLineage");
if (dataGridView1.Columns.Contains("s_Generation") == true)
dataGridView1.Columns.Remove("s_Generation");
if (dataGridView1.Columns.Contains("s_GUID") == true)
dataGridView1.Columns.Remove("s_GUID");
if (dataGridView1.Columns.Contains("s_Lineage") == true)
dataGridView1.Columns.Remove("s_Lineage");
}
public Add_Blocks CreateForm()
{
// Проверяем существование формы
foreach (Form frm in Application.OpenForms)
if (frm is Add_Blocks)
{
frm.Activate();
return frm as Add_Blocks;
}
// Создаем новую форму
Add_Blocks add_ = new Add_Blocks();
add_.blocks_T = myDBs["[Блоки]"].table;
add_.zamech_T = myDBs["[Замечания по БД]"].table;
add_.peregr = this.but_peregruzka;
add_.Show();
return add_;
}
private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
}
public void filtr()
{
if (textBox1.Text == null)
dataGridView1.DataSource = myDBs["[Блоки]"].table;
else
{
var table1 = myDBs["[Блоки]"].table;
int k = 0; bool s_ = false;
if (table1.Columns.Contains("s_ColLineage") == true)
k++; //table1.Columns.Remove("s_ColLineage");
if (table1.Columns.Contains("s_Generation") == true)
k++; // table1.Columns.Remove("s_Generation");
if (table1.Columns.Contains("s_GUID") == true)
k++; // table1.Columns.Remove("s_GUID");
if (table1.Columns.Contains("s_Lineage") == true)
k++;// table1.Columns.Remove("s_Lineage");
var table2 = table1.Copy();
if (k != 0)
s_ = true;
//переписать t1 -> t2 С учетом фильтра
var rows_to_delete = new List<DataRow>();
var rows = table2.Rows;
foreach (DataRow r in rows)
{
bool f = true;
int kolvo = r.ItemArray.Length;
k = 1;
foreach (var c in r.ItemArray)
{
if (s_)
{
if ((k < kolvo) && (k < kolvo - 1) && (k < kolvo - 2) && (k < kolvo - 3))
{
if (c.ToString().Contains(textBox1.Text))
{
f = false;
}
}
else { break; }
}
else
{
if (c.ToString().Contains(textBox1.Text))
{
f = false;
}
}
k++;
}
if (f)
{
rows_to_delete.Add(r);
}
Console.WriteLine();
}
foreach (var r in rows_to_delete)
{
rows.Remove(r);
}
dataGridView1.DataSource = table2;
Datagrid_columns_delete_blocks();
}
}
private void button_filtr_Click()
{
filtr(); // for 1 table
if (textBox1.Text == null)
dataGridView2.DataSource = myDBs["[" + comboBox1.Text + "]"].table;
else
{
var table1 = myDBs["[" + comboBox1.Text + "]"].table;
int k = 0;bool s_ = false;
if (table1.Columns.Contains("s_ColLineage") == true)
k++; //table1.Columns.Remove("s_ColLineage");
if (table1.Columns.Contains("s_Generation") == true)
k++; // table1.Columns.Remove("s_Generation");
if (table1.Columns.Contains("s_GUID") == true)
k++; // table1.Columns.Remove("s_GUID");
if (table1.Columns.Contains("s_Lineage") == true)
k++;// table1.Columns.Remove("s_Lineage");
var table2 = table1.Copy();
if (k != 0)
s_ = true;
//переписать t1 -> t2 С учетом фильтра
var rows_to_delete = new List<DataRow>();
var rows = table2.Rows;
foreach (DataRow r in rows)
{
bool f = true;
int kolvo= r.ItemArray.Length;
k = 1;
foreach (var c in r.ItemArray)
{
if (s_)
{
if ((k < kolvo) && (k < kolvo - 1) && (k < kolvo - 2) && (k < kolvo - 3))
{
if (c.ToString().Contains(textBox1.Text))
{
f = false;
}
}
else { break; }
}
else
{
//Console.Write (c.ToString() + " "); // для проверки
if (c.ToString().Contains(textBox1.Text))
{
f = false;
}
}
k++;
}
if (f)
{
rows_to_delete.Add(r);
}
Console.WriteLine();
}
foreach (var r in rows_to_delete)
{
rows.Remove(r);
}
dataGridView2.DataSource = table2;
Datagrid_columns_delete();
flag_filtr = true;
}
}
private void добавитьБлокиToolStripMenuItem_Click(object sender, EventArgs e)
{
CreateForm();
}
public class MyDB
{
public DataSet ds;
public OleDbDataAdapter adapter;
public DataTable table;
}
private Dictionary<string, MyDB> myDBs = new Dictionary<string, MyDB>();
private void but_peregruzka_Click(object sender, EventArgs e)
{//работает- для замены строк
dataGridView1.DataSource = myDBs["[Блоки]"].table.DefaultView;
Datagrid_columns_delete_blocks();
}
private void menuStrip1_ItemClicked(object sender, ToolStripItemClickedEventArgs e)
{
}
public Form_cod CreateForm_zamena()
{
// Проверяем существование формы
foreach (Form frm in Application.OpenForms)
if (frm is Form_cod)
{
frm.Activate();
return frm as Form_cod;
}
// Создаем новую форму
Form_cod cod = new Form_cod();
cod.dataTables[0] = myDBs["[Блоки]"].table;
i = 1;
foreach (string str in comboBox1.Items)
{
cod.dataTables[i] = myDBs["[" + str + "]"].table;
i++;
}
cod.Show();
return cod;
}
private void поменятьСтрокиМестамиToolStripMenuItem_Click(object sender, EventArgs e)
{
CreateForm_zamena();
}
private void сохранитьToolStripMenuItem_Click(object sender, EventArgs e)
{
//сохранение для таблицы(авто)
ds = new DataSet();
myDBs["[Блоки]"].adapter.Fill(ds);
myDBs["[Блоки]"].ds = ds;
Class_Save_blocks.AnalizTable(myDBs["[Блоки]"].ds.Tables[0], myDBs["[Блоки]"].table, myDBs["[Блоки]"].adapter);
foreach (string str in comboBox1.Items)
{
ds = new DataSet();
myDBs["[" + str + "]"].adapter.Fill(ds);
myDBs["[" + str + "]"].ds = ds;
}
#region SAVE
Class_Save_cannote.AnalizTable(myDBs["[CANNote]"].ds.Tables[0], myDBs["[CANNote]"].table, myDBs["[CANNote]"].adapter);
Class_Save_blockMetro.AnalizTable(myDBs["[БлокиМетро]"].ds.Tables[0], myDBs["[БлокиМетро]"].table, myDBs["[БлокиМетро]"].adapter);
Class_Save_kan.AnalizTable(myDBs["[КАН]"].ds.Tables[0], myDBs["[КАН]"].table, myDBs["[КАН]"].adapter);
Class_Save_kanS.AnalizTable(myDBs["[КАНы]"].ds.Tables[0], myDBs["[КАНы]"].table, myDBs["[КАНы]"].adapter);
Class_Save_operMetro.AnalizTable(myDBs["[ОперацииМетро]"].ds.Tables[0], myDBs["[ОперацииМетро]"].table, myDBs["[ОперацииМетро]"].adapter);
Class_Save_prov.AnalizTable(myDBs["[Проверка]"].ds.Tables[0], myDBs["[Проверка]"].table, myDBs["[Проверка]"].adapter);
Class_Save_provFey.AnalizTable(myDBs["[Проверка ФЭУ]"].ds.Tables[0], myDBs["[Проверка ФЭУ]"].table, myDBs["[Проверка ФЭУ]"].adapter);
Class_Save_provTCPM.AnalizTable(myDBs["[ПроверкаТСРМ61]"].ds.Tables[0], myDBs["[ПроверкаТСРМ61]"].table, myDBs["[ПроверкаТСРМ61]"].adapter);
Class_Save_rabotBD.AnalizTable(myDBs["[Работы по БД]"].ds.Tables[0], myDBs["[Работы по БД]"].table, myDBs["[Работы по БД]"].adapter);
Class_Save_systemVsbore.AnalizTable(myDBs["[Системы в сборе]"].ds.Tables[0], myDBs["[Системы в сборе]"].table, myDBs["[Системы в сборе]"].adapter);
Class_Save_termocalibr.AnalizTable(myDBs["[Термокалибровка]"].ds.Tables[0], myDBs["[Термокалибровка]"].table, myDBs["[Термокалибровка]"].adapter);
Class_Save_zamechPoBD.AnalizTable(myDBs["[Замечания по БД]"].ds.Tables[0], myDBs["[Замечания по БД]"].table, myDBs["[Замечания по БД]"].adapter);
#endregion
}
public static bool zam = false;
private void заменитьНомерБДToolStripMenuItem_Click(object sender, EventArgs e)
{
zam = true;
CreateForm_zamena();
}
}
//замену изменить+
/// калибровку закончила
//сделать проверку на наличие при добавление новых блоков->сделала
// создать блоки и проверить класс замечания по бд->+
}
|
using DevExpress.Mvvm;
using DevExpress.Xpf.Bars;
using DevExpress.Xpf.Grid;
using System;
using System.Runtime.Serialization;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.Diagnostics;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using WpfGridControlTest01.Classes;
using WpfGridControlTest01.Models;
using WpfGridControlTest01.ViewModels;
using System.Runtime.Serialization.Json;
using System.Windows.Controls.Primitives;
using System.Windows.Interop;
namespace WpfGridControlTest01.Views
{
/// <summary>
/// Interaction logic for View1.xaml
/// </summary>
public partial class MainView : UserControl
{
ObservableCollection<Product> Products;
List<Product> originProducts;
List<Product> addProducts;
List<Product> modifyProducts;
List<Product> deleteProducts;
Product deleteProduct;
ObservableCollection<Product1> Products1;
List<Product1> originProducts1;
List<Product1> addProducts1;
List<Product1> modifyProducts1;
List<Product1> deleteProducts1;
Product1 deleteProduct1;
ObservableCollection<Product2> Products2 { get; set; }
List<Product2> originProducts2;
List<Product2> addProducts2;
List<Product2> modifyProducts2;
List<Product2> deleteProducts2;
Product2 deleteProduct2;
DoJobs dojobs;
ProgressingJob progressingJob = ProgressingJob.IDLE;
public MainView()
{
InitializeComponent();
this.Loaded += MainView_Loaded;
this.Unloaded += MainView_Unloaded;
this.PreviewMouseLeftButtonDown += MainView_PreviewMouseLeftButtonDown;
}
Point pointFromMain;
private void MainView_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
//Point position = e.MouseDevice.GetPosition((MainView)sender);
//point = PointToScreen(position);
pointFromMain = e.MouseDevice.GetPosition((MainView)sender);
}
private void MainView_Unloaded(object sender, RoutedEventArgs e)
{
if (popup != null)
{
popup.Close();
}
}
MainViewModel viewmodel;
private void MainView_Loaded(object sender, RoutedEventArgs e)
{
viewmodel = (MainViewModel)this.DataContext;
Products = viewmodel.Products;
Products1 = viewmodel.Products1;
Products2 = viewmodel.Products2;
Product2 tmp = new Product2() {
Chk1 = true,
BandWide = "200",
Chk2 = false,
Freq = "200000"
};
tmp.ToString();
// Products.CollectionChanged += Products_CollectionChanged;
Product3 tmpProduct3 = new Product3() { IsMine = true, Chk1 = true, BandWide = "100", Chk2 = true, Freq = "200" };
var tmpStruct = tmpProduct3.InputStruct<StTest01>();
//StTest01 st = new StTest01();
//var tmpType = st.GetType();
//var tmpProperty = st.GetType().GetMembers();
//foreach (var p in st.GetType().GetProperties())
//{
// // System.Diagnostics.Debug.WriteLine(p.Name + " : ");
//}
}
private void Products_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
{
Debug.WriteLine("Products_CollectionChanged Action: " + e.Action);
if (e.Action == NotifyCollectionChangedAction.Add)
{
if (addProducts == null)
addProducts = new List<Product>();
try
{
addProducts.Add(e.NewItems.Cast<Product>().ToList().First());
}
catch (InvalidOperationException ex)
{
System.Diagnostics.Debug.WriteLine(ex.Message);
}
}
}
private int number = 4;
private void Button_Click(object sender, RoutedEventArgs e)
{
//Products.Add(new Product()
//{;
// BandWide = String.Format("{0}00", number),
// Freq = String.Format("{0}000", number),
// Chk1 = false,
// Chk2 = false
//});
//number++;
testProducts222.Add((Product2)viewmodel.testProduct2.Clone());
viewmodel.testProduct2.BandWide = "9999";
Product2 tmp2 = (Product2)testProducts222.Where(x => x.BandWide == "345").First();
Product2 tmp21 = (Product2)tmp2.Clone();
testProducts23.Add((Product2)tmp2.Clone());
int idx = testProducts23.IndexOf(tmp2);
int idx1 = testProducts222.IndexOf(tmp2);
bool b0 = tmp2.HasSameValues(tmp21);
bool b1 = tmp2.Equals(tmp21);
bool b3 = tmp2 == tmp21;
//tmp2.BandWide = "33333";
viewmodel.testProduct2.SetValues("BandWide", "10000000");
testProducts222.Where(x => x.Freq == "1000").ToList().Clone();
}
List<Product2> testProducts222 = new List<Product2>();
List<Product2> testProducts23 = new List<Product2>();
private void Button_Click_1(object sender, RoutedEventArgs e)
{
//deleteProducts = gridctrl0.SelectedItems.Cast<Product>().ToList();
//deleteProduct = deleteProducts.First();
//byte[] packet = Serialize(deleteProduct);
//dojobs = new DoJobs(packet);
//dojobs.OnJobFinished += Dojobs_OnJobFinished;
//dojobs.Send();
}
private void Dojobs_OnJobFinished(object sender, EventArgs e)
{
//deleteProducts.Remove(deleteProduct);
//Products.Remove(deleteProduct);
//try
//{
// deleteProduct = deleteProducts.First();
//}
//catch (InvalidOperationException ex)
//{
// System.Diagnostics.Debug.WriteLine(ex.Message);
// return;
//}
//dojobs.Send(Serialize(deleteProduct));
}
private void Button_Click_2(object sender, RoutedEventArgs e)
{
Debug.WriteLine("Reload button pressed.", "Debug");
Products = new ObservableCollection<Product>(originProducts);
}
private void Button_Click_3(object sender, RoutedEventArgs e)
{
Debug.WriteLine("Apply button pressed.", "Debug");
int[] tmp = gridctrl0.GetSelectedRowHandles();
//modifyProducts2 = Products2.Where(x => originProducts2.Any(y => y.HasSameValues(x)) == false).ToList();
//this.ChangeUIStatus(ProgressingJob.IDLE);
}
private void btnModify_Click(object sender, RoutedEventArgs e)
{
if (progressingJob == ProgressingJob.IDLE)
{
originProducts = Products.Clone().ToList();
originProducts1 = Products1.Clone().ToList();
originProducts2 = Products2.Clone().ToList();
//this.ChangeUIStatus(ProgressingJob.MODIFY);
}
else if (progressingJob == ProgressingJob.MODIFY)
{
//Products.Clear();
//foreach (Product product in originProducts)
//{
// Products.Add(product);
//}
Products = new ObservableCollection<Product>(originProducts.Clone().ToList());
Products1 = new ObservableCollection<Product1>(originProducts1.Clone().ToList());
// Products2 = new ObservableCollection<Product2>(originProducts2.Clone().ToList());
Products2.Clear();
foreach (Product2 product in originProducts2)
{
Products2.Add(product);
}
//this.ChangeUIStatus(ProgressingJob.IDLE);
}
}
private void ChangeUIStatus(ProgressingJob status)
{
this.progressingJob = status;
switch (status)
{
case ProgressingJob.RELOAD:
break;
case ProgressingJob.IDLE:
tableview0.AllowEditing = false;
viewmodel.EnableBtnAdd = true;
viewmodel.EnableBtnModify = true;
viewmodel.EnableBtnDel = true;
viewmodel.EnableBtnApply = true;
viewmodel.BtnReload = "화면갱신";
viewmodel.BtnAdd = "추가";
viewmodel.BtnModify = "수정";
viewmodel.BtnDel = "삭제";
viewmodel.BtnApply = "적용";
break;
case ProgressingJob.ADD:
break;
case ProgressingJob.MODIFY:
// gridctrl0.SelectionMode = DevExpress.Xpf.Grid.MultiSelectMode.None;
tableview0.AllowEditing = true;
viewmodel.EnableBtnAdd = false;
viewmodel.EnableBtnDel = false;
viewmodel.EnableBtnApply = true;
viewmodel.BtnModify = "수정취소";
break;
case ProgressingJob.DELETE:
break;
}
}
private void tableview0_CellValueChanged(object sender, DevExpress.Xpf.Grid.CellValueChangedEventArgs e)
{
var column = e.Column;
var fieldName = column.FieldName;
var newCellValue = e.Value;
var oldCellValue = e.OldValue;
var row = (Product2)e.Row;
int rowHandle = e.RowHandle;
bool handled = e.Handled;
var cell = e.Cell;
}
private void tableview0_ShowGridMenu(object sender, DevExpress.Xpf.Grid.GridMenuEventArgs e)
{
// 특정 컬럼 컨텍스트 메뉴 팝업
if (e.MenuInfo.Column.VisibleIndex == 4)
{
e.MenuInfo.Column.AllowEditing = DevExpress.Utils.DefaultBoolean.False;
BarButtonItem item0 = new BarButtonItem { Content="일괄 선택" };
item0.ItemClick += (s, ex) => { MessageBox.Show("clicked!!"); };
BarItemLinkActionBase.SetItemLinkIndex(item0, 0);
e.Customizations.Add(item0);
BarItemLinkSeparator item2 = new BarItemLinkSeparator();
BarItemLinkActionBase.SetItemLinkIndex(item2, 1);
e.Customizations.Add(item2);
BarCheckItem item1 = new BarCheckItem { Content = "Checked", IsChecked = true };
BarItemLinkActionBase.SetItemLinkIndex(item1, 2);
e.Customizations.Add(item1);
}
}
private void gridctrl0_SelectionChanged(object sender, GridSelectionChangedEventArgs e)
{
// 본인 데이터가 아니면 선택 못하도록 하려고 했으나 이 이벤트는 활용하기 힘듬
//var tmp0 = e.ControllerRow;
//var tmp1 = e.Action;
//var tmp2 = e.Source.SelectedRows;
}
Point point;
private void tableview0_PreviewMouseLeftButtonDown(object sender, System.Windows.Input.MouseButtonEventArgs e)
{
// MainWindow mainWin = Application.Current.MainWindow as MainWindow;
var info = tableview0.CalcHitInfo((DependencyObject)e.OriginalSource);
Point position = e.MouseDevice.GetPosition(this);
point = PointToScreen(position);
if (info.RowHandle < 0)
{
gridctrl0.SelectedItems.Clear();
}
int[] selectedRowHandles = gridctrl0.GetSelectedRowHandles();
for (int i = 0; i < selectedRowHandles.Length; i++)
{
var row = (Product2)gridctrl0.GetRow(selectedRowHandles[i]);
if (row.IsMine)
{
base.OnPreviewMouseLeftButtonDown(e);
}
else
{
gridctrl0.SelectedItems.Remove(row);
}
}
//if (info.Column != null && Equals(info.Column.FieldName, "ButtonColumn"))
// return;
//else base.OnPreviewMouseLeftButtonDown(e);
}
private void tableview0_ShowingEditor(object sender, ShowingEditorEventArgs e)
{
// 에디터모드 진입 여부 처리
//var RowHandle = e.RowHandle;
//var row0 = gridctrl0.GetRow(RowHandle);
//var row1 = (Product2)e.Row;
//var row = (Product2)e.Row;
//if (row.IsMine)
//{
// System.Diagnostics.Debug.WriteLine("ShowingEditorEvent Raised : It's Mine.");
// // e.Column.AllowEditing = DevExpress.Utils.DefaultBoolean.True;
// e.Cancel = false;
//}
//else
//{
// System.Diagnostics.Debug.WriteLine("ShowingEditorEvent Raised : It's not Mine.");
// // e.Column.AllowEditing = DevExpress.Utils.DefaultBoolean.False;
// e.Cancel = true;
//}
if (e.Column.FieldName == "Freq")
{
e.Cancel = !(bool)gridctrl0.GetCellValue(e.RowHandle, "IsMine");
}
}
PopUp popup;
private void tableview0_RowDoubleClick(object sender, RowDoubleClickEventArgs e)
{
var hitInfo = e.HitInfo;
string headerCaption = hitInfo.Column.HeaderCaption.ToString();
int rowHandle = hitInfo.RowHandle;
if (headerCaption == "Freq")
{
Product2 row = (Product2)gridctrl0.GetRow(rowHandle);
popup = new PopUp();
popup.txtBox.Text = row.Freq;
// popup.WindowStartupLocation = WindowStartupLocation.CenterScreen;
popup.parent = this;
popup.Top = point.Y - popup.Height - 10;
popup.Left = point.X - popup.Width/2;
popup.Show();
}
}
private void tableview0_KeyDown(object sender, KeyEventArgs e)
{
if (e.Key == Key.C && Keyboard.Modifiers == ModifierKeys.Control)
{
int[] rowHandles = gridctrl0.GetSelectedRowHandles();
List<Product2> selectedItems = gridctrl0.SelectedItems.OfType<Product2>().ToList();
List<Product4Clipboard> products = new List<Product4Clipboard>();
foreach (var item in selectedItems)
{
products.Add(new Product4Clipboard() {Txt = "안녕하세요.", BandWide = item.BandWide, Freq = item.Freq });
}
// string jsonStr = JSONSerializer<List<Product4Clipboard>>.Serialize(products);
// Clipboard.SetText(jsonStr);
Clipboard.SetData("custom_format", products);
e.Handled = true;
}
if (e.Key == Key.D && Keyboard.Modifiers == ModifierKeys.Control)
{
int[] rowHandles = gridctrl0.GetSelectedRowHandles();
List<Product2> selectedItems = gridctrl0.SelectedItems.OfType<Product2>().ToList();
List<Product4Clipboard> products = new List<Product4Clipboard>();
foreach (var item in selectedItems)
{
products.Add(new Product4Clipboard() { Txt = "하아하이!!", BandWide = item.BandWide, Freq = item.Freq });
}
// string jsonStr = JSONSerializer<List<Product4Clipboard>>.Serialize(products);
// Clipboard.SetText(jsonStr);
Clipboard.SetData("custom_format2", products);
e.Handled = true;
}
else if (e.Key == Key.V && Keyboard.Modifiers == ModifierKeys.Control)
{
string jsonStr = string.Empty;
// jsonStr = Clipboard.GetText(TextDataFormat.UnicodeText);
bool ret = Clipboard.ContainsData("custom_format");
var data = Clipboard.GetData("custom_format");
e.Handled = true;
}
else if (e.Key == Key.B && Keyboard.Modifiers == ModifierKeys.Control)
{
string jsonStr = string.Empty;
// jsonStr = Clipboard.GetText(TextDataFormat.UnicodeText);
bool ret = Clipboard.ContainsData("custom_format");
var data = Clipboard.GetData("custom_format2");
e.Handled = true;
}
}
private void tableview0_PreviewKeyDown(object sender, KeyEventArgs e)
{
if (e.Key == Key.C && Keyboard.Modifiers == ModifierKeys.Control)
{
int[] rowHandles = gridctrl0.GetSelectedRowHandles();
List<Product2> selectedItems = gridctrl0.SelectedItems.OfType<Product2>().ToList();
List<Product4Clipboard> products = new List<Product4Clipboard>();
foreach (var item in selectedItems)
{
products.Add(new Product4Clipboard() { Txt = "안녕하세요.", BandWide = item.BandWide, Freq = item.Freq });
}
DataObject data = new DataObject();
data.SetData("custom_format", products);
string jsonStr = JSONSerializer<List<Product4Clipboard>>.Serialize(products);
Clipboard.SetText(jsonStr);
Debug.WriteLine(jsonStr);
// string jsonTxt = Clipboard.GetText();
e.Handled = true;
}
else if (e.Key == Key.V && Keyboard.Modifiers == ModifierKeys.Control)
{
string jsonTxt = Clipboard.GetText();
Debug.WriteLine(jsonTxt);
e.Handled = true;
}
}
private void Button_Click_4(object sender, RoutedEventArgs e)
{
//string txtbox = txtBox.Text;
//DXWindow1 win = new DXWindow1();
//win.Show();
if (Popup1.IsOpen)
{
Popup1.IsOpen = false;
}
else
{
//Popup1.CustomPopupPlacementCallback = new CustomPopupPlacementCallback(placePopup);
Popup1.IsOpen = true;
}
}
public CustomPopupPlacement[] placePopup(Size popupSize, Size targetSize, Point offset)
{
//Point _point = PointToScreen(pointFromMain);
//pointFromMain;
double popupTop = pointFromMain.Y - Popup1.Height;
double popupLeft = pointFromMain.X - Popup1.Width;
double popupRight = pointFromMain.X + Popup1.Width;
//if (popupTop < 0)
//{
// pointFromMain.Y = 0;
//}
//if (popupLeft < 0)
//{
// pointFromMain.X = 0;
//}
Point point2Screen = this.PointToScreen(pointFromMain);
Point screen2Point = this.PointFromScreen(pointFromMain);
//double screenWidth = SystemParameters.WorkArea.Width;
//double screenHeight = SystemParameters.WorkArea.Height;
var interopHelper = new WindowInteropHelper(System.Windows.Application.Current.MainWindow);
var activeScreen = System.Windows.Forms.Screen.FromHandle(interopHelper.Handle);
//if (popupRight > )
//{
//}
CustomPopupPlacement placement1 = new CustomPopupPlacement(pointFromMain, PopupPrimaryAxis.Vertical);
CustomPopupPlacement placement2 = new CustomPopupPlacement(pointFromMain, PopupPrimaryAxis.Horizontal);
CustomPopupPlacement[] ttplaces = new CustomPopupPlacement[] { placement1, placement2 };
return ttplaces;
}
private void gridctrl0_PreviewKeyDown(object sender, KeyEventArgs e)
{
if (e.Key == Key.C && Keyboard.Modifiers == ModifierKeys.Control)
{
int[] rowHandles = gridctrl0.GetSelectedRowHandles();
List<Product2> selectedItems = gridctrl0.SelectedItems.OfType<Product2>().ToList();
List<Product4Clipboard> products = new List<Product4Clipboard>();
foreach (var item in selectedItems)
{
products.Add(new Product4Clipboard() { Txt = "안녕하세요.", BandWide = item.BandWide, Freq = item.Freq });
}
// string jsonStr = JSONSerializer<List<Product4Clipboard>>.Serialize(products);
// Clipboard.SetText(jsonStr);
Clipboard.SetData("custom_format", products);
e.Handled = true;
}
else if (e.Key == Key.V && Keyboard.Modifiers == ModifierKeys.Control)
{
string jsonStr = string.Empty;
// jsonStr = Clipboard.GetText(TextDataFormat.UnicodeText);
bool ret = Clipboard.ContainsData("custom_format");
var data = Clipboard.GetData("custom_format");
e.Handled = true;
}
else { }
}
private void tableview0_EditFormShowing(object sender, EditFormShowingEventArgs e)
{
int rowHandle = e.RowHandle;
var row = gridctrl0.GetRow(rowHandle);
}
}
}
|
using System;
using System.Collections.Generic;
namespace DemoEF.Domain.Models
{
public partial class TbFinanceAccount
{
public long Id { get; set; }
public long? DecoratorUser { get; set; }
public string DecoratorUsername { get; set; }
public string Remarks { get; set; }
public string AccountStatus { get; set; }
public DateTime? AddTime { get; set; }
public DateTime? UpdateTime { get; set; }
public string AccountPwd { get; set; }
}
}
|
/*If statements are conditional and executes a block of code
when the condition is true.*/
if (condition);
{
//execute this code when condition is true
};
static void Main (string []args)
{
int x = 8;
int y = 3;
if (x>y)
{
ConsoleWRiteLine("x is greater than y");
}
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
/*Relational Operators are used to evaluate |
using System.ComponentModel.DataAnnotations;
namespace userService.Model
{
public class Sessionw
{
[Key]
public int id_session {get; set;}
public string token_session {get; set;}
}
}
|
/**
* Copyright (c) 2010-2011, Richard Z.H. Wang <http://zhwang.me/>
* Copyright (c) 2010-2011, David Warner <http://quppa.net/>
*
* This library is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this license. If not, see <http://www.gnu.org/licenses/>.
*/
using System;
using System.Collections.Generic;
using System.Drawing;
namespace GestureReminder
{
public class NotifyArea
{
public static Rectangle GetRectangle()
{
IntPtr hTaskbarHandle = NativeMethods.FindWindow("Shell_TrayWnd", null);
if (hTaskbarHandle != IntPtr.Zero)
{
IntPtr hSystemTray = NativeMethods.FindWindowEx(hTaskbarHandle, IntPtr.Zero, "TrayNotifyWnd", null);
if (hSystemTray != IntPtr.Zero)
{
NativeMethods.RECT rect;
NativeMethods.GetWindowRect(hSystemTray, out rect);
if (rect.HasSize())
return rect;
}
}
return Rectangle.Empty;
}
/// <summary>
/// Retrieves the rectangle of the 'Show Hidden Icons' button, or null if it can't be found.
/// </summary>
/// <returns>Rectangle containing bounds of 'Show Hidden Icons' button, or null if it can't be found.</returns>
public static Rectangle GetButtonRectangle()
{
// find the handle of the taskbar
IntPtr taskbarparenthandle = NativeMethods.FindWindow("Shell_TrayWnd", null);
if (taskbarparenthandle == (IntPtr)null)
return Rectangle.Empty;
// find the handle of the notification area
IntPtr naparenthandle = NativeMethods.FindWindowEx(taskbarparenthandle, IntPtr.Zero, "TrayNotifyWnd", null);
if (naparenthandle == (IntPtr)null)
return Rectangle.Empty;
List<IntPtr> nabuttonwindows = NativeMethods.GetChildButtonWindows(naparenthandle);
if (nabuttonwindows.Count == 0)
return Rectangle.Empty; // found no buttons
IntPtr buttonpointer = nabuttonwindows[0]; // just take the first button
NativeMethods.RECT result;
if (!NativeMethods.GetWindowRect(buttonpointer, out result))
return Rectangle.Empty; // return null if we can't find the button
return result;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Collections;
using System.Reflection;
using IRAP.Global;
using IRAPORM;
using IRAPShared;
using IRAP.Server.Global;
using IRAP.Entity.MDM;
using IRAP.Entity.MDM.Tables;
using IRAP.Entity.IRAP;
using IRAP.Entities.MDM;
namespace IRAP.BL.MDM
{
public class IRAPMDM : IRAPBLLBase
{
private static string className =
MethodBase.GetCurrentMethod().DeclaringType.FullName;
public IRAPMDM()
{
WriteLog.Instance.WriteLogFileName =
MethodBase.GetCurrentMethod().DeclaringType.Namespace;
}
/// <summary>
/// 根据父节点获取系统的机构叶节点列表
/// </summary>
/// <param name="parentID">父节点标识</param>
public IRAPJsonResult mfn_GetList_Agencies(
int parentID,
out int errCode,
out string errText)
{
string strProcedureName =
string.Format(
"{0}.{1}",
className,
MethodBase.GetCurrentMethod().Name);
WriteLog.Instance.WriteBeginSplitter(strProcedureName);
try
{
List<Stb053> datas = new List<Stb053>();
#region 创建数据库调用参数组,并赋值
IList<IDataParameter> paramList = new List<IDataParameter>();
paramList.Add(new IRAPProcParameter("@ParentID", DbType.Int32, parentID));
WriteLog.Instance.Write(
string.Format(
"从 IRAP..stb053 表中获取 TreeID=1,Father={0} 的记录",
parentID),
strProcedureName);
#endregion
#region 执行数据库函数或存储过程
try
{
using (IRAPSQLConnection conn = new IRAPSQLConnection())
{
string strSQL = "SELECT * " +
"FROM IRAP..stb053 WHERE TreeID=1 AND Father=@ParetnID";
IList<Stb053> lstDatas = conn.CallTableFunc<Stb053>(strSQL, paramList);
datas = lstDatas.ToList<Stb053>();
errCode = 0;
errText = string.Format("调用成功!共获得 {0} 条记录", datas.Count);
WriteLog.Instance.Write(errText, strProcedureName);
}
}
catch (Exception error)
{
errCode = 99000;
errText = string.Format("从 IRAP..stb053 获取记录发生异常:{0}", error.Message);
WriteLog.Instance.Write(errText, strProcedureName);
WriteLog.Instance.Write(error.StackTrace, strProcedureName);
}
#endregion
return Json(datas);
}
finally
{
WriteLog.Instance.WriteEndSplitter(strProcedureName);
}
}
/// <summary>
/// 获取系统的机构组列表
/// </summary>
public IRAPJsonResult mfn_GetList_AgencyGroups(out int errCode, out string errText)
{
string strProcedureName =
string.Format(
"{0}.{1}",
className,
MethodBase.GetCurrentMethod().Name);
WriteLog.Instance.WriteBeginSplitter(strProcedureName);
try
{
List<Stb052> datas = new List<Stb052>();
#region 创建数据库调用参数组,并赋值
IList<IDataParameter> paramList = new List<IDataParameter>();
WriteLog.Instance.Write(
"从 IRAP..stb053 表中获取 TreeID=1 的记录",
strProcedureName);
#endregion
#region 执行数据库函数或存储过程
try
{
using (IRAPSQLConnection conn = new IRAPSQLConnection())
{
string strSQL = "SELECT * " +
"FROM IRAP..stb052 WHERE TreeID=1" +
"ORDER BY Father, NodeDepth, UDFOrdinal";
IList<Stb052> lstDatas = conn.CallTableFunc<Stb052>(strSQL, paramList);
datas = lstDatas.ToList<Stb052>();
errCode = 0;
errText = string.Format("调用成功!共获得 {0} 条记录", datas.Count);
WriteLog.Instance.Write(errText, strProcedureName);
}
}
catch (Exception error)
{
errCode = 99000;
errText = string.Format("从 IRAP..stb052 获取记录发生异常:{0}", error.Message);
WriteLog.Instance.Write(errText, strProcedureName);
WriteLog.Instance.Write(error.StackTrace, strProcedureName);
}
#endregion
return Json(datas);
}
finally
{
WriteLog.Instance.WriteEndSplitter(strProcedureName);
}
}
/// <summary>
/// 获取一般树视图
/// </summary>
/// <param name="communityID">社区标识</param>
/// <param name="treeID">树标识</param>
/// <param name="includeLeaves">包含树叶子</param>
/// <param name="entryNode">入口节点</param>
/// <param name="sysLogID">系统登录标识</param>
public IRAPJsonResult sfn_TreeView(
int communityID,
int treeID,
bool includeLeaves,
int entryNode,
long sysLogID,
out int errCode,
out string errText)
{
string strProcedureName =
string.Format(
"{0}.{1}",
className,
MethodBase.GetCurrentMethod().Name);
WriteLog.Instance.WriteBeginSplitter(strProcedureName);
try
{
List<TreeViewNode> datas = new List<TreeViewNode>();
#region 创建数据库调用参数组,并赋值
IList<IDataParameter> paramList = new List<IDataParameter>();
paramList.Add(new IRAPProcParameter("@CommunityID", DbType.Int32, communityID));
paramList.Add(new IRAPProcParameter("@TreeID", DbType.Int32, treeID));
paramList.Add(new IRAPProcParameter("@IncludeLeaves", DbType.Boolean, includeLeaves));
paramList.Add(new IRAPProcParameter("@EntryNode", DbType.Int32, entryNode));
paramList.Add(new IRAPProcParameter("@SysLogID", DbType.Int64, sysLogID));
WriteLog.Instance.Write(
string.Format(
"调用函数 IRAP..sfn_TreeView," +
"参数:CommunityID={0}|TreeID={1}|SysLogID={2}|" +
"IncludeLeaves={3}|EntryNode={4}",
communityID, treeID, sysLogID, includeLeaves, entryNode),
strProcedureName);
#endregion
#region 执行数据库函数或存储过程
try
{
using (IRAPSQLConnection conn = new IRAPSQLConnection())
{
string strSQL = "SELECT * " +
"FROM IRAP..sfn_TreeView(" +
"@CommunityID, @TreeID, @SysLogID, @IncludeLeaves, @EntryNode) " +
"ORDER BY NodeDepth, Parent, UDFOrdinal, NodeID";
IList<TreeViewNode> lstDatas = conn.CallTableFunc<TreeViewNode>(strSQL, paramList);
datas = lstDatas.ToList<TreeViewNode>();
errCode = 0;
errText = string.Format("调用成功!共获得 {0} 条记录", datas.Count);
WriteLog.Instance.Write(errText, strProcedureName);
}
}
catch (Exception error)
{
errCode = 99000;
errText = string.Format("调用 IRAP..sfn_TreeView 函数发生异常:{0}", error.Message);
WriteLog.Instance.Write(errText, strProcedureName);
WriteLog.Instance.Write(error.StackTrace, strProcedureName);
}
#endregion
return Json(datas);
}
finally
{
WriteLog.Instance.WriteEndSplitter(strProcedureName);
}
}
/// <summary>
/// 树视图新增一个结点
/// </summary>
/// <param name="communityID">社区标识</param>
/// <param name="irapTreeID">IRAP 树视图标识</param>
/// <param name="treeViewType">
/// IRAP 树视图类型:
/// 1-森林视图;
/// 2-普通树视图;
/// 3~16略。
/// </param>
/// <param name="nodeID">结点标识</param>
/// <param name="nodeType">
/// 结点类型:
/// 1-森林;
/// 2-树;
/// 3-普通结点;
/// 4-叶子;
/// 5-属性。
/// </param>
/// <param name="nodePK">结点分区键</param>
/// <param name="newNodeType">新增结点类型</param>
/// <param name="newNodePK">新增结点分区键</param>
/// <param name="createMode">
/// 创建方式:
/// 1-新增作为本结点末子结点;
/// 2-插入作为本结点末兄结点;
/// </param>
/// <param name="nodeCode">结点代码</param>
/// <param name="alternateCode">替代结点代码</param>
/// <param name="nodeName">结点名称</param>
/// <param name="udfOrdinal">兄弟遍历序</param>
/// <param name="iconID">个性图标标识</param>
/// <param name="ctrlValue">属性控制值</param>
/// <param name="treeViewCacheID">树视图缓冲区标识</param>
/// <param name="xmlString">个性处理XML串</param>
/// <param name="sysLogID">系统登录标识</param>
/// <returns>
/// Hashtable
/// NewNodeID int 新结点标识
/// Accessibility int 新结点可访问性(0-不可选择;1-可单选;2-可复选)
/// SelectStatus int 新结点选中状态(0-未选中;1-已选中)
/// SearchCode1 string 新结点第一检索码
/// SearchCode2 string 新结点第二检索码
/// </returns>
public IRAPJsonResult ssp_NewIRAPTreeNode(
int communityID,
int irapTreeID,
int treeViewType,
int nodeID,
int nodeType,
long nodePK,
int newNodeType,
long newNodePK,
int createMode,
string nodeCode,
string alternateCode,
string nodeName,
double udfOrdinal,
int iconID,
int ctrlValue,
int treeViewCacheID,
string xmlString,
long sysLogID,
out int errCode,
out string errText)
{
string strProcedureName =
string.Format(
"{0}.{1}",
className,
MethodBase.GetCurrentMethod().Name);
WriteLog.Instance.WriteBeginSplitter(strProcedureName);
try
{
#region 创建数据库调用参数组,并赋值
IList<IDataParameter> paramList = new List<IDataParameter>();
paramList.Add(new IRAPProcParameter("@CommunityID", DbType.Int32, communityID));
paramList.Add(new IRAPProcParameter("@IRAPTreeID", DbType.Int32, irapTreeID));
paramList.Add(new IRAPProcParameter("@TreeViewType", DbType.Int32, treeViewType));
paramList.Add(new IRAPProcParameter("@NodeID", DbType.Int32, nodeID));
paramList.Add(new IRAPProcParameter("@NodeType", DbType.Int32, nodeType));
paramList.Add(new IRAPProcParameter("@NodePK", DbType.Int64, nodePK));
paramList.Add(new IRAPProcParameter("@NewNodeType", DbType.Int32, newNodeType));
paramList.Add(new IRAPProcParameter("@NewNodePK", DbType.Int64, newNodePK));
paramList.Add(new IRAPProcParameter("@CreateMode", DbType.Int32, createMode));
paramList.Add(new IRAPProcParameter("@NodeCode", DbType.String, nodeCode));
paramList.Add(new IRAPProcParameter("@AlternateCode", DbType.String, alternateCode));
paramList.Add(new IRAPProcParameter("@NodeName", DbType.String, nodeName));
paramList.Add(new IRAPProcParameter("@UDFOrdinal", DbType.Double, udfOrdinal));
paramList.Add(new IRAPProcParameter("@IconID", DbType.Int32, iconID));
paramList.Add(new IRAPProcParameter("@CtrlValue", DbType.Int32, ctrlValue));
paramList.Add(new IRAPProcParameter("@TreeViewCacheID", DbType.Int32, treeViewCacheID));
paramList.Add(new IRAPProcParameter("@XMLString", DbType.String, xmlString));
paramList.Add(new IRAPProcParameter("@SysLogID", DbType.Int64, sysLogID));
paramList.Add(
new IRAPProcParameter("@NewNodeID", DbType.Int32, ParameterDirection.Output, 4));
paramList.Add(
new IRAPProcParameter("@Accessibility", DbType.Int32, ParameterDirection.Output, 4));
paramList.Add(
new IRAPProcParameter("@SelectStatus", DbType.Int32, ParameterDirection.Output, 4));
paramList.Add(
new IRAPProcParameter("@SearchCode1", DbType.String, ParameterDirection.Output, 20));
paramList.Add(
new IRAPProcParameter("@SearchCode2", DbType.String, ParameterDirection.Output, 20));
paramList.Add(
new IRAPProcParameter("@ErrCode", DbType.Int32, ParameterDirection.Output, 4));
paramList.Add(
new IRAPProcParameter("@ErrText", DbType.String, ParameterDirection.Output, 400));
WriteLog.Instance.Write(
string.Format("执行存储过程 IRAP..ssp_NewIRAPTreeNode,参数:" +
"CommunityID={0}|IRAPTreeID={1}|TreeViewType={2}|" +
"NodeID={3}|NodeType={4}|NodePK={5}|NewNodeType={6}|" +
"NewNodePK={7}|CreatMode={8}|NodeCode={9}|AlternateCode={10}|" +
"NodeName={11}|UDFOrdinal={12}|IconID={13}|CtrlValue={14}|" +
"TreeViewCacheID={15}|XMLString={16}|SysLogID={17}",
communityID, irapTreeID, treeViewType, nodeID, nodeType,
nodePK, newNodeType, newNodePK, createMode, nodeCode,
alternateCode, nodeName, udfOrdinal, iconID, ctrlValue,
treeViewCacheID, xmlString, sysLogID),
strProcedureName);
#endregion
#region 执行数据库函数或存储过程
using (IRAPSQLConnection conn = new IRAPSQLConnection())
{
IRAPError error = conn.CallProc("IRAP..ssp_NewIRAPTreeNode", ref paramList);
errCode = error.ErrCode;
errText = error.ErrText;
WriteLog.Instance.Write(
string.Format(
"({0}){1}",
errCode,
errText),
strProcedureName);
Hashtable rtnParams = new Hashtable();
if (errCode == 0)
{
foreach (IRAPProcParameter param in paramList)
{
if (param.Direction == ParameterDirection.InputOutput || param.Direction == ParameterDirection.Output)
{
if (param.DbType == DbType.Int32 && param.Value == DBNull.Value)
rtnParams.Add(param.ParameterName.Replace("@", ""), 0);
else
rtnParams.Add(param.ParameterName.Replace("@", ""), param.Value);
}
}
}
return Json(rtnParams);
}
#endregion
}
catch (Exception error)
{
errCode = 99000;
errText = string.Format("调用 IRAP..ssp_NewIRAPTreeNode 时发生异常:{0}", error.Message);
return Json(new Hashtable());
}
finally
{
WriteLog.Instance.WriteEndSplitter(strProcedureName);
}
}
/// <summary>
/// 未找到对应的数据库存储过程
/// </summary>
public IRAPJsonResult ssp_AlterNodeName()
{
throw new System.NotImplementedException();
}
/// <summary>
/// 未找到对应的数据库存储过程
/// </summary>
public IRAPJsonResult ssp_AlterCode()
{
throw new System.NotImplementedException();
}
/// <summary>
/// 数据库存储过程没有定义注释
/// </summary>
/// <param name="communityID">社区标识</param>
/// <param name="irapTreeID">IRAP 树视图标识</param>
/// <param name="treeViewType">
/// IRAP 树视图类型:
/// 1-森林视图;
/// 2-普通树视图;
/// 3~16略。
/// </param>
/// <param name="nodeID">结点标识</param>
/// <param name="nodeType">
/// 结点类型:
/// 1-森林;
/// 2-树;
/// 3-普通结点;
/// 4-叶子;
/// 5-属性。
/// </param>
/// <param name="treeViewCacheID">树视图缓冲区标识</param>
/// <param name="sysLogID">系统登录标识</param>
public IRAPJsonResult ssp_DeleIRAPTreeNode(
int communityID,
int irapTreeID,
int treeViewType,
int nodeID,
int nodeType,
int treeViewCacheID,
long sysLogID,
out int errCode,
out string errText)
{
string strProcedureName =
string.Format(
"{0}.{1}",
className,
MethodBase.GetCurrentMethod().Name);
WriteLog.Instance.WriteBeginSplitter(strProcedureName);
try
{
#region 创建数据库调用参数组,并赋值
IList<IDataParameter> paramList = new List<IDataParameter>();
paramList.Add(new IRAPProcParameter("@CommunityID", DbType.Int32, communityID));
paramList.Add(new IRAPProcParameter("@IRAPTreeID", DbType.Int32, irapTreeID));
paramList.Add(new IRAPProcParameter("@TreeViewType", DbType.Int32, treeViewType));
paramList.Add(new IRAPProcParameter("@NodeID", DbType.Int32, nodeID));
paramList.Add(new IRAPProcParameter("@NodeType", DbType.Int32, nodeType));
paramList.Add(new IRAPProcParameter("@TreeViewCacheID", DbType.Int32, treeViewCacheID));
paramList.Add(new IRAPProcParameter("@SysLogID", DbType.Int64, sysLogID));
paramList.Add(
new IRAPProcParameter("@ErrCode", DbType.Int32, ParameterDirection.Output, 4));
paramList.Add(
new IRAPProcParameter("@ErrText", DbType.String, ParameterDirection.Output, 400));
WriteLog.Instance.Write(
string.Format("执行存储过程 IRAP..ssp_DeleIRAPTreeNode,参数:" +
"CommunityID={0}|IRAPTreeID={1}|TreeViewType={2}|" +
"NodeID={3}|NodeType={4}TreeViewCacheID={5}|SysLogID={6}",
communityID, irapTreeID, treeViewType, nodeID, nodeType,
treeViewCacheID, sysLogID),
strProcedureName);
#endregion
#region 执行数据库函数或存储过程
using (IRAPSQLConnection conn = new IRAPSQLConnection())
{
IRAPError error = conn.CallProc("IRAP..ssp_DeleIRAPTreeNode", ref paramList);
errCode = error.ErrCode;
errText = error.ErrText;
WriteLog.Instance.Write(
string.Format(
"({0}){1}",
errCode,
errText),
strProcedureName);
Hashtable rtnParams = new Hashtable();
if (errCode == 0)
{
foreach (IRAPProcParameter param in paramList)
{
if (param.Direction == ParameterDirection.InputOutput || param.Direction == ParameterDirection.Output)
{
if (param.DbType == DbType.Int32 && param.Value == DBNull.Value)
rtnParams.Add(param.ParameterName.Replace("@", ""), 0);
else
rtnParams.Add(param.ParameterName.Replace("@", ""), param.Value);
}
}
}
return Json(rtnParams);
}
#endregion
}
catch (Exception error)
{
errCode = 99000;
errText = string.Format("调用 IRAP..ssp_DeleIRAPTreeNode 时发生异常:{0}", error.Message);
return Json(new Hashtable());
}
finally
{
WriteLog.Instance.WriteEndSplitter(strProcedureName);
}
}
/// <summary>
/// 未找到对应的数据库存储过程
/// </summary>
public IRAPJsonResult ssp_ClassifyAttributeFor132()
{
throw new System.NotImplementedException();
}
/// <summary>
/// 获取排产优先级分类属性下拉列表
/// </summary>
/// <returns>List[IRAP.Entity.MDM.Stb058]</returns>
public IRAPJsonResult mfn_GetList_T213ClassifyAttribute(out int errCode, out string errText)
{
string strProcedureName =
string.Format(
"{0}.{1}",
className,
MethodBase.GetCurrentMethod().Name);
WriteLog.Instance.WriteBeginSplitter(strProcedureName);
try
{
List<Stb058> datas = new List<Stb058>();
#region 创建数据库调用参数组,并赋值
IList<IDataParameter> paramList = new List<IDataParameter>();
#endregion
#region 执行数据库函数或存储过程
try
{
using (IRAPSQLConnection conn = new IRAPSQLConnection())
{
string strSQL = "SELECT * " +
"FROM IRAPMDM..stb058 " +
"WHERE TreeID=213 AND Father=33084";
WriteLog.Instance.Write(strSQL, strProcedureName);
IList<Stb058> lstDatas = conn.CallTableFunc<Stb058>(strSQL, paramList);
datas = lstDatas.ToList<Stb058>();
errCode = 0;
errText = string.Format("调用成功!共获得 {0} 条记录", datas.Count);
WriteLog.Instance.Write(errText, strProcedureName);
}
}
catch (Exception error)
{
errCode = 99000;
errText = string.Format("从 IRAPMDM..stb058 获取记录发生异常:{0}", error.Message);
WriteLog.Instance.Write(errText, strProcedureName);
WriteLog.Instance.Write(error.StackTrace, strProcedureName);
}
#endregion
return Json(datas);
}
finally
{
WriteLog.Instance.WriteEndSplitter(strProcedureName);
}
}
/// <summary>
/// 获取产品族(产品系列)的树
/// </summary>
/// <param name="sysLogID">系统登录标识</param>
/// <returns>List[ProductSeries]</returns>
public IRAPJsonResult mfn_GetTreeList_ProductSeries(long sysLogID, out int errCode, out string errText)
{
string strProcedureName =
string.Format(
"{0}.{1}",
className,
MethodBase.GetCurrentMethod().Name);
WriteLog.Instance.WriteBeginSplitter(strProcedureName);
try
{
List<ProductSeriesTreeNode> datas = new List<ProductSeriesTreeNode>();
#region 创建数据库调用参数组,并赋值
IList<IDataParameter> paramList = new List<IDataParameter>();
#endregion
#region 执行数据库函数或存储过程
try
{
using (IRAPSQLConnection conn = new IRAPSQLConnection())
{
string strSQL =
string.Format(
"SELECT T.*, " +
" T213.LeafID AS T213LeafID, " +
" T213.NodeName AS T213NodeName " +
" FROM IRAP..sfn_TreeView(132, {0}, 1, 10032) T " +
" LEFT OUTER JOIN IRAPMDM..stb063 S132 " +
" ON S132.TreeID = 132 AND " +
" S132.TransactNoLE = 9223372036854775807 AND " +
" S132.LeafID = -T.NodeID" +
" LEFT OUTER JOIN IRAPMDM..stb058 T213 " +
" ON T213.TreeID = 213 AND" +
" T213.LeafID = S132.Leaf01" +
" ORDER BY NodePath, Parent, UDFOrdinal, NodeID",
sysLogID);
WriteLog.Instance.Write(strSQL, strProcedureName);
IList<ProductSeriesTreeNode> lstDatas = conn.CallTableFunc<ProductSeriesTreeNode>(strSQL, paramList);
datas = lstDatas.ToList<ProductSeriesTreeNode>();
errCode = 0;
errText = string.Format("调用成功!共获得 {0} 条记录", datas.Count);
WriteLog.Instance.Write(errText, strProcedureName);
}
}
catch (Exception error)
{
errCode = 99000;
errText = string.Format("获取产品族(产品系列)的树记录发生异常:{0}", error.Message);
WriteLog.Instance.Write(errText, strProcedureName);
WriteLog.Instance.Write(error.StackTrace, strProcedureName);
}
#endregion
return Json(datas);
}
finally
{
WriteLog.Instance.WriteEndSplitter(strProcedureName);
}
}
/// <summary>
/// 获取产品树
/// </summary>
/// <param name="sysLogID">系统登录标识</param>
/// <returns>List[ProductTreeNode]</returns>
public IRAPJsonResult mfn_GetTreeList_Products(long sysLogID, out int errCode, out string errText)
{
string strProcedureName =
string.Format(
"{0}.{1}",
className,
MethodBase.GetCurrentMethod().Name);
WriteLog.Instance.WriteBeginSplitter(strProcedureName);
try
{
List<ProductSeriesTreeNode> datas = new List<ProductSeriesTreeNode>();
#region 创建数据库调用参数组,并赋值
IList<IDataParameter> paramList = new List<IDataParameter>();
#endregion
#region 执行数据库函数或存储过程
try
{
using (IRAPSQLConnection conn = new IRAPSQLConnection())
{
string strSQL =
string.Format(
"SELECT T.*, " +
" T213.LeafID AS T213LeafID, " +
" T213.NodeName AS T213NodeName " +
" FROM IRAP..sfn_TreeView(132, {0}, 1, 10032) T " +
" LEFT OUTER JOIN IRAPMDM..stb063 S132 " +
" ON S132.TreeID = 132 AND " +
" S132.TransactNoLE = 9223372036854775807 AND " +
" S132.LeafID = -T.NodeID" +
" LEFT OUTER JOIN IRAPMDM..stb058 T213 " +
" ON T213.TreeID = 213 AND" +
" T213.LeafID = S132.Leaf01" +
" ORDER BY NodePath, Parent, UDFOrdinal, NodeID",
sysLogID);
WriteLog.Instance.Write(strSQL, strProcedureName);
IList<ProductSeriesTreeNode> lstDatas = conn.CallTableFunc<ProductSeriesTreeNode>(strSQL, paramList);
datas = lstDatas.ToList<ProductSeriesTreeNode>();
errCode = 0;
errText = string.Format("调用成功!共获得 {0} 条记录", datas.Count);
WriteLog.Instance.Write(errText, strProcedureName);
}
}
catch (Exception error)
{
errCode = 99000;
errText = string.Format("获取产品的树记录发生异常:{0}", error.Message);
WriteLog.Instance.Write(errText, strProcedureName);
WriteLog.Instance.Write(error.StackTrace, strProcedureName);
}
#endregion
return Json(datas);
}
finally
{
WriteLog.Instance.WriteEndSplitter(strProcedureName);
}
}
/// <summary>
/// 未找到对应的数据库存储过程
/// </summary>
public IRAPJsonResult ssp_ClassifyAttributeFor102()
{
throw new System.NotImplementedException();
}
/// <summary>
/// 未找到对应的数据库存储过程
/// </summary>
public IRAPJsonResult ssp_InstantaneousAttributeFor102()
{
throw new System.NotImplementedException();
}
public IRAPJsonResult mfn_GetList_T132ClassifyAttribute(out int errCode, out string errText)
{
throw new System.NotImplementedException();
}
/// <param name="sysLogID">系统登录标识</param>
public IRAPJsonResult mfn_GetTreeList_ProductLine(long sysLogID, out int errCode, out string errText)
{
throw new System.NotImplementedException();
}
/// <param name="sysLogID">系统登录标识</param>
public IRAPJsonResult mfn_GetList_ProductLineCapacities(int t134LeafID, long sysLogID, out int errCode, out string errText)
{
throw new System.NotImplementedException();
}
/// <summary>
/// 获取 058 表中指定树标识和代码的叶子信息
/// </summary>
/// <param name="communityID">社区标识</param>
/// <param name="treeID">树标识</param>
/// <param name="code">叶子代码</param>
public IRAPJsonResult mfn_GetInfo_Entity058WithCode(
int communityID,
int treeID,
string code,
out int errCode,
out string errText)
{
string strProcedureName =
string.Format(
"{0}.{1}",
className,
MethodBase.GetCurrentMethod().Name);
WriteLog.Instance.WriteBeginSplitter(strProcedureName);
try
{
Entities.MDM.Tables.Stb058 data = new Entities.MDM.Tables.Stb058();
long partitioningKey = communityID * 10000 + treeID;
#region 创建数据库调用参数组,并赋值
IList<IDataParameter> paramList = new List<IDataParameter>();
paramList.Add(new IRAPProcParameter("@PartitioningKey", DbType.Int64, partitioningKey));
paramList.Add(new IRAPProcParameter("@TreeID", DbType.Int32, treeID));
paramList.Add(new IRAPProcParameter("@Code", DbType.String, code));
WriteLog.Instance.Write(
string.Format(
"查询 IRAPMDM..stb058," +
"过滤条件:PartitioningKey={0}|TreeID={1}|Code={2}",
partitioningKey, treeID, code),
strProcedureName);
#endregion
#region 执行数据库函数或存储过程
try
{
using (IRAPSQLConnection conn = new IRAPSQLConnection())
{
string strSQL = "SELECT * " +
"FROM IRAPMDM..stb058 WHERE " +
"PartitioningKey=@PartitioningKey AND "+
"TreeID=@TreeID AND Code=@Code";
IList<Entities.MDM.Tables.Stb058> lstDatas =
conn.CallTableFunc<Entities.MDM.Tables.Stb058>(strSQL, paramList);
if (lstDatas.Count > 0)
{
data = lstDatas[0].Clone();
errCode = 0;
errText = "查询成功!";
}
else
{
errCode = -99001;
errText = "没有找到";
}
WriteLog.Instance.Write(errText, strProcedureName);
}
}
catch (Exception error)
{
errCode = 99000;
errText =
string.Format(
"查询 IRAPMDM..stb058 表发生异常:{0}",
error.Message);
WriteLog.Instance.Write(errText, strProcedureName);
WriteLog.Instance.Write(error.StackTrace, strProcedureName);
}
#endregion
return Json(data);
}
finally
{
WriteLog.Instance.WriteEndSplitter(strProcedureName);
}
}
/// <summary>
/// 获取指定产品的工段清单
/// </summary>
/// <param name="productCode">产品编号</param>
/// <param name="sysLogID">系统登录标识</param>
/// <returns>List[ProcessSegment]</returns>
public IRAPJsonResult ufn_GetList_ProcessSegmentsOfAProduct(
string productCode,
long sysLogID,
out int errCode,
out string errText)
{
string strProcedureName =
string.Format(
"{0}.{1}",
className,
MethodBase.GetCurrentMethod().Name);
WriteLog.Instance.WriteBeginSplitter(strProcedureName);
try
{
List<ProcessSegment> datas =
new List<ProcessSegment>();
#region 创建数据库调用参数组,并赋值
IList<IDataParameter> paramList = new List<IDataParameter>();
paramList.Add(new IRAPProcParameter("@ProductCode", DbType.String, productCode));
paramList.Add(new IRAPProcParameter("@SysLogID", DbType.Int64, sysLogID));
WriteLog.Instance.Write(
string.Format(
"调用函数 IRAPMDM..ufn_GetList_ProcessSegmentsOfAProduct," +
"参数:ProductCode={0}|SysLogID={1}",
productCode, sysLogID),
strProcedureName);
#endregion
#region 执行数据库函数或存储过程
try
{
using (IRAPSQLConnection conn = new IRAPSQLConnection())
{
string strSQL = "SELECT * " +
"FROM IRAPMDM..ufn_GetList_ProcessSegmentsOfAProduct(" +
"@ProductCode, @SysLogID) " +
"ORDER BY Ordinal";
IList<ProcessSegment> lstDatas =
conn.CallTableFunc<ProcessSegment>(strSQL, paramList);
datas = lstDatas.ToList<ProcessSegment>();
errCode = 0;
errText = string.Format("调用成功!共获得 {0} 条记录", datas.Count);
WriteLog.Instance.Write(errText, strProcedureName);
}
}
catch (Exception error)
{
errCode = 99000;
errText =
string.Format(
"调用 IRAPMDM..ufn_GetList_ProcessSegmentsOfAProduct 函数发生异常:{0}",
error.Message);
WriteLog.Instance.Write(errText, strProcedureName);
WriteLog.Instance.Write(error.StackTrace, strProcedureName);
}
#endregion
return Json(datas);
}
finally
{
WriteLog.Instance.WriteEndSplitter(strProcedureName);
}
}
/// <summary>
/// 获取指定树标识的列表
/// </summary>
public IRAPJsonResult mfn_GetList_EntititesIn058(int treeID, out int errCode, out string errText)
{
throw new System.NotImplementedException();
}
public IRAPJsonResult mfn_GetList_ProductOptions(out int errCode, out string errText)
{
throw new System.NotImplementedException();
}
/// <summary>
/// 获取指定产品编号的产品信息
/// </summary>
/// <param name="productCode">产品编号</param>
/// <param name="sysLogID">系统登录标识</param>
/// <returns>List[IRAP.Entity.IRP.Product]</returns>
public IRAPJsonResult ufn_GetProductName(
string productCode,
long sysLogID,
out int errCode,
out string errText)
{
string strProcedureName =
string.Format(
"{0}.{1}",
className,
MethodBase.GetCurrentMethod().Name);
WriteLog.Instance.WriteBeginSplitter(strProcedureName);
try
{
List<Product> datas =
new List<Product>();
#region 创建数据库调用参数组,并赋值
IList<IDataParameter> paramList = new List<IDataParameter>();
paramList.Add(new IRAPProcParameter("@ProductCode", DbType.String, productCode));
paramList.Add(new IRAPProcParameter("@SysLogID", DbType.Int64, sysLogID));
WriteLog.Instance.Write(
string.Format(
"调用函数 IRAP..ufn_GetProductName," +
"参数:ProductCode={0}|SysLogID={1}",
productCode, sysLogID),
strProcedureName);
#endregion
#region 执行数据库函数或存储过程
try
{
using (IRAPSQLConnection conn = new IRAPSQLConnection())
{
string strSQL = "SELECT * " +
"FROM IRAP..ufn_GetProductName(@ProductCode, @SysLogID) " +
"ORDER BY Ordinal";
IList<Product> lstDatas =
conn.CallTableFunc<Product>(strSQL, paramList);
datas = lstDatas.ToList<Product>();
errCode = 0;
errText = string.Format("调用成功!共获得 {0} 条记录", datas.Count);
WriteLog.Instance.Write(errText, strProcedureName);
}
}
catch (Exception error)
{
errCode = 99000;
errText =
string.Format(
"调用 IRAP..ufn_GetProductName 函数发生异常:{0}",
error.Message);
WriteLog.Instance.Write(errText, strProcedureName);
WriteLog.Instance.Write(error.StackTrace, strProcedureName);
}
#endregion
return Json(datas);
}
finally
{
WriteLog.Instance.WriteEndSplitter(strProcedureName);
}
}
/// <param name="sysLogID">社区标识</param>
/// <returns>List[IRAP.Entity.IRAP.T215Info]</returns>
public IRAPJsonResult ufn_GetList_OptionCode(
long sysLogID,
out int errCode,
out string errText)
{
string strProcedureName =
string.Format(
"{0}.{1}",
className,
MethodBase.GetCurrentMethod().Name);
WriteLog.Instance.WriteBeginSplitter(strProcedureName);
try
{
List<T215Info> datas =
new List<T215Info>();
#region 创建数据库调用参数组,并赋值
IList<IDataParameter> paramList = new List<IDataParameter>();
paramList.Add(new IRAPProcParameter("@SysLogID", DbType.Int64, sysLogID));
WriteLog.Instance.Write(
string.Format(
"调用函数 IRAP..ufn_GetList_OptionCode," +
"参数:SysLogID={0}",
sysLogID),
strProcedureName);
#endregion
#region 执行数据库函数或存储过程
try
{
using (IRAPSQLConnection conn = new IRAPSQLConnection())
{
string strSQL = "SELECT * " +
"FROM IRAP..ufn_GetList_OptionCode(@SysLogID) " +
"ORDER BY Ordinal";
IList<T215Info> lstDatas =
conn.CallTableFunc<T215Info>(strSQL, paramList);
datas = lstDatas.ToList<T215Info>();
errCode = 0;
errText = string.Format("调用成功!共获得 {0} 条记录", datas.Count);
WriteLog.Instance.Write(errText, strProcedureName);
}
}
catch (Exception error)
{
errCode = 99000;
errText =
string.Format(
"调用 IRAP..ufn_GetList_OptionCode 函数发生异常:{0}",
error.Message);
WriteLog.Instance.Write(errText, strProcedureName);
WriteLog.Instance.Write(error.StackTrace, strProcedureName);
}
#endregion
return Json(datas);
}
finally
{
WriteLog.Instance.WriteEndSplitter(strProcedureName);
}
}
/// <summary>
/// 获取可以生产指定产品的产线或工作中心组
/// </summary>
/// <param name="communityID">社区标识</param>
/// <param name="productNo">产品编号</param>
/// <param name="sysLogID">系统登录标识</param>
/// <returns>List[ProductionLineOfProduct]</returns>
public IRAPJsonResult ufn_GetList_ProductionLinesOfProduct(
int communityID,
string productNo,
long sysLogID,
out int errCode,
out string errText)
{
string strProcedureName =
string.Format(
"{0}.{1}",
className,
MethodBase.GetCurrentMethod().Name);
WriteLog.Instance.WriteBeginSplitter(strProcedureName);
try
{
List<ProductionLineOfProduct> datas =
new List<ProductionLineOfProduct>();
#region 创建数据库调用参数组,并赋值
IList<IDataParameter> paramList = new List<IDataParameter>();
paramList.Add(new IRAPProcParameter("@CommunityID", DbType.Int32, communityID));
paramList.Add(new IRAPProcParameter("@ProductNo", DbType.String, productNo));
paramList.Add(new IRAPProcParameter("@SysLogID", DbType.Int64, sysLogID));
WriteLog.Instance.Write(
string.Format(
"调用函数 IRAPMDM..ufn_GetList_ProductionLinesOfProduct," +
"参数:CommunityID={0}|ProductNo={1}|SysLogID={2}",
communityID, productNo, sysLogID),
strProcedureName);
#endregion
#region 执行数据库函数或存储过程
try
{
using (IRAPSQLConnection conn = new IRAPSQLConnection())
{
string strSQL = "SELECT * " +
"FROM IRAPMDM..ufn_GetList_ProductionLinesOfProduct(" +
"@CommunityID, @ProductNo, @SysLogID) " +
"ORDER BY Ordinal";
IList<ProductionLineOfProduct> lstDatas =
conn.CallTableFunc<ProductionLineOfProduct>(strSQL, paramList);
datas = lstDatas.ToList<ProductionLineOfProduct>();
errCode = 0;
errText = string.Format("调用成功!共获得 {0} 条记录", datas.Count);
WriteLog.Instance.Write(errText, strProcedureName);
}
}
catch (Exception error)
{
errCode = 99000;
errText =
string.Format(
"调用 IRAPMDM..ufn_GetList_ProductionLinesOfProduct 函数发生异常:{0}",
error.Message);
WriteLog.Instance.Write(errText, strProcedureName);
WriteLog.Instance.Write(error.StackTrace, strProcedureName);
}
#endregion
return Json(datas);
}
finally
{
WriteLog.Instance.WriteEndSplitter(strProcedureName);
}
}
/// <summary>
/// 获取当前站点的可用目标存储地点清单
/// </summary>
/// <param name="communityID">社区标识</param>
/// <param name="sysLogID">系统登录标识</param>
public IRAPJsonResult ufn_GetList_DstDeliveryStoreSites(
int communityID,
long sysLogID,
out int errCode,
out string errText)
{
string strProcedureName =
string.Format(
"{0}.{1}",
className,
MethodBase.GetCurrentMethod().Name);
WriteLog.Instance.WriteBeginSplitter(strProcedureName);
try
{
List<DstDeliveryStoreSite> datas =
new List<DstDeliveryStoreSite>();
#region 创建数据库调用参数组,并赋值
IList<IDataParameter> paramList = new List<IDataParameter>();
paramList.Add(new IRAPProcParameter("@CommunityID", DbType.Int32, communityID));
paramList.Add(new IRAPProcParameter("@SysLogID", DbType.Int64, sysLogID));
WriteLog.Instance.Write(
string.Format(
"调用函数 IRAPMDM..ufn_GetList_DstDeliveryStoreSites," +
"参数:CommunityID={0}|SysLogID={1}",
communityID, sysLogID),
strProcedureName);
#endregion
#region 执行数据库函数或存储过程
try
{
using (IRAPSQLConnection conn = new IRAPSQLConnection())
{
string strSQL = "SELECT * " +
"FROM IRAPMDM..ufn_GetList_DstDeliveryStoreSites(" +
"@CommunityID, @SysLogID) " +
"ORDER BY Ordinal";
IList<DstDeliveryStoreSite> lstDatas =
conn.CallTableFunc<DstDeliveryStoreSite>(strSQL, paramList);
datas = lstDatas.ToList<DstDeliveryStoreSite>();
errCode = 0;
errText = string.Format("调用成功!共获得 {0} 条记录", datas.Count);
WriteLog.Instance.Write(errText, strProcedureName);
}
}
catch (Exception error)
{
errCode = 99000;
errText =
string.Format(
"调用 IRAPMDM..ufn_GetList_DstDeliveryStoreSites 函数发生异常:{0}",
error.Message);
WriteLog.Instance.Write(errText, strProcedureName);
WriteLog.Instance.Write(error.StackTrace, strProcedureName);
}
#endregion
return Json(datas);
}
finally
{
WriteLog.Instance.WriteEndSplitter(strProcedureName);
}
}
/// <summary>
/// 获取指定产品指定工序的工艺参数标准
/// </summary>
/// <param name="communityID">社区标识</param>
/// <param name="t102LeafID">产品叶标识</param>
/// <param name="t216LeafID">工序叶标识</param>
/// <param name="shotTime">时间点(空串-当面)</param>
/// <param name="sysLogID">系统登录标识</param>
/// <returns>List[MethodStandard]</returns>
public IRAPJsonResult ufn_GetList_MethodStandard(
int communityID,
int t102LeafID,
int t216LeafID,
string shotTime,
long sysLogID,
out int errCode,
out string errText)
{
string strProcedureName =
string.Format(
"{0}.{1}",
className,
MethodBase.GetCurrentMethod().Name);
WriteLog.Instance.WriteBeginSplitter(strProcedureName);
try
{
List<MethodStandard> datas =
new List<MethodStandard>();
#region 创建数据库调用参数组,并赋值
IList<IDataParameter> paramList = new List<IDataParameter>();
paramList.Add(new IRAPProcParameter("@CommunityID", DbType.Int32, communityID));
paramList.Add(new IRAPProcParameter("@T102LeafID", DbType.Int32, t102LeafID));
paramList.Add(new IRAPProcParameter("@T216LeafID", DbType.Int32, t216LeafID));
paramList.Add(new IRAPProcParameter("@ShotTime", DbType.String, shotTime));
paramList.Add(new IRAPProcParameter("@SysLogID", DbType.Int64, sysLogID));
WriteLog.Instance.Write(
string.Format(
"调用函数 IRAPMDM..ufn_GetList_MethodStandard," +
"参数:CommunityID={0}|T102LeafID={1}|T216LeafID={2}|" +
"ShotTime={3}|SysLogID={4}",
communityID, t102LeafID, t216LeafID, shotTime, sysLogID),
strProcedureName);
#endregion
#region 执行数据库函数或存储过程
try
{
using (IRAPSQLConnection conn = new IRAPSQLConnection())
{
string strSQL = "SELECT * " +
"FROM IRAPMDM..ufn_GetList_MethodStandard(" +
"@CommunityID, @T102LeafID, @T216LeafID, " +
"@ShotTime, @SysLogID) " +
"ORDER BY Ordinal";
IList<MethodStandard> lstDatas =
conn.CallTableFunc<MethodStandard>(strSQL, paramList);
datas = lstDatas.ToList<MethodStandard>();
errCode = 0;
errText = string.Format("调用成功!共获得 {0} 条记录", datas.Count);
WriteLog.Instance.Write(errText, strProcedureName);
}
}
catch (Exception error)
{
errCode = 99000;
errText =
string.Format(
"调用 IRAPMDM..ufn_GetList_MethodStandard 函数发生异常:{0}",
error.Message);
WriteLog.Instance.Write(errText, strProcedureName);
WriteLog.Instance.Write(error.StackTrace, strProcedureName);
}
#endregion
return Json(datas);
}
finally
{
WriteLog.Instance.WriteEndSplitter(strProcedureName);
}
}
/// <summary>
/// 获取指定产品指定工序的质量标准
/// </summary>
/// <param name="communityID">社区标识</param>
/// <param name="t102LeafID">产品叶标识</param>
/// <param name="t216LeafID">工序叶标识</param>
/// <param name="shotTime">时间点(空串-当前)</param>
/// <param name="sysLogID">系统登录标识</param>
/// <returns>List[QualityStandard]</returns>
public IRAPJsonResult ufn_GetList_QualityStandard(
int communityID,
int t102LeafID,
int t216LeafID,
string shotTime,
long sysLogID,
out int errCode,
out string errText)
{
string strProcedureName =
string.Format(
"{0}.{1}",
className,
MethodBase.GetCurrentMethod().Name);
WriteLog.Instance.WriteBeginSplitter(strProcedureName);
try
{
List<QualityStandard> datas =
new List<QualityStandard>();
#region 创建数据库调用参数组,并赋值
IList<IDataParameter> paramList = new List<IDataParameter>();
paramList.Add(new IRAPProcParameter("@CommunityID", DbType.Int32, communityID));
paramList.Add(new IRAPProcParameter("@T102LeafID", DbType.Int32, t102LeafID));
paramList.Add(new IRAPProcParameter("@T216LeafID", DbType.Int32, t216LeafID));
paramList.Add(new IRAPProcParameter("@ShotTime", DbType.String, shotTime));
paramList.Add(new IRAPProcParameter("@SysLogID", DbType.Int64, sysLogID));
WriteLog.Instance.Write(
string.Format(
"调用函数 IRAPMDM..ufn_GetList_QualityStandard," +
"参数:CommunityID={0}|T102LeafID={1}|T216LeafID={2}" +
"ShotTime={3}||SysLogID={4}",
communityID, t102LeafID, t216LeafID, shotTime, sysLogID),
strProcedureName);
#endregion
#region 执行数据库函数或存储过程
try
{
using (IRAPSQLConnection conn = new IRAPSQLConnection())
{
string strSQL = "SELECT * " +
"FROM IRAPMDM..ufn_GetList_QualityStandard(" +
"@CommunityID, @T102LeafID, @T216LeafID, " +
"@ShotTime, @SysLogID) " +
"ORDER BY Ordinal";
IList<QualityStandard> lstDatas =
conn.CallTableFunc<QualityStandard>(strSQL, paramList);
datas = lstDatas.ToList<QualityStandard>();
errCode = 0;
errText = string.Format("调用成功!共获得 {0} 条记录", datas.Count);
WriteLog.Instance.Write(errText, strProcedureName);
}
}
catch (Exception error)
{
errCode = 99000;
errText =
string.Format(
"调用 IRAPMDM..ufn_GetList_QualityStandard 函数发生异常:{0}",
error.Message);
WriteLog.Instance.Write(errText, strProcedureName);
WriteLog.Instance.Write(error.StackTrace, strProcedureName);
}
#endregion
return Json(datas);
}
finally
{
WriteLog.Instance.WriteEndSplitter(strProcedureName);
}
}
/// <summary>
/// 获取安灯事件类型清单
/// </summary>
/// <param name="communityID">社区标识</param>
/// <param name="sysLogID">系统登录标识</param>
/// <returns>List[AndonEventType]</returns>
public IRAPJsonResult ufn_GetList_AndonEventTypes(
int communityID,
long sysLogID,
out int errCode,
out string errText)
{
string strProcedureName =
string.Format(
"{0}.{1}",
className,
MethodBase.GetCurrentMethod().Name);
WriteLog.Instance.WriteBeginSplitter(strProcedureName);
try
{
List<AndonEventType> datas =
new List<AndonEventType>();
#region 创建数据库调用参数组,并赋值
IList<IDataParameter> paramList = new List<IDataParameter>();
paramList.Add(new IRAPProcParameter("@CommunityID", DbType.Int32, communityID));
paramList.Add(new IRAPProcParameter("@SysLogID", DbType.Int64, sysLogID));
WriteLog.Instance.Write(
string.Format(
"调用函数 IRAPMDM..ufn_GetList_AndonEventTypes," +
"参数:CommunityID={0}|SysLogID={1}",
communityID, sysLogID),
strProcedureName);
#endregion
#region 执行数据库函数或存储过程
try
{
using (IRAPSQLConnection conn = new IRAPSQLConnection())
{
string strSQL = "SELECT * " +
"FROM IRAPMDM..ufn_GetList_AndonEventTypes(" +
"@CommunityID, @SysLogID) " +
"ORDER BY Ordinal";
IList<AndonEventType> lstDatas =
conn.CallTableFunc<AndonEventType>(strSQL, paramList);
datas = lstDatas.ToList<AndonEventType>();
errCode = 0;
errText = string.Format("调用成功!共获得 {0} 条记录", datas.Count);
WriteLog.Instance.Write(errText, strProcedureName);
}
}
catch (Exception error)
{
errCode = 99000;
errText =
string.Format(
"调用 IRAPMDM..ufn_GetList_AndonEventTypes 函数发生异常:{0}",
error.Message);
WriteLog.Instance.Write(errText, strProcedureName);
WriteLog.Instance.Write(error.StackTrace, strProcedureName);
}
#endregion
return Json(datas);
}
finally
{
WriteLog.Instance.WriteEndSplitter(strProcedureName);
}
}
/// <summary>
/// 获取站点绑定的生产线清单
/// </summary>
/// <remarks>
/// ⑴ 社区标识一定要有效且非0
/// ⑵ 系统登录标识一定要有效
/// ⑶ 登录站点是安灯事件采集站点
/// </remarks>
/// <param name="communityID">社区标识</param>
/// <param name="sysLogID">系统登录标识</param>
/// <returns>List[ProductionLineForStationBound]</returns>
public IRAPJsonResult ufn_GetList_StationBoundProductionLines(
int communityID,
long sysLogID,
out int errCode,
out string errText)
{
string strProcedureName =
string.Format(
"{0}.{1}",
className,
MethodBase.GetCurrentMethod().Name);
WriteLog.Instance.WriteBeginSplitter(strProcedureName);
try
{
List<ProductionLineForStationBound> datas =
new List<ProductionLineForStationBound>();
#region 创建数据库调用参数组,并赋值
IList<IDataParameter> paramList = new List<IDataParameter>();
paramList.Add(new IRAPProcParameter("@CommunityID", DbType.Int32, communityID));
paramList.Add(new IRAPProcParameter("@SysLogID", DbType.Int64, sysLogID));
WriteLog.Instance.Write(
string.Format(
"调用函数 IRAPMDM..ufn_GetList_StationBoundProductionLines," +
"参数:CommunityID={0}|SysLogID={1}",
communityID, sysLogID),
strProcedureName);
#endregion
#region 执行数据库函数或存储过程
try
{
using (IRAPSQLConnection conn = new IRAPSQLConnection())
{
string strSQL = "SELECT * " +
"FROM IRAPMDM..ufn_GetList_StationBoundProductionLines(" +
"@CommunityID, @SysLogID) " +
"ORDER BY Ordinal";
IList<ProductionLineForStationBound> lstDatas =
conn.CallTableFunc<ProductionLineForStationBound>(strSQL, paramList);
datas = lstDatas.ToList<ProductionLineForStationBound>();
errCode = 0;
errText = string.Format("调用成功!共获得 {0} 条记录", datas.Count);
WriteLog.Instance.Write(errText, strProcedureName);
}
}
catch (Exception error)
{
errCode = 99000;
errText =
string.Format(
"调用 IRAPMDM..ufn_GetList_StationBoundProductionLines 函数发生异常:{0}",
error.Message);
WriteLog.Instance.Write(errText, strProcedureName);
WriteLog.Instance.Write(error.StackTrace, strProcedureName);
}
#endregion
return Json(datas);
}
finally
{
WriteLog.Instance.WriteEndSplitter(strProcedureName);
}
}
/// <summary>
/// 将信息站点组切换到指定生产线
/// </summary>
/// <param name="communityID">社区标识</param>
/// <param name="hostName">待切换站点主机名</param>
/// <param name="t134LeafID">产线叶标识</param>
/// <param name="sysLogID">系统登录标识</param>
public IRAPJsonResult usp_SwitchToProductionLine(
int communityID,
string hostName,
int t134LeafID,
long sysLogID,
out int errCode,
out string errText)
{
string strProcedureName =
string.Format(
"{0}.{1}",
className,
MethodBase.GetCurrentMethod().Name);
WriteLog.Instance.WriteBeginSplitter(strProcedureName);
try
{
#region 创建数据库调用参数组,并赋值
IList<IDataParameter> paramList = new List<IDataParameter>();
paramList.Add(new IRAPProcParameter("@CommunityID", DbType.Int32, communityID));
paramList.Add(new IRAPProcParameter("@HostName", DbType.String, hostName));
paramList.Add(new IRAPProcParameter("@T134LeafID", DbType.Int32, t134LeafID));
paramList.Add(new IRAPProcParameter("@SysLogID", DbType.Int64, sysLogID));
paramList.Add(
new IRAPProcParameter(
"@ErrCode",
DbType.Int32,
ParameterDirection.Output,
4));
paramList.Add(
new IRAPProcParameter(
"@ErrText",
DbType.String,
ParameterDirection.Output,
400));
WriteLog.Instance.Write(
string.Format("执行存储过程 IRAPMDM..usp_SwitchToProductionLine,参数:" +
"CommunityID={0}|HostName={1}|T134LeafID={2}|SysLogID={3}",
communityID, hostName, t134LeafID, sysLogID),
strProcedureName);
#endregion
#region 执行数据库函数或存储过程
using (IRAPSQLConnection conn = new IRAPSQLConnection())
{
IRAPError error = conn.CallProc("IRAPMDM..usp_SwitchToProductionLine", ref paramList);
errCode = error.ErrCode;
errText = error.ErrText;
WriteLog.Instance.Write(
string.Format(
"({0}){1}",
errCode,
errText),
strProcedureName);
Hashtable rtnParams = new Hashtable();
if (errCode == 0)
{
foreach (IRAPProcParameter param in paramList)
{
if (param.Direction == ParameterDirection.InputOutput || param.Direction == ParameterDirection.Output)
{
if (param.DbType == DbType.Int32 && param.Value == DBNull.Value)
rtnParams.Add(param.ParameterName.Replace("@", ""), 0);
else
rtnParams.Add(param.ParameterName.Replace("@", ""), param.Value);
}
}
}
return Json(rtnParams);
}
#endregion
}
catch (Exception error)
{
errCode = 99000;
errText = string.Format("调用 IRAPMDM..usp_SwitchToProductionLine 时发生异常:{0}", error.Message);
return Json(new Hashtable());
}
finally
{
WriteLog.Instance.WriteEndSplitter(strProcedureName);
}
}
/// <summary>
/// 获取上下文敏感的安灯呼叫对象清单:
/// ⒈ 获取设备失效模式清单;
/// ⒉ 获取产线物料清单;
/// ⒊ 获取工位失效模式清单;
/// ⒋ 获取设备工装型号清单;
/// ⒌ 获取安全问题清单;
/// ⒍ 获取产线其他支持人员清单。
/// </summary>
/// <remarks>从产线安灯事件采集固定客户端调用时,工位及设备叶标识传入0</remarks>
/// <param name="communityID">社区标识</param>
/// <param name="t179LeafID">安灯事件类型叶标识</param>
/// <param name="t107LeafID">触发呼叫工位叶标识</param>
/// <param name="t133LeafID">触发呼叫设备叶标识</param>
/// <param name="sysLogID">系统登录标识</param>
/// <returns>List[AndonCallObject]</returns>
public IRAPJsonResult ufn_GetList_AndonCallObjects(
int communityID,
int t179LeafID,
int t107LeafID,
int t133LeafID,
long sysLogID,
out int errCode,
out string errText)
{
string strProcedureName =
string.Format(
"{0}.{1}",
className,
MethodBase.GetCurrentMethod().Name);
WriteLog.Instance.WriteBeginSplitter(strProcedureName);
try
{
List<AndonCallObject> datas = new List<AndonCallObject>();
#region 创建数据库调用参数组,并赋值
IList<IDataParameter> paramList = new List<IDataParameter>();
paramList.Add(new IRAPProcParameter("@CommunityID", DbType.Int32, communityID));
paramList.Add(new IRAPProcParameter("@T179LeafID", DbType.Int32, t179LeafID));
paramList.Add(new IRAPProcParameter("@T107LeafID", DbType.Int32, t107LeafID));
paramList.Add(new IRAPProcParameter("@T133LeafID", DbType.Int32, t133LeafID));
paramList.Add(new IRAPProcParameter("@SysLogID", DbType.Int64, sysLogID));
WriteLog.Instance.Write(
string.Format(
"调用函数 IRAPMDM..ufn_GetList_AndonCallObjects," +
"参数:CommunityID={0}|T179LeafID={1}|T107LeafID={2}" +
"T133LeafID={3}|SysLogID={4}",
communityID, t179LeafID, t107LeafID, t133LeafID, sysLogID),
strProcedureName);
#endregion
#region 执行数据库函数或存储过程
try
{
using (IRAPSQLConnection conn = new IRAPSQLConnection())
{
string strSQL = "SELECT * " +
"FROM IRAPMDM..ufn_GetList_AndonCallObjects(" +
"@CommunityID, @T179LeafID, @T107LeafID, " +
"@T133LeafID, @SysLogID) " +
"ORDER BY Ordinal";
IList<AndonCallObject> lstDatas =
conn.CallTableFunc<AndonCallObject>(strSQL, paramList);
datas = lstDatas.ToList<AndonCallObject>();
errCode = 0;
errText = string.Format("调用成功!共获得 {0} 条记录", datas.Count);
WriteLog.Instance.Write(errText, strProcedureName);
}
}
catch (Exception error)
{
errCode = 99000;
errText =
string.Format(
"调用 IRAPMDM..ufn_GetList_AndonCallObjects 函数发生异常:{0}",
error.Message);
WriteLog.Instance.Write(errText, strProcedureName);
WriteLog.Instance.Write(error.StackTrace, strProcedureName);
}
#endregion
return Json(datas);
}
finally
{
WriteLog.Instance.WriteEndSplitter(strProcedureName);
}
}
/// <summary>
/// 获取工序清单
/// </summary>
/// <param name="communityID">社区标识</param>
/// <param name="sysLogID">系统登录标识</param>
/// <returns>List[ProcessOperation]</returns>
public IRAPJsonResult ufn_GetList_ProcessOperations(
int communityID,
long sysLogID,
out int errCode,
out string errText)
{
string strProcedureName =
string.Format(
"{0}.{1}",
className,
MethodBase.GetCurrentMethod().Name);
WriteLog.Instance.WriteBeginSplitter(strProcedureName);
try
{
List<ProcessOperation> datas = new List<ProcessOperation>();
#region 创建数据库调用参数组,并赋值
IList<IDataParameter> paramList = new List<IDataParameter>();
paramList.Add(new IRAPProcParameter("@CommunityID", DbType.Int32, communityID));
paramList.Add(new IRAPProcParameter("@SysLogID", DbType.Int64, sysLogID));
WriteLog.Instance.Write(
string.Format(
"调用函数 IRAPMDM..ufn_GetList_ProcessOperations," +
"参数:CommunityID={0}|SysLogID={1}",
communityID, sysLogID),
strProcedureName);
#endregion
#region 执行数据库函数或存储过程
try
{
using (IRAPSQLConnection conn = new IRAPSQLConnection())
{
string strSQL = "SELECT * " +
"FROM IRAPMDM..ufn_GetList_ProcessOperations(" +
"@CommunityID, @SysLogID) " +
"ORDER BY Ordinal";
IList<ProcessOperation> lstDatas =
conn.CallTableFunc<ProcessOperation>(strSQL, paramList);
datas = lstDatas.ToList<ProcessOperation>();
errCode = 0;
errText = string.Format("调用成功!共获得 {0} 条记录", datas.Count);
WriteLog.Instance.Write(errText, strProcedureName);
}
}
catch (Exception error)
{
errCode = 99000;
errText =
string.Format(
"调用 IRAPMDM..ufn_GetList_ProcessOperations 函数发生异常:{0}",
error.Message);
WriteLog.Instance.Write(errText, strProcedureName);
WriteLog.Instance.Write(error.StackTrace, strProcedureName);
}
#endregion
return Json(datas);
}
finally
{
WriteLog.Instance.WriteEndSplitter(strProcedureName);
}
}
/// <summary>
/// 获取产品指定时点工艺流程
/// </summary>
/// <param name="communityID">社区标识</param>
/// <param name="t102LeafID">产品叶标识</param>
/// <param name="shotTime">关注的时间点(yyyy-mm-dd hh:mm)</param>
/// <param name="sysLogID">系统登录标识</param>
public IRAPJsonResult ufn_GetInfo_ProductProcess(
int communityID,
int t102LeafID,
string shotTime,
long sysLogID,
out int errCode,
out string errText)
{
string strProcedureName =
string.Format(
"{0}.{1}",
className,
MethodBase.GetCurrentMethod().Name);
WriteLog.Instance.WriteBeginSplitter(strProcedureName);
try
{
List<ProductProcess> datas = new List<ProductProcess>();
#region 创建数据库调用参数组,并赋值
IList<IDataParameter> paramList = new List<IDataParameter>();
paramList.Add(new IRAPProcParameter("@CommunityID", DbType.Int32, communityID));
paramList.Add(new IRAPProcParameter("@T102LeafID", DbType.Int32, t102LeafID));
paramList.Add(new IRAPProcParameter("@ShotTime", DbType.String, shotTime));
paramList.Add(new IRAPProcParameter("@SysLogID", DbType.Int64, sysLogID));
WriteLog.Instance.Write(
string.Format(
"调用函数 IRAPMDM..ufn_GetInfo_ProductProcess," +
"参数:CommunityID={0}|T102LeafID={1}|ShotTime={2}|" +
"SysLogID={3}",
communityID, t102LeafID, shotTime, sysLogID),
strProcedureName);
#endregion
#region 执行数据库函数或存储过程
try
{
using (IRAPSQLConnection conn = new IRAPSQLConnection())
{
string strSQL = "SELECT * " +
"FROM IRAPMDM..ufn_GetInfo_ProductProcess(" +
"@CommunityID, @T102LeafID, @ShotTime, @SysLogID)";
IList<ProductProcess> lstDatas = conn.CallTableFunc<ProductProcess>(strSQL, paramList);
datas = lstDatas.ToList<ProductProcess>();
errCode = 0;
errText = string.Format("调用成功!共获得 {0} 条记录", datas.Count);
WriteLog.Instance.Write(errText, strProcedureName);
}
}
catch (Exception error)
{
errCode = 99000;
errText = string.Format("调用 IRAPMDM..ufn_GetInfo_ProductProcess 函数发生异常:{0}", error.Message);
WriteLog.Instance.Write(errText, strProcedureName);
WriteLog.Instance.Write(error.StackTrace, strProcedureName);
}
#endregion
return Json(datas);
}
finally
{
WriteLog.Instance.WriteEndSplitter(strProcedureName);
}
}
/// <summary>
/// 根据系统登录标识获取产线信息
/// </summary>
/// <param name="communityID">社区标识</param>
/// <param name="sysLogID">系统登录标识param>
/// <returns>ProductionLineInfo</returns>
public IRAPJsonResult ufn_GetInfo_ProductionLine(
int communityID,
long sysLogID,
out int errCode,
out string errText)
{
string strProcedureName =
string.Format(
"{0}.{1}",
className,
MethodBase.GetCurrentMethod().Name);
WriteLog.Instance.WriteBeginSplitter(strProcedureName);
try
{
ProductionLineInfo data = new ProductionLineInfo();
#region 创建数据库调用参数组,并赋值
IList<IDataParameter> paramList = new List<IDataParameter>();
paramList.Add(new IRAPProcParameter("@CommunityID", DbType.Int32, communityID));
paramList.Add(new IRAPProcParameter("@SysLogID", DbType.Int64, sysLogID));
WriteLog.Instance.Write(
string.Format(
"调用函数 IRAPMDM..ufn_GetInfo_ProductionLine," +
"参数:CommunityID={0}|SysLogID={1}",
communityID, sysLogID),
strProcedureName);
#endregion
#region 执行数据库函数或存储过程
try
{
using (IRAPSQLConnection conn = new IRAPSQLConnection())
{
string strSQL = "SELECT * " +
"FROM IRAPMDM..ufn_GetInfo_ProductionLine(" +
"@CommunityID, @SysLogID)";
IList<ProductionLineInfo> lstDatas = conn.CallTableFunc<ProductionLineInfo>(strSQL, paramList);
if (lstDatas.Count > 0)
{
data = lstDatas[0].Clone();
errCode = 0;
errText = "调用成功!";
}
else
{
errCode = -99001;
errText = "没有当前站点的产线信息";
}
WriteLog.Instance.Write(errText, strProcedureName);
}
}
catch (Exception error)
{
errCode = 99000;
errText = string.Format("调用 IRAPMDM..ufn_GetInfo_ProductionLine 函数发生异常:{0}", error.Message);
WriteLog.Instance.Write(errText, strProcedureName);
WriteLog.Instance.Write(error.StackTrace, strProcedureName);
}
#endregion
return Json(data);
}
finally
{
WriteLog.Instance.WriteEndSplitter(strProcedureName);
}
}
/// <summary>
/// 获取指定产线指定产品相关的Logo图片信息
/// </summary>
/// <param name="communityID">社区标识 </param>
/// <param name="t134LeafID">产线叶标识</param>
/// <param name="t102LeafID">产品叶标识</param>
/// <returns>FVS_LogoImages</returns>
public IRAPJsonResult ufn_GetInfo_LogoImages(
int communityID,
int t134LeafID,
int t102LeafID,
out int errCode,
out string errText)
{
string strProcedureName =
string.Format(
"{0}.{1}",
className,
MethodBase.GetCurrentMethod().Name);
WriteLog.Instance.WriteBeginSplitter(strProcedureName);
try
{
FVS_LogoImages data = new FVS_LogoImages();
#region 创建数据库调用参数组,并赋值
IList<IDataParameter> paramList = new List<IDataParameter>();
paramList.Add(new IRAPProcParameter("@CommunityID", DbType.Int32, communityID));
paramList.Add(new IRAPProcParameter("@T134LeafID", DbType.Int32, t134LeafID));
paramList.Add(new IRAPProcParameter("@T102LeafID", DbType.Int32, t102LeafID));
WriteLog.Instance.Write(
string.Format(
"调用函数 IRAPMDM..ufn_GetInfo_LogoImages," +
"参数:CommunityID={0}|T134LeafID={1}|T102LeafID={2}",
communityID, t134LeafID, t102LeafID),
strProcedureName);
#endregion
#region 执行数据库函数或存储过程
try
{
using (IRAPSQLConnection conn = new IRAPSQLConnection())
{
string strSQL = "SELECT * " +
"FROM IRAPMDM..ufn_GetInfo_LogoImages(" +
"@CommunityID, @T134LeafID, @T102LeafID)";
IList<FVS_LogoImages> lstDatas = conn.CallTableFunc<FVS_LogoImages>(strSQL, paramList);
if (lstDatas.Count > 0)
{
data = lstDatas[0].Clone();
errCode = 0;
errText = "调用成功!";
}
else
{
errCode = -99001;
errText = "没有配置图片";
}
WriteLog.Instance.Write(errText, strProcedureName);
}
}
catch (Exception error)
{
errCode = 99000;
errText = string.Format("调用 IRAPMDM..ufn_GetInfo_LogoImages 函数发生异常:{0}", error.Message);
WriteLog.Instance.Write(errText, strProcedureName);
WriteLog.Instance.Write(error.StackTrace, strProcedureName);
}
#endregion
return Json(data);
}
finally
{
WriteLog.Instance.WriteEndSplitter(strProcedureName);
}
}
/// <summary>
/// 保存行集属性
/// </summary>
/// <remarks>
/// ⒈ 进行生效时间合法性防错;
/// ⒉ 自动敏感与上一版本之间的数据变化,更新版本历史;
/// ⒊ 不进行版本控制时,也能保存上一版本到版本历史表。
/// </remarks>
/// <param name="communityID">社区标识</param>
/// <param name="treeID">树标识</param>
/// <param name="leafID">叶标识</param>
/// <param name="rowSetID">行集序号</param>
/// <param name="voucherNo">变更凭证号</param>
/// <param name="effectiveTime">生效时间点(yyyy-mm-dd hh:mm),空串表示立刻生效</param>
/// <param name="deleUnapplied">是否删除未应用版本</param>
/// <param name="rsAttrXML">
/// 行集属性
/// [RSAttr]
/// [Row RealOrdinal="1" .../]
/// ...
/// [/RSAttr]
/// </param>
/// <param name="sysLogID">系统登录标识</param>
public IRAPJsonResult ssp_SaveRSAttrChange(
int communityID,
int treeID,
int leafID,
int rowSetID,
string voucherNo,
string effectiveTime,
bool deleUnapplied,
string rsAttrXML,
long sysLogID,
out int errCode,
out string errText)
{
string strProcedureName =
string.Format(
"{0}.{1}",
className,
MethodBase.GetCurrentMethod().Name);
WriteLog.Instance.WriteBeginSplitter(strProcedureName);
try
{
#region 创建数据库调用参数组,并赋值
IList<IDataParameter> paramList = new List<IDataParameter>();
paramList.Add(new IRAPProcParameter("@CommunityID", DbType.Int32, communityID));
paramList.Add(new IRAPProcParameter("@TreeID", DbType.Int32, treeID));
paramList.Add(new IRAPProcParameter("@LeafID", DbType.String, leafID));
paramList.Add(new IRAPProcParameter("@RowSetID", DbType.Int32, rowSetID));
paramList.Add(new IRAPProcParameter("@VoucherNo", DbType.String, voucherNo));
paramList.Add(new IRAPProcParameter("@EffectiveTime", DbType.String, effectiveTime));
paramList.Add(new IRAPProcParameter("@DeleUnapplied", DbType.Boolean, deleUnapplied));
paramList.Add(new IRAPProcParameter("@RSAttrXML", DbType.String, rsAttrXML));
paramList.Add(new IRAPProcParameter("@SysLogID", DbType.Int64, sysLogID));
paramList.Add(
new IRAPProcParameter(
"@ErrCode",
DbType.Int32,
ParameterDirection.Output,
4));
paramList.Add(
new IRAPProcParameter(
"@ErrText",
DbType.String,
ParameterDirection.Output,
400));
WriteLog.Instance.Write(
string.Format("执行存储过程 IRAPMDM..ssp_SaveRSAttrChange,参数:" +
"CommunityID={0}|TreeID={1}|LeafID={2}|RowSetID={3}|" +
"VoucherNo={4}|EffectiveTime={5}|DeleUnapplied={6}|" +
"RSAttrXML={7}|SysLogID={8}",
communityID, treeID, leafID, rowSetID, voucherNo, effectiveTime,
deleUnapplied, rsAttrXML, sysLogID),
strProcedureName);
#endregion
#region 执行数据库函数或存储过程
using (IRAPSQLConnection conn = new IRAPSQLConnection())
{
IRAPError error = conn.CallProc("IRAPMDM..ssp_SaveRSAttrChange", ref paramList);
errCode = error.ErrCode;
errText = error.ErrText;
WriteLog.Instance.Write(
string.Format(
"({0}){1}",
errCode,
errText),
strProcedureName);
Hashtable rtnParams = new Hashtable();
if (errCode == 0)
{
rtnParams = DBUtils.DBParamsToHashtable(paramList);
}
return Json(rtnParams);
}
#endregion
}
catch (Exception error)
{
errCode = 99000;
errText = string.Format("调用 IRAPMDM..ssp_SaveRSAttrChange 时发生异常:{0}", error.Message);
return Json(new Hashtable());
}
finally
{
WriteLog.Instance.WriteEndSplitter(strProcedureName);
}
}
/// <summary>
/// 保存工序属性的变更内容
/// </summary>
/// <param name="communityID">社区标识</param>
/// <param name="t216Leaf">工序叶标识</param>
/// <param name="t216Code">工序编码</param>
/// <param name="t216Name">工序名称</param>
/// <param name="t116Leaf">工序类型叶标识</param>
/// <param name="t124Leaf">工段叶标识</param>
/// <param name="t123Leaf">生产在制品部位叶标识</param>
/// <param name="sysLogID">系统登录标识</param>
/// <returns>
/// Hashtable
/// T216Leaf int
/// </returns>
public IRAPJsonResult usp_SaveAttr_ProcessOperation(
int communityID,
int t216Leaf,
string t216Code,
string t216Name,
int t116Leaf,
int t124Leaf,
int t123Leaf,
long sysLogID,
out int errCode,
out string errText)
{
string strProcedureName =
string.Format(
"{0}.{1}",
className,
MethodBase.GetCurrentMethod().Name);
WriteLog.Instance.WriteBeginSplitter(strProcedureName);
try
{
#region 创建数据库调用参数组,并赋值
IList<IDataParameter> paramList = new List<IDataParameter>();
paramList.Add(new IRAPProcParameter("@CommunityID", DbType.Int32, communityID));
paramList.Add(
new IRAPProcParameter(
"@T216Leaf",
DbType.Int32,
ParameterDirection.Output,
4)
{
Value = t216Leaf,
});
paramList.Add(new IRAPProcParameter("@T216Code", DbType.String, t216Code));
paramList.Add(new IRAPProcParameter("@T216Name", DbType.String, t216Name));
paramList.Add(new IRAPProcParameter("@T116Leaf", DbType.Int32, t116Leaf));
paramList.Add(new IRAPProcParameter("@T124Leaf", DbType.Int32, t124Leaf));
paramList.Add(new IRAPProcParameter("@T123Leaf", DbType.Int32, t123Leaf));
paramList.Add(new IRAPProcParameter("@SysLogID", DbType.Int64, sysLogID));
paramList.Add(
new IRAPProcParameter(
"@ErrCode",
DbType.Int32,
ParameterDirection.Output,
4));
paramList.Add(
new IRAPProcParameter(
"@ErrText",
DbType.String,
ParameterDirection.Output,
400));
WriteLog.Instance.Write(
string.Format("执行存储过程 IRAPMDM..usp_SaveAttr_ProcessOperation,参数:" +
"CommunityID={0}|T216Leaf={1}|T216Code={2}|T216Name={3}" +
"T116Leaf={4}|T124Leaf={5}|T123Leaf={6}|SysLogID={7}",
communityID, t216Leaf, t216Code, t216Name, t116Leaf,
t124Leaf, t123Leaf, sysLogID),
strProcedureName);
#endregion
#region 执行数据库函数或存储过程
using (IRAPSQLConnection conn = new IRAPSQLConnection())
{
IRAPError error =
conn.CallProc(
"IRAPMDM..usp_SaveAttr_ProcessOperation",
ref paramList);
errCode = error.ErrCode;
errText = error.ErrText;
WriteLog.Instance.Write(
string.Format(
"({0}){1}",
errCode,
errText),
strProcedureName);
Hashtable rtnParams = new Hashtable();
if (errCode == 0)
{
foreach (IRAPProcParameter param in paramList)
{
if (param.Direction == ParameterDirection.InputOutput ||
param.Direction == ParameterDirection.Output)
{
if (param.DbType == DbType.Int32 && param.Value == DBNull.Value)
rtnParams.Add(param.ParameterName.Replace("@", ""), 0);
else
rtnParams.Add(param.ParameterName.Replace("@", ""), param.Value);
}
}
}
return Json(rtnParams);
}
#endregion
}
catch (Exception error)
{
errCode = 99000;
errText =
string.Format(
"调用 IRAPMDM..usp_SaveAttr_ProcessOperation 时发生异常:{0}",
error.Message);
return Json(new Hashtable());
}
finally
{
WriteLog.Instance.WriteEndSplitter(strProcedureName);
}
}
/// <summary>
/// 根据102和(216或107)获取C64ID
/// </summary>
/// <returns>[int]</returns>
public IRAPJsonResult ufn_GetMethodID(
int communityID,
int t102LeafID,
int treeID,
int leafID,
long unixTime,
out int errCode,
out string errText)
{
string strProcedureName =
string.Format(
"{0}.{1}",
className,
MethodBase.GetCurrentMethod().Name);
WriteLog.Instance.WriteBeginSplitter(strProcedureName);
try
{
int data = 0;
#region 创建数据库调用参数组,并赋值
IList<IDataParameter> paramList = new List<IDataParameter>();
paramList.Add(new IRAPProcParameter("@CommunityID", DbType.Int32, communityID));
paramList.Add(new IRAPProcParameter("@T102LeafID", DbType.Int32, t102LeafID));
paramList.Add(new IRAPProcParameter("@TreeID", DbType.Int32, treeID));
paramList.Add(new IRAPProcParameter("@LeafID", DbType.Int32, leafID));
paramList.Add(new IRAPProcParameter("@UnixTime", DbType.Int64, unixTime));
WriteLog.Instance.Write(
string.Format(
"调用函数 IRAPMDM.dbo.ufn_GetMethodID,参数:CommunityID={0}|" +
"T102LeafID={1}|TreeID={2}|LeafID={3}|UnixTime={4}",
communityID, t102LeafID, treeID, leafID, unixTime),
strProcedureName);
#endregion
#region 执行数据库函数或存储过程
try
{
using (IRAPSQLConnection conn = new IRAPSQLConnection())
{
data = (int)conn.CallScalarFunc("IRAPMDM.dbo.ufn_GetMethodID", paramList);
errCode = 0;
errText = string.Format("调用成功!返回值:[{0}]", data);
}
}
catch (Exception error)
{
errCode = 99000;
errText = string.Format("调用 IRAPMDM.dbo.ufn_GetMethodID 函数发生异常:{0}", error.Message);
}
#endregion
return Json(data);
}
finally
{
WriteLog.Instance.WriteEndSplitter(strProcedureName);
}
}
/// <summary>
/// 未找到对应的数据库函数
/// </summary>
public IRAPJsonResult ufn_GetList_ProductGroup()
{
throw new System.NotImplementedException();
}
/// <summary>
/// 获取工艺维护菜单
/// </summary>
/// <param name="communityID">社区标识</param>
/// <param name="t116LeafID">工序类型标识</param>
/// <param name="sysLogID">系统登录标识</param>
/// <returns>List[MethodMMenu]</returns>
public IRAPJsonResult ufn_GetList_MethodMMenu(
int communityID,
int t116LeafID,
long sysLogID,
out int errCode,
out string errText)
{
string strProcedureName =
string.Format(
"{0}.{1}",
className,
MethodBase.GetCurrentMethod().Name);
WriteLog.Instance.WriteBeginSplitter(strProcedureName);
try
{
List<MethodMMenu> datas = new List<MethodMMenu>();
#region 创建数据库调用参数组,并赋值
IList<IDataParameter> paramList = new List<IDataParameter>();
paramList.Add(new IRAPProcParameter("@CommunityID", DbType.Int32, communityID));
paramList.Add(new IRAPProcParameter("@T116LeafID", DbType.Int32, t116LeafID));
paramList.Add(new IRAPProcParameter("@SysLogID", DbType.Int64, sysLogID));
WriteLog.Instance.Write(
string.Format(
"调用函数 IRAPMDM..ufn_GetList_MethodMMenu,参数:CommunityID={0}|" +
"T116LeafID={1}|SysLogID={2}",
communityID, t116LeafID, sysLogID),
strProcedureName);
#endregion
#region 执行数据库函数或存储过程
try
{
using (IRAPSQLConnection conn = new IRAPSQLConnection())
{
string strSQL = "SELECT * " +
"FROM IRAPMDM..ufn_GetList_MethodMMenu(" +
"@CommunityID, @T116LeafID, @SysLogID) ORDER BY Ordinal";
IList<MethodMMenu> lstDatas = conn.CallTableFunc<MethodMMenu>(strSQL, paramList);
datas = lstDatas.ToList<MethodMMenu>();
errCode = 0;
errText = string.Format("调用成功!共获得 {0} 条记录", datas.Count);
}
}
catch (Exception error)
{
errCode = 99000;
errText = string.Format("调用 IRAPMDM..ufn_GetList_MethodMMenu 函数发生异常:{0}", error.Message);
}
#endregion
return Json(datas);
}
finally
{
WriteLog.Instance.WriteEndSplitter(strProcedureName);
}
}
/// <summary>
/// 获取指定产品和工序的工装标准清单
/// </summary>
public IRAPJsonResult ufn_GetList_ToolingStandard(
int communityID,
int t102LeafID,
int t216LeafID,
string shotTime,
long sysLogID,
out int errCode,
out string errText)
{
string strProcedureName =
string.Format(
"{0}.{1}",
className,
MethodBase.GetCurrentMethod().Name);
WriteLog.Instance.WriteBeginSplitter(strProcedureName);
try
{
List<ToolingStandard> datas = new List<ToolingStandard>();
#region 创建数据库调用参数组,并赋值
IList<IDataParameter> paramList = new List<IDataParameter>();
paramList.Add(new IRAPProcParameter("@CommunityID", DbType.Int32, communityID));
paramList.Add(new IRAPProcParameter("@T102LeafID", DbType.Int32, t102LeafID));
paramList.Add(new IRAPProcParameter("@T216LeafID", DbType.Int32, t216LeafID));
paramList.Add(new IRAPProcParameter("@ShotTime", DbType.String, shotTime));
paramList.Add(new IRAPProcParameter("@SysLogID", DbType.Int64, sysLogID));
WriteLog.Instance.Write(
string.Format(
"调用函数 IRAPMDM..ufn_GetList_ToolingStandard,参数:CommunityID={0}|" +
"T102LeafID={1}|T216LeafID={2}|ShotTime={3}|SysLogID={4}",
communityID, t102LeafID, t216LeafID, shotTime, sysLogID),
strProcedureName);
#endregion
#region 执行数据库函数或存储过程
try
{
using (IRAPSQLConnection conn = new IRAPSQLConnection())
{
string strSQL = "SELECT * " +
"FROM IRAPMDM..ufn_GetList_ToolingStandard(" +
"@CommunityID, @T102LeafID, @T216LeafID, @ShotTime, " +
"@SysLogID)";
IList<ToolingStandard> lstDatas = conn.CallTableFunc<ToolingStandard>(strSQL, paramList);
datas = lstDatas.ToList<ToolingStandard>();
errCode = 0;
errText = string.Format("调用成功!共获得 {0} 条记录", datas.Count);
}
}
catch (Exception error)
{
errCode = 99000;
errText = string.Format("调用 IRAPMDM..ufn_GetList_ToolingStandard 函数发生异常:{0}", error.Message);
}
#endregion
return Json(datas);
}
finally
{
WriteLog.Instance.WriteEndSplitter(strProcedureName);
}
}
/// <summary>
/// 获取指定产品指定工序的生产程序清单
/// </summary>
/// <param name="communityID">社区标识</param>
/// <param name="t102LeafID">产品叶标识</param>
/// <param name="t216LeafID">工序叶标识</param>
/// <param name="shotTime">时间点(空串=当前)</param>
/// <param name="sysLogID">系统登录标识</param>
/// <returns>List[ProductionPrograms]</returns>
public IRAPJsonResult ufn_GetList_ProductionPrograms(
int communityID,
int t102LeafID,
int t216LeafID,
string shotTime,
long sysLogID,
out int errCode,
out string errText)
{
string strProcedureName =
string.Format(
"{0}.{1}",
className,
MethodBase.GetCurrentMethod().Name);
WriteLog.Instance.WriteBeginSplitter(strProcedureName);
try
{
List<ProductionPrograms> datas = new List<ProductionPrograms>();
#region 创建数据库调用参数组,并赋值
IList<IDataParameter> paramList = new List<IDataParameter>();
paramList.Add(new IRAPProcParameter("@CommunityID", DbType.Int32, communityID));
paramList.Add(new IRAPProcParameter("@T102LeafID", DbType.Int32, t102LeafID));
paramList.Add(new IRAPProcParameter("@T216LeafID", DbType.Int32, t216LeafID));
paramList.Add(new IRAPProcParameter("@ShotTime", DbType.String, shotTime));
paramList.Add(new IRAPProcParameter("@SysLogID", DbType.Int64, sysLogID));
WriteLog.Instance.Write(
string.Format(
"调用函数 IRAPMDM..ufn_GetList_ProductionPrograms,参数:CommunityID={0}|" +
"T102LeafID={1}|T216LeafID={2}|ShotTime={3}|SysLogID={4}",
communityID, t102LeafID, t216LeafID, shotTime, sysLogID),
strProcedureName);
#endregion
#region 执行数据库函数或存储过程
try
{
using (IRAPSQLConnection conn = new IRAPSQLConnection())
{
string strSQL = "SELECT * " +
"FROM IRAPMDM..ufn_GetList_ProductionPrograms(" +
"@CommunityID, @T102LeafID, @T216LeafID, @ShotTime, " +
"@SysLogID)";
IList<ProductionPrograms> lstDatas =
conn.CallTableFunc<ProductionPrograms>(strSQL, paramList);
datas = lstDatas.ToList<ProductionPrograms>();
errCode = 0;
errText = string.Format("调用成功!共获得 {0} 条记录", datas.Count);
}
}
catch (Exception error)
{
errCode = 99000;
errText = string.Format(
"调用 IRAPMDM..ufn_GetList_ProductionPrograms 函数发生异常:{0}",
error.Message);
}
#endregion
return Json(datas);
}
finally
{
WriteLog.Instance.WriteEndSplitter(strProcedureName);
}
}
/// <summary>
/// 获取工序作业标准清单
/// </summary>
/// <param name="communityID">社区标识</param>
/// <param name="t102LeafID">产品叶标识</param>
/// <param name="t216LeafID">工序叶标识</param>
/// <param name="shotTime">时间点(空串=当前)</param>
/// <param name="sysLogID">系统登录标识</param>
/// <returns>List[OPStandard]</returns>
public IRAPJsonResult ufn_GetList_SOP(
int communityID,
int t102LeafID,
int t216LeafID,
string shotTime,
long sysLogID,
out int errCode,
out string errText)
{
string strProcedureName =
string.Format(
"{0}.{1}",
className,
MethodBase.GetCurrentMethod().Name);
WriteLog.Instance.WriteBeginSplitter(strProcedureName);
try
{
List<OPStandard> datas = new List<OPStandard>();
#region 创建数据库调用参数组,并赋值
IList<IDataParameter> paramList = new List<IDataParameter>();
paramList.Add(new IRAPProcParameter("@CommunityID", DbType.Int32, communityID));
paramList.Add(new IRAPProcParameter("@T102LeafID", DbType.Int32, t102LeafID));
paramList.Add(new IRAPProcParameter("@T216LeafID", DbType.Int32, t216LeafID));
paramList.Add(new IRAPProcParameter("@ShotTime", DbType.String, shotTime));
paramList.Add(new IRAPProcParameter("@SysLogID", DbType.Int64, sysLogID));
WriteLog.Instance.Write(
string.Format(
"调用函数 IRAPMDM..ufn_GetList_SOP,参数:CommunityID={0}|" +
"T102LeafID={1}|T216LeafID={2}|ShotTime={3}|SysLogID={4}",
communityID, t102LeafID, t216LeafID, shotTime, sysLogID),
strProcedureName);
#endregion
#region 执行数据库函数或存储过程
try
{
using (IRAPSQLConnection conn = new IRAPSQLConnection())
{
string strSQL = "SELECT * " +
"FROM IRAPMDM..ufn_GetList_SOP(" +
"@CommunityID, @T102LeafID, @T216LeafID, @ShotTime, " +
"@SysLogID)";
IList<OPStandard> lstDatas =
conn.CallTableFunc<OPStandard>(strSQL, paramList);
datas = lstDatas.ToList<OPStandard>();
errCode = 0;
errText = string.Format("调用成功!共获得 {0} 条记录", datas.Count);
}
}
catch (Exception error)
{
errCode = 99000;
errText = string.Format(
"调用 IRAPMDM..ufn_GetList_SOP 函数发生异常:{0}",
error.Message);
}
#endregion
return Json(datas);
}
finally
{
WriteLog.Instance.WriteEndSplitter(strProcedureName);
}
}
/// <summary>
/// 获取工序生产环境参数标准
/// </summary>
/// <param name="communityID">社区标识</param>
/// <param name="t102LeafID">产品叶标识</param>
/// <param name="t216LeafID">工序叶标识</param>
/// <param name="shotTime">时间点(空串=当前)</param>
/// <param name="sysLogID">系统登录标识</param>
/// <returns>List[EnvParamStandard]</returns>
public IRAPJsonResult ufn_GetList_EnvParamStandard(
int communityID,
int t102LeafID,
int t216LeafID,
string shotTime,
long sysLogID,
out int errCode,
out string errText)
{
string strProcedureName =
string.Format(
"{0}.{1}",
className,
MethodBase.GetCurrentMethod().Name);
WriteLog.Instance.WriteBeginSplitter(strProcedureName);
try
{
List<EnvParamStandard> datas = new List<EnvParamStandard>();
#region 创建数据库调用参数组,并赋值
IList<IDataParameter> paramList = new List<IDataParameter>();
paramList.Add(new IRAPProcParameter("@CommunityID", DbType.Int32, communityID));
paramList.Add(new IRAPProcParameter("@T102LeafID", DbType.Int32, t102LeafID));
paramList.Add(new IRAPProcParameter("@T216LeafID", DbType.Int32, t216LeafID));
paramList.Add(new IRAPProcParameter("@ShotTime", DbType.String, shotTime));
paramList.Add(new IRAPProcParameter("@SysLogID", DbType.Int64, sysLogID));
WriteLog.Instance.Write(
string.Format(
"调用函数 IRAPMDM..ufn_GetList_EnvParamStandard,参数:CommunityID={0}|" +
"T102LeafID={1}|T216LeafID={2}|ShotTime={3}|SysLogID={4}",
communityID, t102LeafID, t216LeafID, shotTime, sysLogID),
strProcedureName);
#endregion
#region 执行数据库函数或存储过程
try
{
using (IRAPSQLConnection conn = new IRAPSQLConnection())
{
string strSQL = "SELECT * " +
"FROM IRAPMDM..ufn_GetList_EnvParamStandard(" +
"@CommunityID, @T102LeafID, @T216LeafID, @ShotTime, " +
"@SysLogID)";
IList<EnvParamStandard> lstDatas =
conn.CallTableFunc<EnvParamStandard>(strSQL, paramList);
datas = lstDatas.ToList<EnvParamStandard>();
errCode = 0;
errText = string.Format("调用成功!共获得 {0} 条记录", datas.Count);
}
}
catch (Exception error)
{
errCode = 99000;
errText = string.Format(
"调用 IRAPMDM..ufn_GetList_EnvParamStandard 函数发生异常:{0}",
error.Message);
}
#endregion
return Json(datas);
}
finally
{
WriteLog.Instance.WriteEndSplitter(strProcedureName);
}
}
/// <summary>
/// 获取指定产品指定工序人工检查标准
/// </summary>
/// <param name="communityID">社区标识</param>
/// <param name="t102LeafID">产品叶标识</param>
/// <param name="t216LeafID">工序叶标识</param>
/// <param name="shotTime">时间点(空串=当前)</param>
/// <param name="sysLogID">系统登录标识</param>
/// <returns>List[InspectionStandard]</returns>
public IRAPJsonResult ufn_GetList_InspectionStandard(
int communityID,
int t102LeafID,
int t216LeafID,
string shotTime,
long sysLogID,
out int errCode,
out string errText)
{
string strProcedureName =
string.Format(
"{0}.{1}",
className,
MethodBase.GetCurrentMethod().Name);
WriteLog.Instance.WriteBeginSplitter(strProcedureName);
try
{
List<InspectionStandard> datas = new List<InspectionStandard>();
#region 创建数据库调用参数组,并赋值
IList<IDataParameter> paramList = new List<IDataParameter>();
paramList.Add(new IRAPProcParameter("@CommunityID", DbType.Int32, communityID));
paramList.Add(new IRAPProcParameter("@T102LeafID", DbType.Int32, t102LeafID));
paramList.Add(new IRAPProcParameter("@T216LeafID", DbType.Int32, t216LeafID));
paramList.Add(new IRAPProcParameter("@ShotTime", DbType.String, shotTime));
paramList.Add(new IRAPProcParameter("@SysLogID", DbType.Int64, sysLogID));
WriteLog.Instance.Write(
string.Format(
"调用函数 IRAPMDM..ufn_GetList_InspectionStandard,参数:CommunityID={0}|" +
"T102LeafID={1}|T216LeafID={2}|ShotTime={3}|SysLogID={4}",
communityID, t102LeafID, t216LeafID, shotTime, sysLogID),
strProcedureName);
#endregion
#region 执行数据库函数或存储过程
try
{
using (IRAPSQLConnection conn = new IRAPSQLConnection())
{
string strSQL = "SELECT * " +
"FROM IRAPMDM..ufn_GetList_InspectionStandard(" +
"@CommunityID, @T102LeafID, @T216LeafID, @ShotTime, " +
"@SysLogID)";
IList<InspectionStandard> lstDatas =
conn.CallTableFunc<InspectionStandard>(strSQL, paramList);
datas = lstDatas.ToList<InspectionStandard>();
errCode = 0;
errText = string.Format("调用成功!共获得 {0} 条记录", datas.Count);
}
}
catch (Exception error)
{
errCode = 99000;
errText = string.Format(
"调用 IRAPMDM..ufn_GetList_InspectionStandard 函数发生异常:{0}",
error.Message);
}
#endregion
return Json(datas);
}
finally
{
WriteLog.Instance.WriteEndSplitter(strProcedureName);
}
}
/// <summary>
/// 获取指定产品指定工序物料装料标准
/// </summary>
/// <param name="communityID">社区标识</param>
/// <param name="t102LeafID">产品叶标识</param>
/// <param name="t216LeafID">工序叶标识</param>
/// <param name="shotTime">时间点(空串=当前)</param>
/// <param name="sysLogID">系统登录标识</param>
/// <returns>List[LoadingStandard]</returns>
public IRAPJsonResult ufn_GetList_LoadingStandard(
int communityID,
int t102LeafID,
int t216LeafID,
string shotTime,
long sysLogID,
out int errCode,
out string errText)
{
string strProcedureName =
string.Format(
"{0}.{1}",
className,
MethodBase.GetCurrentMethod().Name);
WriteLog.Instance.WriteBeginSplitter(strProcedureName);
try
{
List<LoadingStandard> datas = new List<LoadingStandard>();
#region 创建数据库调用参数组,并赋值
IList<IDataParameter> paramList = new List<IDataParameter>();
paramList.Add(new IRAPProcParameter("@CommunityID", DbType.Int32, communityID));
paramList.Add(new IRAPProcParameter("@T102LeafID", DbType.Int32, t102LeafID));
paramList.Add(new IRAPProcParameter("@T216LeafID", DbType.Int32, t216LeafID));
paramList.Add(new IRAPProcParameter("@ShotTime", DbType.String, shotTime));
paramList.Add(new IRAPProcParameter("@SysLogID", DbType.Int64, sysLogID));
WriteLog.Instance.Write(
string.Format(
"调用函数 IRAPMDM..ufn_GetList_InspectionStandard,参数:CommunityID={0}|" +
"T102LeafID={1}|T216LeafID={2}|ShotTime={3}|SysLogID={4}",
communityID, t102LeafID, t216LeafID, shotTime, sysLogID),
strProcedureName);
#endregion
#region 执行数据库函数或存储过程
try
{
using (IRAPSQLConnection conn = new IRAPSQLConnection())
{
string strSQL = "SELECT * " +
"FROM IRAPMDM..ufn_GetList_LoadingStandard(" +
"@CommunityID, @T102LeafID, @T216LeafID, @ShotTime, " +
"@SysLogID)";
IList<LoadingStandard> lstDatas =
conn.CallTableFunc<LoadingStandard>(strSQL, paramList);
datas = lstDatas.ToList<LoadingStandard>();
errCode = 0;
errText = string.Format("调用成功!共获得 {0} 条记录", datas.Count);
}
}
catch (Exception error)
{
errCode = 99000;
errText = string.Format(
"调用 IRAPMDM..ufn_GetList_LoadingStandard 函数发生异常:{0}",
error.Message);
}
#endregion
return Json(datas);
}
finally
{
WriteLog.Instance.WriteEndSplitter(strProcedureName);
}
}
/// <summary>
/// 获取失效模式清单的核心函数
/// </summary>
/// <param name="communityID">社区标识</param>
/// <param name="t134LeafID">产线叶标识(0=不限)</param>
/// <param name="t216LeafID">工序叶标识(0=不限)</param>
/// <param name="t132LeafID">产品族叶标识(0=不限)</param>
/// <param name="t102LeafID">产品叶标识(0=不限)</param>
/// <param name="sysLogID">系统登录标识</param>
/// <returns>List[FailureModeCore]</returns>
public IRAPJsonResult ufn_GetList_FailureModes_Core(
int communityID,
int t134LeafID,
int t216LeafID,
int t132LeafID,
int t102LeafID,
long sysLogID,
out int errCode,
out string errText)
{
string strProcedureName =
string.Format(
"{0}.{1}",
className,
MethodBase.GetCurrentMethod().Name);
WriteLog.Instance.WriteBeginSplitter(strProcedureName);
try
{
List<FailureModeCore> datas = new List<FailureModeCore>();
#region 创建数据库调用参数组,并赋值
IList<IDataParameter> paramList = new List<IDataParameter>();
paramList.Add(new IRAPProcParameter("@CommunityID", DbType.Int32, communityID));
paramList.Add(new IRAPProcParameter("@T134LeafID", DbType.Int32, t134LeafID));
paramList.Add(new IRAPProcParameter("@T216LeafID", DbType.Int32, t216LeafID));
paramList.Add(new IRAPProcParameter("@T132LeafID", DbType.Int32, t132LeafID));
paramList.Add(new IRAPProcParameter("@T102LeafID", DbType.Int32, t102LeafID));
paramList.Add(new IRAPProcParameter("@SysLogID", DbType.Int64, sysLogID));
WriteLog.Instance.Write(
string.Format(
"调用函数 IRAPMDM..ufn_GetList_FailureModes_Core,参数:CommunityID={0}|" +
"T134LeafID={1}|T216LeafID={2}|T132LeafID={1}|T102LeafID={2}|SysLogID={3}",
communityID,
t134LeafID,
t216LeafID,
t132LeafID,
t102LeafID,
sysLogID),
strProcedureName);
#endregion
#region 执行数据库函数或存储过程
try
{
using (IRAPSQLConnection conn = new IRAPSQLConnection())
{
string strSQL = "SELECT * " +
"FROM IRAPMDM..ufn_GetList_FailureModes_Core(" +
"@CommunityID, @T134LeafID, @T216LeafID, @T132LeafID, " +
"@T102LeafID, @SysLogID)";
IList<FailureModeCore> lstDatas =
conn.CallTableFunc<FailureModeCore>(strSQL, paramList);
datas = lstDatas.ToList<FailureModeCore>();
errCode = 0;
errText = string.Format("调用成功!共获得 {0} 条记录", datas.Count);
}
}
catch (Exception error)
{
errCode = 99000;
errText = string.Format(
"调用 IRAPMDM..ufn_GetList_FailureModes_Core 函数发生异常:{0}",
error.Message);
}
#endregion
return Json(datas);
}
finally
{
WriteLog.Instance.WriteEndSplitter(strProcedureName);
}
}
/// <summary>
/// 获取工序生产能源质量标准
/// </summary>
/// <param name="communityID">社区标识</param>
/// <param name="t102LeafID">产品叶标识</param>
/// <param name="t216LeafID">工序叶标识</param>
/// <param name="shotTime">时间点(空串=当前)</param>
/// <param name="sysLogID">系统登录标识</param>
/// <returns>List[EnergyStandard]</returns>
public IRAPJsonResult ufn_GetList_EnergyStandard(
int communityID,
int t102LeafID,
int t216LeafID,
string shotTime,
long sysLogID,
out int errCode,
out string errText)
{
string strProcedureName =
string.Format(
"{0}.{1}",
className,
MethodBase.GetCurrentMethod().Name);
WriteLog.Instance.WriteBeginSplitter(strProcedureName);
try
{
List<EnergyStandard> datas = new List<EnergyStandard>();
#region 创建数据库调用参数组,并赋值
IList<IDataParameter> paramList = new List<IDataParameter>();
paramList.Add(new IRAPProcParameter("@CommunityID", DbType.Int32, communityID));
paramList.Add(new IRAPProcParameter("@T102LeafID", DbType.Int32, t102LeafID));
paramList.Add(new IRAPProcParameter("@T216LeafID", DbType.Int32, t216LeafID));
paramList.Add(new IRAPProcParameter("@ShotTime", DbType.String, shotTime));
paramList.Add(new IRAPProcParameter("@SysLogID", DbType.Int64, sysLogID));
WriteLog.Instance.Write(
string.Format(
"调用函数 IRAPMDM..ufn_GetList_EnergyStandard,参数:CommunityID={0}|" +
"T102LeafID={1}|T216LeafID={2}|ShotTime={3}|SysLogID={4}",
communityID, t102LeafID, t216LeafID, shotTime, sysLogID),
strProcedureName);
#endregion
#region 执行数据库函数或存储过程
try
{
using (IRAPSQLConnection conn = new IRAPSQLConnection())
{
string strSQL = "SELECT * " +
"FROM IRAPMDM..ufn_GetList_EnergyStandard(" +
"@CommunityID, @T102LeafID, @T216LeafID, @ShotTime, " +
"@SysLogID)";
IList<EnergyStandard> lstDatas =
conn.CallTableFunc<EnergyStandard>(strSQL, paramList);
datas = lstDatas.ToList<EnergyStandard>();
errCode = 0;
errText = string.Format("调用成功!共获得 {0} 条记录", datas.Count);
}
}
catch (Exception error)
{
errCode = 99000;
errText = string.Format(
"调用 IRAPMDM..ufn_GetList_EnergyStandard 函数发生异常:{0}",
error.Message);
}
#endregion
return Json(datas);
}
finally
{
WriteLog.Instance.WriteEndSplitter(strProcedureName);
}
}
/// <summary>
/// 获取工序生产防错规则
/// </summary>
/// <param name="communityID">社区标识</param>
/// <param name="t102LeafID">产品叶标识</param>
/// <param name="t216LeafID">工序叶标识</param>
/// <param name="shotTime">时间点(空串=当前)</param>
/// <param name="sysLogID">系统登录标识</param>
/// <returns>List[PokaYokeRule]</returns>
public IRAPJsonResult ufn_GetList_PokaYokeRules(
int communityID,
int t102LeafID,
int t216LeafID,
string shotTime,
long sysLogID,
out int errCode,
out string errText)
{
string strProcedureName =
string.Format(
"{0}.{1}",
className,
MethodBase.GetCurrentMethod().Name);
WriteLog.Instance.WriteBeginSplitter(strProcedureName);
try
{
List<PokaYokeRule> datas = new List<PokaYokeRule>();
#region 创建数据库调用参数组,并赋值
IList<IDataParameter> paramList = new List<IDataParameter>();
paramList.Add(new IRAPProcParameter("@CommunityID", DbType.Int32, communityID));
paramList.Add(new IRAPProcParameter("@T102LeafID", DbType.Int32, t102LeafID));
paramList.Add(new IRAPProcParameter("@T216LeafID", DbType.Int32, t216LeafID));
paramList.Add(new IRAPProcParameter("@ShotTime", DbType.String, shotTime));
paramList.Add(new IRAPProcParameter("@SysLogID", DbType.Int64, sysLogID));
WriteLog.Instance.Write(
string.Format(
"调用函数 IRAPMDM..ufn_GetList_PokaYokeRules,参数:CommunityID={0}|" +
"T102LeafID={1}|T216LeafID={2}|ShotTime={3}|SysLogID={4}",
communityID, t102LeafID, t216LeafID, shotTime, sysLogID),
strProcedureName);
#endregion
#region 执行数据库函数或存储过程
try
{
using (IRAPSQLConnection conn = new IRAPSQLConnection())
{
string strSQL = "SELECT * " +
"FROM IRAPMDM..ufn_GetList_PokaYokeRules(" +
"@CommunityID, @T102LeafID, @T216LeafID, @ShotTime, " +
"@SysLogID)";
IList<PokaYokeRule> lstDatas =
conn.CallTableFunc<PokaYokeRule>(strSQL, paramList);
datas = lstDatas.ToList<PokaYokeRule>();
errCode = 0;
errText = string.Format("调用成功!共获得 {0} 条记录", datas.Count);
}
}
catch (Exception error)
{
errCode = 99000;
errText = string.Format(
"调用 IRAPMDM..ufn_GetList_PokaYokeRules 函数发生异常:{0}",
error.Message);
}
#endregion
return Json(datas);
}
finally
{
WriteLog.Instance.WriteEndSplitter(strProcedureName);
}
}
/// <summary>
/// 获取工序生产准备标准
/// </summary>
/// <param name="communityID">社区标识</param>
/// <param name="t102LeafID">产品叶标识</param>
/// <param name="t216LeafID">工序叶标识</param>
/// <param name="shotTime">时间点(空串=当前)</param>
/// <param name="sysLogID">系统登录标识</param>
/// <returns>List[PreparingStandard]</returns>
public IRAPJsonResult ufn_GetList_PreparingStandard(
int communityID,
int t102LeafID,
int t216LeafID,
string shotTime,
long sysLogID,
out int errCode,
out string errText)
{
string strProcedureName =
string.Format(
"{0}.{1}",
className,
MethodBase.GetCurrentMethod().Name);
WriteLog.Instance.WriteBeginSplitter(strProcedureName);
try
{
List<PreparingStandard> datas = new List<PreparingStandard>();
#region 创建数据库调用参数组,并赋值
IList<IDataParameter> paramList = new List<IDataParameter>();
paramList.Add(new IRAPProcParameter("@CommunityID", DbType.Int32, communityID));
paramList.Add(new IRAPProcParameter("@T102LeafID", DbType.Int32, t102LeafID));
paramList.Add(new IRAPProcParameter("@T216LeafID", DbType.Int32, t216LeafID));
paramList.Add(new IRAPProcParameter("@ShotTime", DbType.String, shotTime));
paramList.Add(new IRAPProcParameter("@SysLogID", DbType.Int64, sysLogID));
WriteLog.Instance.Write(
string.Format(
"调用函数 IRAPMDM..ufn_GetList_PreparingStandard,参数:CommunityID={0}|" +
"T102LeafID={1}|T216LeafID={2}|ShotTime={3}|SysLogID={4}",
communityID, t102LeafID, t216LeafID, shotTime, sysLogID),
strProcedureName);
#endregion
#region 执行数据库函数或存储过程
try
{
using (IRAPSQLConnection conn = new IRAPSQLConnection())
{
string strSQL = "SELECT * " +
"FROM IRAPMDM..ufn_GetList_PreparingStandard(" +
"@CommunityID, @T102LeafID, @T216LeafID, @ShotTime, " +
"@SysLogID)";
IList<PreparingStandard> lstDatas =
conn.CallTableFunc<PreparingStandard>(strSQL, paramList);
datas = lstDatas.ToList<PreparingStandard>();
errCode = 0;
errText = string.Format("调用成功!共获得 {0} 条记录", datas.Count);
}
}
catch (Exception error)
{
errCode = 99000;
errText = string.Format(
"调用 IRAPMDM..ufn_GetList_PreparingStandard 函数发生异常:{0}",
error.Message);
}
#endregion
return Json(datas);
}
finally
{
WriteLog.Instance.WriteEndSplitter(strProcedureName);
}
}
/// <summary>
/// 获取指定产品指定工序的操作工技能矩阵
/// </summary>
/// <param name="communityID">社区标识</param>
/// <param name="t102LeafID">产品叶标识</param>
/// <param name="t216LeafID">工序叶标识</param>
/// <param name="shotTime">时间点(空串=当前)</param>
/// <param name="sysLogID">系统登录标识</param>
/// <returns>List[SkillMatrixByMethod]</returns>
public IRAPJsonResult ufn_GetSkillMatrix_ByMethod(
int communityID,
int t102LeafID,
int t216LeafID,
string shotTime,
long sysLogID,
out int errCode,
out string errText)
{
string strProcedureName =
string.Format(
"{0}.{1}",
className,
MethodBase.GetCurrentMethod().Name);
WriteLog.Instance.WriteBeginSplitter(strProcedureName);
try
{
List<SkillMatrixByMethod> datas = new List<SkillMatrixByMethod>();
#region 创建数据库调用参数组,并赋值
IList<IDataParameter> paramList = new List<IDataParameter>();
paramList.Add(new IRAPProcParameter("@CommunityID", DbType.Int32, communityID));
paramList.Add(new IRAPProcParameter("@T102LeafID", DbType.Int32, t102LeafID));
paramList.Add(new IRAPProcParameter("@T216LeafID", DbType.Int32, t216LeafID));
paramList.Add(new IRAPProcParameter("@ShotTime", DbType.String, shotTime));
paramList.Add(new IRAPProcParameter("@SysLogID", DbType.Int64, sysLogID));
WriteLog.Instance.Write(
string.Format(
"调用函数 IRAPMDM..ufn_GetSkillMatrix_ByMethod,参数:CommunityID={0}|" +
"T102LeafID={1}|T216LeafID={2}|ShotTime={3}|SysLogID={4}",
communityID, t102LeafID, t216LeafID, shotTime, sysLogID),
strProcedureName);
#endregion
#region 执行数据库函数或存储过程
try
{
using (IRAPSQLConnection conn = new IRAPSQLConnection())
{
string strSQL = "SELECT * " +
"FROM IRAPMDM..ufn_GetSkillMatrix_ByMethod(" +
"@CommunityID, @T102LeafID, @T216LeafID, @ShotTime, " +
"@SysLogID)";
IList<SkillMatrixByMethod> lstDatas =
conn.CallTableFunc<SkillMatrixByMethod>(strSQL, paramList);
datas = lstDatas.ToList<SkillMatrixByMethod>();
errCode = 0;
errText = string.Format("调用成功!共获得 {0} 条记录", datas.Count);
}
}
catch (Exception error)
{
errCode = 99000;
errText = string.Format(
"调用 IRAPMDM..ufn_GetSkillMatrix_ByMethod 函数发生异常:{0}",
error.Message);
}
#endregion
return Json(datas);
}
finally
{
WriteLog.Instance.WriteEndSplitter(strProcedureName);
}
}
/// <summary>
/// 获取功能的表单控件信息
/// </summary>
/// <param name="communityID">社区标识</param>
/// <param name="menuItemID">菜单项标识</param>
/// <param name="progLanguageID">编程语言标识</param>
/// <param name="sysLogID">系统登录标识</param>
/// <returns>List[FormCtrlInfo]</returns>
public IRAPJsonResult sfn_FunctionFormCtrls(
int communityID,
int menuItemID,
int progLanguageID,
long sysLogID,
out int errCode,
out string errText)
{
string strProcedureName =
string.Format(
"{0}.{1}",
className,
MethodBase.GetCurrentMethod().Name);
WriteLog.Instance.WriteBeginSplitter(strProcedureName);
try
{
List<FormCtrlInfo> datas = new List<FormCtrlInfo>();
#region 创建数据库调用参数组,并赋值
IList<IDataParameter> paramList = new List<IDataParameter>();
paramList.Add(new IRAPProcParameter("@CommunityID", DbType.Int32, communityID));
paramList.Add(new IRAPProcParameter("@MenuItemID", DbType.Int32, menuItemID));
paramList.Add(new IRAPProcParameter("@ProgLanguageID", DbType.Int32, progLanguageID));
paramList.Add(new IRAPProcParameter("@SysLogID", DbType.Int64, sysLogID));
WriteLog.Instance.Write(
string.Format(
"调用函数 IRAP..sfn_FunctionFormCtrls,参数:CommunityID={0}|" +
"MenuItemID={1}|ProgLanguageID={2}|SysLogID={3}",
communityID, menuItemID, progLanguageID, sysLogID),
strProcedureName);
#endregion
#region 执行数据库函数或存储过程
try
{
using (IRAPSQLConnection conn = new IRAPSQLConnection())
{
string strSQL = "SELECT * " +
"FROM IRAP..sfn_FunctionFormCtrls(" +
"@CommunityID, @MenuItemID, @ProgLanguageID, " +
"@SysLogID) ORDER BY Ordinal";
IList<FormCtrlInfo> lstDatas =
conn.CallTableFunc<FormCtrlInfo>(strSQL, paramList);
datas = lstDatas.ToList<FormCtrlInfo>();
errCode = 0;
errText = string.Format("调用成功!共获得 {0} 条记录", datas.Count);
}
}
catch (Exception error)
{
errCode = 99000;
errText = string.Format(
"调用 IRAP..sfn_FunctionFormCtrls 函数发生异常:{0}",
error.Message);
}
#endregion
return Json(datas);
}
finally
{
WriteLog.Instance.WriteEndSplitter(strProcedureName);
}
}
/// <summary>
/// 获取工位生产状态(工艺呈现专用)
/// ⒈ 正在生产时呈现工单号、产品、容器号以及完工时目标库位;
/// ⒉ 未在生产时呈现应该执行的工单号、容器号以及滞在库位,并可呈现工艺信息;
/// ⒊ 正在生产时,点击进入可以呈现各种工艺信息。
/// </summary>
/// <param name="communityID">社区标识</param>
/// <param name="sysLogID">系统登录标识</param>
/// <param name="filterT107LeafID">工位叶标识过滤:0-不过滤</param>
/// <returns>List[WIPStationProductionStatus]</returns>
public IRAPJsonResult ufn_GetList_WIPStationProductionStatus(
int communityID,
long sysLogID,
int filterT107LeafID,
out int errCode,
out string errText)
{
string strProcedureName =
string.Format(
"{0}.{1}",
className,
MethodBase.GetCurrentMethod().Name);
WriteLog.Instance.WriteBeginSplitter(strProcedureName);
try
{
List<WIPStationProductionStatus> datas =
new List<WIPStationProductionStatus>();
#region 创建数据库调用参数组,并赋值
IList<IDataParameter> paramList = new List<IDataParameter>();
paramList.Add(new IRAPProcParameter("@CommunityID", DbType.Int32, communityID));
paramList.Add(new IRAPProcParameter("@SysLogID", DbType.Int64, sysLogID));
WriteLog.Instance.Write(
string.Format(
"调用函数 IRAPMDM..ufn_GetList_WIPStationProductionStatus," +
"参数:CommunityID={0}|SysLogID={1}|FilterT107LeafID={2}",
communityID, sysLogID, filterT107LeafID),
strProcedureName);
#endregion
#region 执行数据库函数或存储过程
try
{
using (IRAPSQLConnection conn = new IRAPSQLConnection())
{
string strSQL = "SELECT * " +
"FROM IRAPMDM..ufn_GetList_WIPStationProductionStatus(" +
"@CommunityID, @SysLogID)";
if (filterT107LeafID != 0)
strSQL += string.Format(" WHERE T107LeafID={0}", filterT107LeafID);
IList<WIPStationProductionStatus> lstDatas =
conn.CallTableFunc<WIPStationProductionStatus>(strSQL, paramList);
datas = lstDatas.ToList<WIPStationProductionStatus>();
errCode = 0;
errText = string.Format("调用成功!共获得 {0} 条记录", datas.Count);
}
}
catch (Exception error)
{
errCode = 99000;
errText = string.Format(
"调用 IRAPMDM..ufn_GetList_WIPStationProductionStatus 函数发生异常:{0}",
error.Message);
}
#endregion
return Json(datas);
}
finally
{
WriteLog.Instance.WriteEndSplitter(strProcedureName);
}
}
/// <summary>
/// 获取工位叶标识
/// </summary>
public IRAPJsonResult ufn_GetT216LeafID(
int communityID,
int t102LeafID,
int t107LeafID,
int unixTime,
out int errCode,
out string errText)
{
string strProcedureName =
string.Format(
"{0}.{1}",
className,
MethodBase.GetCurrentMethod().Name);
WriteLog.Instance.WriteBeginSplitter(strProcedureName);
try
{
#region 创建数据库调用参数组,并赋值
IList<IDataParameter> paramList = new List<IDataParameter>();
paramList.Add(new IRAPProcParameter("@CommunityID", DbType.Int32, communityID));
paramList.Add(new IRAPProcParameter("@T102LeafID", DbType.Int32, t102LeafID));
paramList.Add(new IRAPProcParameter("@T107LeafID", DbType.Int32, t107LeafID));
paramList.Add(new IRAPProcParameter("@UnixTime", DbType.String, unixTime));
WriteLog.Instance.Write(
string.Format(
"调用函数 IRAPMDM.dbo.ufn_GetT216LeafID,参数:CommunityID={0}|" +
"T102LeafID={1}|T107LeafID={2}|UnixTime={3}",
communityID,
t102LeafID,
t107LeafID,
unixTime),
strProcedureName);
#endregion
#region 执行数据库函数或存储过程
try
{
using (IRAPSQLConnection conn = new IRAPSQLConnection())
{
int rlt =
(int)conn.CallScalarFunc(
"IRAPMDM.dbo.ufn_GetT216LeafID",
paramList);
errCode = 0;
errText = "调用成功!";
WriteLog.Instance.Write(errText, strProcedureName);
return Json(rlt);
}
}
catch (Exception error)
{
errCode = 99000;
errText =
string.Format(
"调用 IRAP.dbo.ufn_GetT216LeafID 函数发生异常:{0}",
error.Message);
WriteLog.Instance.Write(errText, strProcedureName);
WriteLog.Instance.Write(error.StackTrace, strProcedureName);
return Json(0);
}
#endregion
}
finally
{
WriteLog.Instance.WriteEndSplitter(strProcedureName);
}
}
/// <summary>
/// 获取指定产品指定部件位置编号的叶标识
/// </summary>
/// <param name="communityID">社区标识</param>
/// <param name="t102LeafID">产品叶标识</param>
/// <param name="symbol">部件位置编号</param>
public IRAPJsonResult ufn_GetT110LeafID(
int communityID,
int t102LeafID,
string symbol,
out int errCode,
out string errText)
{
string strProcedureName =
string.Format(
"{0}.{1}",
className,
MethodBase.GetCurrentMethod().Name);
WriteLog.Instance.WriteBeginSplitter(strProcedureName);
try
{
#region 创建数据库调用参数组,并赋值
IList<IDataParameter> paramList = new List<IDataParameter>();
paramList.Add(new IRAPProcParameter("@CommunityID", DbType.Int32, communityID));
paramList.Add(new IRAPProcParameter("@T102LeafID", DbType.Int32, t102LeafID));
paramList.Add(new IRAPProcParameter("@Symbol", DbType.String, symbol));
WriteLog.Instance.Write(
string.Format(
"调用函数 IRAPMDM.dbo.ufn_GetT110LeafID,参数:CommunityID={0}|" +
"T102LeafID={1}|Symbol={2}",
communityID,
t102LeafID,
symbol),
strProcedureName);
#endregion
#region 执行数据库函数或存储过程
try
{
using (IRAPSQLConnection conn = new IRAPSQLConnection())
{
int rlt =
(int)conn.CallScalarFunc(
"IRAPMDM.dbo.ufn_GetT110LeafID",
paramList);
errCode = 0;
errText = "调用成功!";
WriteLog.Instance.Write(errText, strProcedureName);
return Json(rlt);
}
}
catch (Exception error)
{
errCode = 99000;
errText =
string.Format(
"调用 IRAP.dbo.ufn_GetT110LeafID 函数发生异常:{0}",
error.Message);
WriteLog.Instance.Write(errText, strProcedureName);
WriteLog.Instance.Write(error.StackTrace, strProcedureName);
return Json(0);
}
#endregion
}
finally
{
WriteLog.Instance.WriteEndSplitter(strProcedureName);
}
}
/// <param name="communityID">社区标识</param>
/// <param name="methodID">工艺标识</param>
/// <param name="languageID">语言标识</param>
public IRAPJsonResult ufn_GetList_AvailableMethodStandards(
int communityID,
int methodID,
int languageID,
out int errCode,
out string errText)
{
string strProcedureName =
string.Format(
"{0}.{1}",
className,
MethodBase.GetCurrentMethod().Name);
WriteLog.Instance.WriteBeginSplitter(strProcedureName);
try
{
List<StandardType> datas = new List<StandardType>();
#region 创建数据库调用参数组,并赋值
IList<IDataParameter> paramList = new List<IDataParameter>();
paramList.Add(new IRAPProcParameter("@CommunityID", DbType.Int32, communityID));
paramList.Add(new IRAPProcParameter("@MethodID", DbType.Int32, methodID));
paramList.Add(new IRAPProcParameter("@LanguageID", DbType.Int32, languageID));
WriteLog.Instance.Write(
string.Format(
"调用函数 IRAPMDM..ufn_GetList_AvailableMethodStandards," +
"参数:CommunityID={0}|MethodID={1}|LanguageID={2}",
communityID, methodID, languageID),
strProcedureName);
#endregion
#region 执行数据库函数或存储过程
try
{
using (IRAPSQLConnection conn = new IRAPSQLConnection())
{
string strSQL = "SELECT * " +
"FROM IRAPMDM..ufn_GetList_AvailableMethodStandards(" +
"@CommunityID, @MethodID, @LanguageID)";
IList<StandardType> lstDatas =
conn.CallTableFunc<StandardType>(strSQL, paramList);
datas = lstDatas.ToList<StandardType>();
errCode = 0;
errText = string.Format("调用成功!共获得 {0} 条记录", datas.Count);
}
}
catch (Exception error)
{
errCode = 99000;
errText = string.Format(
"调用 IRAPMDM..ufn_GetList_AvailableMethodStandards 函数发生异常:{0}",
error.Message);
}
#endregion
return Json(datas);
}
finally
{
WriteLog.Instance.WriteEndSplitter(strProcedureName);
}
}
/// <summary>
/// 获取产品一般属性
/// </summary>
/// <param name="communityID">社区标识</param>
/// <param name="t102LeafID">产品叶标识</param>
/// <param name="sysLogID">系统登录标识</param>
/// <returns>[GenAttr_Product]</returns>
public IRAPJsonResult ufn_GetProductSketch(
int communityID,
int t102LeafID,
long sysLogID,
out int errCode,
out string errText)
{
string strProcedureName =
string.Format(
"{0}.{1}",
className,
MethodBase.GetCurrentMethod().Name);
WriteLog.Instance.WriteBeginSplitter(strProcedureName);
try
{
GenAttr_Product rlt = new GenAttr_Product();
WriteLog.Instance.Write(
string.Format(
"获得产品的一般属性,调用参数:CommunityID={0}|T102LeafID={1}|SysLogID={1}",
communityID,
t102LeafID,
sysLogID),
strProcedureName);
try
{
using (IRAPSQLConnection conn = new IRAPSQLConnection())
{
long partitioningKey = communityID * 10000 + 102;
// 从获取 T102LeafID 对应的 EntityID
object tmpResult = null;
Stb058 stb058Entity = null;
tmpResult = conn.Get<Stb058>(new Stb058 { PartitioningKey = partitioningKey, LeafID = t102LeafID });
if (tmpResult == null)
{
errCode = 98001;
errText = string.Format("没有 LeafID = {0} 的产品信息", t102LeafID);
WriteLog.Instance.Write(errText, strProcedureName);
return Json(rlt);
}
else
{
stb058Entity = tmpResult as Stb058;
}
tmpResult = conn.Get<GenAttr_Product>(new GenAttr_Product()
{
PartitioningKey = partitioningKey,
EntityID = stb058Entity.EntityID
});
if (tmpResult == null)
{
errCode = 98001;
errText = string.Format("没有 LeafID = {0} 的产品一般属性", t102LeafID);
WriteLog.Instance.Write(errText, strProcedureName);
return Json(rlt);
}
else
{
rlt = ((GenAttr_Product)tmpResult);
}
errCode = 0;
errText = string.Format("获得 LeafID = {0} 的产品一般属性", t102LeafID);
return Json(rlt);
}
}
catch (Exception error)
{
errCode = 99000;
errText = string.Format("调用 ufn_GetProductSketch 函数发生异常:{0}", error.Message);
WriteLog.Instance.Write(errText, strProcedureName);
return Json(rlt);
}
}
finally
{
WriteLog.Instance.WriteEndSplitter(strProcedureName);
WriteLog.Instance.Write("");
}
}
/// <summary>
/// 获取工序的一般属性
/// </summary>
/// <remarks>
/// Sketch: 产品工序简图
/// </remarks>
/// <returns>[GenAttr_ProcessOperation]</returns>
public IRAPJsonResult ufn_GetProcessOperationGenAttr(
int communityID,
int t216LeafID,
long sysLogID,
out int errCode,
out string errText)
{
string strProcedureName = string.Format("{0}.{1}", className, MethodBase.GetCurrentMethod().Name);
WriteLog.Instance.WriteBeginSplitter(strProcedureName);
try
{
GenAttr_ProcessOperation rlt = new GenAttr_ProcessOperation();
WriteLog.Instance.Write(
string.Format(
"获得工序的一般属性,调用参数:CommunityID={0}|T216LeafID={1}|SysLogID={2}",
communityID,
t216LeafID,
sysLogID),
strProcedureName);
try
{
using (IRAPSQLConnection conn = new IRAPSQLConnection())
{
long partitioningKey = communityID * 10000 + 216;
// 从获取 T216LeafID 对应的 EntityID
object tmpResult = null;
Stb058 stb058Entity = null;
WriteLog.Instance.Write(
string.Format("获取 LeafID={0} 的工序信息", t216LeafID),
strProcedureName);
tmpResult = conn.Get<Stb058>(new Stb058
{
PartitioningKey = partitioningKey,
LeafID = t216LeafID
});
if (tmpResult == null)
{
errCode = 98001;
errText = string.Format("没有 LeafID = {0} 的工序信息", t216LeafID);
WriteLog.Instance.Write(errText, strProcedureName);
return Json(rlt);
}
else
{
stb058Entity = tmpResult as Stb058;
}
WriteLog.Instance.Write(
string.Format("获取 EntityID={0} 的工序一般信息", stb058Entity.EntityID),
strProcedureName);
tmpResult = conn.Get<GenAttr_ProcessOperation>(new GenAttr_ProcessOperation()
{
PartitioningKey = partitioningKey,
EntityID = stb058Entity.EntityID
});
if (tmpResult == null)
{
errCode = 98001;
errText = string.Format("没有 LeafID = {0} 的工序一般属性", t216LeafID);
WriteLog.Instance.Write(errText, strProcedureName);
return Json(rlt);
}
else
{
rlt = ((GenAttr_ProcessOperation)tmpResult);
}
errCode = 0;
errText = string.Format("获得 LeafID = {0} 的工序一般属性", t216LeafID);
return Json(rlt);
}
}
catch (Exception error)
{
errCode = 99000;
errText =
string.Format(
"调用 ufn_GetProcessOperationGenAttr 函数发生异常:{0}\n{1}",
error.Message,
error.StackTrace);
WriteLog.Instance.Write(errText, strProcedureName);
return Json(rlt);
}
}
finally
{
WriteLog.Instance.WriteEndSplitter(strProcedureName);
WriteLog.Instance.Write("");
}
}
/// <summary>
/// 获取注册测量仪表清单
/// </summary>
/// <param name="communityID">社区标识</param>
/// <returns>List[RegInstrument]</returns>
public IRAPJsonResult ufn_GetList_RegInstruments(
int communityID,
out int errCode,
out string errText)
{
string strProcedureName =
string.Format(
"{0}.{1}",
className,
MethodBase.GetCurrentMethod().Name);
WriteLog.Instance.WriteBeginSplitter(strProcedureName);
try
{
List<RegInstrument> datas = new List<RegInstrument>();
#region 创建数据库调用参数组,并赋值
IList<IDataParameter> paramList = new List<IDataParameter>();
paramList.Add(new IRAPProcParameter("@CommunityID", DbType.Int32, communityID));
WriteLog.Instance.Write(
string.Format(
"调用函数 IRAPMDM..ufn_GetList_RegInstruments," +
"参数:CommunityID={0}",
communityID),
strProcedureName);
#endregion
#region 执行数据库函数或存储过程
try
{
using (IRAPSQLConnection conn = new IRAPSQLConnection())
{
string strSQL = "SELECT * " +
"FROM IRAPMDM..ufn_GetList_RegInstruments(" +
"@CommunityID) ORDER BY Ordinal";
IList<RegInstrument> lstDatas =
conn.CallTableFunc<RegInstrument>(strSQL, paramList);
datas = lstDatas.ToList<RegInstrument>();
errCode = 0;
errText = string.Format("调用成功!共获得 {0} 条记录", datas.Count);
}
}
catch (Exception error)
{
errCode = 99000;
errText = string.Format(
"调用 IRAPMDM..ufn_GetList_RegInstruments 函数发生异常:{0}",
error.Message);
WriteLog.Instance.Write(errText, strProcedureName);
}
#endregion
return Json(datas);
}
finally
{
WriteLog.Instance.WriteEndSplitter(strProcedureName);
}
}
/// <summary>
/// 获取工位SPC监控情况
/// </summary>
/// <param name="communityID">社区标识</param>
/// <param name="sysLogID">系统登录标识</param>
/// <param name="filterString">根据工位代码进行过滤</param>
/// <returns>List[WIPStationSPCMonitor]</returns>
public IRAPJsonResult ufn_GetList_WIPStationSPCMonitor(
int communityID,
long sysLogID,
string filterString,
out int errCode,
out string errText)
{
string strProcedureName =
string.Format(
"{0}.{1}",
className,
MethodBase.GetCurrentMethod().Name);
WriteLog.Instance.WriteBeginSplitter(strProcedureName);
try
{
List<WIPStationSPCMonitor> datas = new List<WIPStationSPCMonitor>();
#region 创建数据库调用参数组,并赋值
IList<IDataParameter> paramList = new List<IDataParameter>();
paramList.Add(new IRAPProcParameter("@CommunityID", DbType.Int32, communityID));
paramList.Add(new IRAPProcParameter("@SysLogID", DbType.Int64, sysLogID));
WriteLog.Instance.Write(
string.Format(
"调用函数 IRAPMDM..ufn_GetList_WIPStationSPCMonitor," +
"参数:CommunityID={0}|SysLogID={1}|FilterString={2}",
communityID,
sysLogID,
filterString),
strProcedureName);
#endregion
#region 执行数据库函数或存储过程
try
{
using (IRAPSQLConnection conn = new IRAPSQLConnection())
{
string filter = "";
if (filterString != "")
filter = string.Format("WHERE T107Code='{0}' ", filterString);
string strSQL =
string.Format(
"SELECT * " +
"FROM IRAPMDM..ufn_GetList_WIPStationSPCMonitor(" +
"@CommunityID, @SysLogID) {0}ORDER BY Ordinal",
filter);
WriteLog.Instance.Write(strSQL, strProcedureName);
IList<WIPStationSPCMonitor> lstDatas =
conn.CallTableFunc<WIPStationSPCMonitor>(strSQL, paramList);
datas = lstDatas.ToList();
errCode = 0;
errText = string.Format("调用成功!共获得 {0} 条记录", datas.Count);
WriteLog.Instance.Write(errText, strProcedureName);
}
}
catch (Exception error)
{
errCode = 99000;
errText = string.Format(
"调用 IRAPMDM..ufn_GetList_WIPStationSPCMonitor 函数发生异常:{0}",
error.Message);
WriteLog.Instance.Write(errText, strProcedureName);
}
#endregion
return Json(datas);
}
finally
{
WriteLog.Instance.WriteEndSplitter(strProcedureName);
}
}
/// <summary>
/// 获取产品质量问题一点课资料
/// </summary>
/// <param name="communityID">社区标识</param>
/// <param name="t102LeafID">产品叶标识</param>
/// <param name="shotTime">时间(空串表示最新版本)</param>
/// <param name="sysLogID">系统登录标识</param>
/// <returns>List[OnePointLesson]</returns>
public IRAPJsonResult ufn_GetList_OnePointLessons(
int communityID,
int t102LeafID,
string shotTime,
long sysLogID,
out int errCode,
out string errText)
{
string strProcedureName =
string.Format(
"{0}.{1}",
className,
MethodBase.GetCurrentMethod().Name);
WriteLog.Instance.WriteBeginSplitter(strProcedureName);
try
{
List<OnePointLesson> datas = new List<OnePointLesson>();
#region 创建数据库调用参数组,并赋值
IList<IDataParameter> paramList = new List<IDataParameter>();
paramList.Add(new IRAPProcParameter("@CommunityID", DbType.Int32, communityID));
paramList.Add(new IRAPProcParameter("@T102LeafID", DbType.Int32, t102LeafID));
paramList.Add(new IRAPProcParameter("@ShotTime", DbType.String, shotTime));
paramList.Add(new IRAPProcParameter("@SysLogID", DbType.Int64, sysLogID));
WriteLog.Instance.Write(
string.Format(
"调用函数 IRAPMDM..ufn_GetList_OnePointLessons," +
"参数:CommunityID={0}|T102LeafID={1}|ShotTime={2}|" +
"SysLogID={3}",
communityID,
t102LeafID,
shotTime,
sysLogID),
strProcedureName);
#endregion
#region 执行数据库函数或存储过程
try
{
using (IRAPSQLConnection conn = new IRAPSQLConnection())
{
string strSQL =
"SELECT * " +
"FROM IRAPMDM..ufn_GetList_OnePointLessons(" +
"@CommunityID, @T102LeafID, @ShotTime, @SysLogID) " +
"ORDER BY Ordinal";
WriteLog.Instance.Write(strSQL, strProcedureName);
IList<OnePointLesson> lstDatas =
conn.CallTableFunc<OnePointLesson>(strSQL, paramList);
datas = lstDatas.ToList();
errCode = 0;
errText = string.Format("调用成功!共获得 {0} 条记录", datas.Count);
WriteLog.Instance.Write(errText, strProcedureName);
}
}
catch (Exception error)
{
errCode = 99000;
errText = string.Format(
"调用 IRAPMDM..ufn_GetList_OnePointLessons 函数发生异常:{0}",
error.Message);
WriteLog.Instance.Write(errText, strProcedureName);
}
#endregion
return Json(datas);
}
finally
{
WriteLog.Instance.WriteEndSplitter(strProcedureName);
}
}
/// <summary>
/// 获取质量问题一点课受训者名录
/// </summary>
/// <param name="communityID">社区标识</param>
/// <param name="t102LeafID">产品叶标识</param>
/// <param name="issueNo">问题编号</param>
/// <param name="shotTime">时间(空串标识最新版本)</param>
/// <param name="sysLogID">系统登录标识</param>
/// <returns>List[OPLTrainee]</returns>
public IRAPJsonResult ufn_GetList_OPLTrainees(
int communityID,
int t102LeafID,
int issueNo,
string shotTime,
long sysLogID,
out int errCode,
out string errText)
{
string strProcedureName =
string.Format(
"{0}.{1}",
className,
MethodBase.GetCurrentMethod().Name);
WriteLog.Instance.WriteBeginSplitter(strProcedureName);
try
{
List<OPLTrainee> datas = new List<OPLTrainee>();
#region 创建数据库调用参数组,并赋值
IList<IDataParameter> paramList = new List<IDataParameter>();
paramList.Add(new IRAPProcParameter("@CommunityID", DbType.Int32, communityID));
paramList.Add(new IRAPProcParameter("@T102LeafID", DbType.Int32, t102LeafID));
paramList.Add(new IRAPProcParameter("@IssueNo", DbType.Int32, issueNo));
paramList.Add(new IRAPProcParameter("@ShotTime", DbType.String, shotTime));
paramList.Add(new IRAPProcParameter("@SysLogID", DbType.Int64, sysLogID));
WriteLog.Instance.Write(
string.Format(
"调用函数 IRAPMDM..ufn_GetList_OPLTrainees," +
"参数:CommunityID={0}|T102LeafID={1}|IssueNo={2}|" +
"ShotTime={3}|SysLogID={4}",
communityID,
t102LeafID,
issueNo,
shotTime,
sysLogID),
strProcedureName);
#endregion
#region 执行数据库函数或存储过程
try
{
using (IRAPSQLConnection conn = new IRAPSQLConnection())
{
string strSQL =
"SELECT * " +
"FROM IRAPMDM..ufn_GetList_OPLTrainees(" +
"@CommunityID, @T102LeafID, @IssueNo, " +
"@ShotTime, @SysLogID)";
WriteLog.Instance.Write(strSQL, strProcedureName);
IList<OPLTrainee> lstDatas =
conn.CallTableFunc<OPLTrainee>(strSQL, paramList);
datas = lstDatas.ToList();
errCode = 0;
errText = string.Format("调用成功!共获得 {0} 条记录", datas.Count);
WriteLog.Instance.Write(errText, strProcedureName);
}
}
catch (Exception error)
{
errCode = 99000;
errText = string.Format(
"调用 IRAPMDM..ufn_GetList_OPLTrainees 函数发生异常:{0}",
error.Message);
WriteLog.Instance.Write(errText, strProcedureName);
}
#endregion
return Json(datas);
}
finally
{
WriteLog.Instance.WriteEndSplitter(strProcedureName);
}
}
/// <summary>
/// 获取操作工技能矩阵
/// </summary>
/// <param name="communityID">社区标识</param>
/// <param name="t102LeafID">产品叶标识</param>
/// <param name="t134LeafID">产线叶标识</param>
/// <param name="shotTime">日期时间,空串表示最新</param>
/// <param name="sysLogID">系统登录标识</param>
/// <returns>List[OperatorSkillMatrix]</returns>
public IRAPJsonResult ufn_GetSkillMatrix_Operators(
int communityID,
int t102LeafID,
int t134LeafID,
string shotTime,
long sysLogID,
out int errCode,
out string errText)
{
string strProcedureName =
string.Format(
"{0}.{1}",
className,
MethodBase.GetCurrentMethod().Name);
WriteLog.Instance.WriteBeginSplitter(strProcedureName);
try
{
List<OperatorSkillMatrix> datas = new List<OperatorSkillMatrix>();
#region 创建数据库调用参数组,并赋值
IList<IDataParameter> paramList = new List<IDataParameter>();
paramList.Add(new IRAPProcParameter("@CommunityID", DbType.Int32, communityID));
paramList.Add(new IRAPProcParameter("@T102LeafID", DbType.Int32, t102LeafID));
paramList.Add(new IRAPProcParameter("@T134LeafID", DbType.Int32, t134LeafID));
paramList.Add(new IRAPProcParameter("@ShotTime", DbType.String, shotTime));
paramList.Add(new IRAPProcParameter("@SysLogID", DbType.Int64, sysLogID));
WriteLog.Instance.Write(
string.Format(
"调用函数 IRAPMDM..ufn_GetSkillMatrix_Operators," +
"参数:CommunityID={0}|T102LeafID={1}|T134LeafID={2}|" +
"ShotTime={3}|SysLogID={4}",
communityID,
t102LeafID,
t134LeafID,
shotTime,
sysLogID),
strProcedureName);
#endregion
#region 执行数据库函数或存储过程
try
{
using (IRAPSQLConnection conn = new IRAPSQLConnection())
{
string strSQL =
"SELECT * " +
"FROM IRAPMDM..ufn_GetSkillMatrix_Operators(" +
"@CommunityID, @T102LeafID, @T134LeafID, " +
"@ShotTime, @SysLogID)";
WriteLog.Instance.Write(strSQL, strProcedureName);
IList<OperatorSkillMatrix> lstDatas =
conn.CallTableFunc<OperatorSkillMatrix>(strSQL, paramList);
datas = lstDatas.ToList();
errCode = 0;
errText = string.Format("调用成功!共获得 {0} 条记录", datas.Count);
WriteLog.Instance.Write(errText, strProcedureName);
}
}
catch (Exception error)
{
errCode = 99000;
errText = string.Format(
"调用 IRAPMDM..ufn_GetSkillMatrix_Operators 函数发生异常:{0}",
error.Message);
WriteLog.Instance.Write(errText, strProcedureName);
}
#endregion
return Json(datas);
}
finally
{
WriteLog.Instance.WriteEndSplitter(strProcedureName);
}
}
/// <summary>
/// 从系统登录标识获取公司名称
/// </summary>
/// <param name="communityID">社区标识</param>
/// <param name="sysLogID">系统登录标识</param>
/// <returns>string</returns>
public IRAPJsonResult sfn_GetCompanyName(
int communityID,
long sysLogID,
out int errCode,
out string errText)
{
string strProcedureName =
string.Format(
"{0}.{1}",
className,
MethodBase.GetCurrentMethod().Name);
WriteLog.Instance.WriteBeginSplitter(strProcedureName);
try
{
string rlt = "";
try
{
#region 创建数据库调用参数组,并赋值
IList<IDataParameter> paramList = new List<IDataParameter>();
paramList.Add(new IRAPProcParameter("@CommunityID", DbType.Int32, communityID));
paramList.Add(new IRAPProcParameter("@SysLogID", DbType.Int64, sysLogID));
WriteLog.Instance.Write(string.Format("执行函数 IRAPMDM..sfn_GetCompanyName,参数:" +
"CommunityID={0}|SysLogID={1}",
communityID, sysLogID),
strProcedureName);
#endregion
#region 执行数据库函数或存储过程
using (IRAPSQLConnection conn = new IRAPSQLConnection())
{
rlt = (string)conn.CallScalarFunc("IRAPMDM.dbo.sfn_GetCompanyName", paramList);
errCode = 0;
errText = string.Format("调用成功,获得值: [{0}]", rlt);
WriteLog.Instance.Write(errText, strProcedureName);
}
#endregion
}
catch (Exception error)
{
errCode = 99000;
errText = string.Format("调用 IRAPMDM.dbo.sfn_GetCompanyName 时发生异常:{0}", error.Message);
WriteLog.Instance.Write(errText, strProcedureName);
WriteLog.Instance.Write(error.StackTrace, strProcedureName);
}
return Json(rlt);
}
finally
{
WriteLog.Instance.WriteEndSplitter(strProcedureName);
}
}
/// <summary>
/// 获取公司Logo图像的Base64编码
/// </summary>
/// <param name="communityID">社区标识</param>
/// <param name="sysLogID">系统登录标识</param>
public IRAPJsonResult sfn_GetImage_CompanyLogo(
int communityID,
long sysLogID,
out int errCode,
out string errText)
{
string strProcedureName =
string.Format(
"{0}.{1}",
className,
MethodBase.GetCurrentMethod().Name);
WriteLog.Instance.WriteBeginSplitter(strProcedureName);
try
{
string rlt = "";
try
{
#region 创建数据库调用参数组,并赋值
IList<IDataParameter> paramList = new List<IDataParameter>();
paramList.Add(new IRAPProcParameter("@CommunityID", DbType.Int32, communityID));
paramList.Add(new IRAPProcParameter("@SysLogID", DbType.Int64, sysLogID));
WriteLog.Instance.Write(string.Format("执行函数 IRAPMDM..sfn_GetImage_CompanyLogo,参数:" +
"CommunityID={0}|SysLogID={1}",
communityID, sysLogID),
strProcedureName);
#endregion
#region 执行数据库函数或存储过程
using (IRAPSQLConnection conn = new IRAPSQLConnection())
{
rlt = (string)conn.CallScalarFunc("IRAPMDM.dbo.sfn_GetImage_CompanyLogo", paramList);
errCode = 0;
errText = "调用成功。";
WriteLog.Instance.Write(errText, strProcedureName);
}
#endregion
}
catch (Exception error)
{
errCode = 99000;
errText = string.Format("调用 IRAPMDM.dbo.sfn_GetImage_CompanyLogo 时发生异常:{0}", error.Message);
WriteLog.Instance.Write(errText, strProcedureName);
WriteLog.Instance.Write(error.StackTrace, strProcedureName);
}
return Json(rlt);
}
finally
{
WriteLog.Instance.WriteEndSplitter(strProcedureName);
}
}
/// <param name="communityID">社区标识</param>
/// <param name="sysLogID">系统登录标识</param>
public IRAPJsonResult ufn_GetList_KPIsToMonitor(
int communityID,
long sysLogID,
out int errCode,
out string errText)
{
string strProcedureName =
string.Format(
"{0}.{1}",
className,
MethodBase.GetCurrentMethod().Name);
WriteLog.Instance.WriteBeginSplitter(strProcedureName);
try
{
List<KPIToMonitor> datas = new List<KPIToMonitor>();
#region 创建数据库调用参数组,并赋值
IList<IDataParameter> paramList = new List<IDataParameter>();
paramList.Add(new IRAPProcParameter("@CommunityID", DbType.Int32, communityID));
paramList.Add(new IRAPProcParameter("@SysLogID", DbType.Int64, sysLogID));
WriteLog.Instance.Write(
string.Format(
"调用函数 IRAPMDM..ufn_GetList_KPIsToMonitor," +
"参数:CommunityID={0}|SysLogID={1}",
communityID,
sysLogID),
strProcedureName);
#endregion
#region 执行数据库函数或存储过程
try
{
using (IRAPSQLConnection conn = new IRAPSQLConnection())
{
string strSQL =
"SELECT * " +
"FROM IRAPMDM..ufn_GetList_KPIsToMonitor(" +
"@CommunityID, @SysLogID)";
WriteLog.Instance.Write(strSQL, strProcedureName);
IList<KPIToMonitor> lstDatas =
conn.CallTableFunc<KPIToMonitor>(strSQL, paramList);
datas = lstDatas.ToList();
errCode = 0;
errText = string.Format("调用成功!共获得 {0} 条记录", datas.Count);
WriteLog.Instance.Write(errText, strProcedureName);
}
}
catch (Exception error)
{
errCode = 99000;
errText = string.Format(
"调用 IRAPMDM..ufn_GetList_KPIsToMonitor 函数发生异常:{0}",
error.Message);
WriteLog.Instance.Write(errText, strProcedureName);
}
#endregion
return Json(datas);
}
finally
{
WriteLog.Instance.WriteEndSplitter(strProcedureName);
}
}
/// <summary>
/// 获取产品供给客户清单
/// </summary>
/// <param name="communityID">社区标识</param>
/// <param name="sysLogID">系统登录标识</param>
/// <returns>List[CustomerOfAProduction]</returns>
public IRAPJsonResult ufn_GetList_CustomerProduct(
int communityID,
string t102Code,
long sysLogID,
out int errCode,
out string errText)
{
string strProcedureName =
string.Format(
"{0}.{1}",
className,
MethodBase.GetCurrentMethod().Name);
WriteLog.Instance.WriteBeginSplitter(strProcedureName);
try
{
List<CustomerOfAProduction> datas = new List<CustomerOfAProduction>();
#region 创建数据库调用参数组,并赋值
IList<IDataParameter> paramList = new List<IDataParameter>();
paramList.Add(new IRAPProcParameter("@CommunityID", DbType.Int32, communityID));
paramList.Add(new IRAPProcParameter("@T102Code", DbType.String, t102Code));
paramList.Add(new IRAPProcParameter("@SysLogID", DbType.Int64, sysLogID));
WriteLog.Instance.Write(
string.Format(
"调用函数 IRAPMDM..ufn_GetList_CustomerProduct," +
"参数:CommunityID={0}|T102Code={1}|SysLogID={2}",
communityID,
t102Code,
sysLogID),
strProcedureName);
#endregion
#region 执行数据库函数或存储过程
try
{
using (IRAPSQLConnection conn = new IRAPSQLConnection())
{
string strSQL =
"SELECT * " +
"FROM IRAPMDM..ufn_GetList_CustomerProduct(" +
"@CommunityID, @T102Code, @SysLogID)";
WriteLog.Instance.Write(strSQL, strProcedureName);
IList<CustomerOfAProduction> lstDatas =
conn.CallTableFunc<CustomerOfAProduction>(strSQL, paramList);
datas = lstDatas.ToList();
errCode = 0;
errText = string.Format("调用成功!共获得 {0} 条记录", datas.Count);
WriteLog.Instance.Write(errText, strProcedureName);
}
}
catch (Exception error)
{
errCode = 99000;
errText = string.Format(
"调用 IRAPMDM..ufn_GetList_CustomerProduct 函数发生异常:{0}",
error.Message);
WriteLog.Instance.Write(errText, strProcedureName);
}
#endregion
return Json(datas);
}
finally
{
WriteLog.Instance.WriteEndSplitter(strProcedureName);
}
}
/// <param name="communityID">社区标识</param>
/// <param name="t102LeafID"></param>
/// <param name="t105LeafID">客户叶标识</param>
/// <param name="sysLogID">系统登录标识</param>
/// <returns>List[AvailableSite]</returns>
public IRAPJsonResult ufn_GetList_AvaiableSite(
int communityID,
int t102LeafID,
int t105LeafID,
long sysLogID,
out int errCode,
out string errText)
{
string strProcedureName =
string.Format(
"{0}.{1}",
className,
MethodBase.GetCurrentMethod().Name);
WriteLog.Instance.WriteBeginSplitter(strProcedureName);
try
{
List<AvailableSite> datas = new List<AvailableSite>();
#region 创建数据库调用参数组,并赋值
IList<IDataParameter> paramList = new List<IDataParameter>();
paramList.Add(new IRAPProcParameter("@CommunityID", DbType.Int32, communityID));
paramList.Add(new IRAPProcParameter("@T102LeafID", DbType.Int32, t102LeafID));
paramList.Add(new IRAPProcParameter("@T105LeafID", DbType.Int32, t105LeafID));
paramList.Add(new IRAPProcParameter("@SysLogID", DbType.Int64, sysLogID));
WriteLog.Instance.Write(
string.Format(
"调用函数 IRAPMDM..ufn_GetList_AvaiableSite," +
"参数:CommunityID={0}|T102LeafID={1}|T105LeafID={2}|" +
"SysLogID={3}",
communityID,
t102LeafID,
t105LeafID,
sysLogID),
strProcedureName);
#endregion
#region 执行数据库函数或存储过程
try
{
using (IRAPSQLConnection conn = new IRAPSQLConnection())
{
string strSQL =
"SELECT * " +
"FROM IRAPMDM..ufn_GetList_AvaiableSite(" +
"@CommunityID, @T102LeafID, @T105LeafID, @SysLogID)";
WriteLog.Instance.Write(strSQL, strProcedureName);
IList<AvailableSite> lstDatas =
conn.CallTableFunc<AvailableSite>(strSQL, paramList);
datas = lstDatas.ToList();
errCode = 0;
errText = string.Format("调用成功!共获得 {0} 条记录", datas.Count);
WriteLog.Instance.Write(errText, strProcedureName);
}
}
catch (Exception error)
{
errCode = 99000;
errText = string.Format(
"调用 IRAPMDM..ufn_GetList_AvaiableSite 函数发生异常:{0}",
error.Message);
WriteLog.Instance.Write(errText, strProcedureName);
}
#endregion
return Json(datas);
}
finally
{
WriteLog.Instance.WriteEndSplitter(strProcedureName);
}
}
/// <param name="communityID">社区标识</param>
/// <param name="t117LeafID">标签叶标识</param>
/// <param name="sysLogID">系统登录标识</param>
public IRAPJsonResult ufn_GetInfo_TemplateFMTStr(
int communityID,
int t117LeafID,
long sysLogID,
out int errCode,
out string errText)
{
string strProcedureName =
string.Format(
"{0}.{1}",
className,
MethodBase.GetCurrentMethod().Name);
WriteLog.Instance.WriteBeginSplitter(strProcedureName);
try
{
TemplateContent data = new TemplateContent();
#region 创建数据库调用参数组,并赋值
IList<IDataParameter> paramList = new List<IDataParameter>();
paramList.Add(new IRAPProcParameter("@CommunityID", DbType.Int32, communityID));
paramList.Add(new IRAPProcParameter("@T117LeafID", DbType.Int32, t117LeafID));
paramList.Add(new IRAPProcParameter("@SysLogID", DbType.Int64, sysLogID));
WriteLog.Instance.Write(
string.Format(
"调用函数 IRAPMDM..ufn_GetInfo_TemplateFMTStr," +
"参数:CommunityID={0}|T117LeafID={1}|SysLogID={2}",
communityID, t117LeafID, sysLogID),
strProcedureName);
#endregion
#region 执行数据库函数或存储过程
try
{
using (IRAPSQLConnection conn = new IRAPSQLConnection())
{
string strSQL = "SELECT * " +
"FROM IRAPMDM..ufn_GetInfo_TemplateFMTStr(" +
"@CommunityID, @T117LeafID, @SysLogID)";
IList<TemplateContent> lstDatas =
conn.CallTableFunc<TemplateContent>(strSQL, paramList);
if (lstDatas.Count > 0)
{
data = lstDatas[0].Clone();
errCode = 0;
errText = "调用成功!";
}
else
{
errCode = -99001;
errText = string.Format("没有标识号为[{0}]的模板信息。", t117LeafID);
}
WriteLog.Instance.Write(errText, strProcedureName);
}
}
catch (Exception error)
{
errCode = 99000;
errText = string.Format("调用 IRAPMDM..ufn_GetInfo_TemplateFMTStr 函数发生异常:{0}", error.Message);
WriteLog.Instance.Write(errText, strProcedureName);
WriteLog.Instance.Write(error.StackTrace, strProcedureName);
}
#endregion
return Json(data);
}
finally
{
WriteLog.Instance.WriteEndSplitter(strProcedureName);
}
}
/// <summary>
///
/// </summary>
/// <param name="communityID">社区标识</param>
/// <param name="treeID">树标识</param>
/// <param name="opType">操作类型:A-新增;U-修改;D-删除</param>
/// <param name="srcLeafID">117树叶标识(修改时传入被修改叶标识;新增传入参考模板叶标识)</param>
/// <param name="code">节点代码</param>
/// <param name="alternateCode">节点替代代码</param>
/// <param name="nodeName">节点名称</param>
/// <param name="attrChangeXML">标签模板内容</param>
/// <param name="sysLogID">系统登录标识</param>
/// <param name="newLeafID">新标签模板标识</param>
public IRAPJsonResult usp_SaveFact_IRAP117Node(
int communityID,
int treeID,
string opType,
int srcLeafID,
string code,
string alternateCode,
string nodeName,
string attrChangeXML,
long sysLogID,
out int errCode,
out string errText)
{
string strProcedureName =
string.Format(
"{0}.{1}",
className,
MethodBase.GetCurrentMethod().Name);
WriteLog.Instance.WriteBeginSplitter(strProcedureName);
try
{
#region 创建数据库调用参数组,并赋值
IList<IDataParameter> paramList = new List<IDataParameter>();
paramList.Add(new IRAPProcParameter("@CommunityID", DbType.Int32, communityID));
paramList.Add(new IRAPProcParameter("@TreeID", DbType.Int32, treeID));
paramList.Add(new IRAPProcParameter("@OpType", DbType.String, opType));
paramList.Add(new IRAPProcParameter("@SrcLeafID", DbType.Int32, srcLeafID));
paramList.Add(new IRAPProcParameter("@Code", DbType.String, code));
paramList.Add(new IRAPProcParameter("@AlternateCode", DbType.String, alternateCode));
paramList.Add(new IRAPProcParameter("@NodeName", DbType.String, nodeName));
paramList.Add(new IRAPProcParameter("@AttrChangeXML", DbType.String, attrChangeXML));
paramList.Add(new IRAPProcParameter("@SysLogID", DbType.Int64, sysLogID));
paramList.Add(new IRAPProcParameter("@NewLeafID", DbType.Int32, ParameterDirection.Output, 4));
paramList.Add(
new IRAPProcParameter(
"@ErrCode",
DbType.Int32,
ParameterDirection.Output,
4));
paramList.Add(
new IRAPProcParameter(
"@ErrText",
DbType.String,
ParameterDirection.Output,
400));
WriteLog.Instance.Write(
string.Format("执行存储过程 IRAPMDM..usp_SaveFact_IRAP117Node,参数:" +
"CommunityID={0}|TreeID={1}|OpType={2}|SrcLeafID={3}|" +
"Code={4}|AlternateCode={5}|NodeName={6}|AttrChangeXML={7}|" +
"SysLogID={8}",
communityID, treeID, opType, srcLeafID, code, alternateCode,
nodeName, attrChangeXML, sysLogID),
strProcedureName);
#endregion
#region 执行数据库函数或存储过程
using (IRAPSQLConnection conn = new IRAPSQLConnection())
{
IRAPError error = conn.CallProc("IRAPMDM..usp_SaveFact_IRAP117Node", ref paramList);
errCode = error.ErrCode;
errText = error.ErrText;
WriteLog.Instance.Write(
string.Format(
"({0}){1}",
errCode,
errText),
strProcedureName);
Hashtable rtnParams = new Hashtable();
if (errCode == 0)
{
foreach (IRAPProcParameter param in paramList)
{
if (param.Direction == ParameterDirection.InputOutput ||
param.Direction == ParameterDirection.Output)
{
if (param.DbType == DbType.Int32 && param.Value == DBNull.Value)
rtnParams.Add(param.ParameterName.Replace("@", ""), 0);
else
rtnParams.Add(param.ParameterName.Replace("@", ""), param.Value);
}
}
}
return Json(rtnParams);
}
#endregion
}
catch (Exception error)
{
errCode = 99000;
errText =
string.Format(
"调用 IRAPMDM..usp_SaveFact_IRAP117Node 时发生异常:{0}",
error.Message);
return Json(new Hashtable());
}
finally
{
WriteLog.Instance.WriteEndSplitter(strProcedureName);
}
}
/// <summary>
///
/// </summary>
/// <param name="communityID">社区标识</param>
/// <param name="correlationID">关联号</param>
/// <param name="t117LeafID">标签模板叶标识</param>
public IRAPJsonResult usp_SaveFact_C75(
int communityID,
long correlationID,
int t117LeafID,
out int errCode,
out string errText)
{
string strProcedureName =
string.Format(
"{0}.{1}",
className,
MethodBase.GetCurrentMethod().Name);
WriteLog.Instance.WriteBeginSplitter(strProcedureName);
try
{
#region 创建数据库调用参数组,并赋值
IList<IDataParameter> paramList = new List<IDataParameter>();
paramList.Add(new IRAPProcParameter("@CommunityID", DbType.Int32, communityID));
paramList.Add(new IRAPProcParameter("@CorrelationID", DbType.Int64, correlationID));
paramList.Add(new IRAPProcParameter("@T117LeafID", DbType.Int32, t117LeafID));
paramList.Add(
new IRAPProcParameter(
"@ErrCode",
DbType.Int32,
ParameterDirection.Output,
4));
paramList.Add(
new IRAPProcParameter(
"@ErrText",
DbType.String,
ParameterDirection.Output,
400));
WriteLog.Instance.Write(
string.Format("执行存储过程 IRAPMDM..usp_SaveFact_C75,参数:" +
"CommunityID={0}|CorrelationID={1}|T117LeafID={2}",
communityID, correlationID, t117LeafID),
strProcedureName);
#endregion
#region 执行数据库函数或存储过程
using (IRAPSQLConnection conn = new IRAPSQLConnection())
{
IRAPError error = conn.CallProc("IRAPMDM..usp_SaveFact_C75", ref paramList);
errCode = error.ErrCode;
errText = error.ErrText;
WriteLog.Instance.Write(
string.Format(
"({0}){1}",
errCode,
errText),
strProcedureName);
Hashtable rtnParams = new Hashtable();
if (errCode == 0)
{
foreach (IRAPProcParameter param in paramList)
{
if (param.Direction == ParameterDirection.InputOutput ||
param.Direction == ParameterDirection.Output)
{
if (param.DbType == DbType.Int32 && param.Value == DBNull.Value)
rtnParams.Add(param.ParameterName.Replace("@", ""), 0);
else
rtnParams.Add(param.ParameterName.Replace("@", ""), param.Value);
}
}
}
return Json(rtnParams);
}
#endregion
}
catch (Exception error)
{
errCode = 99000;
errText =
string.Format(
"调用 IRAPMDM..usp_SaveFact_C75 时发生异常:{0}",
error.Message);
return Json(new Hashtable());
}
finally
{
WriteLog.Instance.WriteEndSplitter(strProcedureName);
}
}
/// <summary>
/// 获取产线其他支持人员清单
/// </summary>
/// <param name="communityID">社区标识</param>
/// <param name="t179LeafID">安灯事件类型叶标识</param>
/// <param name="t107LeafID">触发呼叫工位叶标识</param>
/// <param name="t133LeafID">触发呼叫设备叶标识</param>
/// <param name="sysLogID">系统登录标识</param>
public IRAPJsonResult ufn_GetList_AndonCallPersons(
int communityID,
int t179LeafID,
int t107LeafID,
int t133LeafID,
long sysLogID,
out int errCode,
out string errText)
{
string strProcedureName =
string.Format(
"{0}.{1}",
className,
MethodBase.GetCurrentMethod().Name);
WriteLog.Instance.WriteBeginSplitter(strProcedureName);
try
{
List<AndonCallPerson> datas = new List<AndonCallPerson>();
#region 创建数据库调用参数组,并赋值
IList<IDataParameter> paramList = new List<IDataParameter>();
paramList.Add(new IRAPProcParameter("@CommunityID", DbType.Int32, communityID));
paramList.Add(new IRAPProcParameter("@T179LeafID", DbType.Int32, t179LeafID));
paramList.Add(new IRAPProcParameter("@T107LeafID", DbType.Int32, t107LeafID));
paramList.Add(new IRAPProcParameter("@T133LeafID", DbType.Int32, t133LeafID));
paramList.Add(new IRAPProcParameter("@SysLogID", DbType.Int64, sysLogID));
WriteLog.Instance.Write(
string.Format(
"调用函数 IRAPMDM..ufn_GetList_AndonCallPersons," +
"参数:CommunityID={0}|T179LeafID={1}|T107LeafID={2}" +
"T133LeafID={3}|SysLogID={4}",
communityID, t179LeafID, t107LeafID, t133LeafID, sysLogID),
strProcedureName);
#endregion
#region 执行数据库函数或存储过程
try
{
using (IRAPSQLConnection conn = new IRAPSQLConnection())
{
string strSQL = "SELECT * " +
"FROM IRAPMDM..ufn_GetList_AndonCallPersons(" +
"@CommunityID, @T179LeafID, @T107LeafID, " +
"@T133LeafID, @SysLogID) " +
"ORDER BY Ordinal";
IList<AndonCallPerson> lstDatas =
conn.CallTableFunc<AndonCallPerson>(strSQL, paramList);
datas = lstDatas.ToList();
errCode = 0;
errText = string.Format("调用成功!共获得 {0} 条记录", datas.Count);
WriteLog.Instance.Write(errText, strProcedureName);
}
}
catch (Exception error)
{
errCode = 99000;
errText =
string.Format(
"调用 IRAPMDM..ufn_GetList_AndonCallPersons 函数发生异常:{0}",
error.Message);
WriteLog.Instance.Write(errText, strProcedureName);
WriteLog.Instance.Write(error.StackTrace, strProcedureName);
}
#endregion
return Json(datas);
}
finally
{
WriteLog.Instance.WriteEndSplitter(strProcedureName);
}
}
/// <summary>
/// 获取指定产品指定工位可选产品失效模式清单
/// </summary>
/// <param name="communityID">社区标识</param>
/// <param name="productLeaf">产品叶标识</param>
/// <param name="workUnitLeaf">工位叶标识</param>
public IRAPJsonResult ufn_GetList_FailureModes(
int communityID,
int productLeaf,
int workUnitLeaf,
long sysLogID,
out int errCode,
out string errText)
{
string strProcedureName =
string.Format(
"{0}.{1}",
className,
MethodBase.GetCurrentMethod().Name);
WriteLog.Instance.WriteBeginSplitter(strProcedureName);
try
{
List<FailureMode> datas = new List<FailureMode>();
#region 创建数据库调用参数组,并赋值
IList<IDataParameter> paramList = new List<IDataParameter>();
paramList.Add(new IRAPProcParameter("@CommunityID", DbType.Int32, communityID));
paramList.Add(new IRAPProcParameter("@ProductLeaf", DbType.Int32, productLeaf));
paramList.Add(new IRAPProcParameter("@WorkUnitLeaf", DbType.Int32, workUnitLeaf));
paramList.Add(new IRAPProcParameter("@SysLogID", DbType.Int64, sysLogID));
WriteLog.Instance.Write(
string.Format(
"调用函数 IRAPMDM..ufn_GetList_FailureModes," +
"参数:CommunityID={0}|ProductLeaf={1}|WorkUnitLeaf={2}|" +
"SysLogID={3}",
communityID, productLeaf, workUnitLeaf, sysLogID),
strProcedureName);
#endregion
#region 执行数据库函数或存储过程
try
{
using (IRAPSQLConnection conn = new IRAPSQLConnection())
{
string strSQL = "SELECT * " +
"FROM IRAPMDM..ufn_GetList_FailureModes(" +
"@CommunityID, @ProductLeaf, @WorkUnitLeaf, " +
"@SysLogID) " +
"ORDER BY Ordinal";
IList<FailureMode> lstDatas =
conn.CallTableFunc<FailureMode>(strSQL, paramList);
datas = lstDatas.ToList();
errCode = 0;
errText = string.Format("调用成功!共获得 {0} 条记录", datas.Count);
WriteLog.Instance.Write(errText, strProcedureName);
}
}
catch (Exception error)
{
errCode = 99000;
errText =
string.Format(
"调用 IRAPMDM..ufn_GetList_FailureModes 函数发生异常:{0}",
error.Message);
WriteLog.Instance.Write(errText, strProcedureName);
WriteLog.Instance.Write(error.StackTrace, strProcedureName);
}
#endregion
return Json(datas);
}
finally
{
WriteLog.Instance.WriteEndSplitter(strProcedureName);
}
}
/// <summary>
///
/// </summary>
/// <param name="communityID">社区标识</param>
/// <param name="skuID"></param>
/// <param name="sysLogID">系统登录标识</param>
/// <param name="errCode"></param>
/// <param name="errText"></param>
/// <returns></returns>
public IRAPJsonResult ufn_GetInfo_SKUID(
int communityID,
string skuID,
long sysLogID,
out int errCode,
out string errText)
{
string strProcedureName =
string.Format(
"{0}.{1}",
className,
MethodBase.GetCurrentMethod().Name);
WriteLog.Instance.WriteBeginSplitter(strProcedureName);
try
{
BWI_SKUIDInfo data = new BWI_SKUIDInfo();
#region 创建数据库调用参数组,并赋值
IList<IDataParameter> paramList = new List<IDataParameter>();
paramList.Add(new IRAPProcParameter("@CommunityID", DbType.Int32, communityID));
paramList.Add(new IRAPProcParameter("@SKUID", DbType.String, skuID));
paramList.Add(new IRAPProcParameter("@SysLogID", DbType.Int64, sysLogID));
WriteLog.Instance.Write(
string.Format(
"调用函数 IRAPMDM..ufn_GetInfo_SKUID," +
"参数:CommunityID={0}|SKUID={1}|SysLogID={2}",
communityID, skuID, sysLogID),
strProcedureName);
#endregion
#region 执行数据库函数或存储过程
try
{
using (IRAPSQLConnection conn = new IRAPSQLConnection())
{
string strSQL = "SELECT * " +
"FROM IRAPMDM..ufn_GetInfo_SKUID(" +
"@CommunityID, @SKUID, @SysLogID)";
IList<BWI_SKUIDInfo> lstDatas =
conn.CallTableFunc<BWI_SKUIDInfo>(strSQL, paramList);
if (lstDatas.Count > 0)
{
data = lstDatas[0].Clone();
errCode = 0;
errText = "调用成功!";
}
else
{
errCode = -99001;
errText = "没有当前站点的产线信息";
}
WriteLog.Instance.Write(errText, strProcedureName);
}
}
catch (Exception error)
{
errCode = 99000;
errText =
string.Format(
"调用 IRAPMDM..ufn_GetInfo_SKUID 函数发生异常:{0}",
error.Message);
WriteLog.Instance.Write(errText, strProcedureName);
WriteLog.Instance.Write(error.StackTrace, strProcedureName);
}
#endregion
return Json(data);
}
finally
{
WriteLog.Instance.WriteEndSplitter(strProcedureName);
}
}
/// <summary>
/// 根据工位获取失效模式
/// </summary>
/// <param name="communityID">社区标识</param>
/// <param name="t107LeafID">工位叶标识</param>
/// <param name="sysLogID">系统登录标识</param>
/// <param name="errCode"></param>
/// <param name="errText"></param>
/// <returns></returns>
public IRAPJsonResult ufn_GetList_WorkUnitFailureModes(
int communityID,
int t107LeafID,
long sysLogID,
out int errCode,
out string errText)
{
string strProcedureName =
string.Format(
"{0}.{1}",
className,
MethodBase.GetCurrentMethod().Name);
WriteLog.Instance.WriteBeginSplitter(strProcedureName);
try
{
List<FailureModeByWorkUnit> datas = new List<FailureModeByWorkUnit>();
#region 创建数据库调用参数组,并赋值
IList<IDataParameter> paramList = new List<IDataParameter>();
paramList.Add(new IRAPProcParameter("@CommunityID", DbType.Int32, communityID));
paramList.Add(new IRAPProcParameter("@T107LeafID", DbType.Int32, t107LeafID));
paramList.Add(new IRAPProcParameter("@SysLogID", DbType.Int64, sysLogID));
WriteLog.Instance.Write(
string.Format(
"调用函数 IRAPMDM..ufn_GetList_WorkUnitFailureModes," +
"参数:CommunityID={0}|T107LeafID={1}|SysLogID={2}",
communityID, t107LeafID, sysLogID),
strProcedureName);
#endregion
#region 执行数据库函数或存储过程
try
{
using (IRAPSQLConnection conn = new IRAPSQLConnection())
{
string strSQL = "SELECT * " +
"FROM IRAPMDM..ufn_GetList_WorkUnitFailureModes(" +
"@CommunityID, @T107LeafID, @SysLogID) " +
"ORDER BY Ordinal";
IList<FailureModeByWorkUnit> lstDatas =
conn.CallTableFunc<FailureModeByWorkUnit>(strSQL, paramList);
datas = lstDatas.ToList();
errCode = 0;
errText = string.Format("调用成功!共获得 {0} 条记录", datas.Count);
WriteLog.Instance.Write(errText, strProcedureName);
}
}
catch (Exception error)
{
errCode = 99000;
errText =
string.Format(
"调用 IRAPMDM..ufn_GetList_WorkUnitFailureModes 函数发生异常:{0}",
error.Message);
WriteLog.Instance.Write(errText, strProcedureName);
WriteLog.Instance.Write(error.StackTrace, strProcedureName);
}
#endregion
return Json(datas);
}
finally
{
WriteLog.Instance.WriteEndSplitter(strProcedureName);
}
}
/// <summary>
/// 获取信息站点上下文(工位或工作流结点功能信息)
/// </summary>
/// <param name="communityID">社区标识</param>
/// <param name="sysLogID">系统登录标识</param>
/// <returns>List[WIPStation]</returns>
public IRAPJsonResult ufn_GetList_WIPStationsOfAHost(
int communityID,
long sysLogID,
out int errCode,
out string errText)
{
string strProcedureName =
string.Format(
"{0}.{1}",
className,
MethodBase.GetCurrentMethod().Name);
WriteLog.Instance.WriteBeginSplitter(strProcedureName);
try
{
List<WIPStation> datas = new List<WIPStation>();
#region 创建数据库调用参数组,并赋值
IList<IDataParameter> paramList = new List<IDataParameter>();
paramList.Add(new IRAPProcParameter("@CommunityID", DbType.Int32, communityID));
paramList.Add(new IRAPProcParameter("@SysLogID", DbType.Int64, sysLogID));
WriteLog.Instance.Write(
string.Format(
"调用函数 IRAPMDM..ufn_GetList_WIPStationsOfAHost," +
"参数:CommunityID={0}|SysLogID={1}",
communityID, sysLogID),
strProcedureName);
#endregion
#region 执行数据库函数或存储过程
try
{
using (IRAPSQLConnection conn = new IRAPSQLConnection())
{
string strSQL = "SELECT * " +
"FROM IRAPMDM..ufn_GetList_WIPStationsOfAHost(" +
"@CommunityID, @SysLogID) " +
"ORDER BY Ordinal";
IList<WIPStation> lstDatas =
conn.CallTableFunc<WIPStation>(strSQL, paramList);
datas = lstDatas.ToList();
errCode = 0;
errText = string.Format("调用成功!共获得 {0} 条记录", datas.Count);
WriteLog.Instance.Write(errText, strProcedureName);
}
}
catch (Exception error)
{
errCode = 99000;
errText =
string.Format(
"调用 IRAPMDM..ufn_GetList_WIPStationsOfAHost 函数发生异常:{0}",
error.Message);
WriteLog.Instance.Write(errText, strProcedureName);
WriteLog.Instance.Write(error.StackTrace, strProcedureName);
}
#endregion
return Json(datas);
}
finally
{
WriteLog.Instance.WriteEndSplitter(strProcedureName);
}
}
/// <summary>
/// 获取信息站点上下文(工位或工作流结点功能信息)
/// </summary>
/// <param name="communityID">社区标识</param>
/// <param name="sysLogID">系统登录标识</param>
/// <returns>List[WIPStation]</returns>
public IRAPJsonResult ufn_GetList_WIPStationsOfAHostByFunction(
int communityID,
int t3LeafID,
long sysLogID,
out int errCode,
out string errText)
{
string strProcedureName =
string.Format(
"{0}.{1}",
className,
MethodBase.GetCurrentMethod().Name);
WriteLog.Instance.WriteBeginSplitter(strProcedureName);
try
{
List<WIPStation> datas = new List<WIPStation>();
#region 创建数据库调用参数组,并赋值
IList<IDataParameter> paramList = new List<IDataParameter>();
paramList.Add(new IRAPProcParameter("@CommunityID", DbType.Int32, communityID));
paramList.Add(new IRAPProcParameter("@T3LeafID", DbType.Int32, t3LeafID));
paramList.Add(new IRAPProcParameter("@SysLogID", DbType.Int64, sysLogID));
WriteLog.Instance.Write(
string.Format(
"调用函数 IRAPMDM..ufn_GetList_WIPStationsOfAHostByFunction," +
"参数:CommunityID={0}|T3LeafID={1}|SysLogID={2}",
communityID, t3LeafID, sysLogID),
strProcedureName);
#endregion
#region 执行数据库函数或存储过程
try
{
using (IRAPSQLConnection conn = new IRAPSQLConnection())
{
string strSQL = "SELECT * " +
"FROM IRAPMDM..ufn_GetList_WIPStationsOfAHostByFunction(" +
"@CommunityID, @T3LeafID, @SysLogID) " +
"ORDER BY Ordinal";
IList<WIPStation> lstDatas =
conn.CallTableFunc<WIPStation>(strSQL, paramList);
datas = lstDatas.ToList();
errCode = 0;
errText = string.Format("调用成功!共获得 {0} 条记录", datas.Count);
WriteLog.Instance.Write(errText, strProcedureName);
}
}
catch (Exception error)
{
errCode = 99000;
errText =
string.Format(
"调用 IRAPMDM..ufn_GetList_WIPStationsOfAHostByFunction 函数发生异常:{0}",
error.Message);
WriteLog.Instance.Write(errText, strProcedureName);
WriteLog.Instance.Write(error.StackTrace, strProcedureName);
}
#endregion
return Json(datas);
}
finally
{
WriteLog.Instance.WriteEndSplitter(strProcedureName);
}
}
/// <summary>
/// 获取经由指定工位产品清单或经由指定工作流结点的流程清单
/// </summary>
/// <param name="communityID">社区标识</param>
/// <param name="t107LeafID">工位叶标识</param>
/// <param name="isWorkFlowNode">是否工作流结点</param>
/// <param name="sysLogID">系统登录标识</param>
/// <returns>List[ProductViaStation]</returns>
public IRAPJsonResult ufn_GetList_ProductsViaStation(
int communityID,
int t107LeafID,
bool isWorkFlowNode,
long sysLogID,
out int errCode,
out string errText)
{
string strProcedureName =
string.Format(
"{0}.{1}",
className,
MethodBase.GetCurrentMethod().Name);
WriteLog.Instance.WriteBeginSplitter(strProcedureName);
try
{
List<ProductViaStation> datas = new List<ProductViaStation>();
#region 创建数据库调用参数组,并赋值
IList<IDataParameter> paramList = new List<IDataParameter>();
paramList.Add(new IRAPProcParameter("@CommunityID", DbType.Int32, communityID));
paramList.Add(new IRAPProcParameter("@T107LeafID", DbType.Int32, t107LeafID));
paramList.Add(new IRAPProcParameter("@IsWorkFlowNode", DbType.Boolean, isWorkFlowNode));
paramList.Add(new IRAPProcParameter("@SysLogID", DbType.Int64, sysLogID));
WriteLog.Instance.Write(
string.Format(
"调用函数 IRAPMDM..ufn_GetList_ProductsViaStation," +
"参数:CommunityID={0}|T107LeafID={1}|IsWorkFlowNode={2}|SysLogID={3}",
communityID, t107LeafID, isWorkFlowNode, sysLogID),
strProcedureName);
#endregion
#region 执行数据库函数或存储过程
try
{
using (IRAPSQLConnection conn = new IRAPSQLConnection())
{
string strSQL = "SELECT * " +
"FROM IRAPMDM..ufn_GetList_ProductsViaStation(" +
"@CommunityID, @T107LeafID, @IsWorkFlowNode, @SysLogID) " +
"ORDER BY Ordinal";
IList<ProductViaStation> lstDatas =
conn.CallTableFunc<ProductViaStation>(strSQL, paramList);
datas = lstDatas.ToList();
errCode = 0;
errText = string.Format("调用成功!共获得 {0} 条记录", datas.Count);
WriteLog.Instance.Write(errText, strProcedureName);
}
}
catch (Exception error)
{
errCode = 99000;
errText =
string.Format(
"调用 IRAPMDM..ufn_GetList_ProductsViaStation 函数发生异常:{0}",
error.Message);
WriteLog.Instance.Write(errText, strProcedureName);
WriteLog.Instance.Write(error.StackTrace, strProcedureName);
}
#endregion
return Json(datas);
}
finally
{
WriteLog.Instance.WriteEndSplitter(strProcedureName);
}
}
/// <summary>
/// 获取检查工序获取的部件位置清单
/// </summary>
/// <param name="communityID">社区标识</param>
/// <param name="sysLogID">系统登录标识</param>
/// <param name="t102LeafID">产品叶标识</param>
/// <param name="t216LeafID">工位叶标识</param>
/// <returns>List[SymbolInspecting]</returns>
public IRAPJsonResult ufn_GetList_Symbols_Inspecting(
int communityID,
long sysLogID,
int t102LeafID,
int t216LeafID,
out int errCode,
out string errText)
{
string strProcedureName =
string.Format(
"{0}.{1}",
className,
MethodBase.GetCurrentMethod().Name);
WriteLog.Instance.WriteBeginSplitter(strProcedureName);
try
{
List<SymbolInspecting> datas = new List<SymbolInspecting>();
#region 创建数据库调用参数组,并赋值
IList<IDataParameter> paramList = new List<IDataParameter>();
paramList.Add(new IRAPProcParameter("@CommunityID", DbType.Int32, communityID));
paramList.Add(new IRAPProcParameter("@SysLogID", DbType.Int64, sysLogID));
paramList.Add(new IRAPProcParameter("@T102LeafID", DbType.Int32, t102LeafID));
paramList.Add(new IRAPProcParameter("@T216LeafID", DbType.Int32, t216LeafID));
WriteLog.Instance.Write(
string.Format(
"调用函数 IRAPMDM..ufn_GetList_Symbols_Inspecting," +
"参数:CommunityID={0}|SysLogID={1}|T102LeafID={2}|T216LeafID={3}",
communityID, sysLogID, t102LeafID, t216LeafID),
strProcedureName);
#endregion
#region 执行数据库函数或存储过程
try
{
using (IRAPSQLConnection conn = new IRAPSQLConnection())
{
string strSQL = "SELECT * " +
"FROM IRAPMDM..ufn_GetList_Symbols_Inspecting(" +
"@CommunityID, @SysLogID, @T102LeafID, @T216LeafID) " +
"ORDER BY Ordinal";
IList<SymbolInspecting> lstDatas =
conn.CallTableFunc<SymbolInspecting>(strSQL, paramList);
datas = lstDatas.ToList();
errCode = 0;
errText = string.Format("调用成功!共获得 {0} 条记录", datas.Count);
WriteLog.Instance.Write(errText, strProcedureName);
}
}
catch (Exception error)
{
errCode = 99000;
errText =
string.Format(
"调用 IRAPMDM..ufn_GetList_Symbols_Inspecting 函数发生异常:{0}",
error.Message);
WriteLog.Instance.Write(errText, strProcedureName);
WriteLog.Instance.Write(error.StackTrace, strProcedureName);
}
#endregion
return Json(datas);
}
finally
{
WriteLog.Instance.WriteEndSplitter(strProcedureName);
}
}
/// <summary>
/// 获取指定产品指定工序发现缺陷的根源工序
/// </summary>
/// <param name="communityID">社区标识</param>
/// <param name="sysLogID">系统登录标识</param>
/// <param name="t102LeafID">产品叶标识</param>
/// <param name="t216LeafID">工序叶标识</param>
/// <returns>List[DefectRootCause]</returns>
public IRAPJsonResult ufn_GetList_DefectRootCauses(
int communityID,
long sysLogID,
int t102LeafID,
int t216LeafID,
out int errCode,
out string errText)
{
string strProcedureName =
string.Format(
"{0}.{1}",
className,
MethodBase.GetCurrentMethod().Name);
WriteLog.Instance.WriteBeginSplitter(strProcedureName);
try
{
List<DefectRootCause> datas = new List<DefectRootCause>();
#region 创建数据库调用参数组,并赋值
IList<IDataParameter> paramList = new List<IDataParameter>();
paramList.Add(new IRAPProcParameter("@CommunityID", DbType.Int32, communityID));
paramList.Add(new IRAPProcParameter("@SysLogID", DbType.Int64, sysLogID));
paramList.Add(new IRAPProcParameter("@T102LeafID", DbType.Int32, t102LeafID));
paramList.Add(new IRAPProcParameter("@T216LeafID", DbType.Int32, t216LeafID));
WriteLog.Instance.Write(
string.Format(
"调用函数 IRAPMDM..ufn_GetList_DefectRootCauses," +
"参数:CommunityID={0}|SysLogID={1}|T102LeafID={2}|T216LeafID={3}",
communityID, sysLogID, t102LeafID, t216LeafID),
strProcedureName);
#endregion
#region 执行数据库函数或存储过程
try
{
using (IRAPSQLConnection conn = new IRAPSQLConnection())
{
string strSQL = "SELECT * " +
"FROM IRAPMDM..ufn_GetList_DefectRootCauses(" +
"@CommunityID, @SysLogID, @T102LeafID, @T216LeafID) " +
"ORDER BY Ordinal";
IList<DefectRootCause> lstDatas =
conn.CallTableFunc<DefectRootCause>(strSQL, paramList);
datas = lstDatas.ToList();
errCode = 0;
errText = string.Format("调用成功!共获得 {0} 条记录", datas.Count);
WriteLog.Instance.Write(errText, strProcedureName);
}
}
catch (Exception error)
{
errCode = 99000;
errText =
string.Format(
"调用 IRAPMDM..ufn_GetList_DefectRootCauses 函数发生异常:{0}",
error.Message);
WriteLog.Instance.Write(errText, strProcedureName);
WriteLog.Instance.Write(error.StackTrace, strProcedureName);
}
#endregion
return Json(datas);
}
finally
{
WriteLog.Instance.WriteEndSplitter(strProcedureName);
}
}
/// <summary>
/// 功能描述: 请填写本数据库对象功能的简要描述
/// ⒈ 获取指定生产线或工作中心的可用班次清单供选择
/// </summary>
/// <param name="communityID">社区标识</param>
/// <param name="treeID">树标识(134-产线 211-工作中心)</param>
/// <param name="leafID">产线或工作中心叶标识</param>
/// <param name="sysLogID">系统登录标识</param>
/// <returns>List[Shift]</returns>
public IRAPJsonResult ufn_GetList_ShiftsOfAMFGRSC(
int communityID,
int treeID,
int leafID,
long sysLogID,
out int errCode,
out string errText)
{
string strProcedureName =
string.Format(
"{0}.{1}",
className,
MethodBase.GetCurrentMethod().Name);
WriteLog.Instance.WriteBeginSplitter(strProcedureName);
try
{
List<Shift> datas = new List<Shift>();
#region 创建数据库调用参数组,并赋值
IList<IDataParameter> paramList = new List<IDataParameter>();
paramList.Add(new IRAPProcParameter("@CommunityID", DbType.Int32, communityID));
paramList.Add(new IRAPProcParameter("@TreeID", DbType.Int32, treeID));
paramList.Add(new IRAPProcParameter("@LeafID", DbType.Int32, leafID));
paramList.Add(new IRAPProcParameter("@SysLogID", DbType.Int64, sysLogID));
WriteLog.Instance.Write(
string.Format(
"调用函数 IRAPMDM..ufn_GetList_ShiftsOfAMFGRSC," +
"参数:CommunityID={0}|TreeID={1}|LeafID={2}|SysLogID={3}",
communityID, treeID, leafID, sysLogID),
strProcedureName);
#endregion
#region 执行数据库函数或存储过程
try
{
using (IRAPSQLConnection conn = new IRAPSQLConnection())
{
string strSQL = "SELECT * " +
"FROM IRAPMDM..ufn_GetList_ShiftsOfAMFGRSC(" +
"@CommunityID, @TreeID, @LeafID, @SysLogID) " +
"ORDER BY Ordinal";
IList<Shift> lstDatas =
conn.CallTableFunc<Shift>(strSQL, paramList);
datas = lstDatas.ToList();
errCode = 0;
errText = string.Format("调用成功!共获得 {0} 条记录", datas.Count);
WriteLog.Instance.Write(errText, strProcedureName);
}
}
catch (Exception error)
{
errCode = 99000;
errText =
string.Format(
"调用 IRAPMDM..ufn_GetList_ShiftsOfAMFGRSC 函数发生异常:{0}",
error.Message);
WriteLog.Instance.Write(errText, strProcedureName);
WriteLog.Instance.Write(error.StackTrace, strProcedureName);
}
#endregion
return Json(datas);
}
finally
{
WriteLog.Instance.WriteEndSplitter(strProcedureName);
}
}
/// <summary>
/// 获取当前产品当前工序前面所有制造工序清单
/// </summary>
/// <param name="communityID">社区标识</param>
/// <param name="t102LeafID">产品叶标识</param>
/// <param name="t107LeafID">工位叶标识</param>
/// <param name="refUnixTime">参考的Unix时间</param>
/// <param name="sysLogID">系统登录标识</param>
public IRAPJsonResult ufn_GetList_PrevMFGOperations(
int communityID,
int t102LeafID,
int t107LeafID,
int refUnixTime,
long sysLogID,
out int errCode,
out string errText)
{
string strProcedureName =
string.Format(
"{0}.{1}",
className,
MethodBase.GetCurrentMethod().Name);
WriteLog.Instance.WriteBeginSplitter(strProcedureName);
try
{
List<MFGOperation> datas = new List<MFGOperation>();
#region 创建数据库调用参数组,并赋值
IList<IDataParameter> paramList = new List<IDataParameter>();
paramList.Add(new IRAPProcParameter("@CommunityID", DbType.Int32, communityID));
paramList.Add(new IRAPProcParameter("@T102LeafID", DbType.Int32, t102LeafID));
paramList.Add(new IRAPProcParameter("@T107LeafID", DbType.Int32, t107LeafID));
paramList.Add(new IRAPProcParameter("@RefUnixTime", DbType.Int32, refUnixTime));
paramList.Add(new IRAPProcParameter("@SysLogID", DbType.Int64, sysLogID));
WriteLog.Instance.Write(
string.Format(
"调用函数 IRAPMDM..ufn_GetList_PrevMFGOperations," +
"参数:CommunityID={0}|T102LeafID={1}|T107LeafID={2}"+
"RefUnixTime={3}|SysLogID={4}",
communityID, t102LeafID, t107LeafID,
refUnixTime, sysLogID),
strProcedureName);
#endregion
#region 执行数据库函数或存储过程
try
{
using (IRAPSQLConnection conn = new IRAPSQLConnection())
{
string strSQL = "SELECT * " +
"FROM IRAPMDM..ufn_GetList_PrevMFGOperations(" +
"@CommunityID, @T102LeafID, @T107LeafID, "+
"@RefUnixTime, @SysLogID) " +
"ORDER BY Ordinal";
IList<MFGOperation> lstDatas =
conn.CallTableFunc<MFGOperation>(strSQL, paramList);
datas = lstDatas.ToList();
errCode = 0;
errText = string.Format("调用成功!共获得 {0} 条记录", datas.Count);
WriteLog.Instance.Write(errText, strProcedureName);
}
}
catch (Exception error)
{
errCode = 99000;
errText =
string.Format(
"调用 IRAPMDM..ufn_GetList_PrevMFGOperations 函数发生异常:{0}",
error.Message);
WriteLog.Instance.Write(errText, strProcedureName);
WriteLog.Instance.Write(error.StackTrace, strProcedureName);
}
#endregion
return Json(datas);
}
finally
{
WriteLog.Instance.WriteEndSplitter(strProcedureName);
}
}
/// <summary>
/// 获取工序标准周期时间
/// </summary>
/// <param name="communityID">社区标识</param>
/// <param name="t102LeafID">产品叶标识</param>
/// <param name="t107LeafID">工位叶标识</param>
public IRAPJsonResult ufn_GetStdCycleTimeOfOperation(
int communityID,
int t102LeafID,
int t107LeafID,
out int errCode,
out string errText)
{
string strProcedureName =
string.Format(
"{0}.{1}",
className,
MethodBase.GetCurrentMethod().Name);
WriteLog.Instance.WriteBeginSplitter(strProcedureName);
try
{
#region 创建数据库调用参数组,并赋值
IList<IDataParameter> paramList = new List<IDataParameter>();
paramList.Add(new IRAPProcParameter("@CommunityID", DbType.Int32, communityID));
paramList.Add(new IRAPProcParameter("@T102LeafID", DbType.Int32, t102LeafID));
paramList.Add(new IRAPProcParameter("@T107LeafID", DbType.Int32, t107LeafID));
WriteLog.Instance.Write(
string.Format(
"调用函数 IRAPMDM.dbo.ufn_GetStdCycleTimeOfOperation,"+
"参数:CommunityID={0}|T102LeafID={1}|T107LeafID={2}",
communityID,
t102LeafID,
t107LeafID),
strProcedureName);
#endregion
#region 执行数据库函数或存储过程
try
{
using (IRAPSQLConnection conn = new IRAPSQLConnection())
{
long rlt =
(long)conn.CallScalarFunc(
"IRAPMDM.dbo.ufn_GetStdCycleTimeOfOperation",
paramList);
errCode = 0;
errText = "调用成功!";
WriteLog.Instance.Write(errText, strProcedureName);
return Json(rlt);
}
}
catch (Exception error)
{
errCode = 99000;
errText =
string.Format(
"调用 IRAPMDM.dbo.ufn_GetStdCycleTimeOfOperation 函数发生异常:{0}",
error.Message);
WriteLog.Instance.Write(errText, strProcedureName);
WriteLog.Instance.Write(error.StackTrace, strProcedureName);
return Json(0);
}
#endregion
}
finally
{
WriteLog.Instance.WriteEndSplitter(strProcedureName);
}
}
/// <summary>
/// 根据物料号(原材料/半成品/产成品)获取材质
/// </summary>
/// <param name="communityID">社区标识</param>
/// <param name="materialCode">物料号(原材料/半成品/产成品)</param>
/// <param name="errCode"></param>
/// <param name="errText"></param>
/// <returns>string</returns>
public IRAPJsonResult ufn_GetMaterialTextureCodeFromERP_FourthShift(
int communityID,
string materialCode,
out int errCode,
out string errText)
{
string strProcedureName =
string.Format(
"{0}.{1}",
className,
MethodBase.GetCurrentMethod().Name);
WriteLog.Instance.WriteBeginSplitter(strProcedureName);
try
{
#region 创建数据库调用参数组,并赋值
IList<IDataParameter> paramList = new List<IDataParameter>();
paramList.Add(new IRAPProcParameter("@CommunityID", DbType.Int32, communityID));
paramList.Add(new IRAPProcParameter("@MaterialCode", DbType.String, materialCode));
WriteLog.Instance.Write(
string.Format(
"调用函数 IRAPDPA.dbo.ufn_GetMaterialTextureCodeFromERP_FourthShift," +
"参数:CommunityID={0}|MaterialCode={1}",
communityID,
materialCode),
strProcedureName);
#endregion
#region 执行数据库函数或存储过程
try
{
using (IRAPSQLConnection conn = new IRAPSQLConnection())
{
string rlt =
(string)conn.CallScalarFunc(
"IRAPDPA.dbo.ufn_GetMaterialTextureCodeFromERP_FourthShift",
paramList);
errCode = 0;
errText = "调用成功!";
WriteLog.Instance.Write(errText, strProcedureName);
return Json(rlt);
}
}
catch (Exception error)
{
errCode = 99000;
errText =
string.Format(
"调用 IRAPDPA.dbo.ufn_GetMaterialTextureCodeFromERP_FourthShift 函数发生异常:{0}",
error.Message);
WriteLog.Instance.Write(errText, strProcedureName);
WriteLog.Instance.Write(error.StackTrace, strProcedureName);
return Json(0);
}
#endregion
}
finally
{
WriteLog.Instance.WriteEndSplitter(strProcedureName);
}
}
/// <summary>
/// 获取指定产品叶标识的产品类别 T133
/// </summary>
/// <param name="communityID">社区标识</param>
/// <param name="t216LeafID">工序叶标识</param>
/// <param name="t102LeafID">产品叶标识</param>
/// <param name="sysLogID">系统登录标识</param>
/// <param name="errCode"></param>
/// <param name="errText"></param>
/// <returns>List[BatchRingCategory]</returns>
public IRAPJsonResult ufn_GetList_BatchRingCategory(
int communityID,
int t216LeafID,
int t102LeafID,
long sysLogID,
out int errCode,
out string errText)
{
string strProcedureName =
string.Format(
"{0}.{1}",
className,
MethodBase.GetCurrentMethod().Name);
WriteLog.Instance.WriteBeginSplitter(strProcedureName);
try
{
List<BatchRingCategory> datas = new List<BatchRingCategory>();
#region 创建数据库调用参数组,并赋值
IList<IDataParameter> paramList = new List<IDataParameter>();
paramList.Add(new IRAPProcParameter("@CommunityID", DbType.Int32, communityID));
paramList.Add(new IRAPProcParameter("@T216LeafID", DbType.Int32, t216LeafID));
paramList.Add(new IRAPProcParameter("@T102LeafID", DbType.Int32, t102LeafID));
paramList.Add(new IRAPProcParameter("@SysLogID", DbType.Int64, sysLogID));
WriteLog.Instance.Write(
string.Format(
"调用函数 IRAPMDM..ufn_GetList_BatchRingCategory," +
"参数:CommunityID={0}|T216LeafID={1}|T102LeafID={2}|"+
"SysLogID={3}",
communityID, t216LeafID, t102LeafID, sysLogID),
strProcedureName);
#endregion
#region 执行数据库函数或存储过程
try
{
using (IRAPSQLConnection conn = new IRAPSQLConnection())
{
string strSQL = "SELECT * " +
"FROM IRAPMDM..ufn_GetList_BatchRingCategory(" +
"@CommunityID, @T216LeafID, @T102LeafID, @SysLogID) " +
"ORDER BY Ordinal";
IList<BatchRingCategory> lstDatas =
conn.CallTableFunc<BatchRingCategory>(strSQL, paramList);
datas = lstDatas.ToList();
errCode = 0;
errText = string.Format("调用成功!共获得 {0} 条记录", datas.Count);
WriteLog.Instance.Write(errText, strProcedureName);
}
}
catch (Exception error)
{
errCode = 99000;
errText =
string.Format(
"调用 IRAPMDM..ufn_GetList_BatchRingCategory 函数发生异常:{0}",
error.Message);
WriteLog.Instance.Write(errText, strProcedureName);
WriteLog.Instance.Write(error.StackTrace, strProcedureName);
}
#endregion
return Json(datas);
}
finally
{
WriteLog.Instance.WriteEndSplitter(strProcedureName);
}
}
/// <summary>
/// 获取指定工序、环别、炉次号的过程参数项目及过程参数记录值
/// </summary>
/// <param name="communityID">社区标识</param>
/// <param name="t131LeafID">环别叶标识</param>
/// <param name="t216LeafID">工序叶标识</param>
/// <param name="batchNumber">炉次号</param>
/// <param name="sysLogID">系统登录标识</param>
/// <param name="errCode"></param>
/// <param name="errText"></param>
/// <returns>List{ProductionProcessParam]</returns>
public IRAPJsonResult ufn_GetList_MethodItems(
int communityID,
int t131LeafID,
int t216LeafID,
string batchNumber,
long sysLogID,
out int errCode,
out string errText)
{
string strProcedureName =
string.Format(
"{0}.{1}",
className,
MethodBase.GetCurrentMethod().Name);
WriteLog.Instance.WriteBeginSplitter(strProcedureName);
try
{
List<ProductionProcessParam> datas =
new List<ProductionProcessParam>();
#region 创建数据库调用参数组,并赋值
IList<IDataParameter> paramList = new List<IDataParameter>();
paramList.Add(new IRAPProcParameter("@CommunityID", DbType.Int32, communityID));
paramList.Add(new IRAPProcParameter("@T131LeafID", DbType.Int32, t131LeafID));
paramList.Add(new IRAPProcParameter("@T216LeafID", DbType.Int32, t216LeafID));
paramList.Add(new IRAPProcParameter("@BatchNumber", DbType.String, batchNumber));
paramList.Add(new IRAPProcParameter("@SysLogID", DbType.Int64, sysLogID));
WriteLog.Instance.Write(
string.Format(
"调用函数 IRAPMDM..ufn_GetList_MethodItems," +
"参数:CommunityID={0}|T131LeafID={1}|T216LeafID={2}|"+
"BatchNumber={3}|SysLogID={4}",
communityID, t131LeafID, t216LeafID, batchNumber, sysLogID),
strProcedureName);
#endregion
#region 执行数据库函数或存储过程
try
{
using (IRAPSQLConnection conn = new IRAPSQLConnection())
{
string strSQL = "SELECT * " +
"FROM IRAPMDM..ufn_GetList_MethodItems(" +
"@CommunityID, @T131LeafID, @T216LeafID, "+
"@BatchNumber, @SysLogID) " +
"ORDER BY Ordinal";
IList<ProductionProcessParam> lstDatas =
conn.CallTableFunc<ProductionProcessParam>(strSQL, paramList);
datas = lstDatas.ToList();
errCode = 0;
errText = string.Format("调用成功!共获得 {0} 条记录", datas.Count);
WriteLog.Instance.Write(errText, strProcedureName);
}
}
catch (Exception error)
{
errCode = 99000;
errText =
string.Format(
"调用 IRAPMDM..ufn_GetList_MethodItems 函数发生异常:{0}",
error.Message);
WriteLog.Instance.Write(errText, strProcedureName);
WriteLog.Instance.Write(error.StackTrace, strProcedureName);
}
#endregion
return Json(datas);
}
finally
{
WriteLog.Instance.WriteEndSplitter(strProcedureName);
}
}
/// <summary>
/// 获取质量检验项目及检验项目记录值
/// </summary>
/// <param name="communityID">社区标识</param>
/// <param name="t102LeafID">产品叶标识</param>
/// <param name="t216LeafID">工序叶标识</param>
/// <param name="pwoNo">工单号</param>
/// <param name="batchNumber">容次号</param>
/// <param name="sysLogID">系统登录标识</param>
/// <param name="errCode"></param>
/// <param name="errText"></param>
/// <returns>List[InspectionItem]</returns>
public IRAPJsonResult ufn_GetList_InspectionItems(
int communityID,
int t102LeafID,
int t216LeafID,
string pwoNo,
string batchNumber,
long sysLogID,
out int errCode,
out string errText)
{
string strProcedureName =
string.Format(
"{0}.{1}",
className,
MethodBase.GetCurrentMethod().Name);
WriteLog.Instance.WriteBeginSplitter(strProcedureName);
try
{
List<InspectionItem> datas =
new List<InspectionItem>();
#region 创建数据库调用参数组,并赋值
IList<IDataParameter> paramList = new List<IDataParameter>();
paramList.Add(new IRAPProcParameter("@CommunityID", DbType.Int32, communityID));
paramList.Add(new IRAPProcParameter("@T102LeafID", DbType.Int32, t102LeafID));
paramList.Add(new IRAPProcParameter("@T216LeafID", DbType.Int32, t216LeafID));
paramList.Add(new IRAPProcParameter("@PWONo", DbType.String, pwoNo));
paramList.Add(new IRAPProcParameter("@BatchNumber", DbType.String, batchNumber));
paramList.Add(new IRAPProcParameter("@SysLogID", DbType.Int64, sysLogID));
WriteLog.Instance.Write(
string.Format(
"调用函数 IRAPMDM..ufn_GetList_InspectionItems," +
"参数:CommunityID={0}|T102LeafID={1}|T216LeafID={2}|" +
"PWONo={3}|BatchNumber={4}|SysLogID={5}",
communityID, t102LeafID, t216LeafID, pwoNo, batchNumber,
sysLogID),
strProcedureName);
#endregion
#region 执行数据库函数或存储过程
try
{
using (IRAPSQLConnection conn = new IRAPSQLConnection())
{
string strSQL = "SELECT * " +
"FROM IRAPMDM..ufn_GetList_InspectionItems(" +
"@CommunityID, @T102LeafID, @T216LeafID, " +
"@PWONo, @BatchNumber, @SysLogID) " +
"ORDER BY Ordinal";
IList<InspectionItem> lstDatas =
conn.CallTableFunc<InspectionItem>(strSQL, paramList);
datas = lstDatas.ToList();
errCode = 0;
errText = string.Format("调用成功!共获得 {0} 条记录", datas.Count);
WriteLog.Instance.Write(errText, strProcedureName);
}
}
catch (Exception error)
{
errCode = 99000;
errText =
string.Format(
"调用 IRAPMDM..ufn_GetList_InspectionItems 函数发生异常:{0}",
error.Message);
WriteLog.Instance.Write(errText, strProcedureName);
WriteLog.Instance.Write(error.StackTrace, strProcedureName);
}
#endregion
return Json(datas);
}
finally
{
WriteLog.Instance.WriteEndSplitter(strProcedureName);
}
}
/// <summary>
/// 获取工位清单
/// </summary>
/// <param name="communityID">社区标识</param>
/// <param name="t134LeafID">产线叶标识:0-全部;负数-指定车间或工厂或公司;正数-指定产线</param>
/// <param name="t102LeafID">产品叶标识:0-全部</param>
/// <param name="sysLogID">系统登录标识</param>
public IRAPJsonResult ufn_GetList_WorkUnits(
int communityID,
int t134LeafID,
int t102LeafID,
long sysLogID,
out int errCode,
out string errText)
{
string strProcedureName =
string.Format(
"{0}.{1}",
className,
MethodBase.GetCurrentMethod().Name);
WriteLog.Instance.WriteBeginSplitter(strProcedureName);
try
{
List<WorkUnit> datas =
new List<WorkUnit>();
#region 创建数据库调用参数组,并赋值
IList<IDataParameter> paramList = new List<IDataParameter>();
paramList.Add(new IRAPProcParameter("@CommunityID", DbType.Int32, communityID));
paramList.Add(new IRAPProcParameter("@T134LeafID", DbType.Int32, t134LeafID));
paramList.Add(new IRAPProcParameter("@T102LeafID", DbType.Int32, t102LeafID));
paramList.Add(new IRAPProcParameter("@SysLogID", DbType.Int64, sysLogID));
WriteLog.Instance.Write(
string.Format(
"调用函数 IRAPMDM..ufn_GetList_WorkUnits," +
"参数:CommunityID={0}|T134LeafID={1}|T102LeafID={2}|" +
"SysLogID={3}",
communityID, t134LeafID, t102LeafID, sysLogID),
strProcedureName);
#endregion
#region 执行数据库函数或存储过程
try
{
using (IRAPSQLConnection conn = new IRAPSQLConnection())
{
string strSQL = "SELECT * " +
"FROM IRAPMDM..ufn_GetList_WorkUnits(" +
"@CommunityID, @T134LeafID, @T102LeafID, " +
"@SysLogID) " +
"ORDER BY Ordinal";
IList<WorkUnit> lstDatas =
conn.CallTableFunc<WorkUnit>(strSQL, paramList);
datas = lstDatas.ToList();
errCode = 0;
errText = string.Format("调用成功!共获得 {0} 条记录", datas.Count);
WriteLog.Instance.Write(errText, strProcedureName);
}
}
catch (Exception error)
{
errCode = 99000;
errText =
string.Format(
"调用 IRAPMDM..ufn_GetList_WorkUnits 函数发生异常:{0}",
error.Message);
WriteLog.Instance.Write(errText, strProcedureName);
WriteLog.Instance.Write(error.StackTrace, strProcedureName);
}
#endregion
return Json(datas);
}
finally
{
WriteLog.Instance.WriteEndSplitter(strProcedureName);
}
}
/// <summary>
/// 获取当前版本工位装料表
/// </summary>
/// <param name="communityID">社区标识</param>
/// <param name="t102LeafID">产品叶标识</param>
/// <param name="t107LeafID">工位叶标识</param>
/// <param name="sysLogID">系统登录标识</param>
public IRAPJsonResult ufn_GetLoadingSheet_Current(
int communityID,
int t102LeafID,
int t107LeafID,
long sysLogID,
out int errCode,
out string errText)
{
string strProcedureName =
string.Format(
"{0}.{1}",
className,
MethodBase.GetCurrentMethod().Name);
WriteLog.Instance.WriteBeginSplitter(strProcedureName);
try
{
List<CurrentLoadingSheetItem> datas =
new List<CurrentLoadingSheetItem>();
#region 创建数据库调用参数组,并赋值
IList<IDataParameter> paramList = new List<IDataParameter>();
paramList.Add(new IRAPProcParameter("@CommunityID", DbType.Int32, communityID));
paramList.Add(new IRAPProcParameter("@T102LeafID", DbType.Int32, t102LeafID));
paramList.Add(new IRAPProcParameter("@T107LeafID", DbType.Int32, t107LeafID));
paramList.Add(new IRAPProcParameter("@SysLogID", DbType.Int64, sysLogID));
WriteLog.Instance.Write(
string.Format(
"调用函数 IRAPMDM..ufn_GetLoadingSheet_Current," +
"参数:CommunityID={0}|T102LeafID={1}|T107LeafID={2}|" +
"SysLogID={3}",
communityID, t102LeafID, t107LeafID, sysLogID),
strProcedureName);
#endregion
#region 执行数据库函数或存储过程
try
{
using (IRAPSQLConnection conn = new IRAPSQLConnection())
{
string strSQL = "SELECT * " +
"FROM IRAPMDM..ufn_GetLoadingSheet_Current(" +
"@CommunityID, @T102LeafID, @T107LeafID, " +
"@SysLogID) " +
"ORDER BY Ordinal";
IList<CurrentLoadingSheetItem> lstDatas =
conn.CallTableFunc<CurrentLoadingSheetItem>(strSQL, paramList);
datas = lstDatas.ToList();
errCode = 0;
errText = string.Format("调用成功!共获得 {0} 条记录", datas.Count);
WriteLog.Instance.Write(errText, strProcedureName);
}
}
catch (Exception error)
{
errCode = 99000;
errText =
string.Format(
"调用 IRAPMDM..ufn_GetLoadingSheet_Current 函数发生异常:{0}",
error.Message);
WriteLog.Instance.Write(errText, strProcedureName);
WriteLog.Instance.Write(error.StackTrace, strProcedureName);
}
#endregion
return Json(datas);
}
finally
{
WriteLog.Instance.WriteEndSplitter(strProcedureName);
}
}
/// <summary>
/// 获取铸环车间熔炼工序的检验项及检验值
/// </summary>
/// <param name="communityID">社区标识</param>
/// <param name="opType">熔炼操作代码</param>
/// <param name="t102LeafID">环别叶标识</param>
/// <param name="t216LeafID">工序叶标识</param>
/// <param name="pwoNo">工单号</param>
/// <param name="batchNumber">设备生产批次号</param>
/// <param name="sysLogID">系统登录标识</param>
/// <returns></returns>
public IRAPJsonResult ufn_GetList_SmeltInspectionItems(
int communityID,
string opType,
int t102LeafID,
int t216LeafID,
string pwoNo,
string batchNumber,
long sysLogID,
out int errCode,
out string errText)
{
string strProcedureName =
string.Format(
"{0}.{1}",
className,
MethodBase.GetCurrentMethod().Name);
WriteLog.Instance.WriteBeginSplitter(strProcedureName);
try
{
List<SmeltInspectionItem> datas =
new List<SmeltInspectionItem>();
#region 创建数据库调用参数组,并赋值
IList<IDataParameter> paramList = new List<IDataParameter>();
paramList.Add(new IRAPProcParameter("@CommunityID", DbType.Int32, communityID));
paramList.Add(new IRAPProcParameter("@OpType", DbType.String, opType));
paramList.Add(new IRAPProcParameter("@T102LeafID", DbType.Int32, t102LeafID));
paramList.Add(new IRAPProcParameter("@T216LeafID", DbType.Int32, t216LeafID));
paramList.Add(new IRAPProcParameter("@PWONo", DbType.String, pwoNo));
paramList.Add(new IRAPProcParameter("@BatchNumber", DbType.String, batchNumber));
paramList.Add(new IRAPProcParameter("@SysLogID", DbType.Int64, sysLogID));
WriteLog.Instance.Write(
string.Format(
"调用函数 IRAPMDM..ufn_GetList_SmeltInspectionItems," +
"参数:CommunityID={0}|OpType={1}|T102LeafID={2}|"+
"T216LeafID={2}|PWONo={3}|BatchNumber={4}|SysLogID={5}",
communityID, opType, t102LeafID, t216LeafID, pwoNo, batchNumber, sysLogID),
strProcedureName);
#endregion
#region 执行数据库函数或存储过程
try
{
using (IRAPSQLConnection conn = new IRAPSQLConnection())
{
string strSQL = "SELECT * " +
"FROM IRAPMDM..ufn_GetList_SmeltInspectionItems(" +
"@CommunityID, @OpType, @T102LeafID, @T216LeafID, " +
"@PWONo, @BatchNumber, @SysLogID) " +
"ORDER BY Ordinal";
IList<SmeltInspectionItem> lstDatas =
conn.CallTableFunc<SmeltInspectionItem>(strSQL, paramList);
datas = lstDatas.ToList();
errCode = 0;
errText = string.Format("调用成功!共获得 {0} 条记录", datas.Count);
WriteLog.Instance.Write(errText, strProcedureName);
}
}
catch (Exception error)
{
errCode = 99000;
errText =
string.Format(
"调用 IRAPMDM..ufn_GetList_SmeltInspectionItems 函数发生异常:{0}",
error.Message);
WriteLog.Instance.Write(errText, strProcedureName);
WriteLog.Instance.Write(error.StackTrace, strProcedureName);
}
#endregion
return Json(datas);
}
finally
{
WriteLog.Instance.WriteEndSplitter(strProcedureName);
}
}
/// <summary>
/// 根据社区标识和事实编号,获取检验报告文件内容
/// </summary>
/// <param name="communityID">社区标识</param>
/// <param name="factID">检验报表事实编号</param>
/// <param name="sysLogID"></param>
/// <param name="errCode"></param>
/// <param name="errText"></param>
/// <returns></returns>
public IRAPJsonResult ufn_GetList_BatchIDC_IQCReport(
int communityID,
long factID,
long sysLogID,
out int errCode,
out string errText)
{
string strProcedureName =
string.Format(
"{0}.{1}",
className,
MethodBase.GetCurrentMethod().Name);
WriteLog.Instance.WriteBeginSplitter(strProcedureName);
try
{
List<BatchIQCReport> datas = new List<BatchIQCReport>();
#region 创建数据库调用参数组,并赋值
IList<IDataParameter> paramList = new List<IDataParameter>();
paramList.Add(new IRAPProcParameter("@CommunityID", DbType.Int32, communityID));
paramList.Add(new IRAPProcParameter("@FactID", DbType.Int64, factID));
paramList.Add(new IRAPProcParameter("@SysLogID", DbType.Int64, sysLogID));
WriteLog.Instance.Write(
string.Format(
"调用函数 IRAPMDM..ufn_GetList_BatchIDC_IQCReport," +
"参数:CommunityID={0}|FactID={1}|SysLogID={2}",
communityID, factID, sysLogID),
strProcedureName);
#endregion
#region 执行数据库函数或存储过程
try
{
using (IRAPSQLConnection conn = new IRAPSQLConnection())
{
string strSQL = "SELECT * " +
"FROM IRAPMDM..ufn_GetList_BatchIDC_IQCReport(" +
"@CommunityID, @FactID, @SysLogID)";
IList<BatchIQCReport> lstDatas =
conn.CallTableFunc<BatchIQCReport>(strSQL, paramList);
datas = lstDatas.ToList();
errCode = 0;
errText = string.Format("调用成功!共获得 {0} 条记录", datas.Count);
WriteLog.Instance.Write(errText, strProcedureName);
}
}
catch (Exception error)
{
errCode = 99000;
errText =
string.Format(
"调用 IRAPMDM..ufn_GetList_BatchIDC_IQCReport 函数发生异常:{0}",
error.Message);
WriteLog.Instance.Write(errText, strProcedureName);
WriteLog.Instance.Write(error.StackTrace, strProcedureName);
}
#endregion
return Json(datas);
}
finally
{
WriteLog.Instance.WriteEndSplitter(strProcedureName);
}
}
/// <summary>
/// 获取未显示设备清单
/// </summary>
/// <param name="communityID">社区标识</param>
/// <param name="sysLogID">系统登录标识</param>
/// <returns>List[StationEquipment]</returns>
public IRAPJsonResult ufn_GetList_NotOnStationEquipment(
int communityID,
long sysLogID,
out int errCode,
out string errText)
{
string strProcedureName =
string.Format(
"{0}.{1}",
className,
MethodBase.GetCurrentMethod().Name);
WriteLog.Instance.WriteBeginSplitter(strProcedureName);
try
{
List<StationEquipment> datas = new List<StationEquipment>();
#region 创建数据库调用参数组,并赋值
IList<IDataParameter> paramList = new List<IDataParameter>();
paramList.Add(new IRAPProcParameter("@CommunityID", DbType.Int32, communityID));
paramList.Add(new IRAPProcParameter("@SysLogID", DbType.Int64, sysLogID));
WriteLog.Instance.Write(
string.Format(
"调用函数 IRAPMDM..ufn_GetList_NotOnStationEquipment," +
"参数:CommunityID={0}|SysLogID={1}",
communityID,
sysLogID),
strProcedureName);
#endregion
#region 执行数据库函数或存储过程
try
{
using (IRAPSQLConnection conn = new IRAPSQLConnection())
{
string strSQL =
"SELECT * " +
"FROM IRAPMDM..ufn_GetList_NotOnStationEquipment(" +
"@CommunityID, @SysLogID) ORDER BY Ordinal";
WriteLog.Instance.Write(strSQL, strProcedureName);
IList<StationEquipment> lstDatas =
conn.CallTableFunc<StationEquipment>(strSQL, paramList);
datas = lstDatas.ToList();
errCode = 0;
errText = string.Format("调用成功!共获得 {0} 条记录", datas.Count);
WriteLog.Instance.Write(errText, strProcedureName);
}
}
catch (Exception error)
{
errCode = 99000;
errText = string.Format(
"调用 IRAPMDM..ufn_GetList_NotOnStationEquipment 函数发生异常:{0}",
error.Message);
WriteLog.Instance.Write(errText, strProcedureName);
}
#endregion
return Json(datas);
}
finally
{
WriteLog.Instance.WriteEndSplitter(strProcedureName);
}
}
/// <summary>
/// 获取已显示设备清单
/// </summary>
/// <param name="communityID">社区标识</param>
/// <param name="sysLogID">系统登录标识</param>
/// <returns>List[StationEquipment]</returns>
public IRAPJsonResult ufn_GetList_OnStationT133(
int communityID,
long sysLogID,
out int errCode,
out string errText)
{
string strProcedureName =
string.Format(
"{0}.{1}",
className,
MethodBase.GetCurrentMethod().Name);
WriteLog.Instance.WriteBeginSplitter(strProcedureName);
try
{
List<StationEquipment> datas = new List<StationEquipment>();
#region 创建数据库调用参数组,并赋值
IList<IDataParameter> paramList = new List<IDataParameter>();
paramList.Add(new IRAPProcParameter("@CommunityID", DbType.Int32, communityID));
paramList.Add(new IRAPProcParameter("@SysLogID", DbType.Int64, sysLogID));
WriteLog.Instance.Write(
string.Format(
"调用函数 IRAPMDM..ufn_GetList_OnStationT133," +
"参数:CommunityID={0}|SysLogID={1}",
communityID,
sysLogID),
strProcedureName);
#endregion
#region 执行数据库函数或存储过程
try
{
using (IRAPSQLConnection conn = new IRAPSQLConnection())
{
string strSQL =
"SELECT * " +
"FROM IRAPMDM..ufn_GetList_OnStationT133(" +
"@CommunityID, @SysLogID) ORDER BY Ordinal";
WriteLog.Instance.Write(strSQL, strProcedureName);
IList<StationEquipment> lstDatas =
conn.CallTableFunc<StationEquipment>(strSQL, paramList);
datas = lstDatas.ToList();
errCode = 0;
errText = string.Format("调用成功!共获得 {0} 条记录", datas.Count);
WriteLog.Instance.Write(errText, strProcedureName);
}
}
catch (Exception error)
{
errCode = 99000;
errText = string.Format(
"调用 IRAPMDM..ufn_GetList_OnStationT133 函数发生异常:{0}",
error.Message);
WriteLog.Instance.Write(errText, strProcedureName);
}
#endregion
return Json(datas);
}
finally
{
WriteLog.Instance.WriteEndSplitter(strProcedureName);
}
}
public IRAPJsonResult usp_SaveFact_MDVCSetting(
int communityID,
string T133XML,
long sysLogID,
out int errCode,
out string errText)
{
string strProcedureName =
string.Format(
"{0}.{1}",
className,
MethodBase.GetCurrentMethod().Name);
WriteLog.Instance.WriteBeginSplitter(strProcedureName);
try
{
#region 创建数据库调用参数组,并赋值
IList<IDataParameter> paramList = new List<IDataParameter>();
paramList.Add(new IRAPProcParameter("@CommunityID", DbType.Int32, communityID));
paramList.Add(new IRAPProcParameter("@T133XML", DbType.String, T133XML));
paramList.Add(new IRAPProcParameter("@SysLogID", DbType.Int64, sysLogID));
paramList.Add(
new IRAPProcParameter(
"@ErrCode",
DbType.Int32,
ParameterDirection.Output,
4));
paramList.Add(
new IRAPProcParameter(
"@ErrText",
DbType.String,
ParameterDirection.Output,
400));
WriteLog.Instance.Write(
string.Format("执行存储过程 IRAP..usp_SaveFact_MDVCSetting,参数:" +
"CommunityID={0}|T133XML={1}|SysLogID={2}",
communityID,T133XML,sysLogID),
strProcedureName);
#endregion
#region 执行数据库函数或存储过程
using (IRAPSQLConnection conn = new IRAPSQLConnection())
{
IRAPError error = conn.CallProc("IRAP..usp_SaveFact_MDVCSetting", ref paramList);
errCode = error.ErrCode;
errText = error.ErrText;
WriteLog.Instance.Write(
string.Format(
"({0}){1}",
errCode,
errText),
strProcedureName);
Hashtable rtnParams = new Hashtable();
if (errCode == 0)
{
foreach (IRAPProcParameter param in paramList)
{
if (param.Direction == ParameterDirection.InputOutput || param.Direction == ParameterDirection.Output)
{
if (param.DbType == DbType.Int32 && param.Value == DBNull.Value)
rtnParams.Add(param.ParameterName.Replace("@", ""), 0);
else
rtnParams.Add(param.ParameterName.Replace("@", ""), param.Value);
}
}
}
return Json(rtnParams);
}
#endregion
}
catch (Exception error)
{
errCode = 99000;
errText = string.Format("调用 IRAP..usp_SaveFact_MDVCSetting 时发生异常:{0}", error.Message);
return Json(new Hashtable());
}
finally
{
WriteLog.Instance.WriteEndSplitter(strProcedureName);
}
}
/// <summary>
/// 获取产品单杆数量
/// </summary>
/// <param name="communityID">社区标识</param>
/// <param name="productCode">产品代码</param>
/// <param name="shotTime">关注的时间点(当前版本传空串)</param>
/// <param name="sysLogID">系统登录标识</param>
public IRAPJsonResult ufn_GetList_CapacityForT101OrT102(
int communityID,
string productCode,
string shotTime,
long sysLogID,
out int errCode,
out string errText)
{
string strProcedureName =
string.Format(
"{0}.{1}",
className,
MethodBase.GetCurrentMethod().Name);
WriteLog.Instance.WriteBeginSplitter(strProcedureName);
try
{
List<CapacityForT101OrT102> datas = new List<CapacityForT101OrT102>();
#region 创建数据库调用参数组,并赋值
IList<IDataParameter> paramList = new List<IDataParameter>();
paramList.Add(new IRAPProcParameter("@CommunityID", DbType.Int32, communityID));
paramList.Add(new IRAPProcParameter("@ProductCode", DbType.String, productCode));
paramList.Add(new IRAPProcParameter("@ShotTime", DbType.String, shotTime));
paramList.Add(new IRAPProcParameter("@SysLogID", DbType.Int64, sysLogID));
WriteLog.Instance.Write(
string.Format(
"调用函数 IRAPMDM..ufn_GetList_CapacityForT101OrT102," +
"参数:CommunityID={0}|ProductCode={1}|ShotTime={2}|SysLogID={3}",
communityID,
productCode,
shotTime,
sysLogID),
strProcedureName);
#endregion
#region 执行数据库函数或存储过程
try
{
using (IRAPSQLConnection conn = new IRAPSQLConnection())
{
string strSQL =
"SELECT * " +
"FROM IRAPMDM..ufn_GetList_CapacityForT101OrT102(" +
"@CommunityID, @ProductCode, @ShotTime, @SysLogID) "+
"ORDER BY Ordinal";
WriteLog.Instance.Write(strSQL, strProcedureName);
IList<CapacityForT101OrT102> lstDatas =
conn.CallTableFunc<CapacityForT101OrT102>(strSQL, paramList);
datas = lstDatas.ToList();
errCode = 0;
errText = string.Format("调用成功!共获得 {0} 条记录", datas.Count);
WriteLog.Instance.Write(errText, strProcedureName);
}
}
catch (Exception error)
{
errCode = 99000;
errText = string.Format(
"调用 IRAPMDM..ufn_GetList_CapacityForT101OrT102 函数发生异常:{0}",
error.Message);
WriteLog.Instance.Write(errText, strProcedureName);
}
#endregion
return Json(datas);
}
finally
{
WriteLog.Instance.WriteEndSplitter(strProcedureName);
}
}
/// <summary>
/// 保存指定产品的单杆数量
/// </summary>
/// <param name="communityID">社区标识</param>
/// <param name="attrChangeXML">属性变更 XML ,格式:
/// [ROOT][MDM T157LeafID="" TreeID="101/102" LeafID="" StdQty="" /][/ROOT]
/// </param>
public IRAPJsonResult usp_SaveRSAttr_T157RX(
int communityID,
string attrChangeXML,
long sysLogID,
out int errCode,
out string errText)
{
string strProcedureName =
string.Format(
"{0}.{1}",
className,
MethodBase.GetCurrentMethod().Name);
WriteLog.Instance.WriteBeginSplitter(strProcedureName);
try
{
#region 创建数据库调用参数组,并赋值
IList<IDataParameter> paramList = new List<IDataParameter>();
paramList.Add(new IRAPProcParameter("@CommunityID", DbType.Int32, communityID));
paramList.Add(new IRAPProcParameter("@AttrChangeXML", DbType.String, attrChangeXML));
paramList.Add(new IRAPProcParameter("@SysLogID", DbType.Int64, sysLogID));
paramList.Add(
new IRAPProcParameter(
"@ErrCode",
DbType.Int32,
ParameterDirection.Output,
4));
paramList.Add(
new IRAPProcParameter(
"@ErrText",
DbType.String,
ParameterDirection.Output,
400));
WriteLog.Instance.Write(
string.Format("执行存储过程 IRAPMDM..usp_SaveRSAttr_T157RX,参数:" +
"CommunityID={0}|AttrChangeXML={1}|SysLogID={2}",
communityID, attrChangeXML, sysLogID),
strProcedureName);
#endregion
#region 执行数据库函数或存储过程
using (IRAPSQLConnection conn = new IRAPSQLConnection())
{
IRAPError error = conn.CallProc("IRAPMDM..usp_SaveRSAttr_T157RX", ref paramList);
errCode = error.ErrCode;
errText = error.ErrText;
WriteLog.Instance.Write(
string.Format(
"({0}){1}",
errCode,
errText),
strProcedureName);
Hashtable rtnParams = new Hashtable();
if (errCode == 0)
{
foreach (IRAPProcParameter param in paramList)
{
if (param.Direction == ParameterDirection.InputOutput ||
param.Direction == ParameterDirection.Output)
{
if (param.DbType == DbType.Int32 && param.Value == DBNull.Value)
rtnParams.Add(param.ParameterName.Replace("@", ""), 0);
else
rtnParams.Add(param.ParameterName.Replace("@", ""), param.Value);
}
}
}
return Json(rtnParams);
}
#endregion
}
catch (Exception error)
{
errCode = 99000;
errText = string.Format("调用 IRAPMDM..usp_SaveRSAttr_T157RX 时发生异常:{0}", error.Message);
return Json(new Hashtable());
}
finally
{
WriteLog.Instance.WriteEndSplitter(strProcedureName);
}
}
/// <summary>
/// 根据维修站位叶标识,获取维修模式列表
/// </summary>
/// <param name="communityID">社区标识</param>
/// <param name="t107LeafID_TS">维修站位叶标识</param>
/// <param name="sysLogID">系统登录标识</param>
/// <returns></returns>
public IRAPJsonResult ufn_GetList_ProductRepairModes(
int communityID,
int t107LeafID_TS,
long sysLogID,
out int errCode,
out string errText)
{
string strProcedureName =
string.Format(
"{0}.{1}",
className,
MethodBase.GetCurrentMethod().Name);
WriteLog.Instance.WriteBeginSplitter(strProcedureName);
try
{
List<ProductRepairMode> datas = new List<ProductRepairMode>();
#region 创建数据库调用参数组,并赋值
IList<IDataParameter> paramList = new List<IDataParameter>();
paramList.Add(new IRAPProcParameter("@CommunityID", DbType.Int32, communityID));
paramList.Add(new IRAPProcParameter("@T107LeafID_TS", DbType.Int32, t107LeafID_TS));
paramList.Add(new IRAPProcParameter("@SysLogID", DbType.Int64, sysLogID));
WriteLog.Instance.Write(
string.Format(
"调用函数 IRAPMDM..ufn_GetList_ProductRepairModes,参数:CommunityID={0}|" +
"T107LeafID_TS={1}|SysLogID={2}",
communityID, t107LeafID_TS, sysLogID),
strProcedureName);
#endregion
#region 执行数据库函数或存储过程
try
{
using (IRAPSQLConnection conn = new IRAPSQLConnection())
{
string strSQL = "SELECT * " +
"FROM IRAPMDM..ufn_GetList_ProductRepairModes(" +
"@CommunityID, @T107LeafID_TS, @SysLogID)";
IList<ProductRepairMode> lstDatas =
conn.CallTableFunc<ProductRepairMode>(strSQL, paramList);
datas = lstDatas.ToList<ProductRepairMode>();
errCode = 0;
errText = string.Format("调用成功!共获得 {0} 条记录", datas.Count);
}
}
catch (Exception error)
{
errCode = 99000;
errText =
string.Format(
"调用 IRAPMDM..ufn_GetList_ProductRepairModes 函数发生异常:{0}",
error.Message);
}
#endregion
return Json(datas);
}
finally
{
WriteLog.Instance.WriteEndSplitter(strProcedureName);
}
}
/// <summary>
/// 保存指定产品的单车棒数以及单棒数量
/// </summary>
/// <param name="communityID">社区标识</param>
/// <param name="attrChangeXML">
/// 属性变更 XML ,格式:
/// [ROOT][MDM T157LeafID="" TreeID="101/102" LeafID="" StickStdQty="" StickQty="" /][/ROOT]
/// </param>
/// <param name="sysLogID">系统登录标识</param>
public IRAPJsonResult usp_SaveRSAttr_T157R3(
int communityID,
string attrChangeXML,
long sysLogID,
out int errCode,
out string errText)
{
string strProcedureName =
string.Format(
"{0}.{1}",
className,
MethodBase.GetCurrentMethod().Name);
WriteLog.Instance.WriteBeginSplitter(strProcedureName);
try
{
#region 创建数据库调用参数组,并赋值
IList<IDataParameter> paramList = new List<IDataParameter>();
paramList.Add(new IRAPProcParameter("@CommunityID", DbType.Int32, communityID));
paramList.Add(new IRAPProcParameter("@AttrChangeXML", DbType.String, attrChangeXML));
paramList.Add(new IRAPProcParameter("@SysLogID", DbType.Int64, sysLogID));
paramList.Add(
new IRAPProcParameter(
"@ErrCode",
DbType.Int32,
ParameterDirection.Output,
4));
paramList.Add(
new IRAPProcParameter(
"@ErrText",
DbType.String,
ParameterDirection.Output,
400));
WriteLog.Instance.Write(
string.Format("执行存储过程 IRAPMDM..usp_SaveRSAttr_T157R3,参数:" +
"CommunityID={0}|AttrChangeXML={1}|SysLogID={2}",
communityID, attrChangeXML, sysLogID),
strProcedureName);
#endregion
#region 执行数据库函数或存储过程
using (IRAPSQLConnection conn = new IRAPSQLConnection())
{
IRAPError error = conn.CallProc("IRAPMDM..usp_SaveRSAttr_T157R3", ref paramList);
errCode = error.ErrCode;
errText = error.ErrText;
WriteLog.Instance.Write(
string.Format(
"({0}){1}",
errCode,
errText),
strProcedureName);
Hashtable rtnParams = new Hashtable();
if (errCode == 0)
{
foreach (IRAPProcParameter param in paramList)
{
if (param.Direction == ParameterDirection.InputOutput ||
param.Direction == ParameterDirection.Output)
{
if (param.DbType == DbType.Int32 && param.Value == DBNull.Value)
rtnParams.Add(param.ParameterName.Replace("@", ""), 0);
else
rtnParams.Add(param.ParameterName.Replace("@", ""), param.Value);
}
}
}
return Json(rtnParams);
}
#endregion
}
catch (Exception error)
{
errCode = 99000;
errText = string.Format("调用 IRAPMDM..usp_SaveRSAttr_T157R3 时发生异常:{0}", error.Message);
return Json(new Hashtable());
}
finally
{
WriteLog.Instance.WriteEndSplitter(strProcedureName);
}
}
}
} |
namespace P11Rectangles
{
using System;
using Properties;
public class Rectangles
{
public static void Main()
{
var newHtml = Resources.HTML.Replace(
"<link rel=\"stylesheet\" href=\"styles/rectangles.css\" />",
$"<style>{Resources.rectangles}</style>");
Console.WriteLine(newHtml);
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
namespace Social_Media_Exam.Classes
{
public class SystemFunc
{
public static List<Person> people = new List<Person>();
public static List<String> posts = new List<String>();
public static List<String> friends = new List<String>();
public static bool resetData()
{
try
{
File.Delete("data.csv");
people.Clear();
return true;
}
catch
{
return false;
}
}
public static bool exportData()
{
try
{
string output = "";
foreach (Person p in people)
{
string posts = string.Join(":", p.posts);
string friends = string.Join(":", p.friends);
output += p.userIdentification + "," + p.password + "," + posts + "," + friends + Environment.NewLine;
}
File.WriteAllText("data.csv", output);
return true;
}
catch
{
return false;
}
}
//reads data in
public static bool importData()
{
try
{
foreach (string line in File.ReadAllLines("data.csv"))
{
string[] linesplit = line.Split(',');
string userID = linesplit[0];
string password = linesplit[1];
List<int> postID = new List<int>();
List<string> friends = linesplit[3].Split(':').ToList<string>();
foreach (string id in linesplit[2].Split(':'))
{
postID.Add(Convert.ToInt32(id));
}
people.Add(new Person()
{
userIdentification = userID,
password = password,
posts = postID,
friends = friends
});
}
return true;
}
catch
{
return false;
}
}
}
}
|
using System;
using System.Linq;
using System.Security.Claims;
using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;
using HotelBooking.ControllerHelpers.RoomControllerHelpers.Abstract;
using HotelBooking.Models;
namespace HotelBooking.ControllerHelpers.RoomControllerHelpers.Concrete {
public class BookingHandler : IBookingHandler {
private readonly WdaContext wdaContext;
private readonly UserManager<User> userManager;
public BookingHandler(WdaContext wdaContext, UserManager<User> userManager) {
this.wdaContext = wdaContext;
this.userManager = userManager;
}
public bool TryMakeBooking(ClaimsPrincipal claimsPrincipal, int roomId, string checkInDate, string checkOutDate) {
var room = wdaContext.Room.Where(r => r.RoomId == roomId).First();
bool isBooked = wdaContext.Bookings.Include(booking => booking.Room).Where(booking => booking.Room.Equals(room) &&
booking.CheckInDate.CompareTo(checkOutDate) <= 0 &&
checkInDate.CompareTo(booking.CheckOutDate) <= 0).Any();
if (!isBooked) {
var booking = new Bookings {
UserId = userManager.GetUserAsync(claimsPrincipal).Result.UserId,
RoomId = roomId,
CheckInDate = checkInDate,
CheckOutDate = checkOutDate,
DateCreated = DateTime.Now
};
wdaContext.Bookings.Add(booking);
wdaContext.SaveChanges();
return true;
}
return false;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Net;
using System.Text;
using System.IO;
using jaytwo.Common.System;
using jaytwo.Common.Collections;
namespace jaytwo.Common.Http
{
public partial class HttpClient
{
public HttpWebResponse SubmitJson(string url, string method, NameValueCollection content)
{
var request = CreateRequest(url);
return SubmitJson(request, method, content);
}
public HttpWebResponse SubmitJson(Uri uri, string method, NameValueCollection content)
{
var request = CreateRequest(uri);
return SubmitJson(request, method, content);
}
public HttpWebResponse SubmitJson(string url, string method, NameValueCollection content, string contentType)
{
var request = CreateRequest(url);
return SubmitJson(request, method, content, contentType);
}
public HttpWebResponse SubmitJson(Uri uri, string method, NameValueCollection content, string contentType)
{
var request = CreateRequest(uri);
return SubmitJson(request, method, content, contentType);
}
public HttpWebResponse SubmitJson(HttpWebRequest request, string method, NameValueCollection content)
{
var contentDictionary = GetNameValueCollectionAsDictionaryOrNull(content);
return SubmitJson(request, method, contentDictionary);
}
public HttpWebResponse SubmitJson(HttpWebRequest request, string method, NameValueCollection content, string contentType)
{
var contentDictionary = GetNameValueCollectionAsDictionaryOrNull(content);
return SubmitJson(request, method, contentDictionary, contentType);
}
public HttpWebResponse SubmitJson(string url, string method, object content)
{
var request = CreateRequest(url);
return SubmitJson(request, method, content);
}
public HttpWebResponse SubmitJson(Uri uri, string method, object content)
{
var request = CreateRequest(uri);
return SubmitJson(request, method, content);
}
public HttpWebResponse SubmitJson(string url, string method, object content, string contentType)
{
var request = CreateRequest(url);
return SubmitJson(request, method, content, contentType);
}
public HttpWebResponse SubmitJson(Uri uri, string method, object content, string contentType)
{
var request = CreateRequest(uri);
return SubmitJson(request, method, content, contentType);
}
public HttpWebResponse SubmitJson(HttpWebRequest request, string method, object content)
{
var contentType = InternalHttpHelpers.GetContentTypeOrDefault(request, ContentType.application_json);
return SubmitJson(request, method, content, contentType);
}
public HttpWebResponse SubmitJson(HttpWebRequest request, string method, object content, string contentType)
{
var contentString = GetJsonContentStringOrNull(content);
var contentBytes = GetStringRequestContentBytesOrNull(contentString);
return Submit(request, method, contentBytes, contentType);
}
public HttpWebResponse Submit(string url, string method)
{
var request = CreateRequest(url);
return Submit(request, method);
}
public HttpWebResponse Submit(string url, string method, NameValueCollection content)
{
var request = CreateRequest(url);
return Submit(request, method, content);
}
public HttpWebResponse Submit(string url, string method, string content)
{
var request = CreateRequest(url);
return Submit(request, method, content);
}
public HttpWebResponse Submit(string url, string method, string content, string contentType)
{
var request = CreateRequest(url);
return Submit(request, method, content, contentType);
}
public HttpWebResponse Submit(string url, string method, byte[] content)
{
var request = CreateRequest(url);
return Submit(request, method, content);
}
public HttpWebResponse Submit(string url, string method, byte[] content, string contentType)
{
var request = CreateRequest(url);
return Submit(request, method, content, contentType);
}
public HttpWebResponse Submit(Uri uri, string method)
{
var request = CreateRequest(uri);
return Submit(request, method);
}
public HttpWebResponse Submit(Uri uri, string method, NameValueCollection content)
{
var request = CreateRequest(uri);
return Submit(request, method, content);
}
public HttpWebResponse Submit(Uri uri, string method, string content)
{
var request = CreateRequest(uri);
return Submit(request, method, content);
}
public HttpWebResponse Submit(Uri uri, string method, string content, string contentType)
{
var request = CreateRequest(uri);
return Submit(request, method, content, contentType);
}
public HttpWebResponse Submit(Uri uri, string method, byte[] content)
{
var request = CreateRequest(uri);
return Submit(request, method, content);
}
public HttpWebResponse Submit(Uri uri, string method, byte[] content, string contentType)
{
var request = CreateRequest(uri);
return Submit(request, method, content, contentType);
}
public HttpWebResponse Submit(HttpWebRequest request)
{
if (request == null)
{
throw new ArgumentNullException("request");
}
byte[] content = null;
return Submit(request, request.Method, content, request.ContentType);
}
public HttpWebResponse Submit(HttpWebRequest request, string method)
{
if (request == null)
{
throw new ArgumentNullException("request");
}
byte[] content = null;
return Submit(request, method, content, request.ContentType);
}
public HttpWebResponse Submit(HttpWebRequest request, string method, NameValueCollection content)
{
var contentString = GetNameValueCollectionContentStringOrNull(content);
var contentType = InternalHttpHelpers.GetContentTypeOrDefault(request, ContentType.application_x_www_form_urlencoded);
return Submit(request, method, contentString, contentType);
}
public HttpWebResponse Submit(HttpWebRequest request, string method, string content)
{
var contentType = InternalHttpHelpers.GetContentTypeOrDefault(request, ContentType.text_plain);
return Submit(request, method, content, contentType);
}
public HttpWebResponse Submit(HttpWebRequest request, string method, string content, string contentType)
{
var contentBytes = GetStringRequestContentBytesOrNull(content);
return Submit(request, method, contentBytes, contentType);
}
public HttpWebResponse Submit(HttpWebRequest request, string method, byte[] content)
{
var contentType = InternalHttpHelpers.GetContentTypeOrDefault(request, ContentType.application_octet_stream);
return Submit(request, method, content, contentType);
}
public HttpWebResponse Submit(string url, string method, Stream content)
{
var request = CreateRequest(url);
return Submit(request, method, content);
}
public HttpWebResponse Submit(string url, string method, Stream content, string contentType)
{
var request = CreateRequest(url);
return Submit(request, method, content, contentType);
}
public HttpWebResponse Submit(string url, string method, Stream content, long contentLength)
{
var request = CreateRequest(url);
return Submit(request, method, content, contentLength);
}
public HttpWebResponse Submit(string url, string method, Stream content, long contentLength, string contentType)
{
var request = CreateRequest(url);
return Submit(request, method, content, contentLength, contentType);
}
public HttpWebResponse Submit(Uri uri, string method, Stream content)
{
var request = CreateRequest(uri);
return Submit(request, method, content);
}
public HttpWebResponse Submit(Uri uri, string method, Stream content, string contentType)
{
var request = CreateRequest(uri);
return Submit(request, method, content, contentType);
}
public HttpWebResponse Submit(Uri uri, string method, Stream content, long contentLength)
{
var request = CreateRequest(uri);
return Submit(request, method, content, contentLength);
}
public HttpWebResponse Submit(Uri uri, string method, Stream content, long contentLength, string contentType)
{
var request = CreateRequest(uri);
return Submit(request, method, content, contentLength, contentType);
}
public HttpWebResponse Submit(HttpWebRequest request, string method, Stream content)
{
if (request == null)
{
throw new ArgumentNullException("request");
}
var contentLength = InternalHttpHelpers.GetContentLength(request, content);
return Submit(request, method, content, contentLength, request.ContentType);
}
public HttpWebResponse Submit(HttpWebRequest request, string method, Stream content, string contentType)
{
var contentLength = InternalHttpHelpers.GetContentLength(request, content);
return Submit(request, method, content, contentLength, contentType);
}
public HttpWebResponse Submit(HttpWebRequest request, string method, Stream content, long contentLength)
{
if (request == null)
{
throw new ArgumentNullException("request");
}
return Submit(request, method, content, contentLength, request.ContentType);
}
internal byte[] GetStringRequestContentBytesOrNull(string content)
{
if (content != null)
{
return RequestEncoding.GetBytes(content);
}
else
{
return null;
}
}
internal string GetNameValueCollectionContentStringOrNull(NameValueCollection content)
{
if (content != null)
{
return CollectionUtility.ToPercentEncodedQueryString(content);
}
else
{
return null;
}
}
internal IDictionary<string, string> GetNameValueCollectionAsDictionaryOrNull(NameValueCollection content)
{
if (content != null)
{
return CollectionUtility.ToDictionary(content);
}
else
{
return null;
}
}
internal string GetJsonContentStringOrNull(object content)
{
if (content != null)
{
return SerializeToJson(content);
}
else
{
return null;
}
}
}
}
|
using Newtonsoft.Json.Linq;
using OrgMan.API.Controllers.ControllerBase;
using OrgMan.Common.DynamicSearchService.DynamicSearchModel;
using OrgMan.Domain.Handler.Meeting;
using OrgMan.DomainContracts.Meeting;
using OrgMan.DomainObjects;
using System;
using System.Collections.Generic;
using System.Data;
using System.Net;
using System.Net.Http;
using System.Web.Http;
namespace OrgMan.API.Controllers
{
public class MeetingController : ApiControllerBase
{
[HttpGet]
[Route("api/meeting")]
public HttpResponseMessage Get([FromUri] List<SearchCriteriaDomainModel> searchCriterias = null, [FromUri]int? numberOfRows = null)
{
try
{
SearchMeetingQuery query = new SearchMeetingQuery()
{
MandatorUIDs = RequestMandatorUIDs,
SearchCriterias = searchCriterias,
NumberOfRows = numberOfRows
};
SearchMeetingQueryHandler handler = new SearchMeetingQueryHandler(query, UnityContainer);
return Request.CreateResponse(HttpStatusCode.OK, handler.Handle());
}
catch (UnauthorizedAccessException e)
{
return Request.CreateErrorResponse(HttpStatusCode.Unauthorized, e);
}
catch (DataException e)
{
return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, e);
}
catch (Exception e)
{
return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, e);
}
}
[HttpGet]
[Route("api/meeting/{uid}")]
public HttpResponseMessage Get(Guid uid)
{
try
{
GetMeetingQuery query = new GetMeetingQuery()
{
MandatorUIDs = RequestMandatorUIDs,
MeetingUID = uid
};
GetMeetingQueryHandler handler = new GetMeetingQueryHandler(query, UnityContainer);
return Request.CreateResponse(HttpStatusCode.OK, handler.Handle());
}
catch (UnauthorizedAccessException e)
{
return Request.CreateErrorResponse(HttpStatusCode.Unauthorized, e);
}
catch (DataException e)
{
return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, e);
}
catch (Exception e)
{
return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, e);
}
}
[HttpPost]
[Route("api/meeting")]
public HttpResponseMessage Post([FromBody] JObject jsonObject)
{
try
{
MeetingDetailDomainModel meetinDomainModel = jsonObject.ToObject<MeetingDetailDomainModel>();
if(meetinDomainModel == null)
{
throw new Exception("Invalid JSON Object");
}
UpdateMeetingQuery query = new UpdateMeetingQuery()
{
MandatorUIDs = RequestMandatorUIDs,
MeetingDetailDomainModel = meetinDomainModel
};
UpdateMeetingQueryHandler handler = new UpdateMeetingQueryHandler(query, UnityContainer);
return Request.CreateResponse(HttpStatusCode.OK, handler.Handle());
}
catch (UnauthorizedAccessException e)
{
return Request.CreateErrorResponse(HttpStatusCode.Unauthorized, e);
}
catch (DataException e)
{
return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, e);
}
catch (Exception e)
{
return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, e);
}
}
[HttpPut]
[Route("api/meeting")]
public HttpResponseMessage Put([FromBody] JObject jsonObject)
{
try
{
MeetingDetailDomainModel meetingDomainModel =
jsonObject.ToObject<MeetingDetailDomainModel>();
if (meetingDomainModel == null)
{
throw new Exception("Invalid JSON Object");
}
InsertMeetingQuery query = new InsertMeetingQuery()
{
MandatorUIDs = RequestMandatorUIDs,
MeetingDetailDomainModel = meetingDomainModel
};
InsertMeetingQueryHandler handler = new InsertMeetingQueryHandler(query, UnityContainer);
return Request.CreateResponse(HttpStatusCode.Accepted, handler.Handle());
}
catch (UnauthorizedAccessException e)
{
return Request.CreateErrorResponse(HttpStatusCode.Unauthorized, e);
}
catch (DataException e)
{
return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, e);
}
catch (Exception e)
{
return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, e);
}
}
[HttpDelete]
[Route("api/meeting/{uid}")]
public HttpResponseMessage Delete(Guid uid)
{
try
{
DeleteMeetingQuery query = new DeleteMeetingQuery()
{
MandatorUIDs = RequestMandatorUIDs,
MeetingUID = uid
};
DeleteMeetingQueryHandler handler = new DeleteMeetingQueryHandler(query, UnityContainer);
handler.Handle();
return Request.CreateResponse(HttpStatusCode.Accepted);
}
catch (UnauthorizedAccessException e)
{
return Request.CreateErrorResponse(HttpStatusCode.Unauthorized, e);
}
catch (DataException e)
{
return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, e);
}
catch (Exception e)
{
return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, e);
}
}
}
} |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
namespace CredNet
{
/// <summary>
/// ASCII string used by LSA
/// </summary>
[StructLayout(LayoutKind.Sequential)]
public struct LsaString : IDisposable
{
public ushort Length;
public ushort MaxLength;
public IntPtr Buffer;
public LsaString(string value)
{
Length = (ushort)value.Length;
MaxLength = Length;
Buffer = Marshal.StringToHGlobalAnsi(value);
}
public static implicit operator LsaString(string value) => new LsaString(value);
public static implicit operator string(LsaString value) => value.ToString();
public override string ToString()
{
return Marshal.PtrToStringAnsi(Buffer) ?? string.Empty;
}
public void Dispose()
{
Marshal.FreeHGlobal(Buffer);
}
}
/// <summary>
/// Unicode string used by LSA
/// </summary>
[StructLayout(LayoutKind.Sequential)]
public struct LsaStringUni : IDisposable
{
public ushort Length;
public ushort MaxLength;
public IntPtr Buffer;
public LsaStringUni(string value)
{
Length = (ushort)(value.Length * sizeof(ushort));
MaxLength = Length;
Buffer = Marshal.StringToHGlobalUni(value);
}
public static implicit operator LsaStringUni(string value) => new LsaStringUni(value);
public static implicit operator string(LsaStringUni value) => value.ToString();
public override string ToString()
{
return Marshal.PtrToStringUni(Buffer) ?? string.Empty;
}
public void Dispose()
{
Marshal.FreeHGlobal(Buffer);
}
}
public struct LsaHandle : IDisposable
{
public IntPtr Handle;
public LsaHandle(IntPtr handle)
{
Handle = handle;
}
public static implicit operator LsaHandle(IntPtr handle) => new LsaHandle(handle);
public static implicit operator IntPtr(LsaHandle handle) => handle.Handle;
public static LsaHandle ConnectUntrusted()
{
Native.LsaConnectUntrusted(out var handle);
return handle;
}
public bool IsValid()
{
return Handle != IntPtr.Zero;
}
public void Dispose()
{
Native.LsaDeregisterLogonProcess(Handle);
}
}
public class Native
{
[DllImport("secur32.dll", SetLastError = false)]
public static extern uint LsaConnectUntrusted(out IntPtr LsaHandle);
[DllImport("secur32.dll", SetLastError = false)]
public static extern IntPtr LsaDeregisterLogonProcess([In] IntPtr handle);
[DllImport("secur32.dll", SetLastError = false)]
public static extern uint LsaLookupAuthenticationPackage(IntPtr lsaHandle, ref LsaString packageName, out uint authenticationPackage);
[DllImport("advapi32.dll", SetLastError = true)]
public static extern uint LsaNtStatusToWinError(uint status);
[DllImport("kernel32.dll", SetLastError = true)]
public static extern bool GetComputerName(StringBuilder buffer, ref uint size);
[DllImport("gdi32.dll")]
public static extern bool DeleteObject(IntPtr hObject);
public static string GetComputerName(uint bufferSize = 25)
{
var buffer = new StringBuilder((int)bufferSize);
if (GetComputerName(buffer, ref bufferSize))
{
return buffer.ToString();
}
throw new Win32Exception(Marshal.GetLastWin32Error());
}
public static uint LookupAuthenticationPackage(LsaString packageName)
{
using (var handle = LsaHandle.ConnectUntrusted())
{
LsaLookupAuthenticationPackage(handle, ref packageName, out var package);
return package;
}
}
}
public enum KerbLogonSubmitType : uint
{
InteractiveLogon = 2,
SmartCardLogon = 6,
WorkstationUnlockLogon = 7,
SmartCardUnlockLogon = 8,
ProxyLogon = 9,
TicketLogon = 10,
TicketUnlockLogon = 11,
S4ULogon = 12,
CertificateLogon = 13,
CertificateS4ULogon = 14,
CertificateUnlockLogon = 15,
NoElevationLogon = 83,
LuidLogon = 84,
}
[StructLayout(LayoutKind.Sequential)]
public struct KerberosInteractiveUnlockLogon
{
public KerbLogonSubmitType SubmitType;
public LsaStringUni LogonDomainName;
public LsaStringUni Username;
public LsaStringUni Password;
public long LoginId;
}
}
|
using System;
namespace ConsoleApp
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Start Program");
IFluentInterface fluent = new FluentImplementation();
fluent.DoSomething()
.DoSomethingElse()
.ThisMethodIsNotFluent();
Console.WriteLine("End of Program");
Console.ReadLine();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Security.Cryptography;
using Libraries;
using System.Net;
using Newtonsoft.Json;
using System.Numerics;
using System.Globalization;
using Newtonsoft.Json.Linq;
namespace shamkaLEupdater
{
class LE : IDisposable
{
private string e;
private string n;
private string json_jwk_raw;
private string json_jwk;
private string thumbprint;
public string lastLocation;
public string profLocation;
public string finalize;
public string certURI;
private static readonly string JWK_HEADERPLACE_PART1 = "{\"nonce\": \"";
private static readonly string JWK_HEADERPLACE_PART2 = "\", \"alg\": \"RS256\"";//
public static readonly string pdf = "https://letsencrypt.org/documents/LE-SA-v1.1.1-August-1-2016.pdf";
public static readonly string pdf2 = "https://letsencrypt.org/documents/LE-SA-v1.2-November-15-2017.pdf";
public static readonly string acme1 = "https://acme-v01.api.letsencrypt.org/directory";
public static readonly string acme2 = "https://acme-v02.api.letsencrypt.org/directory";
private static string nonce_reply = "";
private static JObject SAPI=null;
public static Dictionary<string, string> acme1to2;
private byte[] _csr;
private keyInfo _key;
public int code;
public string details;
private static LE me=null;
public LE(){
acme1to2 = new Dictionary<string, string>();
acme1to2.Add("new-reg", "newAccount");
acme1to2.Add("new-nonce", "newNoncet");
acme1to2.Add("new-cert", "newOrder");
acme1to2.Add("revoke-cert", "revokeCert");
acme1to2.Add("key-change", "keyChange");
}
public static LE ME
{
get { return me; }
}
public static string getThumbprint() {
return me.thumbprint;
}
public static string th
{
get { return me.thumbprint; }
}
public void setKey(keyInfo key){
byte[] y = null;
if (key.pub.childs[1].childs[0].childs[0].payload[0] == 0) {
y = key.pub.childs[1].childs[0].childs[0].payload.Skip(1).ToArray();
}
else {
y = key.pub.childs[1].childs[0].childs[0].payload;
}
n = Convert.ToBase64String(y).TrimEnd('=').Replace('+', '-').Replace('/', '_');
if (key.pub.childs[1].childs[0].childs[1].payload[0] == 0)
{
y = key.pub.childs[1].childs[0].childs[1].payload.Skip(1).ToArray();
}
else
{
y = key.pub.childs[1].childs[0].childs[1].payload;
}
e = Convert.ToBase64String(y).TrimEnd('=').Replace('+', '-').Replace('/', '_');
json_jwk_raw = String.Format("{{\"e\":\"{0}\",\"kty\":\"RSA\",\"n\":\"{1}\"}}", e, n);
thumbprint = Convert.ToBase64String(SHA256.Create().ComputeHash(Encoding.UTF8.GetBytes(json_jwk_raw))).TrimEnd('=').Replace('+', '-').Replace('/', '_');
json_jwk = "{\"alg\":\"RS256\",\"jwk\":"+ json_jwk_raw + "}";
e = null;
n = null;
me = this;
_key = key;
}
public void Dispose()
{
_csr = null;
json_jwk_raw = null;
json_jwk = null;
thumbprint = null;
me = null;
}
public byte[] csr {
get { return _csr; }
set { _csr=value; }
}
static public object makeReq2(string method, object data, System.ComponentModel.BackgroundWorker worker, bool isRaw) {
if (me == null) return null;
Dictionary<string, string> api_serv = new Dictionary<string, string>();
if (worker != null) worker.ReportProgress(101, new object[] { -3, "GET_DIR.." });
if (worker != null) if (worker.CancellationPending)
{
worker.ReportProgress(101, new object[] { -3, "CANCEL" });
return null;
}
if (SAPI == null)
{
SAPI = (JObject)GET(acme2 + "?cachebuster=" + utils.getHex(MD5.Create().ComputeHash(BitConverter.GetBytes(DateTime.UtcNow.ToBinary()))), api_serv, false);
}
string url = (SAPI[method] != null) ? SAPI[method].ToObject<string>() : method;
if (nonce_reply == "" && api_serv.ContainsKey("r") && api_serv["r"] != "") nonce_reply = api_serv["r"];
if (nonce_reply == "") {
if(SAPI["newNonce"]==null) throw new Exception("Сервер: No Nonce");
api_serv.Clear();
GET(SAPI["newNonce"].ToObject<string>(), api_serv, false);
if (nonce_reply == "" && api_serv.ContainsKey("r") && api_serv["r"] != "") nonce_reply = api_serv["r"];
}
if (nonce_reply == "") throw new Exception("Сервер: No Nonce in nonce");
if (worker != null) worker.ReportProgress(101, new object[] { -3, "OK\r\ncalc protect.." });
string protect = Convert.ToBase64String(Encoding.UTF8.GetBytes((method== "revokeCert" || method== "newAccount") ?
(JWK_HEADERPLACE_PART1+ nonce_reply + "\", \"url\":\""+ url+ JWK_HEADERPLACE_PART2+ ",\"jwk\":"+ me.json_jwk_raw+"}") :
(JWK_HEADERPLACE_PART1 + nonce_reply + "\", \"url\":\"" + url + JWK_HEADERPLACE_PART2 + ",\"kid\":\"" + me.profLocation + "\"}")
)).TrimEnd('=').Replace('+', '-').Replace('/', '_');
if (worker != null) worker.ReportProgress(101, new object[] { -3, "OK\r\ncalc payload.." });
string payload = Convert.ToBase64String(Encoding.UTF8.GetBytes((data.GetType().Name != "String") ? JsonConvert.SerializeObject(data) : (string)data)).TrimEnd('=').Replace('+', '-').Replace('/', '_');
if (worker != null) worker.ReportProgress(101, new object[] { -3, "OK\r\ncalc sign.." });
string sign = Convert.ToBase64String(utils.makeSign(me._key, Encoding.UTF8.GetBytes(protect + "." + payload))).TrimEnd('=').Replace('+', '-').Replace('/', '_');
if (worker != null) worker.ReportProgress(101, new object[] { -3, "OK\r\nPOST_API.." });
string json = "{\"protected\":\"" + protect + "\"" +
",\"payload\":\"" + payload + "\"" +
",\"signature\":\"" + sign + "\"}";
if (worker != null) if (worker.CancellationPending)
{
worker.ReportProgress(101, new object[] { -3, "CANCEL" });
return null;
}
api_serv.Clear();
nonce_reply = "";
if (isRaw)
{
try
{
return POST(url, json, true, api_serv);
}
finally {
if (nonce_reply == "" && api_serv.ContainsKey("r") && api_serv["r"] != "") nonce_reply = api_serv["r"];
}
}
JObject API = (JObject)POST(url, json, false, api_serv);
if (nonce_reply == "" && api_serv.ContainsKey("r") && api_serv["r"] != "") nonce_reply = api_serv["r"];
if (worker != null) worker.ReportProgress(101, new object[] { -2, "OK" });
if (API == null)
{
if (me.code == 409)
{
worker.ReportProgress(101, new object[] { -2, "Вы уже зарегистрированы!" });
}
else if (me.code == 400) {
return JsonConvert.DeserializeObject<object>("{\"rt\":400}");
}
}
return API;
}
static public object makeReq(string method, object data, System.ComponentModel.BackgroundWorker worker, bool isRaw)
{
if (me == null) return null;
Dictionary<string, string> api_serv = new Dictionary<string, string>();
if (worker != null) worker.ReportProgress(101,new object[] { -3, "GET_DIR.." });
if (worker != null) if (worker.CancellationPending)
{
worker.ReportProgress(101, new object[] { -3, "CANCEL" });
return null;
}
JObject API = (JObject)GET(acme1 + "?cachebuster=" + utils.getHex(MD5.Create().ComputeHash(BitConverter.GetBytes(DateTime.UtcNow.ToBinary()))), api_serv, false);
if (worker != null) worker.ReportProgress(101, new object[] { -3, "OK\r\ncalc protect.." });
string protect = Convert.ToBase64String(Encoding.UTF8.GetBytes("{\"nonce\":\"" + api_serv["r"] + "\"}")).TrimEnd('=').Replace('+', '-').Replace('/', '_');
if (worker != null) worker.ReportProgress(101, new object[] { -3, "OK\r\ncalc payload.." });
string payload = Convert.ToBase64String(Encoding.UTF8.GetBytes((data.GetType().Name != "String") ? JsonConvert.SerializeObject(data) : (string)data)).TrimEnd('=').Replace('+', '-').Replace('/', '_');
if (worker != null) worker.ReportProgress(101, new object[] { -3, "OK\r\ncalc sign.." });
string sign = Convert.ToBase64String(utils.makeSign(me._key,Encoding.UTF8.GetBytes(protect + "." + payload))).TrimEnd('=').Replace('+', '-').Replace('/', '_');
if (worker != null) worker.ReportProgress(101, new object[] { -3, "OK\r\nPOST_API.." });
string url = (API[method] != null) ? API[method].ToObject<string>() : method;
string json = "{\"header\":" + me.json_jwk +
",\"protected\":\"" + protect + "\"" +
",\"payload\":\"" + payload + "\"" +
",\"signature\":\"" + sign + "\"}";
if (worker != null) if (worker.CancellationPending)
{
worker.ReportProgress(101, new object[] { -3, "CANCEL" });
return null;
}
if (isRaw) {
return POST(url, json, true, null);
}
API = (JObject)POST(url, json, false, null);
if (worker != null) worker.ReportProgress(101, new object[] { -2, "OK" });
if (API == null && me.code == 409)
{
worker.ReportProgress(101, new object[] { -2, "Вы уже зарегистрированы!" });
}
return API;
}
static public object POST(string url, object data, bool isRaw, Dictionary<string, string> serv_api)
{
me.lastLocation = null;
me.code = 0;
me.details = null;
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.AllowAutoRedirect = false;
request.ContinueTimeout = 10000;
request.Timeout = 30000;
request.ReadWriteTimeout = 60000;
request.KeepAlive = false;
if(!isRaw)request.Accept = "application/json";
request.ContentType = "application/json";
request.UserAgent = "C# client v1.00 shamka.ru";
request.Method = "POST";
request.ServicePoint.Expect100Continue = false;
request.Credentials = CredentialCache.DefaultCredentials;
byte[] byteArray = Encoding.UTF8.GetBytes((data.GetType().Name!="String")?JsonConvert.SerializeObject(data):(string)data);
request.ContentLength = byteArray.Length;
Stream dataStream = request.GetRequestStream();
dataStream.Write(byteArray, 0, byteArray.Length);
dataStream.Close();
try
{
if (isRaw) {
if (serv_api != null)
{
serv_api.Add("r", ((HttpWebResponse)request.GetResponse()).GetResponseHeader("Replay-Nonce"));
}
using (Stream responseStream = request.GetResponse().GetResponseStream())
{
using (MemoryStream memoryStream = new MemoryStream())
{
int count = 0;
byte[] ooo = new byte[4096];
do
{
count = responseStream.Read(ooo, 0, ooo.Length);
memoryStream.Write(ooo, 0, count);
} while (count != 0);
return memoryStream.ToArray();
}
}
}
else
{
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
me.code = (int)response.StatusCode;
if (serv_api != null)
{
serv_api.Add("r", response.GetResponseHeader("Replay-Nonce"));
}
me.lastLocation = response.GetResponseHeader("Location");
object raw = (new StreamReader(response.GetResponseStream()).ReadToEnd());
response.Close();
raw = JsonConvert.DeserializeObject<object>((string)raw);
return raw;
}
}
catch (WebException www)
{
if (www.Status == WebExceptionStatus.Timeout) {
throw new Exception("Сервер: " + www.Message);
}
else if (www.Status == WebExceptionStatus.ProtocolError)
{
HttpWebResponse response1 = (HttpWebResponse)www.Response;
me.code = (int)response1.StatusCode;
me.details = (new StreamReader(response1.GetResponseStream()).ReadToEnd());
response1.Close();
return null;
}
HttpWebResponse response = (HttpWebResponse)www.Response;
object raw = null;
if (response != null)
{
me.code = (int)response.StatusCode;
raw = (new StreamReader(response.GetResponseStream()).ReadToEnd());
response.Close();
}
else
{
raw = "Нет связи";
}
throw new Exception("Сервер: " + (string)raw);
}
}
static public object GET(string url, Dictionary<string, string> serv_api, bool isRaw)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.AllowAutoRedirect = false;
request.ContinueTimeout = 10000;
request.Timeout = 30000;
request.ReadWriteTimeout = 60000;
request.KeepAlive = false;
request.Accept = "application/json";
request.UserAgent = "C# client v1.00 shamka.ru";
request.Method = "GET";
request.ServicePoint.Expect100Continue = false;
request.Credentials = CredentialCache.DefaultCredentials;
try
{
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
me.code = (int)response.StatusCode;
if (serv_api != null)
{
//serv_api.Add("b", response.GetResponseHeader("Boulder-Request-Id"));
serv_api.Add("r", response.GetResponseHeader("Replay-Nonce"));
}
object raw = (new StreamReader(response.GetResponseStream()).ReadToEnd());
if (isRaw) return (string)raw;
byte[] byteArray = Encoding.UTF8.GetBytes((string)raw);
response.Close();
raw = JsonConvert.DeserializeObject<object>((string)raw);
return raw;
}
catch (WebException www)
{
if (www.Status == WebExceptionStatus.Timeout)
{
throw new Exception("Сервер: " + www.Message);
}
else if (www.Status == WebExceptionStatus.ProtocolError)
{
me.code = (int)((HttpWebResponse)www.Response).StatusCode;
return null;
}
HttpWebResponse response = (HttpWebResponse)www.Response;
object raw = null;
if (response != null)
{
me.code = (int)response.StatusCode;
raw = (new StreamReader(response.GetResponseStream()).ReadToEnd());
response.Close();
}
else {
raw = "Нет связи";
}
throw new Exception("Сервер: " + (string)raw);
}
}
public keyInfo getUserKey() {
return _key;
}
}
}
|
using ProjectPortal.Models;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Web;
namespace ProjectPortal.DataContexts
{
public class ProjectsDbContext : DbContext
{
public ProjectsDbContext() : base("DefaultConnection")
{
}
public DbSet<Project> Projects { get; set; }
}
} |
using System;
using System.Data;
using System.Configuration;
using System.Linq;
using System.Xml.Linq;
using System.ComponentModel;
using System.Drawing;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Runtime.InteropServices;
using System.Drawing.Imaging;
using System.Drawing.Drawing2D;
namespace Common
{
/// <summary>
///pic_zip 图片缩略图生成类
/// </summary>
public class ImageThumbnailMake
{
/// <summary>
/// 图片缩略图生成
/// </summary>
public ImageThumbnailMake()
{
}
/// <summary>
/// 图片缩略图生成算法
/// </summary>
/// <param name="int_Width">宽度</param>
/// <param name="int_Height">高度</param>
/// <param name="input_ImgFile">文件路径</param>
/// <param name="out_ImgFile">保存文件路径</param>
/// <param name="filename">文件名</param>
/// <returns></returns>
public static bool MakeThumbnail(int int_Width, int int_Height, string input_ImgFile, string out_ImgFile, string filename)
{
System.Drawing.Image oldimage = System.Drawing.Image.FromFile(input_ImgFile + filename);
float New_Width; // 新的宽度
float New_Height; // 新的高度
float Old_Width, Old_Height; //原始高宽
int flat = 0;//标记图片是不是等比
int xPoint = 0;//若果要补白边的话,原图像所在的x,y坐标。
int yPoint = 0;
//判断图片
Old_Width = (float)oldimage.Width;
Old_Height = (float)oldimage.Height;
if ((Old_Width / Old_Height) > ((float)int_Width / (float)int_Height)) //当图片太宽的时候
{
New_Height = Old_Height * ((float)int_Width / (float)Old_Width);
New_Width = (float)int_Width;
//此时x坐标不用修改
yPoint = (int)(((float)int_Height - New_Height) / 2);
flat = 1;
}
else if ((oldimage.Width / oldimage.Height) == ((float)int_Width / (float)int_Height))
{
New_Width = int_Width;
New_Height = int_Height;
}
else
{
New_Width = (int)oldimage.Width * ((float)int_Height / (float)oldimage.Height); //太高的时候
New_Height = int_Height;
//此时y坐标不用修改
xPoint = (int)(((float)int_Width - New_Width) / 2);
flat = 1;
}
System.Drawing.Image.GetThumbnailImageAbort callb = null;
// ===缩小图片===
//调用缩放算法
System.Drawing.Image thumbnailImage = Makesmallimage(oldimage, (int)New_Width, (int)New_Height);
Bitmap bm = new Bitmap(thumbnailImage);
if (flat != 0)
{
Bitmap bmOutput = new Bitmap(int_Width, int_Height);
Graphics gc = Graphics.FromImage(bmOutput);
//SolidBrush tbBg = new SolidBrush(Color.White);
//gc.FillRectangle(tbBg, 0, 0, int_Width, int_Height); //填充为白色
gc.DrawImage(bm, xPoint, yPoint, (int)New_Width, (int)New_Height);
bmOutput.Save(out_ImgFile + filename + "_" + int_Width + "x" + int_Height + ".jpg");
}
else
{
bm.Save(out_ImgFile + filename + "_" + int_Width + "x" + int_Height + ".jpg");
}
oldimage.Dispose();
return true;
}
/// <summary>
/// 图片缩略图生成算法
/// </summary>
/// <param name="int_Width">宽度</param>
/// <param name="int_Height">高度</param>
/// <param name="input_ImgFile">文件路径</param>
/// <param name="out_ImgFile">保存文件路径</param>
/// <param name="filename">文件名</param>
/// <returns></returns>
public static bool MakeCompressionThumbnail(int int_Width, int int_Height, string input_ImgFile, string out_ImgFile, string filename)
{
System.Drawing.Image oldimage = System.Drawing.Image.FromFile(input_ImgFile + filename);
float New_Width; // 新的宽度
float New_Height; // 新的高度
float Old_Width, Old_Height; //原始高宽
int flat = 0;//标记图片是不是等比
int xPoint = 0;//若果要补白边的话,原图像所在的x,y坐标。
int yPoint = 0;
//判断图片
Old_Width = (float)oldimage.Width;
Old_Height = (float)oldimage.Height;
if ((Old_Width / Old_Height) > ((float)int_Width / (float)int_Height)) //当图片太宽的时候
{
New_Height = Old_Height * ((float)int_Width / (float)Old_Width);
New_Width = (float)int_Width;
//此时x坐标不用修改
yPoint = (int)(((float)int_Height - New_Height) / 2);
flat = 1;
}
else if ((oldimage.Width / oldimage.Height) == ((float)int_Width / (float)int_Height))
{
New_Width = int_Width;
New_Height = int_Height;
}
else
{
New_Width = (int)oldimage.Width * ((float)int_Height / (float)oldimage.Height); //太高的时候
New_Height = int_Height;
//此时y坐标不用修改
xPoint = (int)(((float)int_Width - New_Width) / 2);
flat = 1;
}
System.Drawing.Image.GetThumbnailImageAbort callb = null;
// ===缩小图片===
//调用缩放算法
System.Drawing.Image thumbnailImage = Makesmallimage(oldimage, (int)New_Width, (int)New_Height);
Bitmap bm = new Bitmap(thumbnailImage);
try
{
if (flat != 0)
{
Bitmap bmOutput = new Bitmap(int_Width, int_Height);
Graphics gc = Graphics.FromImage(bmOutput);
SolidBrush tbBg = new SolidBrush(Color.White);
gc.FillRectangle(tbBg, 0, 0, int_Width, int_Height); //填充为白色
gc.DrawImage(bm, xPoint, yPoint, (int)New_Width, (int)New_Height);
bmOutput.Save(out_ImgFile + filename + "_" + int_Width + "x" + int_Height + ".jpg");
//bmOutput.Save(out_ImgFile + filename + "_" + int_Width+"x"+int_Height+".jpg");
}
else
{
bm.Save(out_ImgFile + filename + "_" + int_Width + "x" + int_Height + ".jpg");
}
}
catch (Exception)
{
throw;
}
finally
{
oldimage.Dispose();
bm.Dispose();
}
return true;
}
/// <summary>
/// 生成缩略图 (高清缩放)
/// </summary>
/// <param name="originalImage">原图片</param>
/// <param name="width">缩放宽度</param>
/// <param name="height">缩放高度</param>
/// <returns></returns>
public static Image Makesmallimage(System.Drawing.Image originalImage, int width, int height)
{
int towidth = 0;
int toheight = 0;
if (originalImage.Width > width && originalImage.Height < height)
{
towidth = width;
toheight = originalImage.Height;
}
if (originalImage.Width < width && originalImage.Height > height)
{
towidth = originalImage.Width;
toheight = height;
}
if (originalImage.Width > width && originalImage.Height > height)
{
towidth = width;
toheight = height;
}
if (originalImage.Width < width && originalImage.Height < height)
{
towidth = originalImage.Width;
toheight = originalImage.Height;
}
int x = 0;//左上角的x坐标
int y = 0;//左上角的y坐标
//新建一个bmp图片
System.Drawing.Image bitmap = new System.Drawing.Bitmap(towidth, toheight);
//新建一个画板
Graphics g = System.Drawing.Graphics.FromImage(bitmap);
g.CompositingQuality = CompositingQuality.HighQuality;
//设置高质量插值法
g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
//设置高质量,低速度呈现平滑程度
g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
//清空画布并以透明背景色填充
g.Clear(Color.Transparent);
//在指定位置并且按指定大小绘制原图片的指定部分
g.DrawImage(originalImage, x, y, towidth, toheight);
originalImage.Dispose();
//bitmap.Dispose();
g.Dispose();
return bitmap;
}
/// <summary>
/// 生成缩略图 (没有补白)
/// </summary>
/// <param name="originalImagePath">源图路径(物理路径)</param>
/// <param name="thumbnailPath">缩略图路径(物理路径)</param>
/// <param name="width">缩略图宽度</param>
/// <param name="height">缩略图高度</param>
public static void MakeThumbnail(string originalImagePath, string thumbnailPath, int width, int height)
{
System.Drawing.Image originalImage = System.Drawing.Image.FromFile(originalImagePath);
int towidth = 0;
int toheight = 0;
if (originalImage.Width > width && originalImage.Height < height)
{
towidth = width;
toheight = originalImage.Height;
}
if (originalImage.Width < width && originalImage.Height > height)
{
towidth = originalImage.Width;
toheight = height;
}
if (originalImage.Width > width && originalImage.Height > height)
{
towidth = width;
toheight = height;
}
if (originalImage.Width < width && originalImage.Height < height)
{
towidth = originalImage.Width;
toheight = originalImage.Height;
}
int x = 0;//左上角的x坐标
int y = 0;//左上角的y坐标
//新建一个bmp图片
System.Drawing.Image bitmap = new System.Drawing.Bitmap(towidth, toheight);
//新建一个画板
Graphics g = System.Drawing.Graphics.FromImage(bitmap);
g.CompositingQuality = CompositingQuality.HighQuality;
//设置高质量插值法
g.InterpolationMode = InterpolationMode.HighQualityBicubic;
//设置高质量,低速度呈现平滑程度
g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
//清空画布并以透明背景色填充
g.Clear(Color.Transparent);
//在指定位置并且按指定大小绘制原图片的指定部分
g.DrawImage(originalImage, x, y, towidth, toheight);
try
{
bitmap.Save(thumbnailPath);
}
catch (System.Exception e)
{
throw e;
}
finally
{
originalImage.Dispose();
bitmap.Dispose();
g.Dispose();
}
}
/// <summary>
/// 压缩图片
/// </summary>
/// <param name="filePath">要压缩的图片的路径</param>
/// <param name="filePath_ystp">压缩后的图片的路径</param>
public static void ystp(string filePath, string filePath_ystp)
{
//Bitmap
Bitmap bmp = null;
//ImageCoderInfo
ImageCodecInfo ici = null;
//Encoder
System.Drawing.Imaging.Encoder ecd = null;
//EncoderParameter
EncoderParameter ept = null;
//EncoderParameters
EncoderParameters eptS = null;
try
{
bmp = new Bitmap(filePath);
ici = getImageCoderInfo("image/jpeg");
ecd = System.Drawing.Imaging.Encoder.Quality;
eptS = new EncoderParameters(1);
ept = new EncoderParameter(ecd, 50L);
eptS.Param[0] = ept;
bmp.Save(filePath_ystp, ici, eptS);
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
finally
{
bmp.Dispose();
ept.Dispose();
eptS.Dispose();
}
}
/// <summary>
/// 获取图片编码类型信息
/// </summary>
/// <param name="coderType">编码类型</param>
/// <returns>ImageCodecInfo</returns>
private static ImageCodecInfo getImageCoderInfo(string coderType)
{
ImageCodecInfo[] iciS = ImageCodecInfo.GetImageEncoders();
ImageCodecInfo retIci = null;
foreach (ImageCodecInfo ici in iciS)
{
if (ici.MimeType.Equals(coderType))
retIci = ici;
}
return retIci;
}
/// <summary>
/// 无损压缩图片
/// </summary>
/// <param name="sFile">原图片</param>
/// <param name="dFile">压缩后保存位置</param>
/// <param name="dHeight">高度</param>
/// <param name="dWidth">宽度</param>
/// <param name="flag">压缩质量 1-100</param>
/// <returns></returns>
public static bool CompressImage(string sFile, string dFile, int dHeight, int dWidth, int flag)
{
System.Drawing.Image iSource = System.Drawing.Image.FromFile(sFile);
ImageFormat tFormat = iSource.RawFormat;
int sW = 0, sH = 0;
//按比例缩放
Size tem_size = new Size(iSource.Width, iSource.Height);
if (tem_size.Width > dHeight ||tem_size.Width > dWidth)
{
if ((tem_size.Width * dHeight) > (tem_size.Height * dWidth))
{
sW = dWidth;
sH = (dWidth * tem_size.Height) / tem_size.Width;
}
else
{
sH = dHeight;
sW = (tem_size.Width * dHeight) / tem_size.Height;
}
}
else
{
sW = tem_size.Width;
sH = tem_size.Height;
}
Bitmap ob = new Bitmap(dWidth, dHeight);
Graphics g = Graphics.FromImage(ob);
g.Clear(Color.White);
g.CompositingQuality = CompositingQuality.HighQuality;
g.SmoothingMode = SmoothingMode.HighQuality;
g.InterpolationMode = InterpolationMode.HighQualityBicubic;
g.DrawImage(iSource, new Rectangle((dWidth - sW) / 2, (dHeight - sH) / 2, sW, sH), 0, 0, iSource.Width, iSource.Height, GraphicsUnit.Pixel);
g.Dispose();
//以下代码为保存图片时,设置压缩质量
EncoderParameters ep = new EncoderParameters();
long[] qy = new long[1];
qy[0] = flag;//设置压缩的比例1-100
EncoderParameter eParam = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, qy);
ep.Param[0] = eParam;
try
{
ImageCodecInfo[] arrayICI = ImageCodecInfo.GetImageEncoders();
ImageCodecInfo jpegICIinfo = null;
for (int x = 0; x < arrayICI.Length; x++)
{
if (arrayICI[x].FormatDescription.Equals("JPEG"))
{
jpegICIinfo = arrayICI[x];
break;
}
}
if (jpegICIinfo != null)
{
ob.Save(dFile, jpegICIinfo, ep);//dFile是压缩后的新路径
}
else
{
ob.Save(dFile, tFormat);
}
return true;
}
catch
{
return false;
}
finally
{
iSource.Dispose();
ob.Dispose();
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Http;
using System.Web.Http.OData.Builder;
using System.Web.Http.OData.Extensions;
using AngularTablesDataManager.DataLayer;
namespace AngularTablesDataManager
{
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
ODataConventionModelBuilder builder = new ODataConventionModelBuilder();
builder.EntitySet<City>("Cities");
builder.EntitySet<Zip>("Zips");
builder.EntitySet<FieldConfiguration>("FieldConfigurations");
config.Routes.MapODataServiceRoute("odata", "odata", builder.GetEdmModel());
}
}
} |
using MongoDB.Driver;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace RestaurantAPI.Config
{
public class MongoDbConection
{
public MongoClient client;
public IMongoDatabase db;
public MongoDbConection()
{
client = new MongoClient("mongodb://127.0.0.1:27017");
db = client.GetDatabase("RestaurantDB");
}
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using Kadastr.View.Forms;
namespace Kadastr.View.UserControls
{
public partial class Clients : DevExpress.XtraEditors.XtraUserControl
{
public Clients()
{
InitializeComponent();
}
private void simpleButton1_Click_1(object sender, EventArgs e)
{
ClientCatalog clientCatalog = new ClientCatalog();
clientCatalog.ShowDialog();
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace GodMorgon.Models
{
/**
* Classe de la carte de type stuff (équipement)
* Elle hérite de BasicCard qui contient ses infos de base (nom, description, ...)
* Elle contient ses effets propres à elle
*/
[CreateAssetMenu(fileName = "New Card", menuName = "Cards/StuffCard")]
public class StuffCard : BasicCard
{
public int lifeBonus = 10;
public int powerBonus = 5;
public StuffTypes StuffType;
public enum StuffTypes
{
HAT,
CHEST,
PANTS,
SHOES
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ChutesAndLadders.Entities;
using ChutesAndLadders.GamePlay;
namespace Chute
{
public static class SupplementalDemoExtensions
{
public static void SupplementalDemo_SingleGame(this GameBoard board)
{
var greedyStrategy = new ChutesAndLadders.Strategy.Greedy.Engine();
var linearStrategy = new ChutesAndLadders.Strategy.Linear.Engine();
var geneticStrategy = new ChutesAndLadders.Strategy.Rules.Engine("Best Found");
geneticStrategy.AddBestStrategyRules();
var shortestPathStrategy = new ChutesAndLadders.Strategy.ShortestPath.Engine();
// Remember that player 1 has a big advantage
var player1 = new Player("Player 1", greedyStrategy);
var player2 = new Player("Player 2", linearStrategy);
var player3 = new Player("Player 3", geneticStrategy);
var player4 = new Player("Player 4", shortestPathStrategy);
var players = new Player[] { player1, player2, player3, player4 };
var gameEngine = new Game(board);
// Set the last parameter to a value 1-6 to have all rolls be that value
// This allow us to compare the strategies when all use the same roll
// It would be better if the roll varied by round but all players
// got the same roll in a given round
var results = gameEngine.Play(players, 1, 16, true, 0);
Console.WriteLine(results.ToString());
Console.WriteLine();
Console.WriteLine(player4.Strategy.ToString());
}
public static void SupplementalDemo_Player1Advantage(this GameBoard board)
{
const int gameCount = 36000;
const int maxStartingLocation = 33;
var gameStrategy = new ChutesAndLadders.Strategy.Greedy.Engine();
// var gameStrategy = new ChutesAndLadders.Strategy.TakeAllLadders.Engine();
// var gameStrategy = new ChutesAndLadders.Strategy.Linear.Engine();
var player1 = new Player("Player 1", gameStrategy);
var player2 = new Player("Player 2", gameStrategy);
var player3 = new Player("Player 3", gameStrategy);
var player4 = new Player("Player 4", gameStrategy);
var player5 = new Player("Player 5", gameStrategy);
var player6 = new Player("Player 6", gameStrategy);
var players = new Player[] { player1, player2, player3, player4, player5, player6 };
var engine = new Simulation(maxStartingLocation);
var results = engine.Run(players, gameCount);
foreach (var player in results.Players)
Console.WriteLine($"{player.Name} ({player.Strategy.Name}) won {player.WinCount} of the {gameCount} games.");
}
}
}
|
using Newtonsoft.Json;
using SecureNetRestApiSDK.Api.Models;
namespace SecureNetRestApiSDK.Api.Responses
{
public class CreateCustomerResponse : SecureNetResponse
{
#region Properties
[JsonProperty("vaultCustomer")]
public VaultCustomer VaultCustomer { get; set; }
[JsonProperty("customerId")]
public string CustomerId { get; set; }
#endregion
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class respawnHealthCheck : MonoBehaviour
{
public GameObject[] player;
public GameObject ThePlayer;
// Start is called before the first frame update
void Start()
{
ThePlayer = GameObject.Find("Player");
}
// Update is called once per frame
void Update() {
player = GameObject.FindGameObjectsWithTag("Player");
if (player.Length < 1) {
ThePlayer.SetActive(true);
ThePlayer.GetComponent<playerHealthInformation>().playerCurrentHp = 30;
}
}
}
|
using System.Collections.Generic;
using System.Linq;
using Uintra.Core.Feed.Models;
namespace Uintra.Features.CentralFeed.Models
{
public class LatestActivitiesModel
{
public bool IsShowMore { get; set; }
public IEnumerable<LatestActivitiesItemViewModel> FeedItems { get; set; } = Enumerable.Empty<LatestActivitiesItemViewModel>();
}
} |
namespace Exercises.Constants
{
using System.Data.Entity;
using CodeFirstFromDatabase;
using Commands;
using GringottsCodeFirstFromDatabase;
using Interfaces;
using Models.Queries;
using Models.Writers;
public static class QueryResultableExtensions
{
public static void FirstLetterExercise(this GringottsContext context)
{
context.Exercies(new FirstLetter(), "FirstLetter.txt");
}
public static void FindEmployeesByFirstNameStartingWithSAExercise(
this SoftuniContext context)
{
context.Exercies(
new FindEmployeesByFirstNameStartingWithSA(),
"FindEmployeesByFirstNameStartingWithSA.txt");
}
public static void IncreaseSalariesExercise(this SoftuniContext context)
{
context.Exercies(new IncreaseSalaries(), "IncreaseSalaries.txt");
}
public static void FindLatest10ProjectsExercise(this SoftuniContext context)
{
context.Exercies(new FindLatest10Projects(), "FindLatest10Projects.txt");
}
public static void NativeSQLQueryExercisePartTwo(this SoftuniContext context)
{
context.Exercies(
new NativeSQLQueryNativeQueryPart(), "NativeSQLQuery.txt", true);
}
public static void NativeSQLQueryExercisePartOne(this SoftuniContext context)
{
context.Exercies(new NativeSQLQueryCodeFirstPart(), "NativeSQLQuery.txt");
}
public static void DepartmentsWithMoreThan5EmployeesExercise(
this SoftuniContext context)
{
context.Exercies(
new DepartmentsWithMoreThan5Employees(),
"DepartmentsWithMoreThan5Employees.txt");
}
public static void EmployeeWithId147SortedByProjectNamesExercise(
this SoftuniContext context)
{
context.Exercies(
new EmployeeWithId147SortedByProjectNames(),
"EmployeeWithId147SortedByProjectNames.txt");
}
public static void AddressesByTownNameExercise(this SoftuniContext context)
{
context.Exercies(new AddressesByTownName(), "AddressesByTownName.txt");
}
public static void FindEmployeesInPeriodExercise(this SoftuniContext context)
{
context.Exercies(new FindEmployeesInPeriod(), "FindEmployeesInPeriod.txt");
}
public static void DeleteProjectByIdExercise(this SoftuniContext context)
{
context.Exercies(new DeleteProjectById(), "DeleteProjectById.txt");
}
public static void AddingNewAddressAndUpdatingEmployeeExercise(
this SoftuniContext context)
{
context.Exercies(
new AddingNewAddressAndUpdatingEmployee(),
"AddingNewAddressAndUpdatingEmployee.txt");
}
public static void EmployeesFromSeattleExercise(this SoftuniContext context)
{
context.Exercies(
new EmployeesFromSeattle(),
"EmployeesFromSeattle.txt");
}
public static void EmployeesWithSalaryOver50000Exercise(this SoftuniContext context)
{
context.Exercies(
new EmployeesWithSalaryOver50000(),
"EmployeesWithSalaryOver50000.txt");
}
public static void EmployeesFullInformationExercise(this SoftuniContext context)
{
context.Exercies(new EmployeesFullInformation(), "EmployeeFullInformation.txt");
}
private static void Exercies<T>(
this T context,
IQueryResultable<T> queryResultable,
string fileName,
bool hasSetToAppend = false) where T : DbContext
{
var command = new ExerciseCommand<T>(context);
command.Execute(queryResultable, new FileWriter(fileName, hasSetToAppend));
}
}
} |
using System.Web.Mvc;
namespace AttendanceWebApp.Controllers
{
public class IncomeTaxController : Controller
{
public ActionResult IncomeTaxDeclaration()
{
if (Session["EmpUnqId"] != null && Session["UserRole"] != null)
{
return View();
}
else
{
return RedirectToAction("Index", "Login");
}
}
//Income Declaration Report as per SAP Upload Format.
public ActionResult ITDeclarationReport()
{
if (Session["EmpUnqId"] != null && Session["UserRole"] != null)
{
return View();
}
else
{
return RedirectToAction("Index", "Login");
}
}
//Update / Delete User Income Tax Declaration Details
public ActionResult IncomeTaxDecFin()
{
if (Session["EmpUnqId"] != null && Session["UserRole"] != null)
{
return View();
}
else
{
return RedirectToAction("Index", "Login");
}
}
//Tax Comparison Report
//public ActionResult TaxComparisonReport()
//{
// if (Session["EmpUnqId"] != null && Session["UserRole"] != null)
// {
// return View();
// }
// else
// {
// return RedirectToAction("Index", "Login");
// }
//}
public ActionResult Form16Upload()
{
if (Session["EmpUnqId"] != null && Session["UserRole"] != null)
{
return View();
}
else
{
return RedirectToAction("Index", "Login");
}
}
public ActionResult Form16()
{
if (Session["EmpUnqId"] != null && Session["UserRole"] != null)
{
return View();
}
else
{
return RedirectToAction("Index", "Login");
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Input;
using FitApp.Views;
using Xamarin.Forms;
using FitApp.Services;
using System.Collections.ObjectModel;
namespace FitApp.ViewModels
{
public class WorkoutsPlanViewModel : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
public ObservableCollection<WorkoutService> ListOfWorkouts { get; set; }
public WorkoutService workoutService;
// W1 -> Workout1
// T1 -> Time1
//
public string _w1;
public string W1
{
get
{
return _w1;
}
set
{
_w1 = value;
OnPropertyChanged();
}
}
public string _t1;
public string T1
{
get
{
return _t1;
}
set
{
_t1 = value;
OnPropertyChanged();
}
}
public string _et;
public string ET
{
get
{
return _et;
}
set
{
_et = value;
OnPropertyChanged();
}
}
public WorkoutsPlanViewModel()
{
workoutService = App.ws;
ListOfWorkouts = App.ListOfWorkouts;
}
protected void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.