text stringlengths 13 6.01M |
|---|
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace QuanLyQuanCafe.DAO
{
public class AccountDAO
{
private static AccountDAO instance;
private DataRow item;
public static AccountDAO Instance
{
get { if (instance == null) instance = new AccountDAO(); return instance; }
private set { instance = value; }
}
private AccountDAO() { }
public AccountDAO(DataRow item)
{
// TODO: Complete member initialization
this.item = item;
}
public bool Login(string Username, string Password)
{
string query = "select * from Account where UserName=@username and Password=@password";
var parameters = new SqlParameter[2];
parameters[0] = new SqlParameter() { ParameterName = "@username", Value = Username };
parameters[1] = new SqlParameter() { ParameterName = "@password", Value = Password };
DataTable result = DataProvider.Instance.ExecuteQuery(query, parameters);
return result.Rows.Count > 0;
}
public AccountDAO GetAccountbyUserName(string userName)
{
DataTable data = DataProvider.Instance.ExecuteQuery("select * from Account where UserName = '" + userName+"'");
foreach (DataRow item in data.Rows)
{
return new AccountDAO(item);
}
return null;
}
SqlConnection con = new SqlConnection(@"Data Source=VINHTOAN-PC;Integrated Security=True");
}
}
|
//
// Copyright 2015 Carbonfrost Systems, Inc. (http://carbonfrost.com)
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
using System;
using System.Linq;
using System.Reflection;
using Carbonfrost.Commons.Core.Runtime;
using Carbonfrost.Commons.PropertyTrees.ValueSerializers;
namespace Carbonfrost.Commons.PropertyTrees {
[Providers]
public partial class ValueSerializer {
public static readonly IValueSerializer Default = new TransparentValueSerializer();
public static readonly IValueSerializer Invalid = new InvalidValueSerializer();
public static readonly IValueSerializer Percentage = new PercentageValueSerializer();
public static readonly IValueSerializer PercentageRange = new PercentageValueSerializer();
public static readonly IValueSerializer Timeout = new TimeoutValueSerializer();
[ValueSerializerUsage(Name = "hex")]
public static readonly IValueSerializer Base16 = new Base16ValueSerializer();
public static readonly IValueSerializer Base64 = new Base64ValueSerializer();
public static IValueSerializer GetValueSerializer(ParameterInfo parameter) {
if (parameter == null) {
throw new ArgumentNullException("parameter");
}
return CreateInstance(GetValueSerializerType(parameter));
}
public static IValueSerializer GetValueSerializer(PropertyInfo property) {
if (property == null) {
throw new ArgumentNullException("property");
}
return CreateInstance(GetValueSerializerType(property));
}
public static Type GetValueSerializerType(ParameterInfo parameter) {
if (parameter == null)
throw new ArgumentNullException("parameter");
var gen = (ValueSerializerAttribute) parameter.GetCustomAttribute(typeof(ValueSerializerAttribute));
return gen == null ? GetValueSerializerType(parameter.ParameterType) : gen.ValueSerializerType;
}
public static Type GetValueSerializerType(PropertyInfo property) {
if (property == null) {
throw new ArgumentNullException("property");
}
var gen = property.GetCustomAttribute<ValueSerializerAttribute>();
return gen == null ? GetValueSerializerType(property.PropertyType) : gen.ValueSerializerType;
}
public static IValueSerializer GetValueSerializer(Type type) {
if (type == null) {
throw new ArgumentNullException("type");
}
return ValueSerializerFactory.Default.GetValueSerializer(type) ?? Invalid;
}
public static Type GetValueSerializerType(Type type) {
if (type == null) {
throw new ArgumentNullException("type");
}
return ValueSerializerFactory.Default.GetValueSerializerType(type);
}
public static IValueSerializer FromName(string name) {
return App.GetProvider<IValueSerializer>(name);
}
static IValueSerializer GetValueSerializerFromAttributes(ValueSerializerAttribute gen) {
Type type = gen.ValueSerializerType;
return type == null ? null : Activation.CreateInstance<IValueSerializer>(type);
}
static IValueSerializer CreateInstance(Type type) {
if (type == null) {
return Invalid;
}
return (IValueSerializer) Activation.CreateInstance(type);
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
///<summary>
/// Script Manager: Denver
/// Description: Handles the difficulty of the level, scroll direction and speed as well as moves the player
/// Date Modified: 1/11/2018
///</summary>
public class LevelManager : MonoBehaviour
{
[Tooltip("The play field of the level.")]
public GameObject m_playField;
[Tooltip("The speed at which the level will scroll.")]
public float m_fLevelScrollSpeed;
[Tooltip("Maximum scroll speed.")]
private float m_fMaxLevelScrollSpeed;
public float MaxScrollSpeed {
get {
return m_fMaxLevelScrollSpeed;
}
}
[Tooltip("The direction the level will scroll.")]
public Vector3 m_v3LevelScrollDirection;
void Start()
{
// check that tag has been set
if (gameObject.tag != "LevelManager") {
Debug.LogError("Tag must be LevelManager", gameObject);
}
if (m_playField.tag != "Playfield") {
Debug.LogError("Tag must be Playfield", m_playField);
}
// set Max scroll speed
m_fMaxLevelScrollSpeed = m_fLevelScrollSpeed;
// set scene state to running
SceneManager.Instance.SceneState = eSceneState.RUNNING;
}
void FixedUpdate()
{
// move the player's movement area
m_playField.transform.Translate(m_v3LevelScrollDirection * m_fLevelScrollSpeed * Time.deltaTime);
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Presentation : MonoBehaviour {
public List<GameObject> slides = new List<GameObject>();
private int currentSlide = 0;
// Use this for initialization
void Start () {
}
void Update() {
if(Input.GetMouseButtonDown(0)) {
Next();
}
if (Input.GetMouseButtonDown(1)) {
NextSlide();
}
}
public void Next() {
Debug.Log("Next");
GameManager.instance.episodeManager.CallEpisodeAudioAndSubs(Episode.Presentation);
//GameManager.instance.episodeManager.ProceedInDialogue(Episode.Presentation);
}
public void NextSlide() {
if (currentSlide != 0) {
slides[currentSlide].SetActive(true);
slides[currentSlide - 1].SetActive(false);
}
else {
slides[currentSlide].SetActive(true);
}
if (currentSlide != slides.Count-1) {
currentSlide++;
}
else { slides[currentSlide].SetActive(false); currentSlide = 0; }
}
}
|
using System;
using System.Collections.Generic;
namespace StudyEspanol.Utilities
{
public static partial class SEPreferences
{
#region Const Fields
private const string THEME = "theme";
private const string LANGUAGE = "language";
private const string NO_ADS_EXPIRATION = "no_ads_expiration";
private const string ALWAYS_TRANSLATE = "always_translate";
#endregion
#region Properties
public static Dictionary<int, int> ThemeDictionary
{
get { return themeDict; }
}
public static Dictionary<int, int> ColorDictionary
{
get { return colorDict; }
}
public static Dictionary<int, int> ColorDarkDictionary
{
get { return colorDarkDict; }
}
public static Dictionary<int, int> ColorFadedDictionary
{
get { return colorFadedDict; }
}
public static int Color { get; private set; }
public static int ColorFaded { get; private set; }
public static int ColorDark { get; private set; }
#endregion
}
}
|
using App.Entity.AttibutesProperty;
using System;
using System.Windows.Forms;
namespace App.Utilities.Controls
{
/// <summary>
/// Control that implements the funtionality to set text.
/// </summary>
/// <seealso cref="System.Windows.Forms.DateControl" />
/// <seealso cref="DateControl" />
public partial class DateControl : UserControl
{
#region Variables
/// <summary>
/// The changed value
/// </summary>
public EventHandler DateChange;
/// <summary>
/// The date selected
/// </summary>
public DateTime DateSelected
{
get => dateTimePicker1.Value;
set
{
dateTimePicker1.Value = value;
DateChange?.Invoke(ValueCorrect, new EventArgs());
}
}
/// <summary>
/// Gets or sets the minimum date.
/// </summary>
/// <value>
/// The minimum date.
/// </value>
public DateTime MinDate { get; set; }
/// <summary>
/// Gets or sets the maximum date.
/// </summary>
/// <value>
/// The maximum date.
/// </value>
public DateTime MaxDate { get; set; }
/// <summary>
/// Gets the message.
/// </summary>
/// <value>
/// The message.
/// </value>
public string Message { get; private set; }
/// <summary>
/// The configuration attributes
/// </summary>
private ConfigurationAttributes _ConfigurationAttributes;
#endregion
#region Events
/// <summary>
/// Initializes a new instance of the <see cref="DateControl" /> class.
/// </summary>
public DateControl()
{
InitializeComponent();
dateTimePicker1.Value = DateTime.Now;
}
/// <summary>
/// Handles the TextChanged event of the textBox1 control.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="EventArgs" /> instance containing the event data.</param>
private void textBox1_TextChanged(object sender, EventArgs e)
{
if (MinDate != null && dateTimePicker1.Value < MinDate)
{
toolTip1.SetToolTip(dateTimePicker1, $"El {_ConfigurationAttributes.Label} excede el valor mínimo ({MinDate}).");
return;
}
if (MaxDate != null && dateTimePicker1.Value > MaxDate)
{
toolTip1.SetToolTip(dateTimePicker1, $"El {_ConfigurationAttributes.Label} excede el valor máximo ({MaxDate}).");
return;
}
DateChange?.Invoke(ValueCorrect, new EventArgs());
}
#endregion
#region Methods
/// <summary>
/// The configuration attributes
/// </summary>
/// <value>
/// The configuration attributes.
/// </value>
public ConfigurationAttributes ConfigurationAttributes
{
set
{
_ConfigurationAttributes = value;
if (_ConfigurationAttributes != null)
{
label1.Text = _ConfigurationAttributes.Label + ":";
DateSelected = (DateTime)(_ConfigurationAttributes.Value ?? DateTime.Now);
dateTimePicker1.Tag = _ConfigurationAttributes.Label;
}
}
}
/// <summary>
/// Gets a value indicating whether [value correct].
/// </summary>
/// <value>
/// <c>true</c> if [value correct]; otherwise, <c>false</c>.
/// </value>
public bool ValueCorrect => ValidateControl();
/// <summary>
/// Verifies the value of the control losing focus by causing the <see cref="E:System.Windows.Forms.Control.Validating" /> and <see cref="E:System.Windows.Forms.Control.Validated" /> events to occur, in that order.
/// </summary>
/// <returns>
/// true if validation is successful; otherwise, false. If called from the <see cref="E:System.Windows.Forms.Control.Validating" /> or <see cref="E:System.Windows.Forms.Control.Validated" /> event handlers, this method will always return false.
/// </returns>
/// <PermissionSet>
/// <IPermission class="System.Security.Permissions.EnvironmentPermission, mscorlib, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" version="1" Unrestricted="true" />
/// <IPermission class="System.Security.Permissions.FileIOPermission, mscorlib, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" version="1" Unrestricted="true" />
/// <IPermission class="System.Security.Permissions.SecurityPermission, mscorlib, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" version="1" Flags="UnmanagedCode, ControlEvidence" />
/// <IPermission class="System.Diagnostics.PerformanceCounterPermission, System, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" version="1" Unrestricted="true" />
/// </PermissionSet>
public bool ValidateControl()
{
bool result = true;
if (!_ConfigurationAttributes.CauseValidation)
{
return true;
}
if (_ConfigurationAttributes.Required && dateTimePicker1.Value == null)
{
toolTip1.SetToolTip(dateTimePicker1, string.Format("El {0} es requerido.", _ConfigurationAttributes.Label));
return false;
}
if (dateTimePicker1.Value < MinDate)
{
toolTip1.SetToolTip(dateTimePicker1, $"El {_ConfigurationAttributes.Label} excede el valor mínimo ({MinDate}).");
return false;
}
if (dateTimePicker1.Value > MaxDate)
{
toolTip1.SetToolTip(dateTimePicker1, $"El {_ConfigurationAttributes.Label} excede el valor máximo ({MaxDate}).");
return false;
}
toolTip1.SetToolTip(dateTimePicker1, string.Format("Correcto!!", _ConfigurationAttributes.Label));
return result;
}
/// <summary>
/// Initializes a new instance of the <see cref="TextControl" /> class.
/// </summary>
/// <param name="configurationAttributes">The configuration attributes.</param>
public void TextControl(ConfigurationAttributes configurationAttributes)
{
InitializeComponent();
_ConfigurationAttributes = configurationAttributes;
label1.Text = _ConfigurationAttributes.Label;
}
/// <summary>
/// Handles the ValueChanged event of the dateTimePicker1 control.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
private void dateTimePicker1_ValueChanged(object sender, EventArgs e)
{
DateChange?.Invoke(ValueCorrect, new EventArgs());
}
#endregion
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ToolGood.Algorithm.MathNet.Numerics.Statistics
{
public static class Statistics
{
public static double QuantileCustom(this IEnumerable<double> data, double tau, QuantileDefinition definition)
{
double[] array = data.ToArray();
return ArrayStatistics.QuantileCustomInplace(array, tau, definition);
}
public static double QuantileRank(this IEnumerable<double> data, double x, RankDefinition definition = RankDefinition.Default)
{
double[] array = data.ToArray();
Array.Sort(array);
return SortedArrayStatistics.QuantileRank(array, x, definition);
}
}
}
|
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using LanchesFF.Repository;
using LanchesFF.ViewModels;
using LanchesFF.Models;
namespace LanchesFF.Controllers
{
public class LancheController : Controller
{
private readonly ILancheRepository _lancheRepository;
private readonly ICategoriaRepository _categoriaRepository;
public LancheController(ILancheRepository lancheRepository, ICategoriaRepository categoriaRepository)
{
_lancheRepository = lancheRepository;
_categoriaRepository = categoriaRepository;
}
public IActionResult List(string categoria)
{
string _categoria = categoria;
IEnumerable<Lanche> lanches;
string categoriaAtual = string.Empty;
if (string.IsNullOrEmpty(categoria))
{
lanches = _lancheRepository.Lanches.OrderBy(L => L.LancheId);
categoriaAtual = "Todos os lanches.";
}
else
{
if (string.Equals("Normal", _categoria, StringComparison.OrdinalIgnoreCase))
{
lanches = _lancheRepository.Lanches.Where(L =>
L.Categorias.CategoriaNome.Equals("Normal")).OrderBy(L => L.Nome);
}
else
{
lanches = _lancheRepository.Lanches.Where(L =>
L.Categorias.CategoriaNome.Equals("Natural")).OrderBy(L => L.Nome);
}
categoriaAtual = _categoria;
}
var lancheslistViewModel = new LancheListViewModel
{
Lanches = lanches,
CategoriaAtual = categoriaAtual
};
return View(lancheslistViewModel);
}
}
}
|
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using CareerCup150;
namespace CareerCupTest
{
[TestClass]
public class UnitTest_Chapter20
{
[TestMethod]
public void TestQuestion20_12 ()
{
Question20_12 target = new Question20_12();
int[,] input = { { -1, -1, -1, -1, -1 }, { -1, -1, 2, 2, -1 }, { -1, -1, 2, 2, -1 }, { -1, -1, 2, 2, -1 }, { -1, -1, -1, -1, -1 } };
int actual = target.FindMax(input, 5);
Assert.AreEqual(12, actual);
}
[TestMethod]
public void TestQuestion20_11()
{
_20_11_blackBoarder target = new _20_11_blackBoarder();
char[,] input = { {'w','b','b','b'},{'w','b','b','w'},{'w','b','b','w'},{'b','b','b','w'} };
int actual = target.FindBlackSubMatrix(input, 4);
}
}
}
|
/*
* Copyright © 2019 GGG KILLER <gggkiller2@gmail.com>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software
* and associated documentation files (the “Software”), to deal in the Software without
* restriction, including without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom
* the Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or
* substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
* BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
* DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using Tsu.CLI.Commands.Help;
namespace Tsu.CLI.Commands
{
/// <summary>
/// Represents a command that was registered in a command manager
/// </summary>
public class Command
{
/// <summary>
/// The names that this command can be referred by
/// </summary>
public ImmutableArray<String> Names { get; }
/// <summary>
/// The description shown when the help command is invoked
/// </summary>
public String Description { get; }
/// <summary>
/// Whether this command accepts raw input
/// </summary>
public Boolean IsRaw { get; }
/// <summary>
/// The arguments this command accepts
/// </summary>
public ImmutableArray<ArgumentHelpData> Arguments { get; }
/// <summary>
/// The command invokation examples provided (or not)
/// </summary>
public ImmutableArray<String> Examples { get; }
/// <summary>
/// Initializes a new command instance.
/// </summary>
/// <param name="names"></param>
/// <param name="description"></param>
/// <param name="isRaw"></param>
/// <param name="arguments"></param>
/// <param name="examples"></param>
public Command ( IEnumerable<String> names,
String description = "No description provided for this command.",
Boolean isRaw = false,
IEnumerable<ArgumentHelpData> arguments = null,
IEnumerable<String> examples = null )
{
if ( names == null )
throw new ArgumentNullException ( nameof ( names ) );
if ( !names.Any ( ) )
throw new ArgumentException ( "No names provided", nameof ( names ) );
this.Names = names.ToImmutableArray ( );
this.Description = description ?? throw new ArgumentNullException ( nameof ( description ) );
this.IsRaw = isRaw;
this.Arguments = arguments?.ToImmutableArray ( ) ?? ImmutableArray<ArgumentHelpData>.Empty;
this.Examples = examples?.ToImmutableArray ( ) ?? ImmutableArray<String>.Empty;
}
}
}
|
using System;
using System.Data;
using System.Text;
using System.Collections.Generic;
using System.Configuration;
namespace Karkas.Ornek.TypeLibrary.Ornekler
{
public partial class Musteri
{
}
}
|
//------------------------------------------------------------------------------
//
// CosmosEngine - The Lightweight Unity3D Game Develop Framework
//
// Version 0.8 (20140904)
// Copyright © 2011-2014
// MrKelly <23110388@qq.com>
// https://github.com/mr-kelly/CosmosEngine
//
//------------------------------------------------------------------------------
using System;
using UnityEngine;
using UnityEditor;
using System.Collections;
using System.IO;
using System.Reflection;
using System.Collections.Generic;
using Object = UnityEngine.Object;
public partial class CBuildTools
{
struct XVersionControlInfo
{
public string Server;
public int Port;
public string Database;
public string User;
public string Pass;
};
static int PushedAssetCount = 0;
public static event Action<UnityEngine.Object, string, string> BeforeBuildAssetBundleEvent;
public static event Action<UnityEngine.Object, string, string> AfterBuildAssetBundleEvent;
#region 打包功能
public static string MakeSureExportPath(string path, BuildTarget buildTarget)
{
path = CBuildTools.GetExportPath(buildTarget) + path;
string exportDirectory = path.Substring(0, path.LastIndexOf('/'));
if (!System.IO.Directory.Exists(exportDirectory))
System.IO.Directory.CreateDirectory(exportDirectory);
return path;
}
public static string GetExportPath(BuildTarget platfrom)
{
string basePath = Path.GetFullPath(Application.dataPath + "/" + CCosmosEngine.GetConfig("AssetBundleRelPath") + "/");
if (!Directory.Exists(basePath))
{
CBuildTools.ShowDialog("路径配置错误: " + basePath);
throw new System.Exception("路径配置错误");
}
string path = null;
switch (platfrom)
{
case BuildTarget.Android:
case BuildTarget.iPhone:
case BuildTarget.StandaloneWindows:
path = basePath + CResourceModule.GetBuildPlatformName() + "/";
break;
default:
CBuildTools.ShowDialog("构建平台配置错误");
throw new System.Exception("构建平台配置错误");
}
return path;
}
public static void ClearConsole()
{
Assembly assembly = Assembly.GetAssembly(typeof(SceneView));
System.Type type = assembly.GetType("UnityEditorInternal.LogEntries");
MethodInfo method = type.GetMethod("Clear");
method.Invoke(null, null);
}
public static void ShowDialog(string msg, string title = "提示", string button = "确定")
{
EditorUtility.DisplayDialog(title, msg, button);
}
public static void PushAssetBundle(Object asset, string path)
{
BuildPipeline.PushAssetDependencies();
BuildAssetBundle(asset, path);
PushedAssetCount++;
}
public static void PopAllAssetBundle()
{
for (int i = 0; i < PushedAssetCount; ++i)
{
BuildPipeline.PopAssetDependencies();
}
PushedAssetCount = 0;
}
public static void PopAssetBundle()
{
BuildPipeline.PopAssetDependencies();
PushedAssetCount--;
}
#endregion
public static void BuildError(string fmt, params string[] args)
{
fmt = "[BuildError]" + fmt;
Debug.LogWarning(string.Format(fmt, args));
}
public static uint BuildAssetBundle(Object asset, string path)
{
return BuildAssetBundle(asset, path, EditorUserBuildSettings.activeBuildTarget);
}
public static uint BuildAssetBundle(Object asset, string path, BuildTarget buildTarget)
{
if (asset == null || string.IsNullOrEmpty(path))
{
BuildError("BuildAssetBundle: {0}", path);
return 0;
}
string tmpPrefabPath = string.Format("Assets/{0}.prefab", asset.name);
PrefabType prefabType = PrefabUtility.GetPrefabType(asset);
GameObject tmpObj = null;
Object tmpPrefab = null;
string relativePath = path;
path = MakeSureExportPath(path, buildTarget);
if (asset is Texture)
{
//asset = asset; // Texutre不复制拷贝一份
}
else if ((prefabType == PrefabType.None && AssetDatabase.GetAssetPath(asset) == string.Empty) ||
(prefabType == PrefabType.ModelPrefabInstance))
{
tmpObj = (GameObject)GameObject.Instantiate(asset);
tmpPrefab = PrefabUtility.CreatePrefab(tmpPrefabPath, tmpObj, ReplacePrefabOptions.ConnectToPrefab);
asset = tmpPrefab;
}
else if (prefabType == PrefabType.PrefabInstance)
{
asset = PrefabUtility.GetPrefabParent(asset);
}
if (BeforeBuildAssetBundleEvent != null)
BeforeBuildAssetBundleEvent(asset, path, relativePath);
uint crc;
BuildPipeline.BuildAssetBundle(
asset,
null,
path,
out crc,
BuildAssetBundleOptions.CollectDependencies | BuildAssetBundleOptions.CompleteAssets | BuildAssetBundleOptions.DeterministicAssetBundle,
buildTarget);
if (tmpObj != null)
{
GameObject.DestroyImmediate(tmpObj);
AssetDatabase.DeleteAsset(tmpPrefabPath);
}
CDebug.Log("生成文件: {0}", path);
if (AfterBuildAssetBundleEvent != null)
AfterBuildAssetBundleEvent(asset, path, relativePath);
return crc;
}
public static uint BuildScriptableObject<T>(T scriptObject, string path) where T : ScriptableObject
{
return BuildScriptableObject(scriptObject, path, EditorUserBuildSettings.activeBuildTarget);
}
public static uint BuildScriptableObject<T>(T scriptObject, string path, BuildTarget buildTarget) where T : ScriptableObject
{
const string tempAssetPath = "Assets/~Temp.asset";
AssetDatabase.CreateAsset(scriptObject, tempAssetPath);
T tempObj = (T)AssetDatabase.LoadAssetAtPath(tempAssetPath, typeof(T));
if (tempObj == null)
{
throw new System.Exception();
}
uint crc = CBuildTools.BuildAssetBundle(tempObj, path, buildTarget);
AssetDatabase.DeleteAsset(tempAssetPath);
return crc;
}
public static void CopyFolder(string sPath, string dPath)
{
if (!Directory.Exists(dPath))
{
Directory.CreateDirectory(dPath);
}
DirectoryInfo sDir = new DirectoryInfo(sPath);
FileInfo[] fileArray = sDir.GetFiles();
foreach (FileInfo file in fileArray)
{
if (file.Extension != ".meta")
file.CopyTo(dPath + "/" + file.Name, true);
}
DirectoryInfo[] subDirArray = sDir.GetDirectories();
foreach (DirectoryInfo subDir in subDirArray)
{
CopyFolder(subDir.FullName, dPath + "/" + subDir.Name);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ScripterTestCmd
{
public class CreateObjectTestClass<T>
{
public string Name { get; set; }
public T Data { get; set; }
public CreateObjectTestClass(string name)
{
Name = name;
}
public CreateObjectTestClass(string name, T data)
{
Name = name;
Data = data;
}
public CreateObjectTestClass()
{
}
}
}
|
using ProConstructionsManagment.Desktop.Views.Base;
using System.Windows.Controls;
namespace ProConstructionsManagment.Desktop.Views.EndedProjects
{
public partial class EndedProjects : UserControl
{
public EndedProjects()
{
InitializeComponent();
var viewModel = ViewModelLocator.Get<EndedProjectsViewModel>();
DataContext = viewModel;
Loaded += async (sender, args) => await viewModel.Initialize();
Unloaded += (sender, args) => viewModel.Cleanup();
}
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Slime : BaseUnitFunction
{
public override void Unit_Skill()
{
if (Random.value <= Mod_Critical / 100)
{
critHit = true;
DamageDealType = "Critcal";
Debug.Log(gameObject.name + " : do critical attack!");
}
if (Random.value <= Mod_Penetration / 100)
{
peneHit = true;
DamageDealType = "Penetrate";
Debug.Log(gameObject.name + " : do penetrate attack!");
}
if (!critHit && !peneHit)
{
DamageDealType = "Normal";
Debug.Log(gameObject.name + " : do normal attack!");
}
target_Unit.GetComponent<BaseUnitFunction>().DamageReceive = DealingDamage_Calculation(Mod_Attack);
target_Unit.GetComponent<BaseUnitFunction>().DamageReceiveType = DamageDealType;
target_Unit.GetComponent<BaseUnitFunction>().getAttack = true;
unitStatus = state.Attacking;
critHit = false;
peneHit = false;
}
}
|
using Newtonsoft.Json.Linq;
using System.Collections.Generic;
namespace NMoSql.Helpers
{
public interface IQueryHelper : IHelper
{
string Fn(JToken value, IList<object> values, Query query);
}
}
|
namespace SchoolSystem.Db
{
using System.Collections.Generic;
using Contracts;
public class DictionaryDataBase : IDataBase
{
private static IDictionary<int, IStudent> students;
private static IDictionary<int, ITeacher> teachers;
public DictionaryDataBase()
{
students = new Dictionary<int, IStudent>();
teachers = new Dictionary<int, ITeacher>();
}
public void AddStudent(IStudent student)
{
students.Add(student.Id, student);
}
public void AddTeacher(ITeacher teacher)
{
teachers.Add(teacher.Id, teacher);
}
public IStudent GetStudentById(int id)
{
return students[id];
}
public ITeacher GetTeacherById(int id)
{
return teachers[id];
}
public bool RemoveStudentById(int id)
{
var isRemoved = students.Remove(id);
return isRemoved;
}
public bool RemoveTeacherById(int id)
{
var isRemoved = teachers.Remove(id);
return isRemoved;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace LambaExpression1
{
class Program
{
private static void Main(string[] args)
{
Func<int, int> func1= x => x + 1;
Console.WriteLine(func1.Invoke(2));
Func<double, double, double> Multiply = (x, y) => x*y;
Console.WriteLine(Multiply(2,3));
Func<int, int> func7 = delegate(int x) { return x + 1; };
Console.WriteLine(func7.Invoke(1));
Console.ReadKey();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Converter.UI.Settings
{
public class ModFile
{
public string FileName { get; set; }
public string SourcePath { get; set; }
public string TargetPath { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using CommonDX;
using SumoNinjaMonkey.Framework.Controls.DrawingSurface;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.Graphics.Display;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
namespace JF.Studio.Controls
{
public sealed partial class DrawingSurfaceSCBP : SwapChainBackgroundPanel
{
private DeviceManager deviceManager;
private SwapChainBackgroundPanelTarget d2dTarget;
private IRenderer effectRenderer;
bool hasInitializedSurface = false;
public int FrameCountPerRender { get; set; } //number of frames per render (default = 1);
public DrawingSurfaceSCBP(IRenderer renderer)
{
this.FrameCountPerRender = 1;
//this.InitializeComponent();
//if (!hasInitializedSurface)
//{
// //effectRenderer = new EffectRenderer();
// var fpsRenderer = new FpsRenderer();
// d2dTarget = new SwapChainBackgroundPanelTarget(root);
// d2dTarget.OnRender += effectRenderer.Render;
// d2dTarget.OnRender += fpsRenderer.Render;
// deviceManager = new DeviceManager();
// deviceManager.OnInitialize += d2dTarget.Initialize;
// deviceManager.OnInitialize += effectRenderer.Initialize;
// deviceManager.OnInitialize += fpsRenderer.Initialize;
// deviceManager.Initialize(DisplayProperties.LogicalDpi);
// effectRenderer.InitializeUI(root, root);
// // Setup rendering callback
// CompositionTarget.Rendering += CompositionTarget_Rendering;
// if (_assetUri != string.Empty) effectRenderer.LoadLocalAsset(_assetUri);
//}
}
private string _assetUri;
public void LoadImage(string assetUri)
{
_assetUri = assetUri;
if (effectRenderer == null) return;
effectRenderer.LoadLocalAsset(_assetUri);
}
int iCounter = 0;
void CompositionTarget_Rendering(object sender, object e)
{
iCounter++;
if (iCounter == FrameCountPerRender) //we need to increase this fcr when mixing xaml/dx at times
{
d2dTarget.RenderAll();
d2dTarget.Present();
iCounter = 0;
}
}
}
}
|
using System;
using System.Collections.Generic;
namespace NineGagNumbers
{
class NineGagNumbers
{
static void Main(string[] args)
{
string nineGagNumber = Console.ReadLine();
List<int> nineNumberDigits = new List<int>();
string currentNineGagDigit = string.Empty;
for (int i = 0; i < nineGagNumber.Length; i++)
{
currentNineGagDigit += nineGagNumber[i];
int currentNineDigit = NineGagDigitToNineDigit(currentNineGagDigit);
if (currentNineDigit >= 0)
{
nineNumberDigits.Add(currentNineDigit);
currentNineGagDigit = string.Empty;
}
}
ulong decimalNumber = 0;
for (int i = 0; i < nineNumberDigits.Count; i++)
{
decimalNumber += (ulong)nineNumberDigits[i] * Pow(9, nineNumberDigits.Count - i - 1);
}
Console.WriteLine(decimalNumber);
}
private static int NineGagDigitToNineDigit(string nineGagDigit)
{
List<string> nineGagDigits = new List<string>()
{
"-!", "**", "!!!", "&&", "&-", "!-", "*!!!", "&*!", "!!**!-"
};
if (nineGagDigits.Contains(nineGagDigit))
{
return nineGagDigits.IndexOf(nineGagDigit);
}
return -1;
}
private static ulong Pow(int number, int power)
{
ulong result = 1;
for (int i = 1; i <= power; i++)
{
result *= (ulong)number;
}
return result;
}
}
}
|
using UnityEngine;
using System.Collections;
/// <summary>
/// A class for the Bin object in the train station.
/// </summary>
public class Bin : MonoBehaviour {
/// <summary>
/// <c>T</c> if clue is in the sofa
/// </summary>
private bool hasClue = false;
/// <summary>
/// A reference to the main HUD in the scene.
/// </summary>
private HUDController HUDC;
/// <summary>
/// The GameObject of the clue contained in the bin.
/// </summary>
private GameObject containedClue;
/// <summary>
/// A state storing whether or not the mouse cursor is placed over the beer pump or not.
/// </summary>
private bool entered;
/// <summary>
/// Opens the cupboard to view contents & output to HUD text.
/// </summary>
private void showClue (){
HUDC.displayHUDText ("You managed to pull something out of the bin!");
containedClue.SetActive (true); //make clue visible
}
/// <summary>
/// Initialise this instance.
/// </summary>
public void Initialise(){
gameObject.GetComponent<SpriteRenderer> ().sprite = Resources.Load<Sprite> ("Furniture/bin");
Vector2 S = this.gameObject.GetComponent<SpriteRenderer>().sprite.bounds.size; //get size of sprite
gameObject.GetComponent<BoxCollider2D>().size = S; //change size of boxcollider to match
this.HUDC = GameObject.Find("HUD").GetComponent<HUDController>();
}
/// <summary>
/// Raises the mouse down event. If sofa has clue then show.
/// </summary>
void OnMouseDown(){
if ((this.hasClue)){
this.showClue ();
this.gameObject.GetComponent<AudioSource> ().Play ();
this.hasClue = false;
} else {
HUDC.displayHUDText ("Nothing worth collecting in here. Unless you have a crisp packet collection.");
}
}
/// <summary>
/// Adds a clue to be stored inside the bin.
/// </summary>
/// <param name="clueObject">The Clue to be stored inside the bin..</param>
public void addClue(GameObject clueObject){
this.hasClue = true;
clueObject.transform.position = this.gameObject.transform.position + new Vector3(0f, 1.2f, 0f);
clueObject.SetActive (false);
this.containedClue = clueObject;
}
void OnMouseEnter(){
Cursor.SetCursor (Resources.Load<Texture2D> ("clueCursor"), Vector2.zero, CursorMode.Auto);
entered = true;
}
void OnMouseExit(){
Cursor.SetCursor (null, Vector2.zero, CursorMode.Auto);
entered = false;
}
void Update(){
if (entered) {
Cursor.SetCursor (Resources.Load<Texture2D> ("clueCursor"), Vector2.zero, CursorMode.Auto);
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.UI;
public class Player_Movement : MonoBehaviour {
[SerializeField]float score = 0;
[SerializeField] Text scoretext;
[SerializeField] GameObject shield;
private float speed = 9;
private bool crash = false;
private bool controllable = true;
private bool shielded = false;
// Use this for initialization
void Start () {
shield.SetActive(false);
}
// Update is called once per frame
void Update () {
score=score + 0.01f;
PosCheck();
scoretext.text = "score: " + score.ToString("f0");
if (controllable && Input.GetKey(KeyCode.W)) transform.Translate(Vector3.up * speed * Time.deltaTime, Space.World);
if (controllable && Input.GetKey(KeyCode.S)) transform.Translate(Vector3.down * speed * Time.deltaTime, Space.World);
if (crash) {
controllable = false;
transform.Rotate(new Vector3 (0,0,1),-30);
transform.Translate(new Vector2(2, -2) * 4 * Time.deltaTime, Space.World);
}
}
public void OnTriggerEnter2D(Collider2D collision)
{
if (collision.gameObject.tag == "hostile")
{
if (shielded)
{
shield.SetActive(false);
Destroy(collision.gameObject);
shielded = false;
}
else
{
crash = true;
StartCoroutine(Restart());
}
}
if (collision.gameObject.tag == "coin")
{
score = score + 10;
Destroy(collision.gameObject);
}
if (collision.gameObject.tag == "shield")
{
shielded = true;
shield.SetActive(true);
Destroy(collision.gameObject);
}
}
IEnumerator Restart()
{
yield return new WaitForSeconds(1.0f);
SceneManager.LoadScene(1);
}
public float GetScore()
{
return score;
}
private void PosCheck()
{
if (!crash) {
if (transform.position.y < -3.3f)
{
transform.position = new Vector2(transform.position.x, -3.31f);
}
if (transform.position.y > 5.3f)
{
transform.position = new Vector2(transform.position.x, 5.31f);
}
}
}
}
|
using System;
namespace filter.framework.core.Db
{
/// <summary>
/// 编码标识
/// </summary>
[AttributeUsage(AttributeTargets.Property)]
public class CodeAttribute : Attribute
{
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class UStateBar : _UP
{
public override string Name => "UStateBar";
public Text TextYear, TextHour, TextState, TextSpeed;
public Button ButtonSlow, ButtonPlay, ButtonFaster;
public GameObject ImagePlaying, ImagePausing;
public override void WhenFirstShow()
{
ButtonSlow.onClick.AddListener(OnClickSlower);
ButtonFaster.onClick.AddListener(OnClickFaster);
ButtonPlay.onClick.AddListener(OnClickPlaying);
_E.AddListener(EventID.TickEnd, WhenRefresh);
base.WhenFirstShow();
}
public override void WhenDestroy()
{
_E.RemoveListener(EventID.TickEnd, WhenRefresh);
base.WhenDestroy();
}
public override void WhenRefresh()
{
// 速度
if (_D.Inst.Playing)
{
ImagePausing.SetActive(true);
ImagePlaying.SetActive(false);
TextSpeed.text = string.Format("x{0}", _D.Inst.Speed);
// 时间
TextYear.text = string.Format("{0}年{1}月{2}日",
2019 + _D.Inst.Years,
_D.Inst.Months,
_D.Inst.Days);
TextHour.text = string.Format("{0:D02}:{1:D02}:{2:D02}",
_D.Inst.Hours,
_D.Inst.Minutes,
Random.Range(0, 60));
// 人数
TextState.text = string.Format("总人口:{0} 患病人数:{1}",
_D.Inst.Health + _D.Inst.Patient, _D.Inst.Patient);
}
else {
ImagePausing.SetActive(false);
ImagePlaying.SetActive(true);
TextSpeed.text = "Pausing";
}
base.WhenRefresh();
}
private void OnClickPlaying()
{
if (_D.Inst.Playing)
_D.Inst.Pause();
else
_D.Inst.Unpause();
}
private void OnClickSlower()
{
_D.Inst.Slower();
}
private void OnClickFaster()
{
_D.Inst.Faster();
}
}
|
using System;
using System.Collections.Generic;
class List
{
public static int Sum(List<int> myList)
{
int neo = 0, x = 0, y = 0;
foreach (int e in myList)
{
y += 1;
if (y > 1)
{
if (e == x)
continue;
else
neo += e;
}
else
{
neo += e;
}
x = e;
}
return neo;
}
}
|
using UnityEngine;
using System.Collections;
public class PaddleController : MonoBehaviour {
public float paddleSpeed = 1.0f;
Vector3 paddlePos;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
float xPos = Mathf.Clamp (transform.position.x + Input.GetAxis ("Horizontal") * paddleSpeed,-8.0f,8.0f);
paddlePos = new Vector3 (xPos, -9.5f, 0f);
transform.position = paddlePos;
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using UnitedPigeonAirlines.Domain.Abstract;
using UnitedPigeonAirlines.Data.Repositories;
using UnitedPigeonAirlines.Data.Entities.CartAggregate;
namespace UnitedPigeonAirlines.Domain.Concrete
{
public class DefaultCalculationStrategy:IPriceCalculationStrategy
{
private IPigeonRepository pigrepo;
public DefaultCalculationStrategy(IPigeonRepository pigeonrepo)
{
pigrepo = pigeonrepo;
}
public decimal CalculatePrice(Cart cart,CartLine line)
{
int quant = line.Quantity;
decimal Price = pigrepo.GetPigeon(line.PigeonId).BasicPrice;
if (quant > 1)
{
return Price * quant;
}
else
{
return Price;
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Semon.Yahtzee.Rules.Helpers
{
public class DiceValue
{
public int Value { get; private set; }
public bool Used { get; private set; }
public DiceValue(int value)
{
Value = value;
Used = false;
}
public bool Use()
{
return Used = true;
}
}
}
|
using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata;
#nullable disable
namespace TestDbFirst
{
public partial class FootballClubKPZContext : DbContext
{
public FootballClubKPZContext()
{
}
public FootballClubKPZContext(DbContextOptions<FootballClubKPZContext> options)
: base(options)
{
}
public virtual DbSet<Club> Clubs { get; set; }
public virtual DbSet<Contract> Contracts { get; set; }
public virtual DbSet<Match> Matches { get; set; }
public virtual DbSet<Player> Players { get; set; }
public virtual DbSet<PlayerMatch> PlayerMatches { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
if (!optionsBuilder.IsConfigured)
{
#warning To protect potentially sensitive information in your connection string, you should move it out of source code. You can avoid scaffolding the connection string by using the Name= syntax to read it from configuration - see https://go.microsoft.com/fwlink/?linkid=2131148. For more guidance on storing connection strings, see http://go.microsoft.com/fwlink/?LinkId=723263.
optionsBuilder.UseSqlServer("Server=(localdb)\\mssqllocaldb;Database=FootballClubKPZ;Trusted_Connection=True;");
}
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.HasAnnotation("Relational:Collation", "SQL_Latin1_General_CP1_CI_AS");
modelBuilder.Entity<Club>(entity =>
{
entity.ToTable("Club");
entity.Property(e => e.Id).HasColumnName("id");
entity.Property(e => e.Budget).HasColumnName("budget");
entity.Property(e => e.Country)
.HasMaxLength(50)
.HasColumnName("country");
entity.Property(e => e.Name)
.HasMaxLength(50)
.HasColumnName("name");
entity.Property(e => e.YearFounded).HasColumnName("year_founded");
});
modelBuilder.Entity<Contract>(entity =>
{
entity.Property(e => e.SignedDate).HasDefaultValueSql("(getutcdate())");
});
modelBuilder.Entity<Match>(entity =>
{
entity.HasIndex(e => e.ClubId, "IX_Matches_Club_Id");
entity.Property(e => e.ClubEnemyName)
.HasMaxLength(50)
.HasColumnName("Club_Enemy_Name");
entity.Property(e => e.ClubId).HasColumnName("Club_Id");
entity.Property(e => e.Location).HasMaxLength(255);
entity.Property(e => e.Team1Goals).HasColumnName("Team1_Goals");
entity.Property(e => e.Team2Goals).HasColumnName("Team2_Goals");
entity.HasOne(d => d.Club)
.WithMany(p => p.Matches)
.HasForeignKey(d => d.ClubId)
.OnDelete(DeleteBehavior.Cascade);
});
modelBuilder.Entity<Player>(entity =>
{
entity.ToTable("Player");
entity.HasIndex(e => e.ClubId, "IX_Player_Club_Id");
entity.HasIndex(e => e.ContractId, "IX_Player_Contract_Id")
.IsUnique()
.HasFilter("([Contract_Id] IS NOT NULL)");
entity.Property(e => e.ClubId).HasColumnName("Club_Id");
entity.Property(e => e.ContractId).HasColumnName("Contract_Id");
entity.Property(e => e.FirstName)
.IsRequired()
.HasMaxLength(50);
entity.Property(e => e.LastName).IsRequired();
entity.Property(e => e.Position)
.IsRequired()
.HasMaxLength(3)
.HasDefaultValueSql("(N'CM')");
entity.HasOne(d => d.Club)
.WithMany(p => p.Players)
.HasForeignKey(d => d.ClubId)
.OnDelete(DeleteBehavior.Cascade);
entity.HasOne(d => d.Contract)
.WithOne(p => p.Player)
.HasForeignKey<Player>(d => d.ContractId)
.OnDelete(DeleteBehavior.Cascade);
});
modelBuilder.Entity<PlayerMatch>(entity =>
{
entity.HasKey(e => new { e.PlayerId, e.MatchId });
entity.HasIndex(e => e.MatchId, "IX_PlayerMatches_Match_Id");
entity.Property(e => e.PlayerId).HasColumnName("Player_Id");
entity.Property(e => e.MatchId).HasColumnName("Match_Id");
entity.HasOne(d => d.Match)
.WithMany(p => p.PlayerMatches)
.HasForeignKey(d => d.MatchId);
entity.HasOne(d => d.Player)
.WithMany(p => p.PlayerMatches)
.HasForeignKey(d => d.PlayerId)
.OnDelete(DeleteBehavior.ClientSetNull);
});
OnModelCreatingPartial(modelBuilder);
}
partial void OnModelCreatingPartial(ModelBuilder modelBuilder);
}
}
|
using System.Threading.Tasks;
namespace ALTechTest.Interfaces
{
public interface IServiceCaller
{
public Task<string> GetApiResponseString(string requestUri);
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SS.Test.Handler
{
public static class RConstant
{
//##[序号][实例ID][Route]body%%
public static string MarkBeginChar = "##";
public static string MarkEndChar = "%%";
public readonly static byte[] BeginMarkByte = new byte[] { 0x23, 0x23 };//##
public readonly static byte[] EndMarkByte = new byte[] { 0x25, 0x25 };//%%
public readonly static byte Semicolon = 0x3B;
public static readonly string UserUniqueKey = "userUnique";
}
}
|
using ProBuilder2.Math;
using System;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
namespace ProBuilder2.Common
{
public class pb_MeshUtility
{
public static void CollapseSharedVertices(pb_Object pb)
{
List<List<int>> inIndices = pb_MeshUtility.FindDuplicateVertices(pb);
Mesh msh = pb.msh;
pb_MeshUtility.MergeVertices(inIndices, ref msh);
}
public static void MergeVertices(List<List<int>> InIndices, ref Mesh InMesh)
{
Dictionary<int, int> dictionary = new Dictionary<int, int>();
using (List<List<int>>.Enumerator enumerator = InIndices.GetEnumerator())
{
while (enumerator.MoveNext())
{
List<int> current = enumerator.get_Current();
for (int i = 1; i < current.get_Count(); i++)
{
dictionary.Add(current.get_Item(i), current.get_Item(0));
}
}
}
for (int j = 0; j < InMesh.get_subMeshCount(); j++)
{
int[] triangles = InMesh.GetTriangles(j);
for (int k = 0; k < triangles.Length; k++)
{
if (dictionary.ContainsKey(triangles[k]))
{
triangles[k] = dictionary.get_Item(triangles[k]);
}
}
InMesh.SetTriangles(triangles, j);
}
List<int> inUnusedVertices = Enumerable.ToList<int>(Enumerable.SelectMany<List<int>, int>(InIndices, (List<int> x) => x.GetRange(1, x.get_Count() - 1)));
pb_MeshUtility.RemoveVertices(inUnusedVertices, ref InMesh);
}
public static void RemoveVertices(List<int> InUnusedVertices, ref Mesh InMesh)
{
int vertexCount = InMesh.get_vertexCount();
int count = InUnusedVertices.get_Count();
Vector3[] vertices = InMesh.get_vertices();
Vector3[] array = new Vector3[vertexCount - count];
Vector3[] normals = InMesh.get_normals();
Vector3[] array2 = new Vector3[vertexCount - count];
Vector4[] tangents = InMesh.get_tangents();
Vector4[] array3 = new Vector4[vertexCount - count];
Vector2[] uv = InMesh.get_uv();
Vector2[] array4 = new Vector2[vertexCount - count];
Color[] colors = InMesh.get_colors();
Color[] array5 = new Color[vertexCount - count];
InUnusedVertices.Sort();
int num;
for (int i = 0; i < InMesh.get_subMeshCount(); i++)
{
int[] triangles = InMesh.GetTriangles(i);
for (int j = 0; j < triangles.Length; j++)
{
num = pbUtil.NearestIndexPriorToValue<int>(InUnusedVertices, triangles[j]) + 1;
triangles[j] -= num;
}
InMesh.SetTriangles(triangles, i);
}
num = 0;
int num2 = 0;
for (int k = 0; k < vertexCount; k++)
{
if (num < count && k >= InUnusedVertices.get_Item(num))
{
num++;
}
else
{
array[num2] = vertices[k];
array2[num2] = normals[k];
array3[num2] = tangents[k];
array4[num2] = uv[k];
array5[num2] = colors[k];
num2++;
}
}
InMesh.set_vertices(array);
InMesh.set_normals(array2);
InMesh.set_tangents(array3);
InMesh.set_uv(array4);
InMesh.set_colors(array5);
}
public static List<List<int>> FindDuplicateVertices(pb_Object pb)
{
Vector3[] normals = pb.msh.get_normals();
Vector2[] uv = pb.uv;
int[] array = new int[normals.Length];
pb_Face[] faces = pb.faces;
for (int i = 0; i < faces.Length; i++)
{
pb_Face pb_Face = faces[i];
int[] distinctIndices = pb_Face.distinctIndices;
for (int j = 0; j < distinctIndices.Length; j++)
{
int num = distinctIndices[j];
array[num] = pb_Face.smoothingGroup;
}
}
List<List<int>> list = new List<List<int>>();
for (int k = 0; k < pb.sharedIndices.Length; k++)
{
Dictionary<int, List<int>> dictionary = new Dictionary<int, List<int>>();
int[] array2 = pb.sharedIndices[k].array;
for (int l = 0; l < array2.Length; l++)
{
int num2 = array2[l];
if (array[num2] >= 1 && array[num2] <= 24)
{
List<int> list2;
if (dictionary.TryGetValue(array[num2], ref list2))
{
list2.Add(num2);
}
else
{
Dictionary<int, List<int>> arg_FC_0 = dictionary;
int arg_FC_1 = array[num2];
List<int> list3 = new List<int>();
list3.Add(num2);
arg_FC_0.Add(arg_FC_1, list3);
}
}
}
using (Dictionary<int, List<int>>.Enumerator enumerator = dictionary.GetEnumerator())
{
while (enumerator.MoveNext())
{
KeyValuePair<int, List<int>> current = enumerator.get_Current();
List<List<int>> list4 = new List<List<int>>();
using (List<int>.Enumerator enumerator2 = current.get_Value().GetEnumerator())
{
while (enumerator2.MoveNext())
{
int current2 = enumerator2.get_Current();
bool flag = false;
for (int m = 0; m < list4.get_Count(); m++)
{
if (uv[list4.get_Item(m).get_Item(0)].Approx(uv[current2], 0.001f))
{
list4.get_Item(m).Add(current2);
flag = true;
break;
}
}
if (!flag)
{
List<List<int>> arg_1D4_0 = list4;
List<int> list3 = new List<int>();
list3.Add(current2);
arg_1D4_0.Add(list3);
}
}
}
list.AddRange(Enumerable.Where<List<int>>(list4, (List<int> x) => x.get_Count() > 1));
}
}
}
return list;
}
public static void GenerateTangent(ref Mesh InMesh)
{
int[] triangles = InMesh.get_triangles();
Vector3[] vertices = InMesh.get_vertices();
Vector2[] uv = InMesh.get_uv();
Vector3[] normals = InMesh.get_normals();
int num = triangles.Length;
int num2 = vertices.Length;
Vector3[] array = new Vector3[num2];
Vector3[] array2 = new Vector3[num2];
Vector4[] array3 = new Vector4[num2];
for (long num3 = 0L; num3 < (long)num; num3 += 3L)
{
long num4 = (long)triangles[(int)(checked((IntPtr)num3))];
long num5 = (long)triangles[(int)(checked((IntPtr)(unchecked(num3 + 1L))))];
long num6 = (long)triangles[(int)(checked((IntPtr)(unchecked(num3 + 2L))))];
Vector3 vector;
Vector3 vector2;
Vector3 vector3;
Vector2 vector4;
Vector2 vector5;
Vector2 vector6;
checked
{
vector = vertices[(int)((IntPtr)num4)];
vector2 = vertices[(int)((IntPtr)num5)];
vector3 = vertices[(int)((IntPtr)num6)];
vector4 = uv[(int)((IntPtr)num4)];
vector5 = uv[(int)((IntPtr)num5)];
vector6 = uv[(int)((IntPtr)num6)];
}
float num7 = vector2.x - vector.x;
float num8 = vector3.x - vector.x;
float num9 = vector2.y - vector.y;
float num10 = vector3.y - vector.y;
float num11 = vector2.z - vector.z;
float num12 = vector3.z - vector.z;
float num13 = vector5.x - vector4.x;
float num14 = vector6.x - vector4.x;
float num15 = vector5.y - vector4.y;
float num16 = vector6.y - vector4.y;
float num17 = 1f / (num13 * num16 - num14 * num15);
Vector3 vector7 = new Vector3((num16 * num7 - num15 * num8) * num17, (num16 * num9 - num15 * num10) * num17, (num16 * num11 - num15 * num12) * num17);
Vector3 vector8 = new Vector3((num13 * num8 - num14 * num7) * num17, (num13 * num10 - num14 * num9) * num17, (num13 * num12 - num14 * num11) * num17);
checked
{
array[(int)((IntPtr)num4)] += vector7;
array[(int)((IntPtr)num5)] += vector7;
array[(int)((IntPtr)num6)] += vector7;
array2[(int)((IntPtr)num4)] += vector8;
array2[(int)((IntPtr)num5)] += vector8;
array2[(int)((IntPtr)num6)] += vector8;
}
}
for (long num18 = 0L; num18 < (long)num2; num18 += 1L)
{
checked
{
Vector3 vector9 = normals[(int)((IntPtr)num18)];
Vector3 vector10 = array[(int)((IntPtr)num18)];
Vector3.OrthoNormalize(ref vector9, ref vector10);
array3[(int)((IntPtr)num18)].x = vector10.x;
array3[(int)((IntPtr)num18)].y = vector10.y;
array3[(int)((IntPtr)num18)].z = vector10.z;
array3[(int)((IntPtr)num18)].w = ((Vector3.Dot(Vector3.Cross(vector9, vector10), array2[(int)((IntPtr)num18)]) >= 0f) ? 1f : -1f);
}
}
InMesh.set_tangents(array3);
}
}
}
|
namespace Triton.Game.Mapping
{
using ns25;
using ns26;
using System;
using System.Collections.Generic;
using Triton.Game;
using Triton.Game.Mono;
[Attribute38("AchieveManager")]
public class AchieveManager : MonoClass
{
public AchieveManager(IntPtr address) : this(address, "AchieveManager")
{
}
public AchieveManager(IntPtr address, string className) : base(address, className)
{
}
public bool CanCancelQuest(int achieveID)
{
object[] objArray1 = new object[] { achieveID };
return base.method_11<bool>("CanCancelQuest", objArray1);
}
public bool CanCancelQuestNow()
{
return base.method_11<bool>("CanCancelQuestNow", Array.Empty<object>());
}
public void CancelQuest(int achieveID)
{
object[] objArray1 = new object[] { achieveID };
base.method_8("CancelQuest", objArray1);
}
public void CheckAllCardGainAchieves()
{
base.method_8("CheckAllCardGainAchieves", Array.Empty<object>());
}
public void CheckTimedTimedEventsAndLicenses(DateTime utcNow)
{
object[] objArray1 = new object[] { utcNow };
base.method_8("CheckTimedTimedEventsAndLicenses", objArray1);
}
public void FireAchieveCanceledEvent(int achieveID, bool success)
{
object[] objArray1 = new object[] { achieveID, success };
base.method_8("FireAchieveCanceledEvent", objArray1);
}
public void FireLicenseAddedAchievesUpdatedEvent()
{
base.method_8("FireLicenseAddedAchievesUpdatedEvent", Array.Empty<object>());
}
public static AchieveManager Get()
{
return MonoClass.smethod_15<AchieveManager>(TritonHs.MainAssemblyPath, "", "AchieveManager", "Get", Array.Empty<object>());
}
public Achievement GetAchievement(int achieveID)
{
object[] objArray1 = new object[] { achieveID };
return base.method_14<Achievement>("GetAchievement", objArray1);
}
public List<Achievement> GetAchievesInGroup(Achievement.Group achieveGroup)
{
Class272.Enum20[] enumArray1 = new Class272.Enum20[] { Class272.Enum20.ValueType };
object[] objArray1 = new object[] { achieveGroup };
Class267<Achievement> class2 = base.method_15<Class267<Achievement>>("GetAchievesInGroup", enumArray1, objArray1);
if (class2 != null)
{
return class2.method_25();
}
return null;
}
public List<Achievement> GetAchievesInGroup(Achievement.Group achieveGroup, bool isComplete)
{
Class272.Enum20[] enumArray1 = new Class272.Enum20[] { Class272.Enum20.ValueType, Class272.Enum20.Boolean };
object[] objArray1 = new object[] { achieveGroup, isComplete };
Class267<Achievement> class2 = base.method_15<Class267<Achievement>>("GetAchievesInGroup", enumArray1, objArray1);
if (class2 != null)
{
return class2.method_25();
}
return null;
}
public List<Achievement> GetActiveLicenseAddedAchieves()
{
Class267<Achievement> class2 = base.method_14<Class267<Achievement>>("GetActiveLicenseAddedAchieves", Array.Empty<object>());
if (class2 != null)
{
return class2.method_25();
}
return null;
}
public List<Achievement> GetActiveQuests(bool onlyNewlyActive)
{
object[] objArray1 = new object[] { onlyNewlyActive };
Class267<Achievement> class2 = base.method_14<Class267<Achievement>>("GetActiveQuests", objArray1);
if (class2 != null)
{
return class2.method_25();
}
return null;
}
public List<Achievement> GetCompletedAchieves()
{
Class267<Achievement> class2 = base.method_14<Class267<Achievement>>("GetCompletedAchieves", Array.Empty<object>());
if (class2 != null)
{
return class2.method_25();
}
return null;
}
public List<Achievement> GetNewCompletedAchieves()
{
Class267<Achievement> class2 = base.method_14<Class267<Achievement>>("GetNewCompletedAchieves", Array.Empty<object>());
if (class2 != null)
{
return class2.method_25();
}
return null;
}
public List<Achievement> GetNewlyProgressedQuests()
{
Class267<Achievement> class2 = base.method_14<Class267<Achievement>>("GetNewlyProgressedQuests", Array.Empty<object>());
if (class2 != null)
{
return class2.method_25();
}
return null;
}
public int GetNumAchievesInGroup(Achievement.Group achieveGroup)
{
object[] objArray1 = new object[] { achieveGroup };
return base.method_11<int>("GetNumAchievesInGroup", objArray1);
}
public Achievement GetUnlockGoldenHeroAchievement(string heroCardID, TAG_PREMIUM premium)
{
object[] objArray1 = new object[] { heroCardID, premium };
return base.method_14<Achievement>("GetUnlockGoldenHeroAchievement", objArray1);
}
public bool HasActiveAchievesForEvent(SpecialEventType eventTrigger)
{
object[] objArray1 = new object[] { eventTrigger };
return base.method_11<bool>("HasActiveAchievesForEvent", objArray1);
}
public bool HasActiveLicenseAddedAchieves()
{
return base.method_11<bool>("HasActiveLicenseAddedAchieves", Array.Empty<object>());
}
public bool HasActiveQuests(bool onlyNewlyActive)
{
object[] objArray1 = new object[] { onlyNewlyActive };
return base.method_11<bool>("HasActiveQuests", objArray1);
}
public bool HasIncompletePurchaseAchieves()
{
return base.method_11<bool>("HasIncompletePurchaseAchieves", Array.Empty<object>());
}
public bool HasUnlockedFeature(Achievement.UnlockableFeature feature)
{
object[] objArray1 = new object[] { feature };
return base.method_11<bool>("HasUnlockedFeature", objArray1);
}
public void Heartbeat()
{
base.method_8("Heartbeat", Array.Empty<object>());
}
public static void Init()
{
MonoClass.smethod_17(TritonHs.MainAssemblyPath, "", "AchieveManager", "Init");
}
public void InitAchieveManager()
{
base.method_8("InitAchieveManager", Array.Empty<object>());
}
public void InitAchievement(Achievement achievement)
{
object[] objArray1 = new object[] { achievement };
base.method_8("InitAchievement", objArray1);
}
public static void InitRequests()
{
MonoClass.smethod_17(TritonHs.MainAssemblyPath, "", "AchieveManager", "InitRequests");
}
public static bool IsActiveQuest(Achievement obj, bool onlyNewlyActive)
{
object[] objArray1 = new object[] { obj, onlyNewlyActive };
return MonoClass.smethod_14<bool>(TritonHs.MainAssemblyPath, "", "AchieveManager", "IsActiveQuest", objArray1);
}
public bool IsReady()
{
return base.method_11<bool>("IsReady", Array.Empty<object>());
}
public void LoadAchievesFromDBF()
{
base.method_8("LoadAchievesFromDBF", Array.Empty<object>());
}
public void NotifyOfCardGained(EntityDef entityDef, TAG_PREMIUM premium, int totalCount)
{
object[] objArray1 = new object[] { entityDef, premium, totalCount };
base.method_8("NotifyOfCardGained", objArray1);
}
public void NotifyOfClick(Achievement.ClickTriggerType clickType)
{
object[] objArray1 = new object[] { clickType };
base.method_8("NotifyOfClick", objArray1);
}
public void OnAccountLicenseAchieveResponse()
{
base.method_8("OnAccountLicenseAchieveResponse", Array.Empty<object>());
}
public void OnAccountLicenseAchievesUpdated(object userData)
{
object[] objArray1 = new object[] { userData };
base.method_8("OnAccountLicenseAchievesUpdated", objArray1);
}
public void OnAchieves()
{
base.method_8("OnAchieves", Array.Empty<object>());
}
public void OnAchieveValidated()
{
base.method_8("OnAchieveValidated", Array.Empty<object>());
}
public void OnActiveAndNewCompleteAchieves(Network.AchieveList activeAchievesList)
{
object[] objArray1 = new object[] { activeAchievesList };
base.method_8("OnActiveAndNewCompleteAchieves", objArray1);
}
public void OnAllAchieves(Network.AchieveList allAchievesList)
{
object[] objArray1 = new object[] { allAchievesList };
base.method_8("OnAllAchieves", objArray1);
}
public void OnEventTriggered()
{
base.method_8("OnEventTriggered", Array.Empty<object>());
}
public void OnQuestCanceled()
{
base.method_8("OnQuestCanceled", Array.Empty<object>());
}
public void TriggerLaunchDayEvent()
{
base.method_8("TriggerLaunchDayEvent", Array.Empty<object>());
}
public void WillReset()
{
base.method_8("WillReset", Array.Empty<object>());
}
public static long CHECK_LICENSE_ADDED_ACHIEVE_DELAY_TICKS
{
get
{
return MonoClass.smethod_6<long>(TritonHs.MainAssemblyPath, "", "AchieveManager", "CHECK_LICENSE_ADDED_ACHIEVE_DELAY_TICKS");
}
}
public bool m_allNetAchievesReceived
{
get
{
return base.method_2<bool>("m_allNetAchievesReceived");
}
}
public bool m_disableCancelButtonUntilServerReturns
{
get
{
return base.method_2<bool>("m_disableCancelButtonUntilServerReturns");
}
}
public long m_lastEventTimingAndLicenseAchieveCheck
{
get
{
return base.method_2<long>("m_lastEventTimingAndLicenseAchieveCheck");
}
}
public int m_numEventResponsesNeeded
{
get
{
return base.method_2<int>("m_numEventResponsesNeeded");
}
}
public bool m_waitingForActiveAchieves
{
get
{
return base.method_2<bool>("m_waitingForActiveAchieves");
}
}
public static long TIMED_ACHIEVE_VALIDATION_DELAY_TICKS
{
get
{
return MonoClass.smethod_6<long>(TritonHs.MainAssemblyPath, "", "AchieveManager", "TIMED_ACHIEVE_VALIDATION_DELAY_TICKS");
}
}
public static long TIMED_AND_LICENSE_ACHIEVE_CHECK_DELAY_TICKS
{
get
{
return MonoClass.smethod_6<long>(TritonHs.MainAssemblyPath, "", "AchieveManager", "TIMED_AND_LICENSE_ACHIEVE_CHECK_DELAY_TICKS");
}
}
}
}
|
using Xamarin.Forms;
using Xamarin.Forms.Platform.Android;
using Android.Graphics;
using Liddup.Controls;
using Liddup.Droid.Renderers;
[assembly: ExportRenderer(typeof(Entry), typeof(UnderlinedEntryRenderer))]
namespace Liddup.Droid.Renderers
{
class UnderlinedEntryRenderer : EntryRenderer
{
protected override void OnElementChanged(ElementChangedEventArgs<Entry> e)
{
base.OnElementChanged(e);
if (Control == null || Element == null || e.OldElement != null) return;
var element = (UnderlinedEntry)Element;
Control.Background.SetColorFilter(element.BorderColor.ToAndroid(), PorterDuff.Mode.SrcAtop);
Control.LetterSpacing = element.LetterSpacing;
UpdateLayout();
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.ComponentModel.DataAnnotations;
namespace Facultate.Models
{
public class Course
{
public int Id { get; set; }
[Required]
[Display(Name = "Course Name")]
[StringLength(30, ErrorMessage = "Limit Title to 30 characters.")]
public string Title { get; set; }
[Required]
[Display(Name = "Number of sessions")]
public int NumberOfSessions { get; set; }
}
}
|
namespace ns11
{
using System;
using System.Runtime.InteropServices;
[StructLayout(LayoutKind.Sequential)]
internal struct Struct13
{
private readonly Struct11[] struct11_0;
private readonly int int_0;
public Struct13(int numBitLevels)
{
this.int_0 = numBitLevels;
this.struct11_0 = new Struct11[((int) 1) << numBitLevels];
}
public void method_0()
{
for (uint i = 1; i < (((int) 1) << this.int_0); i++)
{
this.struct11_0[i].method_0();
}
}
public void method_1(Class61 class61_0, uint uint_0)
{
uint index = 1;
int num2 = this.int_0;
while (num2 > 0)
{
num2--;
uint num3 = (uint_0 >> num2) & 1;
this.struct11_0[index].method_2(class61_0, num3);
index = (index << 1) | num3;
}
}
public void method_2(Class61 class61_0, uint uint_0)
{
uint index = 1;
for (uint i = 0; i < this.int_0; i++)
{
uint num3 = uint_0 & 1;
this.struct11_0[index].method_2(class61_0, num3);
index = (index << 1) | num3;
uint_0 = uint_0 >> 1;
}
}
public uint method_3(uint uint_0)
{
uint num = 0;
uint index = 1;
int num3 = this.int_0;
while (num3 > 0)
{
num3--;
uint num4 = (uint_0 >> num3) & 1;
num += this.struct11_0[index].method_3(num4);
index = (index << 1) + num4;
}
return num;
}
public uint method_4(uint uint_0)
{
uint num = 0;
uint index = 1;
for (int i = this.int_0; i > 0; i--)
{
uint num4 = uint_0 & 1;
uint_0 = uint_0 >> 1;
num += this.struct11_0[index].method_3(num4);
index = (index << 1) | num4;
}
return num;
}
public static uint smethod_0(Struct11[] struct11_1, uint uint_0, int int_1, uint uint_1)
{
uint num = 0;
uint num2 = 1;
for (int i = int_1; i > 0; i--)
{
uint num4 = uint_1 & 1;
uint_1 = uint_1 >> 1;
num += struct11_1[uint_0 + num2].method_3(num4);
num2 = (num2 << 1) | num4;
}
return num;
}
public static void smethod_1(Struct11[] struct11_1, uint uint_0, Class61 class61_0, int int_1, uint uint_1)
{
uint num = 1;
for (int i = 0; i < int_1; i++)
{
uint num3 = uint_1 & 1;
struct11_1[uint_0 + num].method_2(class61_0, num3);
num = (num << 1) | num3;
uint_1 = uint_1 >> 1;
}
}
}
}
|
using System;
using MongoDB.Bson.Serialization.Attributes;
namespace FIUChat.DatabaseAccessObject.CommandObjects
{
public abstract class Command
{
public Command(Guid? ID)
{
if(ID == null)
{
ID = Guid.NewGuid();
}
else
{
this.ID = ID.Value;
}
}
[BsonId]
public Guid ID { get; set; }
public string Email { get; set; }
public string Password { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Identity.UI;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.EntityFrameworkCore;
using Webshop.Data;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using System.Reflection;
using System.IO;
using Microsoft.OpenApi.Models;
using AutoMapper;
using Microsoft.Extensions.FileProviders;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using System.Text;
using Microsoft.IdentityModel.Tokens;
using Webshop.Data.Models;
using Microsoft.AspNetCore.Http.Features;
using IHostingEnvironment = Microsoft.AspNetCore.Hosting.IHostingEnvironment;
namespace Webshop
{
public class Startup
{
public Startup(IConfiguration configuration, IHostingEnvironment env)
{
Configuration = configuration;
_env = env;
}
public IConfiguration Configuration { get; }
private IHostingEnvironment _env;
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
// inject appsettings
services.Configure<ApplicationSettings>(Configuration.GetSection("ApplicationSettings"));
// policy
services.AddCors(options =>
{
options.AddPolicy("MyCorsPolicy", builder => builder
.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader());
});
services.Configure<FormOptions>(o =>
{
o.ValueLengthLimit = int.MaxValue;
o.MultipartBodyLengthLimit = int.MaxValue;
o.MemoryBufferThreshold = int.MaxValue;
});
services.AddAutoMapper(typeof(Startup));
services.AddControllers();
services.AddMvc();
services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(
Configuration.GetConnectionString("DefaultConnection")));
//Ahhoz, hogy a role hozzáadás működjön az ehhez szükséges service-t hozzá kell adni
services.AddDefaultIdentity<User>(options => options.SignIn.RequireConfirmedAccount = true)
.AddRoles<IdentityRole>()
.AddEntityFrameworkStores<ApplicationDbContext>();
services.AddRazorPages();
// Register the Swagger generator, defining 1 or more Swagger documents
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new OpenApiInfo
{
Version = "v1",
Title = "WebShop API",
Description = "Egy webshop ASP.NET Core technologiaval",
TermsOfService = new Uri("https://example.com/terms"),
Contact = new OpenApiContact
{
Name = "Surmann Roland, Varga Kristof Laszlo",
Email = string.Empty
},
License = new OpenApiLicense
{
Name = "Use under LICX",
Url = new Uri("https://example.com/license"),
}
});
// Set the comments path for the Swagger JSON and UI.
var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
c.IncludeXmlComments(xmlPath);
});
//Titkosításhoz használt kulcs
var key = Encoding.UTF8.GetBytes(Configuration["ApplicationSettings:JWT_Secret"].ToString());
//JWT Authentication
services.AddAuthentication(x => {
//JWT authentication scheme settings
x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
x.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
}).AddJwtBearer(x => {
//JWT configuration
x.RequireHttpsMetadata = false;
//Szerveren nem tároljuk a token-t
x.SaveToken = false;
x.TokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters
{
//Security key-t ellenőrzi amikor token-t maj használja
ValidateIssuerSigningKey = true,
//A kulcs amit a titkosításhoz használunk
IssuerSigningKey = new SymmetricSecurityKey(key),
ValidateIssuer = false,
ValidateAudience = false,
ClockSkew = TimeSpan.Zero
};
});
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseDatabaseErrorPage();
}
else
{
app.UseExceptionHandler("/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseCors("MyCorsPolicy");
// Enable middleware to serve generated Swagger as a JSON endpoint.
app.UseSwagger(c =>
{
c.SerializeAsV2 = true;
});
// Enable middleware to serve generated Swagger as a JSON endpoint.
app.UseSwagger();
// Enable middleware to serve swagger-ui (HTML, JS, CSS, etc.),
// specifying the Swagger JSON endpoint.
app.UseSwaggerUI(c =>
{
c.SwaggerEndpoint("/swagger/v1/swagger.json", "WebShop");
c.RoutePrefix = "swagger/teszt";
});
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseStaticFiles(new StaticFileOptions
{
FileProvider = new PhysicalFileProvider(Path.Combine(Directory.GetCurrentDirectory(),@"Resources")),
RequestPath = new PathString("/Resources")
});
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseDefaultFiles();
app.Use(async (context, next) =>
{
await next();
if (context.Response.StatusCode == 404 &&
!Path.HasExtension(context.Request.Path.Value) &&
!context.Request.Path.Value.StartsWith("/api/"))
{
context.Request.Path = "/index.html";
await next();
}
});
app.UseEndpoints(endpoints =>
{
endpoints.MapRazorPages();
endpoints.MapControllers();
});
}
}
}
|
using System;
using System.Linq;
using DapperExtensions;
using Insurance.Model.App.Enum;
using Insurance.Model.Interfaces;
using Insurance.Model.Poco;
namespace Insurance.Services.DataSourse
{
public class ContactService : BaseService, IContactService
{
public Contact Login(string phone) {
try {
phone = new string(phone.Where(c => !char.IsWhiteSpace(c) && char.IsDigit(c)).ToArray());
return Connection.GetList<Contact>(Predicates.Field<Contact>(x => x.Phone, Operator.Eq, phone)).FirstOrDefault();
}
catch {
return null;
}
}
public Contact GetByPublicKey(string pk) {
try {
Guid publicKey;
return Guid.TryParse(pk, out publicKey) ?
Connection.GetList<Contact>(Predicates.Field<Contact>(x => x.PublicKey, Operator.Eq, publicKey)).SingleOrDefault() :
null;
}
catch {
return null;
}
}
public bool IsInRole(string pk, AppRole role) {
try {
return Connection.GetList<Contact>(Predicates.Field<Contact>(x => x.PublicKey.ToString(), Operator.Eq, pk)).Any();
}
catch {
return false;
}
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Webcorp.lin.binpack
{
// Method for Non Increasing Sort of Stocks
public class NonIncreasingSortOnStockSize : IComparer<BinStock>
{
public int Compare(BinStock x, BinStock y)
{
if (x.Size < y.Size) return 1;
else if (x.Size > y.Size) return -1;
else return 0;
}
}
// Method for Non Decreasing Sort of Items
public class NonDecreasingSortOnItemSize : IComparer<BinItem>
{
public int Compare(BinItem x, BinItem y)
{
if (x.Size > y.Size) return 1;
else if (x.Size < y.Size) return -1;
else return 0;
}
}
// Method for Non Increasing Sort of Items
public class NonIncreasingSortOnItemSize : IComparer<BinItem>
{
public int Compare(BinItem x, BinItem y)
{
if (x.Size < y.Size) return 1;
else if (x.Size > y.Size) return -1;
else return 0;
}
}
// Method for Non Decreasing Sort on Size of the Branch & Bound List
public class NonDecreasingSortOnBranchAndBoundSize : IComparer<BranchAndBound.BranchBound>
{
public int Compare(BranchAndBound.BranchBound x, BranchAndBound.BranchBound y)
{
if (x.Size > y.Size) return 1;
else if (x.Size < y.Size) return -1;
else return 0;
}
}
// Method for Non Decreasing Sort on Cost of the Branch & Bound List
public class NonDecreasingSortOnBranchAndBoundCost : IComparer<BranchAndBound.BranchBound>
{
public int Compare(BranchAndBound.BranchBound x, BranchAndBound.BranchBound y)
{
if (x.Cost > y.Cost) return 1;
else if (x.Cost < y.Cost) return -1;
else return 0;
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace UIFramework
{
public class UIRoot
{
static Transform transform;
static Canvas curCanvas;
static Transform recyclePool;//回收的窗体 隐藏
static Transform workstation;//前台显示/工作的窗体
static Transform noticestation;//提示类型的窗体
static bool isInit = false;
public static void Init()
{
if (transform == null)
{
var obj = Resources.Load<GameObject>("MainCanvas");
transform = Object.Instantiate(obj).transform;
curCanvas = transform.GetComponent<Canvas>();
}
if (recyclePool == null)
{
recyclePool = transform.Find("recyclePool");
}
if (workstation == null)
{
workstation = transform.Find("workstation");
}
if (noticestation == null)
{
noticestation = transform.Find("noticestation");
}
isInit = true;
}
public static void SetParent(Transform window, bool isOpen, bool isTipsWindow = false)
{
if (isInit == false)
{
Init();
}
if (isOpen == true)
{
if (isTipsWindow)
{
window.SetParent(noticestation, false);
}
else
{
window.SetParent(workstation, false);
}
}
else
{
window.SetParent(recyclePool, false);
}
}
public static void SetRenderCamera(Camera _uiCamera)
{
curCanvas.worldCamera = _uiCamera;
}
}
} |
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
namespace WebEditor
{
public class PageViewModel : ViewModelBase
{
private ReferenceViewModel _activeReference;
public string Name { get; set; }
public ReferenceViewModel ActiveReference
{
get
{
return _activeReference;
}
set
{
_activeReference = value;
OnPropertyChanged("ActiveReference");
}
}
public List<ReferenceViewModel> References { get; set; }
public static PageViewModel FromJson(string filepath)
{
string content = File.ReadAllText(filepath);
return JsonConvert.DeserializeObject<PageViewModel>(content);
}
}
public class ReferenceViewModel
{
public string Identifier { get; set; }
public List<SectionViewModel> Sections { get; set; }
}
public class SectionViewModel : ViewModelBase
{
private string _content;
public string Type { get; set; }
public string Content
{
get
{
return _content;
}
set
{
_content = value;
ApplicationManager.Instance.OnContentChanged();
OnPropertyChanged("Content");
}
}
}
}
|
using System;
using System.ComponentModel;
using BilibiliDM_PluginFramework.Annotations;
namespace BilibiliDM_PluginFramework
{
public class GiftRank : INotifyPropertyChanged
{
private decimal _coin;
private int _uid;
private string _uid_str;
private long _uidLong;
private string _userName;
/// <summary>
/// 用戶名
/// </summary>
public string UserName
{
get => _userName;
set
{
if (value == _userName) return;
_userName = value;
OnPropertyChanged(nameof(UserName));
}
}
/// <summary>
/// 花銷
/// </summary>
public decimal coin
{
get => _coin;
set
{
if (value == _coin) return;
_coin = value;
OnPropertyChanged(nameof(coin));
}
}
/// <summary>
/// UID 弃用
/// </summary>
[Obsolete("由于B站开始使用超长UID, 此字段定义已无法满足, 在int范围内的UID会继续赋值, 超范围会赋值为-1, 请使用uid_long和uid_str")]
public int uid
{
get => _uid;
set
{
if (value == _uid) return;
_uid = value;
OnPropertyChanged(nameof(uid));
}
}
public long uid_long
{
get => _uidLong;
set
{
if (value == _uidLong) return;
_uidLong = value;
OnPropertyChanged(nameof(uid_long));
}
}
/// <summary>
/// UID
/// </summary>
public string uid_str
{
get => _uid_str;
set
{
if (value == _uid_str) return;
_uid_str = value;
OnPropertyChanged(nameof(uid_str));
}
}
public event PropertyChangedEventHandler PropertyChanged;
[NotifyPropertyChangedInvocator]
protected virtual void OnPropertyChanged(string propertyName)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
} |
using KPI.Model.EF;
using KPI.Model.helpers;
using KPI.Model.ViewModel;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using System.IO;
using System.Configuration;
using PagedList;
using System.Data.Entity;
using System.Data.SqlClient;
namespace KPI.Model.DAO
{
public class UploadDAO : IDisposable
{
public KPIDbContext _dbContext = null;
public UploadDAO() => _dbContext = new KPIDbContext();
public bool AddRange1(List<EF.Data> entity)
{
foreach (var item in entity)
{
var itemcode = _dbContext.Datas.FirstOrDefault(x => x.KPILevelCode == item.KPILevelCode);
if (itemcode == null)
{
try
{
_dbContext.Datas.Add(item);
_dbContext.SaveChanges();
}
catch (Exception ex)
{
var message = ex.Message;
return false;
}
}
else if (item.Week > 0 && itemcode.Week == item.Week)
{
itemcode.Week = item.Week;
try
{
_dbContext.SaveChanges();
}
catch (Exception ex)
{
var message = ex.Message;
return false;
}
}
else if (item.Month > 0 && itemcode.Month == item.Month)
{
itemcode.Month = item.Month;
try
{
_dbContext.SaveChanges();
}
catch (Exception ex)
{
var message = ex.Message;
return false;
}
}
else if (item.Quarter > 0 && itemcode.Quarter == item.Quarter)
{
itemcode.Quarter = item.Quarter;
try
{
_dbContext.SaveChanges();
}
catch (Exception ex)
{
var message = ex.Message;
return false;
}
}
else if (item.Year > 0 && itemcode.Year == item.Year)
{
itemcode.Year = item.Year;
try
{
_dbContext.SaveChanges();
}
catch (Exception ex)
{
var message = ex.Message;
return false;
}
}
}
return true;
}
#region *) Helper của hàm ImportData
/// <summary>
/// Kiểm tra tồn tại Data
/// </summary>
/// <param name="kpilevelcode"></param>
/// <param name="period"></param>
/// <param name="periodValue"></param>
/// <param name="year"></param>
/// <returns></returns>
public Data IsExistKPILevelData(string kpilevelcode, string period, int periodValue, int year)
{
switch (period.ToSafetyString().ToUpper())
{
case "W":
return _dbContext.Datas.FirstOrDefault(x => x.KPILevelCode == kpilevelcode && x.Period == period && x.Week == periodValue && x.Yearly == year);
case "M":
return _dbContext.Datas.FirstOrDefault(x => x.KPILevelCode == kpilevelcode && x.Period == period && x.Month == periodValue && x.Yearly == year);
case "Q":
return _dbContext.Datas.FirstOrDefault(x => x.KPILevelCode == kpilevelcode && x.Period == period && x.Quarter == periodValue && x.Yearly == year);
case "Y":
return _dbContext.Datas.FirstOrDefault(x => x.KPILevelCode == kpilevelcode && x.Period == period && x.Year == periodValue && x.Yearly == year);
default:
return null;
}
}
/// <summary>
/// Hàm này dùng để lọc dữ liệu "Tạo mới" hay là "Cập nhật" đọc từ file Excel.
/// </summary>
/// <param name="entity">Danh sách đọc từ excel</param>
/// <returns>Trả về 2 danh sách "Tạo mới" và "Cập nhật" đọc từ file Excel</returns>
public Tuple<List<Data>, List<Data>> CreateOrUpdateData(List<UploadDataVM> entity)
{
List<Data> listCreateData = new List<Data>();
List<Data> listUpdateData = new List<Data>();
List<UploadDataVM> list = new List<UploadDataVM>();
foreach (var item in entity)
{
var value = item.KPILevelCode;
var kpilevelcode = value.Substring(0, value.Length - 1);
var period = value.Substring(value.Length - 1, 1);
var year = item.Year; //dữ liệu trong năm vd: năm 2019
var valuePeriod = item.Value;
var target = item.TargetValue;
//query trong bảng data nếu updated thì update lại db
var isExistData = IsExistKPILevelData(kpilevelcode, period, item.PeriodValue, year);
switch (period)
{
case "W":
var dataW = new Data();
dataW.KPILevelCode = kpilevelcode;
dataW.Value = item.Value;
dataW.Week = item.PeriodValue;
dataW.Yearly = year;
dataW.CreateTime = item.CreateTime;
dataW.Period = period;
if (item.TargetValue.ToDouble() > 0)
dataW.Target = item.TargetValue.ToString();
else dataW.Target = "0";
if (isExistData == null)
listCreateData.Add(dataW);
else if (isExistData != null)
{
if (dataW.Value != valuePeriod || dataW.Target != target)
{
dataW.ID = isExistData.ID;
listUpdateData.Add(dataW);
}
}
else
list.Add(item);
break;
case "M":
var dataM = new Data();
dataM.KPILevelCode = kpilevelcode;
dataM.Value = item.Value;
dataM.Month = item.PeriodValue;
dataM.Yearly = year;
dataM.CreateTime = item.CreateTime;
dataM.Period = period;
if (item.TargetValue.ToDouble() > 0)
dataM.Target = item.TargetValue.ToString();
else dataM.Target = "0";
if (isExistData == null)
listCreateData.Add(dataM);
else if (isExistData != null)
{
if (isExistData.Value != valuePeriod || isExistData.Target != target)
{
dataM.ID = isExistData.ID;
listUpdateData.Add(dataM);
}
}
else
list.Add(item);
break;
case "Q":
var dataQ = new Data();
dataQ.KPILevelCode = kpilevelcode;
dataQ.Value = item.Value;
dataQ.Quarter = item.PeriodValue;
dataQ.Yearly = year;
dataQ.CreateTime = item.CreateTime;
dataQ.Period = period;
if (item.TargetValue.ToDouble() > 0)
dataQ.Target = item.TargetValue.ToString();
else dataQ.Target = "0";
if (isExistData == null)
listCreateData.Add(dataQ);
else if (isExistData != null)
{
if (isExistData.Value != valuePeriod || isExistData.Target != target)
{
dataQ.ID = isExistData.ID;
listUpdateData.Add(dataQ);
}
}
else
list.Add(item);
break;
case "Y":
var dataY = new Data();
dataY.KPILevelCode = kpilevelcode;
dataY.Value = item.Value;
dataY.Year = item.PeriodValue;
dataY.Yearly = year;
dataY.CreateTime = item.CreateTime;
dataY.Period = period;
if (item.TargetValue.ToDouble() > 0)
dataY.Target = item.TargetValue.ToString();
else dataY.Target = "0";
if (isExistData == null)
listCreateData.Add(dataY);
else if (isExistData != null)
{
if (isExistData.Value != valuePeriod || isExistData.Target != target)
{
dataY.ID = isExistData.ID;
listUpdateData.Add(dataY);
}
}
else
list.Add(item);
break;
default:
break;
}
}
return Tuple.Create(listCreateData, listUpdateData);
}
public async Task<bool> IsExistsTag(int userId, int notifyId)
{
return await _dbContext.Tags.AnyAsync(x => x.UserID == userId && x.NotificationID == notifyId);
}
/// <summary>
/// Hàm này dùng để tìm CÁC category của mỗi kpilevelcode
/// </summary>
/// <param name="code"></param>
/// <returns></returns>
private async Task<List<int>> GetAllCategoryByKPILevel(string code)
{
var item = await _dbContext.KPILevels.FirstOrDefaultAsync(x => x.KPILevelCode == code && x.Checked == true);
var kpilevelID = item.ID;
var listCategory = await _dbContext.CategoryKPILevels.Where(x => x.KPILevelID == kpilevelID && x.Status == true).Select(x => x.CategoryID).ToListAsync();
return listCategory;
}
public async Task<string> GetKPIName(string code)
{
var item = await _dbContext.KPILevels.FirstOrDefaultAsync(x => x.KPILevelCode == code && x.Checked == true);
var kpilevelID = item.KPIID;
var listCategory = await _dbContext.KPIs.Where(x => x.ID == kpilevelID).FirstOrDefaultAsync();
return listCategory.Name;
}
/// <summary>
/// Hàm này dùng để tạo url chuyển tới trang ChartPriod của từng data khi update hoặc create
/// </summary>
/// <param name="datas"></param>
/// <returns></returns>
private async Task<List<string[]>> ListURLToChartPriodAsync(List<Data> datas)
{
var listURLToChartPeriod = new List<string[]>();
string http = ConfigurationManager.AppSettings["Http"].ToSafetyString();
string url = string.Empty;
foreach (var item in datas.DistinctBy(x => x.KPILevelCode))
{
var oc = new LevelDAO().GetNode(item.KPILevelCode);
var kpiname = await GetKPIName(item.KPILevelCode);
var listCategories = await GetAllCategoryByKPILevel(item.KPILevelCode);
if (item.Period == "W")
{
foreach (var cat in listCategories)
{
url = http + $"/ChartPeriod/?kpilevelcode={item.KPILevelCode}&catid={cat}&period={item.Period}&year={item.Yearly}&start=1&end=53";
listURLToChartPeriod.Add(new string[3]
{
url,kpiname,oc
});
}
}
if (item.Period == "M")
{
foreach (var cat in listCategories)
{
url = http + $"/ChartPeriod/?kpilevelcode={item.KPILevelCode}&catid={cat}&period={item.Period}&year={item.Yearly}&start=1&end=12";
listURLToChartPeriod.Add(new string[3]
{
url,kpiname,oc
});
}
}
if (item.Period == "Q")
{
foreach (var cat in listCategories)
{
url = http + $"/ChartPeriod/?kpilevelcode={item.KPILevelCode}&catid={cat}&period={item.Period}&year={item.Yearly}&start=1&end=4";
listURLToChartPeriod.Add(new string[3]
{
url,kpiname,oc
});
}
}
if (item.Period == "Y")
{
foreach (var cat in listCategories)
{
url = http + $"/ChartPeriod/?kpilevelcode={item.KPILevelCode}&catid={cat}&period={item.Period}&year={item.Yearly}&start={item.Yearly}&end={item.Yearly}";
listURLToChartPeriod.Add(new string[3]
{
url,kpiname,oc
});
}
}
}
return listURLToChartPeriod;
}
/// <summary>
/// Hàm này dùng để xem chi tiết cụ thể của thông báo
/// </summary>
/// <param name="datas"></param>
/// <param name="users"></param>
/// <param name="notificationId"></param>
/// <returns></returns>
public async Task CreateListTagAndNotificationDetail(List<string[]> datas, IEnumerable<int> users, int notificationId)
{
var listNotification = new List<NotificationDetail>();
foreach (var item in users)
{
foreach (var item2 in datas)
{
listNotification.Add(new NotificationDetail
{
Content = item2[2] + " & " + item2[1],
URL = item2[0],
NotificationID = notificationId,
UserID = item
});
}
}
_dbContext.NotificationDetails.AddRange(listNotification);
await _dbContext.SaveChangesAsync();
}
/// <summary>
/// Tạo thông báo
/// </summary>
/// <param name="notification"></param>
/// <returns></returns>
public async Task<int> CreateNotification(Notification notification)
{
_dbContext.Notifications.Add(notification);
await _dbContext.SaveChangesAsync();
return notification.ID;
}
/// <summary>
/// Tạo list PIC để thông báo gửi mail
/// </summary>
/// <param name="listKPILevelID"></param>
/// <returns></returns>
public async Task<List<int>> CreateListPIC(List<int> listKPILevelID)
{
#region *) Thông báo với các manager, owner, sponsor, updater khi upload xong
var listManager = (await _dbContext.Managers.Where(x => listKPILevelID.Contains(x.KPILevelID)).ToListAsync()).DistinctBy(x => x.KPILevelID).Select(x => x.UserID).ToList();
var listOwner = (await _dbContext.Owners.Where(x => listKPILevelID.Contains(x.KPILevelID)).ToListAsync()).DistinctBy(x => x.KPILevelID).Select(x => x.UserID).ToList();
var listSponsor = (await _dbContext.Sponsors.Where(x => listKPILevelID.Contains(x.KPILevelID)).ToListAsync()).DistinctBy(x => x.KPILevelID).Select(x => x.UserID).ToList();
var listUpdater = (await _dbContext.Uploaders.Where(x => listKPILevelID.Contains(x.KPILevelID)).ToListAsync()).DistinctBy(x => x.KPILevelID).Select(x => x.UserID).ToList();
var listAll = listManager.Union(listOwner).Union(listOwner).Union(listSponsor).Union(listUpdater);
#endregion
return listManager.Union(listOwner).Union(listOwner).Union(listSponsor).Union(listUpdater).ToList();
}
#endregion
public async Task<ImportDataVM> ImportData(List<UploadDataVM> entity, string userUpdate, UserProfileVM userProfileVM)
{
#region *) Biến toàn cục
string http = ConfigurationManager.AppSettings["Http"].ToSafetyString();
var listAdd = new List<Data>();
var listTag = new List<Tag>();
var listSendMail = new List<string>();
var listUploadKPIVMs = new List<UploadKPIVM>();
var listDataSuccess = new List<UploadKPIVM>();
var dataModel = _dbContext.Datas;
var kpiLevelModel = _dbContext.KPILevels;
var kpiModel = _dbContext.KPIs;
var levelModel = _dbContext.Levels;
#endregion
#region *) Lọc dữ liệu làm 2 loại là tạo mới và cập nhật
var tuple = CreateOrUpdateData(entity);
var listCreate = tuple.Item1;
var listUpdate = tuple.Item2;
#endregion
try
{
#region *) Tạo mới
if (listCreate.Count() > 0)
{
_dbContext.Datas.AddRange(listCreate);
await _dbContext.SaveChangesAsync();
//Gui mail list nay khi update
//Tạo mới xong rồi thì thêm vào list gửi mail
foreach (var item in listCreate)
{
var tblKPILevelByKPILevelCode = await kpiLevelModel.FirstOrDefaultAsync(x => x.KPILevelCode == item.KPILevelCode);
#region *) Upload thành công thì sẽ gửi mail thông báo
if (item.Value.ToDouble() > 0)
{
var dataSuccess = new UploadKPIVM()
{
KPILevelCode = item.KPILevelCode,
Area = levelModel.FirstOrDefault(x => x.ID == tblKPILevelByKPILevelCode.LevelID).Name,
KPIName = kpiModel.FirstOrDefault(x => x.ID == tblKPILevelByKPILevelCode.KPIID).Name,
Week = item.Week,
Month = item.Month,
Quarter = item.Quarter,
Year = item.Year
};
listDataSuccess.Add(dataSuccess);
}
#endregion
#region *) Dưới target thì sẽ gửi mail thông báo
if (item.Value.ToDouble() < item.Target.ToDouble())
{
var dataUploadKPIVM = new UploadKPIVM()
{
KPILevelCode = item.KPILevelCode,
Area = levelModel.FirstOrDefault(x => x.ID == tblKPILevelByKPILevelCode.LevelID).Name,
KPIName = kpiModel.FirstOrDefault(x => x.ID == tblKPILevelByKPILevelCode.KPIID).Name,
Week = item.Week,
Month = item.Month,
Quarter = item.Quarter,
Year = item.Year
};
listUploadKPIVMs.Add(dataUploadKPIVM);
}
#endregion
}
//Tìm ID theo KPILevelCode trong bản KPILevel
var listKPILevel = listCreate.Select(x => x.KPILevelCode).Distinct().ToArray();
var listKPILevelID = _dbContext.KPILevels.Where(a => listKPILevel.Contains(a.KPILevelCode)).Select(a => a.ID).ToList();
#region *) Lưu vào bảng thông báo
var notifyId = await CreateNotification(new Notification
{
Content = "You have just uploaded some KPIs.",
Action = "Upload",
TaskName = "Upload KPI Data",
UserID = userProfileVM.User.ID,
Link = http + "/Home/ListSubNotificationDetail/"
});
#endregion
#region *) Thông báo với các manager, owner, sponsor, updater khi upload xong
var listAll =await CreateListPIC(listKPILevelID);
#endregion
#region *) Tạo danh sách gửi mail
listSendMail = _dbContext.Users.Where(x => listAll.Contains(x.ID)).Select(x => x.Email).ToList();
#endregion
#region *) Thêm vào bảng chi tiết thông báo
var listUrls = await ListURLToChartPriodAsync(listCreate);
await CreateListTagAndNotificationDetail(listUrls, listAll, notifyId);
#endregion
}
#endregion
#region *) Cập nhật
if (listUpdate.Count() > 0)
{
foreach (var item in listUpdate)
{
switch (item.Period)
{
case "W":
var dataW = await dataModel.FirstOrDefaultAsync(x => x.KPILevelCode == item.KPILevelCode && x.Period == item.Period && x.Week == item.Week && x.Yearly == item.Yearly);
dataW.Value = item.Value;
dataW.Target = item.Target;
_dbContext.SaveChanges();
break;
case "M":
var dataM = await dataModel.FirstOrDefaultAsync(x => x.KPILevelCode == item.KPILevelCode && x.Period == item.Period && x.Month == item.Month && x.Yearly == item.Yearly);
dataM.Value = item.Value;
dataM.Target = item.Target;
_dbContext.SaveChanges();
break;
case "Q":
var dataQ = await dataModel.FirstOrDefaultAsync(x => x.KPILevelCode == item.KPILevelCode && x.Period == item.Period && x.Quarter == item.Quarter && x.Yearly == item.Yearly);
dataQ.Value = item.Value;
dataQ.Target = item.Target;
_dbContext.SaveChanges();
break;
case "Y":
var dataY = await dataModel.FirstOrDefaultAsync(x => x.KPILevelCode == item.KPILevelCode && x.Period == item.Period && x.Year == item.Year && x.Yearly == item.Yearly);
dataY.Value = item.Value;
dataY.Target = item.Target;
_dbContext.SaveChanges();
break;
default:
break;
}
var tblKPILevelByKPILevelCode = await kpiLevelModel.FirstOrDefaultAsync(x => x.KPILevelCode == item.KPILevelCode);
#region *)
if (item.Value.ToDouble() > 0)
{
var dataSuccess = new UploadKPIVM()
{
KPILevelCode = item.KPILevelCode,
Area = levelModel.FirstOrDefault(x => x.ID == tblKPILevelByKPILevelCode.LevelID).Name,
KPIName = kpiModel.FirstOrDefault(x => x.ID == tblKPILevelByKPILevelCode.KPIID).Name,
Week = item.Week,
Month = item.Month,
Quarter = item.Quarter,
Year = item.Year
};
listDataSuccess.Add(dataSuccess);
}
#endregion
#region *) Nếu dữ liệu mà nhỏ hơn mục tiêu thì sẽ gửi mail
if (item.Value.ToDouble() < item.Target.ToDouble())
{
var dataUploadKPIVM = new UploadKPIVM()
{
KPILevelCode = item.KPILevelCode,
Area = levelModel.FirstOrDefault(x => x.ID == tblKPILevelByKPILevelCode.LevelID).Name,
KPIName = kpiModel.FirstOrDefault(x => x.ID == tblKPILevelByKPILevelCode.KPIID).Name,
Week = item.Week,
Month = item.Month,
Quarter = item.Quarter,
Year = item.Year
};
listUploadKPIVMs.Add(dataUploadKPIVM);
}
#endregion
}
//Tìm ID theo KPILevelCode trong bản KPILevel
var listKPILevel = listUpdate.Select(x => x.KPILevelCode).Distinct().ToArray();
var listKPILevelID = _dbContext.KPILevels.Where(a => listKPILevel.Contains(a.KPILevelCode)).Select(a => a.ID).ToList();
#region *) Lưu vào bảng thông báo
var notifyId = await CreateNotification(new Notification
{
Content = "You have just uploaded some KPIs.",
Action = "Upload",
TaskName = "Upload KPI Data",
UserID = userProfileVM.User.ID,
Link = http + "/Home/ListSubNotificationDetail/"
});
#endregion
#region *) Thông báo với các manager, owner, sponsor, updater khi upload xong
var listAll = await CreateListPIC(listKPILevelID);
#endregion
#region Tạo danh sách gửi mail
listSendMail = _dbContext.Users.Where(x => listAll.Contains(x.ID)).Select(x => x.Email).ToList();
#endregion
#region *) Thêm vào bảng chi tiết thông báo
var listUrls = await ListURLToChartPriodAsync(listUpdate);
await CreateListTagAndNotificationDetail(listUrls, listAll, notifyId);
#endregion
}
#endregion
if (listUploadKPIVMs.Count > 0 || listDataSuccess.Count > 0)
{
return new ImportDataVM
{
ListUploadKPIVMs = listUploadKPIVMs,
ListDataSuccess = listDataSuccess,
ListSendMail = listSendMail,
Status = true,
};
}
else
{
return new ImportDataVM
{
ListUploadKPIVMs = listUploadKPIVMs,
ListSendMail = listSendMail,
Status = true,
};
}
}
catch (Exception ex)
{
var message = ex.Message;
return new ImportDataVM
{
ListUploadKPIVMs = listUploadKPIVMs,
Status = false,
};
}
}
public async Task<IEnumerable<NotificationDetail>> GetAllSubNotificationsByIdAsync(int notificationId, int user)
{
return await _dbContext.NotificationDetails.Where(x => x.NotificationID == notificationId && x.UserID == user).ToListAsync();
}
public bool Update(EF.Data entity)
{
var item = _dbContext.Datas.FirstOrDefault(x => x.KPILevelCode == entity.KPILevelCode);
try
{
item = entity;
_dbContext.SaveChanges();
return true;
}
catch (Exception ex)
{
var message = ex.Message;
return false;
}
}
public async Task<bool> IsUpdater(int id)
{
if (await _dbContext.Uploaders.FirstOrDefaultAsync(x => x.UserID == id) == null)
return false;
return true;
}
public object UploadData()
{
var model = (from a in _dbContext.KPILevels
join h in _dbContext.KPIs on a.KPIID equals h.ID
join c in _dbContext.Levels on a.LevelID equals c.ID
where a.KPILevelCode != null && a.KPILevelCode != string.Empty
select new
{
KPILevelCode = a.KPILevelCode,
KPIName = h.Name,
LevelName = c.Name,
StatusW = _dbContext.KPILevels.FirstOrDefault(x => x.KPILevelCode == a.KPILevelCode).Weekly != null ? true : false,
StatusM = _dbContext.KPILevels.FirstOrDefault(x => x.KPILevelCode == a.KPILevelCode).Monthly != null ? true : false,
StatusQ = _dbContext.KPILevels.FirstOrDefault(x => x.KPILevelCode == a.KPILevelCode).Quarterly != null ? true : false,
StatusY = _dbContext.KPILevels.FirstOrDefault(x => x.KPILevelCode == a.KPILevelCode).Yearly != null ? true : false,
}).AsEnumerable();
model = model.ToList();
return model;
}
//public object DataUpLoad(int updaterid, int page, int pageSize)
//{
// var sql = @"SELECT DISTINCT(upl.KPILevelID),
// kpilevel.ID as KPILevelID,
// kpilevel.KPILevelCode,
// kpi.Name as KPIName,
// kpilevel.WeeklyChecked,
// kpilevel.MonthlyChecked,
// kpilevel.QuarterlyChecked,
// kpilevel.YearlyChecked
// FROM dbo.Uploaders as upl,
// dbo.KPILevels as kpilevel,
// dbo.KPIs as kpi
// WHERE upl.KPILevelID = kpilevel.ID
// and kpi.ID = kpilevel.KPIID
// and upl.UserID = @UserID";
// var model = _dbContext.Database.SqlQuery<ListDataUploadVM>(sql, new SqlParameter("UserID", updaterid)).ToList();
// var data = model.DistinctBy(x => x.KPIName).Select(x => new
// {
// x.KPILevelID,
// x.KPILevelCode,
// x.KPIName,
// StateDataW = _dbContext.Datas.Max(a => a.Week) > 0 ? true : false,
// StateDataM = _dbContext.Datas.Max(a => a.Month) > 0 ? true : false,
// StateDataQ = _dbContext.Datas.Max(a => a.Quarter) > 0 ? true : false,
// StateDataY = _dbContext.Datas.Max(a => a.Year) > 0 ? true : false,
// StateW = x.StateW.ToInt() > 0 ? true : false,
// StateM = x.StateM.ToInt() > 0 ? true : false,
// StateQ = x.StateQ.ToInt() > 0 ? true : false,
// StateY = x.StateY.ToInt() > 0 ? true : false,
// }).ToList();
// int totalRow = data.Count();
// data = data.OrderByDescending(x => x.KPIName)
// .Skip((page - 1) * pageSize)
// .Take(pageSize).ToList();
// return new
// {
// data = data,
// page,
// pageSize,
// status = true,
// total = totalRow,
// isUpdater = true
// };
//}
public async Task<object> ListKPIUpload(int updaterid, int page, int pageSize)
{
var datas = await _dbContext.Datas.ToListAsync();
var model = (await (from u in _dbContext.Uploaders.Where(x => x.UserID == updaterid)
join item in _dbContext.KPILevels on u.KPILevelID equals item.ID
join cat in _dbContext.CategoryKPILevels.Where(x => x.Status == true) on u.KPILevelID equals cat.KPILevelID
join kpi in _dbContext.KPIs on item.KPIID equals kpi.ID
select new
{
KPILevelID = u.KPILevelID,
KPIName = kpi.Name,
StateDataW = item.WeeklyChecked ?? false,
StateDataM = item.MonthlyChecked ?? false,
StateDataQ = item.QuarterlyChecked ?? false,
StateDataY = item.YearlyChecked ?? false,
}).ToListAsync())
.Select(x => new ListKPIUploadVM
{
KPILevelID = x.KPILevelID,
KPIName = x.KPIName,
StateW = datas.Max(x => x.Week) > 0 ? true : false,
StateM = datas.Max(x => x.Month) > 0 ? true : false,
StateQ = datas.Max(x => x.Quarter) > 0 ? true : false,
StateY = datas.Max(x => x.Year) > 0 ? true : false,
StateDataW = x.StateDataW,
StateDataM = x.StateDataM,
StateDataQ = x.StateDataQ,
StateDataY = x.StateDataY
}).DistinctBy(p => p.KPIName).ToList();
//bảng uploader có nhiều KPILevel trùng nhau vì 1 KPILevel thuộc nhiều Category khác nhau
//nên ta phải distinctBy KPILevelID để lấy ra danh sách KPI không bị trùng nhau vì yêu cầu chỉ cần lấy ra KPI để upload dữ liệu
////Mỗi KPILevel ứng với 1 KPI khác nhau
int totalRow = model.Count();
model = model.OrderByDescending(x => x.KPIName)
.Skip((page - 1) * pageSize)
.Take(pageSize).ToList();
return new
{
data = model,
page,
pageSize,
status = true,
total = totalRow,
isUpdater = true
};
}
public async Task<object> UpLoadKPILevel(int userid, int page, int pageSize)
{
var datas = _dbContext.Datas;
var model = await (from u in _dbContext.Users
join l in _dbContext.Levels on u.LevelID equals l.ID
join item in _dbContext.KPILevels on l.ID equals item.LevelID
join kpi in _dbContext.KPIs on item.KPIID equals kpi.ID
where u.ID == userid && item.Checked == true
select new KPIUpLoadVM
{
KPIName = kpi.Name,
StateW = item.WeeklyChecked == true && datas.Where(x => x.KPILevelCode == item.KPILevelCode).Max(x => x.Week) > 0 ? true : false,
StateM = item.MonthlyChecked == true && datas.Where(x => x.KPILevelCode == item.KPILevelCode).Max(x => x.Month) > 0 ? true : false,
StateQ = item.QuarterlyChecked == true && datas.Where(x => x.KPILevelCode == item.KPILevelCode).Max(x => x.Quarter) > 0 ? true : false,
StateY = item.YearlyChecked == true && datas.Where(x => x.KPILevelCode == item.KPILevelCode).Max(x => x.Year) > 0 ? true : false,
StateDataW = item.WeeklyChecked ?? false,
StateDataM = item.MonthlyChecked ?? false,
StateDataQ = item.QuarterlyChecked ?? false,
StateDataY = item.YearlyChecked ?? false,
}).ToListAsync();
int totalRow = model.Count();
model = model.OrderByDescending(x => x.KPIName)
.Skip((page - 1) * pageSize)
.Take(pageSize).ToList();
var vm = new WorkplaceVM()
{
KPIUpLoads = model,
total = totalRow,
page = page,
pageSize = pageSize
};
return vm;
}
public async Task<List<ActionPlanTagVM>> ListTasks(string code)
{
var actionPlans = new List<ActionPlanTagVM>();
var model = await _dbContext.ActionPlans.Where(x=>x.KPILevelCode == code).ToListAsync();
foreach (var x in model)
{
var kpilevel =await _dbContext.KPILevels.FirstOrDefaultAsync(a=>a.KPILevelCode == x.KPILevelCode);
var ocName = new LevelDAO().GetNode(kpilevel.LevelID);
var kpiName = (await _dbContext.KPIs.FirstOrDefaultAsync(a => a.ID == kpilevel.KPIID)).Name;
var createdBy = (await _dbContext.Users.FirstOrDefaultAsync(a => a.ID == x.UserID)).Alias;
actionPlans.Add(new ActionPlanTagVM
{
TaskName = x.Title,
Description = x.Description,
DueDate = x.Deadline.ToString("dddd, dd MMMM yyyy"),
UpdateSheduleDate = x.UpdateSheduleDate?.ToString("dddd, dd MMMM yyyy")??"#N/A",
ActualFinishDate = x.ActualFinishDate?.ToString("dddd, dd MMMM yyyy") ?? "#N/A",
Status = x.Status,
PIC = x.Tag,
Approved = x.ApprovedStatus,
KPIName = kpiName,
OC = ocName,
URL=_dbContext.Notifications.FirstOrDefault(a=>a.ActionplanID == x.ID)?.Link,
CreatedBy = createdBy,
CreatedDate = x.CreateTime.ToString("dddd, dd MMMM yyyy")
});
}
return actionPlans;
}
public async Task<object> LoadActionPlan(string role, int page, int pageSize,int userid)
{
var model = new List<ActionPlanTagVM>();
switch (role.ToSafetyString().ToUpper())
{
case "MAN":
if (_dbContext.Managers.Any(x => x.UserID.Equals(userid)))
{
model = (await (from d in _dbContext.Datas
join ac in _dbContext.ActionPlans on d.ID equals ac.DataID
join kpilevelcode in _dbContext.KPILevels on d.KPILevelCode equals kpilevelcode.KPILevelCode
join own in _dbContext.Managers on kpilevelcode.ID equals own.KPILevelID
select new
{
ac.ID,
TaskName = ac.Title,
Description = ac.Description,
DuaDate = ac.Deadline,
UpdateSheuleDate = ac.UpdateSheduleDate,
ActualFinishDate = ac.ActualFinishDate,
Status = ac.Status,
PIC = ac.Tag,
Code = ac.KPILevelCode,
Approved = ac.ApprovedStatus,
KPIID = _dbContext.KPILevels.FirstOrDefault(a => a.KPILevelCode == d.KPILevelCode).KPIID,
KPILevelID = _dbContext.KPILevels.FirstOrDefault(a => a.KPILevelCode == d.KPILevelCode).ID
}).Distinct()
.ToListAsync())
.Select(x => new ActionPlanTagVM
{
TaskName = x.TaskName,
Description = x.Description,
DueDate = x.DuaDate.ToString("dddd, dd MMMM yyyy"),
UpdateSheduleDate = x.UpdateSheuleDate?.ToString("dddd, dd MMMM yyyy"),
ActualFinishDate = x.ActualFinishDate?.ToString("dddd, dd MMMM yyyy"),
Status = x.Status,
PIC = x.PIC,
OC = new LevelDAO().GetNode(x.Code),
Approved = x.Approved,
KPIName = _dbContext.KPIs.FirstOrDefault(a => a.ID == x.KPIID).Name,
URL = _dbContext.Notifications.FirstOrDefault(a => a.ActionplanID == x.ID)?.Link ?? "/"
}).ToList();
break;
}
break;
case "OWN":
if (_dbContext.Owners.Any(x => x.UserID.Equals(userid)))
{
model = (await (from d in _dbContext.Datas
join ac in _dbContext.ActionPlans on d.ID equals ac.DataID
join kpilevelcode in _dbContext.KPILevels on d.KPILevelCode equals kpilevelcode.KPILevelCode
join own in _dbContext.Owners on kpilevelcode.ID equals own.KPILevelID
select new
{
ac.ID,
TaskName = ac.Title,
Description = ac.Description,
DuaDate = ac.Deadline,
UpdateSheuleDate = ac.UpdateSheduleDate,
ActualFinishDate = ac.ActualFinishDate,
Code = ac.KPILevelCode,
Status = ac.Status,
PIC = ac.Tag,
Approved = ac.ApprovedStatus,
KPIID = _dbContext.KPILevels.FirstOrDefault(a => a.KPILevelCode == d.KPILevelCode).KPIID,
KPILevelID = _dbContext.KPILevels.FirstOrDefault(a => a.KPILevelCode == d.KPILevelCode).ID
}).Distinct()
.ToListAsync())
.Select(x => new ActionPlanTagVM
{
TaskName = x.TaskName,
Description = x.Description,
DueDate = x.DuaDate.ToString("dddd, dd MMMM yyyy"),
UpdateSheduleDate = x.UpdateSheuleDate?.ToString("dddd, dd MMMM yyyy"),
ActualFinishDate = x.ActualFinishDate?.ToString("dddd, dd MMMM yyyy"),
Status = x.Status,
PIC = x.PIC,
OC = new LevelDAO().GetNode(x.Code),
Approved = x.Approved,
KPIName = _dbContext.KPIs.FirstOrDefault(a => a.ID == x.KPIID).Name
,
URL = _dbContext.Notifications.FirstOrDefault(a => a.ActionplanID == x.ID)?.Link ?? "/"
}).ToList();
break;
}
break;
case "UPD":
if (_dbContext.Uploaders.Any(x => x.UserID.Equals(userid)))
{
model = (await (from d in _dbContext.Datas
join ac in _dbContext.ActionPlans on d.ID equals ac.DataID
join kpilevelcode in _dbContext.KPILevels on d.KPILevelCode equals kpilevelcode.KPILevelCode
join own in _dbContext.Uploaders on kpilevelcode.ID equals own.KPILevelID
select new
{
ac.ID,
KPILevelCode = d.KPILevelCode,
TaskName = ac.Title,
Description = ac.Description,
DuaDate = ac.Deadline,
UpdateSheuleDate = ac.UpdateSheduleDate,
ActualFinishDate = ac.ActualFinishDate,
Code = ac.KPILevelCode,
Status = ac.Status,
PIC = ac.Tag,
Approved = ac.ApprovedStatus,
KPIID = _dbContext.KPILevels.FirstOrDefault(a => a.KPILevelCode == d.KPILevelCode).KPIID,
KPILevelID = _dbContext.KPILevels.FirstOrDefault(a => a.KPILevelCode == d.KPILevelCode).ID
}).Distinct()
.ToListAsync())
.Select(x => new ActionPlanTagVM
{
TaskName = x.TaskName,
Description = x.Description,
DueDate = x.DuaDate.ToString("dddd, dd MMMM yyyy"),
UpdateSheduleDate = x.UpdateSheuleDate?.ToString("dddd, dd MMMM yyyy"),
ActualFinishDate = x.ActualFinishDate?.ToString("dddd, dd MMMM yyyy"),
Status = x.Status,
OC = new LevelDAO().GetNode(x.Code),
PIC = x.PIC,
Approved = x.Approved,
KPIName = _dbContext.KPIs.FirstOrDefault(a => a.ID == x.KPIID).Name,
URL = _dbContext.Notifications.FirstOrDefault(a => a.ActionplanID == x.ID)?.Link ?? "/"
}).ToList();
break;
}
break;
case "SPO":
if (_dbContext.Sponsors.Any(x => x.UserID.Equals(userid)))
{
model = (await (from d in _dbContext.Datas
join ac in _dbContext.ActionPlans on d.ID equals ac.DataID
join kpilevelcode in _dbContext.KPILevels on d.KPILevelCode equals kpilevelcode.KPILevelCode
join own in _dbContext.Sponsors on kpilevelcode.ID equals own.KPILevelID
select new
{
ac.ID,
TaskName = ac.Title,
Description = ac.Description,
DuaDate = ac.Deadline,
UpdateSheuleDate = ac.UpdateSheduleDate,
ActualFinishDate = ac.ActualFinishDate,
Status = ac.Status,
Code = ac.KPILevelCode,
PIC = ac.Tag,
Approved = ac.ApprovedStatus,
KPIID = _dbContext.KPILevels.FirstOrDefault(a => a.KPILevelCode == d.KPILevelCode).KPIID,
KPILevelID = _dbContext.KPILevels.FirstOrDefault(a => a.KPILevelCode == d.KPILevelCode).ID
}).Distinct()
.ToListAsync())
.Select(x => new ActionPlanTagVM
{
TaskName = x.TaskName,
KPIName = _dbContext.KPIs.FirstOrDefault(a => a.ID == x.KPIID).Name,
Description = x.Description,
DueDate = x.DuaDate.ToString("dddd, dd MMMM yyyy"),
UpdateSheduleDate = x.UpdateSheuleDate?.ToString("dddd, dd MMMM yyyy"),
ActualFinishDate = x.ActualFinishDate?.ToString("dddd, dd MMMM yyyy"),
OC = new LevelDAO().GetNode(x.Code),
Status = x.Status,
PIC = x.PIC,
Approved = x.Approved,
URL = _dbContext.Notifications.FirstOrDefault(a => a.ActionplanID == x.ID)?.Link ?? "/"
}).ToList();
break;
}
break;
case "PAR":
if (_dbContext.Participants.Any(x => x.UserID.Equals(userid)))
{
model = (await (from d in _dbContext.Datas
join ac in _dbContext.ActionPlans on d.ID equals ac.DataID
join kpilevelcode in _dbContext.KPILevels on d.KPILevelCode equals kpilevelcode.KPILevelCode
join own in _dbContext.Participants on kpilevelcode.ID equals own.KPILevelID
select new
{
ac.ID,
TaskName = ac.Title,
Description = ac.Description,
DuaDate = ac.Deadline,
UpdateSheuleDate = ac.UpdateSheduleDate,
ActualFinishDate = ac.ActualFinishDate,
Code = ac.KPILevelCode,
Status = ac.Status,
PIC = ac.Tag,
Approved = ac.ApprovedStatus,
KPIID = _dbContext.KPILevels.FirstOrDefault(a => a.KPILevelCode == d.KPILevelCode).KPIID,
KPILevelID = _dbContext.KPILevels.FirstOrDefault(a => a.KPILevelCode == d.KPILevelCode).ID
}).Distinct()
.ToListAsync())
.Select(x => new ActionPlanTagVM
{
TaskName = x.TaskName,
Description = x.Description,
DueDate = x.DuaDate.ToString("dddd, dd MMMM yyyy"),
UpdateSheduleDate = x.UpdateSheuleDate?.ToString("dddd, dd MMMM yyyy"),
ActualFinishDate = x.ActualFinishDate?.ToString("dddd, dd MMMM yyyy"),
Status = x.Status,
OC = new LevelDAO().GetNode(x.Code),
PIC = x.PIC,
Approved = x.Approved,
KPIName = _dbContext.KPIs.FirstOrDefault(a => a.ID == x.KPIID).Name,
URL = _dbContext.Notifications.FirstOrDefault(a => a.ActionplanID == x.ID)?.Link ?? "/"
}).ToList();
break;
}
break;
default:
break;
}
int totalRow = model.Count();
model = model.OrderByDescending(x => x.KPIName)
.Skip((page - 1) * pageSize)
.Take(pageSize).ToList();
return new
{
status = true,
data = model,
total = totalRow,
page = page,
pageSize = pageSize
};
}
public string GetValueData(string KPILevelCode, string CharacterPeriod, int period)
{
var value = CharacterPeriod.ToSafetyString();
string obj = "0";
switch (value)
{
case "W":
var item = _dbContext.Datas.FirstOrDefault(x => x.KPILevelCode == KPILevelCode && x.Period == "W" && x.Week == period);
if (item != null)
obj = item.Value;
break;
case "M":
var item1 = _dbContext.Datas.FirstOrDefault(x => x.KPILevelCode == KPILevelCode && x.Period == "M" && x.Month == period);
if (item1 != null)
obj = item1.Value;
break;
case "Q":
var item2 = _dbContext.Datas.FirstOrDefault(x => x.KPILevelCode == KPILevelCode && x.Period == "Q" && x.Quarter == period);
if (item2 != null)
obj = item2.Value;
break;
case "Y":
var item3 = _dbContext.Datas.FirstOrDefault(x => x.KPILevelCode == KPILevelCode && x.Period == "Y" && x.Year == period);
if (item3 != null)
obj = item3.Value;
break;
}
return obj;
}
public string GetTargetData(string KPILevelCode, string CharacterPeriod, int period)
{
var value = CharacterPeriod.ToSafetyString();
string obj = "0";
switch (value)
{
case "W":
var item = _dbContext.Datas.FirstOrDefault(x => x.KPILevelCode == KPILevelCode && x.Period == "W" && x.Week == period);
if (item != null)
obj = item.Target;
break;
case "M":
var item1 = _dbContext.Datas.FirstOrDefault(x => x.KPILevelCode == KPILevelCode && x.Period == "M" && x.Month == period);
if (item1 != null)
obj = item1.Target;
break;
case "Q":
var item2 = _dbContext.Datas.FirstOrDefault(x => x.KPILevelCode == KPILevelCode && x.Period == "Q" && x.Quarter == period);
if (item2 != null)
obj = item2.Target;
break;
case "Y":
var item3 = _dbContext.Datas.FirstOrDefault(x => x.KPILevelCode == KPILevelCode && x.Period == "Y" && x.Year == period);
if (item3 != null)
obj = item3.Target;
break;
}
return obj;
}
public List<DataExportVM> DataExport(int userid)
{
var datas = _dbContext.Datas;
var kpis = _dbContext.KPIs;
var model = (from u in _dbContext.Uploaders.Where(x => x.UserID == userid).DistinctBy(x => x.KPILevelID)
join kpiLevel in _dbContext.KPILevels on u.KPILevelID equals kpiLevel.ID
join cat in _dbContext.CategoryKPILevels.Where(x => x.Status == true) on u.KPILevelID equals cat.KPILevelID
join kpi in _dbContext.KPIs on kpiLevel.KPIID equals kpi.ID
join l in _dbContext.Levels on kpiLevel.LevelID equals l.ID
where kpiLevel.Checked == true
select new DataExportVM
{
Area = l.Name,
KPILevelCode = kpiLevel.KPILevelCode,
KPIName = kpi.Name,
StateW = kpiLevel.WeeklyChecked ?? false,
StateM = kpiLevel.MonthlyChecked ?? false,
StateQ = kpiLevel.QuarterlyChecked ?? false,
StateY = kpiLevel.YearlyChecked ?? false,
PeriodValueW = datas.Where(x => x.KPILevelCode == kpiLevel.KPILevelCode).FirstOrDefault() != null ? (int?)datas.Where(x => x.KPILevelCode == kpiLevel.KPILevelCode).Max(x => x.Week) ?? 0 : 0,
PeriodValueM = datas.Where(x => x.KPILevelCode == kpiLevel.KPILevelCode).FirstOrDefault() != null ? (int?)datas.Where(x => x.KPILevelCode == kpiLevel.KPILevelCode).Max(x => x.Month) ?? 0 : 0,
PeriodValueQ = datas.Where(x => x.KPILevelCode == kpiLevel.KPILevelCode).FirstOrDefault() != null ? (int?)datas.Where(x => x.KPILevelCode == kpiLevel.KPILevelCode).Max(x => x.Quarter) ?? 0 : 0,
PeriodValueY = datas.Where(x => x.KPILevelCode == kpiLevel.KPILevelCode).FirstOrDefault() != null ? (int?)datas.Where(x => x.KPILevelCode == kpiLevel.KPILevelCode).Max(x => x.Year) ?? 0 : 0,
UploadTimeW = kpiLevel.Weekly,
UploadTimeM = kpiLevel.Monthly,
UploadTimeQ = kpiLevel.Quarterly,
UploadTimeY = kpiLevel.Yearly,
//TargetValueW = kpi.Unit == 1 ? "not require" : "require"
}).ToList();
return model;
}
//group by, join sample
//This is a sample
public List<DataExportVM> DataExport2(int userid)
{
var currentYear = DateTime.Now.Year;
var currentWeek = DateTime.Now.GetIso8601WeekOfYear();
var currentMonth = DateTime.Now.Month;
var currentQuarter = DateTime.Now.GetQuarter();
var model = (from l in _dbContext.Levels
join u in _dbContext.Users on l.ID equals u.LevelID
join item in _dbContext.KPILevels on l.ID equals item.LevelID
join d in _dbContext.Datas on item.KPILevelCode equals d.KPILevelCode into JoinItem
from joi in JoinItem.DefaultIfEmpty()
join k in _dbContext.KPIs on item.KPIID equals k.ID
where u.ID == userid && item.Checked == true
group new { u, l, item, joi, k } by new
{
u.Username,
Area = l.Name,
KPIName = k.Name,
item.KPILevelCode,
item.Checked,
item.WeeklyChecked,
item.MonthlyChecked,
item.QuarterlyChecked,
item.YearlyChecked,
} into g
select new
{
g.Key.Username,
Area = g.Key.Area,
KPIName = g.Key.KPIName,
g.Key.KPILevelCode,
g.Key.Checked,
g.Key.WeeklyChecked,
g.Key.MonthlyChecked,
g.Key.QuarterlyChecked,
g.Key.YearlyChecked,
PeriodValueW = g.Select(x => x.joi.Week).Max(),
PeriodValueM = g.Select(x => x.joi.Month).Max(),
PeriodValueQ = g.Select(x => x.joi.Quarter).Max(),
PeriodValueY = g.Select(x => x.joi.Year).Max(),
}).AsEnumerable()
.Select(x => new DataExportVM
{
Value = "0",
Year = currentYear,
KPILevelCode = x.KPILevelCode,
KPIName = x.KPIName,
Area = x.Area,
Remark = string.Empty,
PeriodValueW = x.PeriodValueW,
PeriodValueM = x.PeriodValueM,
PeriodValueQ = x.PeriodValueQ,
PeriodValueY = x.PeriodValueY,
});
return model.ToList();
}
public async Task<object> UpLoadKPILevelTrack(int userid, int page, int pageSize)
{
var model1 = await new LevelDAO().GetListTreeForWorkplace(userid);
var relative = ConvertHierarchicalToFlattenObject(model1);
var itemuser = _dbContext.Users.FirstOrDefault(x => x.ID == userid).LevelID;
var level = _dbContext.Levels.Select(
x => new LevelVM
{
ID = x.ID,
Name = x.Name,
Code = x.Code,
ParentID = x.ParentID,
ParentCode = x.ParentCode,
LevelNumber = x.LevelNumber,
State = x.State,
CreateTime = x.CreateTime
}).ToList();
// here you get your list
var itemlevel = _dbContext.Levels.FirstOrDefault(x => x.ID == itemuser);
var tree = GetTree(level, itemuser).FirstOrDefault();
var relative2 = ConvertHierarchicalToFlattenObject2(tree);
//var KPILevels = _dbContext.KPILevels.Where(x => x.Checked == true).ToList();
var list = new List<KPIUpLoadVM>();
var userKPIlevel = _dbContext.KPILevels.Where(x => x.Checked == true && x.LevelID == itemuser).ToList();
foreach (var item in userKPIlevel)
{
var data = new KPIUpLoadVM()
{
KPIName = _dbContext.KPIs.FirstOrDefault(x => x.ID == item.KPIID).Name,
Area = _dbContext.Levels.FirstOrDefault(x => x.ID == item.LevelID).Name,
StateW = item.WeeklyChecked == true && _dbContext.Datas.FirstOrDefault(x => x.KPILevelCode == item.KPILevelCode && x.Week > 0) != null ? true : false,
StateM = item.MonthlyChecked == true && _dbContext.Datas.FirstOrDefault(x => x.KPILevelCode == item.KPILevelCode && x.Month > 0) != null ? true : false,
StateQ = item.QuarterlyChecked == true && _dbContext.Datas.FirstOrDefault(x => x.KPILevelCode == item.KPILevelCode && x.Quarter > 0) != null ? true : false,
StateY = item.YearlyChecked == true && _dbContext.Datas.FirstOrDefault(x => x.KPILevelCode == item.KPILevelCode && x.Year > 0) != null ? true : false,
StateDataW = (bool?)item.WeeklyChecked ?? false,
StateDataM = (bool?)item.MonthlyChecked ?? false,
StateDataQ = (bool?)item.QuarterlyChecked ?? false,
StateDataY = (bool?)item.YearlyChecked ?? false,
};
list.Add(data);
}
var total = 0;
if (relative2 != null)
{
var KPILevels = new List<KPILevel>();
foreach (var aa in relative2)
{
if (aa != null)
{
KPILevels = (await _dbContext.KPILevels.Where(x => x.Checked == true && x.LevelID == aa.ID)
.Select(a => new
{
a.KPIID,
a.LevelID,
a.WeeklyChecked,
a.MonthlyChecked,
a.QuarterlyChecked,
a.YearlyChecked,
a.KPILevelCode
}).ToListAsync())
.Select(x => new KPILevel
{
KPIID = x.KPIID,
LevelID = x.LevelID,
WeeklyChecked = x.WeeklyChecked,
MonthlyChecked = x.MonthlyChecked,
QuarterlyChecked = x.QuarterlyChecked,
YearlyChecked = x.YearlyChecked,
KPILevelCode = x.KPILevelCode
}).ToList();
}
if (KPILevels != null)
{
foreach (var item in KPILevels)
{
var data = new KPIUpLoadVM()
{
KPIName = (await _dbContext.KPIs.FirstOrDefaultAsync(x => x.ID == item.KPIID)).Name,
Area = (await _dbContext.Levels.FirstOrDefaultAsync(x => x.ID == item.LevelID)).Name,
StateW = item.WeeklyChecked == true && (await _dbContext.Datas.FirstOrDefaultAsync(x => x.KPILevelCode == item.KPILevelCode && x.Week > 0)) != null ? true : false,
StateM = item.MonthlyChecked == true && (await _dbContext.Datas.FirstOrDefaultAsync(x => x.KPILevelCode == item.KPILevelCode && x.Month > 0)) != null ? true : false,
StateQ = item.QuarterlyChecked == true && (await _dbContext.Datas.FirstOrDefaultAsync(x => x.KPILevelCode == item.KPILevelCode && x.Quarter > 0)) != null ? true : false,
StateY = item.YearlyChecked == true && (await _dbContext.Datas.FirstOrDefaultAsync(x => x.KPILevelCode == item.KPILevelCode && x.Year > 0)) != null ? true : false
};
list.Add(data);
}
}
}
total = list.Count();
list = list.OrderBy(x => x.KPIName).Skip((page - 1) * pageSize).Take(pageSize).ToList();
}
return new
{
model = list,
total,
page,
pageSize
};
}
/// <summary>
/// Convert the nested hierarchical object to flatten object
/// </summary>
/// <param name="parent"></param>
/// <returns></returns>
public IEnumerable<KPITreeViewModel> ConvertHierarchicalToFlattenObject(KPITreeViewModel parent)
{
yield return parent;
foreach (KPITreeViewModel child in parent.children) // check null if you must
foreach (KPITreeViewModel relative in ConvertHierarchicalToFlattenObject(child))
yield return relative;
}
public IEnumerable<LevelVM> ConvertHierarchicalToFlattenObject2(LevelVM parent)
{
if (parent == null)
parent = new LevelVM();
if (parent.Levels == null)
parent.Levels = new List<LevelVM>();
yield return parent;
foreach (LevelVM child in parent.Levels) // check null if you must
foreach (LevelVM relative in ConvertHierarchicalToFlattenObject2(child))
yield return relative;
}
public List<LevelVM> GetTree(List<LevelVM> list, int parent)
{
return list.Where(x => x.ParentID == parent).Select(x => new LevelVM
{
ID = x.ID,
Name = x.Name,
Levels = GetTree(list, x.ID)
}).ToList();
}
public async Task<object> KPIRelated(int levelId, int page, int pageSize)
{
var obj = await _dbContext.KPILevels.Where(x => x.LevelID == levelId && x.Checked == true).ToListAsync();
var kpiName = _dbContext.KPIs;
var datas = _dbContext.Datas;
var list = new List<KPIUpLoadVM>();
if (obj != null)
{
foreach (var item in obj)
{
var data = new KPIUpLoadVM()
{
KPIName = kpiName.FirstOrDefault(x => x.ID == item.KPIID).Name,
StateW = item.WeeklyChecked == true && datas.FirstOrDefault(x => x.KPILevelCode == item.KPILevelCode && x.Week > 0) != null ? true : false,
StateM = item.MonthlyChecked == true && datas.FirstOrDefault(x => x.KPILevelCode == item.KPILevelCode && x.Month > 0) != null ? true : false,
StateQ = item.QuarterlyChecked == true && datas.FirstOrDefault(x => x.KPILevelCode == item.KPILevelCode && x.Quarter > 0) != null ? true : false,
StateY = item.YearlyChecked == true && datas.FirstOrDefault(x => x.KPILevelCode == item.KPILevelCode && x.Year > 0) != null ? true : false,
StateDataW = item.WeeklyChecked ?? false,
StateDataM = item.MonthlyChecked ?? false,
StateDataQ = item.QuarterlyChecked ?? false,
StateDataY = item.YearlyChecked ?? false,
};
list.Add(data);
}
var total = list.Count();
list = list.OrderBy(x => x.KPIName).Skip((page - 1) * pageSize).Take(pageSize).ToList();
return new
{
model = list,
total,
page,
pageSize,
status = true
};
}
return new
{
status = false
};
}
public object MyWorkplace(int levelId, int page, int pageSize)
{
var obj = _dbContext.KPILevels.Where(x => x.LevelID == levelId && x.Checked == true).ToList();
var kpiName = _dbContext.KPIs;
var datas = _dbContext.Datas;
var list = new List<KPIUpLoadVM>();
if (obj != null)
{
foreach (var item in obj)
{
var data = new KPIUpLoadVM()
{
KPIName = kpiName.FirstOrDefault(x => x.ID == item.KPIID).Name,
StateW = item.WeeklyChecked == true && datas.FirstOrDefault(x => x.KPILevelCode == item.KPILevelCode && x.Week > 0) != null ? true : false,
StateM = item.MonthlyChecked == true && datas.FirstOrDefault(x => x.KPILevelCode == item.KPILevelCode && x.Month > 0) != null ? true : false,
StateQ = item.QuarterlyChecked == true && datas.FirstOrDefault(x => x.KPILevelCode == item.KPILevelCode && x.Quarter > 0) != null ? true : false,
StateY = item.YearlyChecked == true && datas.FirstOrDefault(x => x.KPILevelCode == item.KPILevelCode && x.Year > 0) != null ? true : false
};
list.Add(data);
}
var total = list.Count();
list = list.OrderBy(x => x.KPIName).Skip((page - 1) * pageSize).Take(pageSize).ToList();
return new
{
model = list,
total,
status = true
};
}
return new
{
status = false
};
}
private bool disposed = false;
protected virtual void Dispose(bool disposing)
{
if (!this.disposed)
{
if (disposing)
{
_dbContext.Dispose();
}
}
this.disposed = true;
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WinFormsDI
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private IRepository<Process> _processRepository;
public Form1(IRepository<Process> productionRepository)
{
this._processRepository = productionRepository;
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
MessageBox.Show(_processRepository.ToString());
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace FixyNet.Clases.Listas
{
class ListaIpMonAct
{
public string uuid_dispositivo { set; get; }
public string ip { set; get; }
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace GestDep.Entities
{
public partial class Room
{
public Room() {
Activities = new List<Activity>();
}
public Room(int number) {
Number = number;
Activities = new List<Activity>();
}
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[CreateAssetMenu (menuName = "Narrative")]
public class Narrative : ScriptableObject
{
public string id;
public Color color = Color.white;
[TextArea (minLines:7, maxLines: 7)]
public string line;
public string person;
public string GetLine()
{
return person + ": " + line;
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
namespace Naruto_Quiz
{
public class Final_Score : INotifyPropertyChanged
{
int total_Score;
public int Total_Score
{
get { return total_Score; }
set { total_Score = value; OnPropertyChanged("Total_Score"); }
}
int total_Time;
public int Total_Time
{
get { return total_Time; }
set { total_Time = value; OnPropertyChanged("Total_Time"); }
}
int correct_Answer;
public int Correct_Answer
{
get { return correct_Answer; }
set { correct_Answer = value; OnPropertyChanged("Correct_Answer"); }
}
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged(string propertyName)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
handler(this, new PropertyChangedEventArgs(propertyName));
}
public void Reset_Score()
{
Total_Score = Total_Time = Correct_Answer = 0;
}
public Final_Score()
{
Reset_Score();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace NADD
{
public class Discursiva : IQuestao
{
private double valor;
private string tipo;
private string observacao;
public Discursiva(double valor, string tipo, string observacao)
{
this.valor = valor;
this.tipo = tipo;
this.observacao = observacao;
}
public override void VerificaPontuacao()
{
Console.WriteLine("Entrou no VerificaPontuacao");
}
public override void VerificaClareza()
{
Console.WriteLine("Entrou no VerificaClareza");
}
}
}
|
using Dapper;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Script.Serialization;
using System.Web.Security;
using UrbanScience.Si2.Mvc.InjectableServices;
using UrbanScience.Si2.Website.Module.InactiveCustomer.Handlers.PartsOpportunity;
namespace UrbanScience.Si2.Website.Areas.PartsOpportunity.Controllers
{
public class PartsOpportunityController : Controller
{
public class PartsOppReportDates
{
public string ReportStart { get; set; }
public string ReportEnd { get; set; }
}
public class PartsOppRepairTypes
{
public string Value { get; set; }
public string Text { get; set; }
}
[NonAction]
public IEnumerable<PartsOppRepairTypes> GetPartsOppRepairTypes()
{
using (var connection = DatabaseProvider.GetDataConnection())
{
string sql = "select id as Value, PartRepairTypeName as Text from [dbo].[PartsOpportunityRepairType] order by 2";
var result = connection.Query<PartsOppRepairTypes>(sql);
return result;
}
}
[NonAction]
public PartsOppReportDates GetPartsOppReportDates()
{
using (var connection = DatabaseProvider.GetDataConnection())
{
var results = connection.QuerySingle<PartsOppReportDates>("PartsOpportunity_ReportDates",
new
{
}, commandType: System.Data.CommandType.StoredProcedure);
return results;
}
}
[NonAction]
public IEnumerable<String> GetPartsOppMaxGeography()
{
using (var connection = DatabaseProvider.GetDataConnection())
{
var results = connection.Query<String>("GetUserMaxGeographyAccess",
new
{
userId = (int)Membership.GetUser().ProviderUserKey
}, commandType: CommandType.StoredProcedure);
return results;
}
}
// GET: PartsOpportunity/PartsOpportunity/Index
public ActionResult Index()
{
IEnumerable<String> MaxGeog = this.GetPartsOppMaxGeography();
PartsOppReportDates ReportDates = this.GetPartsOppReportDates();
ViewData["MaxGeography"] = MaxGeog;
ViewData["ReportStart"] = ReportDates.ReportStart;
ViewData["ReportEnd"] = ReportDates.ReportEnd;
return View();
}
// GET: PartsOpportunity/PartsOpportunity/Part
public ActionResult Part()
{
IEnumerable<String> MaxGeog = this.GetPartsOppMaxGeography();
PartsOppReportDates ReportDates = this.GetPartsOppReportDates();
IEnumerable<PartsOppRepairTypes> PartsList = this.GetPartsOppRepairTypes();
ViewData["MaxGeography"] = MaxGeog;
ViewData["ReportStart"] = ReportDates.ReportStart;
ViewData["ReportEnd"] = ReportDates.ReportEnd;
ViewData["RepairTypes"] = new SelectList(PartsList, "Value", "Text");
return View();
}
// GET: PartsOpportunity/PartsOpportunity/Overview
public ActionResult Overview()
{
return View();
}
// GET: PartsOpportunity/PartsOpportunity/DealerList
public ActionResult DealerList()
{
IEnumerable<String> MaxGeog = this.GetPartsOppMaxGeography();
PartsOppReportDates ReportDates = this.GetPartsOppReportDates();
IEnumerable<PartsOppRepairTypes> PartsList = this.GetPartsOppRepairTypes();
ViewData["MaxGeography"] = MaxGeog;
ViewData["ReportStart"] = ReportDates.ReportStart;
ViewData["ReportEnd"] = ReportDates.ReportEnd;
ViewData["RepairTypes"] = new SelectList(PartsList, "Text", "Text");
return View();
}
}
} |
namespace Blorc.OpenIdConnect.Tests
{
using System.Reflection;
public class Stub<T>
{
public T Instance { get; }
public Stub(T instance)
{
Instance = instance;
}
public void SetField(string fieldName, object value)
{
var field = typeof(T).GetField(fieldName, BindingFlags.NonPublic | BindingFlags.Instance);
if (field is not null)
{
field.SetValue(Instance, value);
}
}
}
}
|
using Cubecraft.Data.World;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public abstract class Block
{
public abstract int BlockID { get; }
public abstract bool Transparent { get; }
public virtual bool Solid { get { return true; } }
public static float offset = 0.001f;
public enum Direction
{
Back,
Left,
Front,
Right,
Up,
Down
};
const float tileSize = 0.125f;
public struct Tile { public int x; public int y; }
public virtual Tile TexturePosition (Direction direction)
{
Tile tile = new Tile();
tile.x = 0;
tile.y = 0;
return tile;
}
public virtual void SetMeshUp(Chunk chunk, int x, int y, int z)
{
if (Block.IsTransparent(chunk.GetBlock(x, y + 1, z)))
{
if (Solid)
{
chunk.blockMeshData.useRenderDataForCol = true;
FaceDataUp(x, y, z, chunk.blockMeshData);
}
else
{
chunk.objectMeshData.useRenderDataForCol = true;
FaceDataUp(x, y, z, chunk.objectMeshData);
}
}
}
public virtual void SetMeshDown(Chunk chunk, int x, int y, int z)
{
if (Block.IsTransparent(chunk.GetBlock(x, y - 1, z)))
{
if (Solid)
{
chunk.blockMeshData.useRenderDataForCol = true;
FaceDataDown(x, y, z, chunk.blockMeshData);
}
else
{
chunk.objectMeshData.useRenderDataForCol = true;
FaceDataDown(x, y, z, chunk.objectMeshData);
}
}
}
public virtual void SetMeshLeft(Chunk chunk, int x, int y, int z)
{
if (Block.IsTransparent(chunk.GetBlock(x - 1, y, z)))
{
if (Solid)
{
chunk.blockMeshData.useRenderDataForCol = true;
FaceDataLeft(x, y, z, chunk.blockMeshData);
}
else
{
chunk.objectMeshData.useRenderDataForCol = true;
FaceDataLeft(x, y, z, chunk.objectMeshData);
}
}
}
public virtual void SetMeshRight(Chunk chunk, int x, int y, int z)
{
if (Block.IsTransparent(chunk.GetBlock(x + 1, y, z)))
{
if (Solid)
{
chunk.blockMeshData.useRenderDataForCol = true;
FaceDataRight(x, y, z, chunk.blockMeshData);
}
else
{
chunk.objectMeshData.useRenderDataForCol = true;
FaceDataRight(x, y, z, chunk.objectMeshData);
}
}
}
public virtual void SetMeshFront(Chunk chunk, int x, int y, int z)
{
if (Block.IsTransparent(chunk.GetBlock(x, y, z - 1)))
{
if (Solid)
{
chunk.blockMeshData.useRenderDataForCol = true;
FaceDataFront(x, y, z, chunk.blockMeshData);
}
else
{
chunk.objectMeshData.useRenderDataForCol = true;
FaceDataFront(x, y, z, chunk.objectMeshData);
}
}
}
public virtual void SetMeshBack(Chunk chunk, int x, int y, int z)
{
if (Block.IsTransparent(chunk.GetBlock(x, y, z + 1)))
{
if (Solid)
{
chunk.blockMeshData.useRenderDataForCol = true;
FaceDataBack(x, y, z, chunk.blockMeshData);
}
else
{
chunk.objectMeshData.useRenderDataForCol = true;
FaceDataBack(x, y, z, chunk.objectMeshData);
}
}
}
public static Vector2[] FaceUVs(Direction direction, Block block)
{
Vector2[] UVs = new Vector2[4];
Tile tilePos = block.TexturePosition(direction);
UVs[0] = new Vector2(tileSize * tilePos.x + tileSize - offset,
tileSize * tilePos.y + offset);
UVs[1] = new Vector2(tileSize * tilePos.x + tileSize - offset,
tileSize * tilePos.y + tileSize - offset);
UVs[2] = new Vector2(tileSize * tilePos.x + offset,
tileSize * tilePos.y + tileSize - offset);
UVs[3] = new Vector2(tileSize * tilePos.x + offset,
tileSize * tilePos.y + offset);
return UVs;
}
public static bool IsTransparent(Block block)
{
return block.Transparent;
}
protected virtual MeshData FaceDataUp(int x, int y, int z, MeshData meshData)
{
//meshData.vertices.Add(new Vector3(x - 0.5f, y + 0.5f, z + 0.5f)); //原来的方式
meshData.AddVertex(new Vector3(x - 0.5f, y + 0.5f, z + 0.5f)); //转换的方式
meshData.AddVertex(new Vector3(x + 0.5f, y + 0.5f, z + 0.5f));
meshData.AddVertex(new Vector3(x + 0.5f, y + 0.5f, z - 0.5f));
meshData.AddVertex(new Vector3(x - 0.5f, y + 0.5f, z - 0.5f));
meshData.AddQuadTriangles();
//其它方向上的函数也要添加下面这行代码。
meshData.uv.AddRange(FaceUVs(Direction.Up, this));
return meshData;
}
protected virtual MeshData FaceDataDown(int x, int y, int z, MeshData meshData)
{
meshData.AddVertex(new Vector3(x - 0.5f, y - 0.5f, z - 0.5f));
meshData.AddVertex(new Vector3(x + 0.5f, y - 0.5f, z - 0.5f));
meshData.AddVertex(new Vector3(x + 0.5f, y - 0.5f, z + 0.5f));
meshData.AddVertex(new Vector3(x - 0.5f, y - 0.5f, z + 0.5f));
meshData.AddQuadTriangles();
//Add the following line to every FaceData function with the direction of the face
meshData.uv.AddRange(FaceUVs(Direction.Down, this));
return meshData;
}
protected virtual MeshData FaceDataBack(int x, int y, int z, MeshData meshData)
{
meshData.AddVertex(new Vector3(x + 0.5f, y - 0.5f, z + 0.5f));
meshData.AddVertex(new Vector3(x + 0.5f, y + 0.5f, z + 0.5f));
meshData.AddVertex(new Vector3(x - 0.5f, y + 0.5f, z + 0.5f));
meshData.AddVertex(new Vector3(x - 0.5f, y - 0.5f, z + 0.5f));
meshData.AddQuadTriangles();
//Add the following line to every FaceData function with the direction of the face
meshData.uv.AddRange(FaceUVs(Direction.Front, this));
return meshData;
}
protected virtual MeshData FaceDataRight(int x, int y, int z, MeshData meshData)
{
meshData.AddVertex(new Vector3(x + 0.5f, y - 0.5f, z - 0.5f));
meshData.AddVertex(new Vector3(x + 0.5f, y + 0.5f, z - 0.5f));
meshData.AddVertex(new Vector3(x + 0.5f, y + 0.5f, z + 0.5f));
meshData.AddVertex(new Vector3(x + 0.5f, y - 0.5f, z + 0.5f));
meshData.AddQuadTriangles();
//Add the following line to every FaceData function with the direction of the face
meshData.uv.AddRange(FaceUVs(Direction.Right, this));
return meshData;
}
protected virtual MeshData FaceDataFront(int x, int y, int z, MeshData meshData)
{
meshData.AddVertex(new Vector3(x - 0.5f, y - 0.5f, z - 0.5f));
meshData.AddVertex(new Vector3(x - 0.5f, y + 0.5f, z - 0.5f));
meshData.AddVertex(new Vector3(x + 0.5f, y + 0.5f, z - 0.5f));
meshData.AddVertex(new Vector3(x + 0.5f, y - 0.5f, z - 0.5f));
meshData.AddQuadTriangles();
//Add the following line to every FaceData function with the direction of the face
meshData.uv.AddRange(FaceUVs(Direction.Back, this));
return meshData;
}
protected virtual MeshData FaceDataLeft(int x, int y, int z, MeshData meshData)
{
meshData.AddVertex(new Vector3(x - 0.5f, y - 0.5f, z + 0.5f));
meshData.AddVertex(new Vector3(x - 0.5f, y + 0.5f, z + 0.5f));
meshData.AddVertex(new Vector3(x - 0.5f, y + 0.5f, z - 0.5f));
meshData.AddVertex(new Vector3(x - 0.5f, y - 0.5f, z - 0.5f));
meshData.AddQuadTriangles();
//Add the following line to every FaceData function with the direction of the face
meshData.uv.AddRange(FaceUVs(Direction.Left, this));
return meshData;
}
public override bool Equals(object obj)
{
Block block = null;
return (block = (Block)obj) != null ? this.BlockID == block.BlockID : false;
}
public override int GetHashCode()
{
return this.BlockID;
}
}
|
using NUnit.Framework;
using JustEnoughVi;
namespace JustEnoughViTests
{
[TestFixture]
public class DeleteTests : TextEditorTestBase
{
[Test]
public void Should_delete_two_end_of_line()
{
//TODO - caret finishes in wrong position
var source =
@"aaaaaa
bb$bbbb
cccccc
dddddd
eeeeee";
var expected =
@"aaaaaa
dddddd
eeeeee";
Test(source, "Vjd", expected, typeof(NormalMode));
}
[TestCase("aaa$", "x", "aa$")]
[TestCase("aaa$", "xx", "a$")]
[TestCase("aaa$", "xxx", "$")]
[TestCase("aaa$", "xxxx", "$")]
public void X_tests(string source, string keys, string expected)
{
Test(source, keys, expected, typeof(NormalMode));
}
[TestCase("a$ksjdf alsdfklasdjf", "dw", "a$lsdfklasdjf")]
[TestCase("a$slkdjf alsdfklasdjf", "de", " $alsdfklasdjf")]
[TestCase("while (endOffset < searchText.Length", "5dw", ".$Length")]
[TestCase("while (endOffset < searchText.Length", "5de", ".$Length")]
[TestCase("this$ is a test", "dtt", "thit$est")]
[TestCase("this$ is a test", "d2tt", "thit$")]
[TestCase("this$ is a test", "dft", "thie$st")]
[TestCase("aa$lkdjf alsdfklasdjf", "D", "a$")]
[TestCase("aas$kdjf alsdfklasdjf", "d$", "aa$")]
[TestCase("aaa$aaa\nbbbbb\nccccc\n", "dd","b$bbbb\nccccc\n")]
[TestCase("( asl$kdjf )", "di(", "()$")]
[TestCase("[ aaa,\n\tbbb]$\n", "di[", "[]$\n")]
[TestCase("($ aslkdjf )", "di(", "()$")]
[TestCase("{ aaa$aaaa; }", "di{", "{}$")]
[TestCase("{\n\tint$ a;\n\tint b;\n}\n", "di{", "{\n}$\n")]
[TestCase("(int $a,\n int b)\n", "di(", "()$\n")]
[TestCase("\"as$ldkjfasf bbb\"", "di\"", "\"\"$")]
[TestCase("\"aaaaa\" \"$bbb\"", "di\"", "\"aaaaa\" \"\"$")]
[TestCase("\"aaaaa\"$ \"bbb\"", "di\"", "\"\"$ \"bbb\"")]
[TestCase("\n'a'$ '\n", "di'", "\n''$ '\n")]
[TestCase("'$a'", "di'", "''$")]
[TestCase("'a$'", "di'","''$")]
[TestCase("{\n\tif$ (true)\n\t{\n\t\ta();{int a}\n\t}\n}\n", "di{", "{\n}$\n")]
[TestCase("Test(typeof(Normal$Mode()));", "di(", "Test(typeof()$);")]
[TestCase("hello ( hello() w$hile(true) )", "di(", "hello ()$")]
public void D_tests(string source, string keys, string expected)
{
Test(source, keys, expected, typeof(NormalMode));
}
}
}
|
using System;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
namespace MyRESTService
{
// NOTE: You can use the "Rename" command on the "Refactor" menu to change the class name "Service1" in code, svc and config file together.
// NOTE: In order to launch WCF Test Client for testing this service, please select Service1.svc or Service1.svc.cs at the Solution Explorer and start debugging.
public class Service1 : IService1
{
static String str;
public string GetData(int value)
{
return string.Format("You entered: {0}", value);
}
public string SetData(string value)
{
return string.Format("You entered: {0}", value);
}
public string GetTeste()
{
SqlDataAdapter da = new SqlDataAdapter("select texto from mensagens", ConfigurationManager.ConnectionStrings["dbMessages"].ConnectionString);
//DataSet ds = new DataSet();
//da.Fill(ds);
return ""; // ds.Tables[0].Columns.ToString();
//return str;
}
public void SetTeste(string parStr)
{
str = parStr;
}
public CompositeType GetDataUsingDataContract(CompositeType composite)
{
if (composite == null)
{
throw new ArgumentNullException("composite");
}
if (composite.BoolValue)
{
composite.StringValue += "Suffix";
}
return composite;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
namespace Uxnet.Com.DataAccessLayer
{
public static class ExtensionMethods
{
public static DataTable ToDataTable<T>(this IEnumerable<T> query)
{
DataTable tbl = new DataTable();
PropertyInfo[] props = BuildDataColumns(query, tbl);
foreach (T item in query)
{
DataRow row = tbl.NewRow();
foreach (PropertyInfo pi in props)
{
row[pi.Name] = pi.GetValue(item, null) ?? DBNull.Value;
}
tbl.Rows.Add(row);
}
return tbl;
}
public static PropertyInfo[] BuildDataColumns<T>(this IEnumerable<T> query, DataTable table)
{
PropertyInfo[] props = null;
if (props == null) //尚未初始化
{
Type t = typeof(T);
props = t.GetProperties();
foreach (PropertyInfo pi in props)
{
Type colType = pi.PropertyType;
//針對Nullable<>特別處理
if (colType.IsGenericType && colType.GetGenericTypeDefinition() == typeof(Nullable<>))
{
colType = colType.GetGenericArguments()[0];
}
//建立欄位
table.Columns.Add(pi.Name, colType);
}
}
return props;
}
public static PropertyInfo[] BuildDataColumns<T>(this IQueryable<T> query, DataTable table)
{
PropertyInfo[] props = null;
if (props == null) //尚未初始化
{
Type t = typeof(T);
props = t.GetProperties();
foreach (PropertyInfo pi in props)
{
Type colType = pi.PropertyType;
//針對Nullable<>特別處理
if (colType.IsGenericType && colType.GetGenericTypeDefinition() == typeof(Nullable<>))
{
colType = colType.GetGenericArguments()[0];
}
//建立欄位
table.Columns.Add(pi.Name, colType);
}
}
return props;
}
public static IQueryable<TSource> OrderBy<TSource, TKey>(this IQueryable<TSource> source,Expression<Func<TSource, TKey>> keySelector,int? order,bool isOrdered = false)
{
if (order == 0)
return source;
if(isOrdered || source.Expression.ToString().Contains("OrderBy"))
{
IOrderedQueryable<TSource> items = (IOrderedQueryable<TSource>)source;
return order > 0
? items.ThenBy(keySelector)
: items.ThenByDescending(keySelector);
}
else
{
return order > 0
? source.OrderBy(keySelector)
: source.OrderByDescending(keySelector);
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using TestGap.Api.Class;
namespace TestGap.Api.Models
{
public class Respuesta
{
/// <summary>
///
/// </summary>
public Respuesta()
{
MensajeError();
}
/// <summary>
///
/// </summary>
/// <param name="objetoRespuesta"></param>
public void MensajeExito(object objetoRespuesta=null)
{
CodigoRepuesta = Parametros.CodigosMensajes.Exito;
MensajeRespuesta = Parametros.Mensajes.MSJExito;
ObjetoRetornado = objetoRespuesta;
}
/// <summary>
///
/// </summary>
public void MensajeError(object objetoRespuesta = null)
{
CodigoRepuesta = Parametros.CodigosMensajes.Error;
MensajeRespuesta = Parametros.Mensajes.MSJError;
ObjetoRetornado = objetoRespuesta;
}
/// <summary>
///
/// </summary>
public int CodigoRepuesta { get; set; }
/// <summary>
///
/// </summary>
public string MensajeRespuesta { get; set; }
/// <summary>
///
/// </summary>
public object ObjetoRetornado { get; set; }
}
} |
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Web;
namespace EdubranApi.Models
{
public class Skill
{
[Key]
public int Id { get; set; }
public string skill { get; set; }
//Foreign key
public int studentId { get; set; }
[ForeignKey("studentId")]
public Student student { get; set; }
}
} |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using DevExpress.XtraCharts;
using QuanLyBaoHiem.Models;
using QuanLyBaoHiem.ModelDoanhThu;
namespace QuanLyBaoHiem
{
public partial class Formtest2 : DevExpress.XtraEditors.XtraForm
{
QLBHContext db = new QLBHContext();
decimal[] doanhthutungthang = new decimal[12] { 0,0,0,0,0,0,0,0,0,0,0,0};
List<DoanhThu> listdoanhthu = new List<DoanhThu>();
public Formtest2()
{
InitializeComponent();
laydulieu();
xulyradoanhthuhangthang();
showketquatest();
ve();
}
public void ve()
{
ChartControl pointChart = new ChartControl();
// Create a point series.
Series series1 = new Series("Doanh thu", ViewType.Bar);
// Set the numerical argument scale type for the series,
// as it is qualitative, by default.
series1.ArgumentScaleType = ScaleType.Auto;
// Add points to it.
for(int i=0;i<12;i++)
{
series1.Points.Add(new SeriesPoint("Tháng "+(i+1)+"", doanhthutungthang[i]));
}
/*series1.Points.Add(new SeriesPoint("Tháng 1", 10));
series1.Points.Add(new SeriesPoint("Tháng 2", 22));
series1.Points.Add(new SeriesPoint("Tháng 3", 14));
series1.Points.Add(new SeriesPoint("Tháng 4", 27));
series1.Points.Add(new SeriesPoint("Tháng 5", 15));
series1.Points.Add(new SeriesPoint("Tháng 6", 28));
series1.Points.Add(new SeriesPoint("Tháng 7", 15));
series1.Points.Add(new SeriesPoint("Tháng 8", 33));
series1.Points.Add(new SeriesPoint("Tháng 9", 33));
series1.Points.Add(new SeriesPoint("Tháng 10", 33));
series1.Points.Add(new SeriesPoint("Tháng 11", 33));
series1.Points.Add(new SeriesPoint("Tháng 12", 33));*/
// Add the series to the chart.
pointChart.Series.Add(series1);
// Access the view-type-specific options of the series.
BarSeriesView myView1 = (BarSeriesView)series1.View;
//myView1.PointMarkerOptions.Kind = MarkerKind.Star;
//myView1.PointMarkerOptions.StarPointCount = 5;
//myView1.PointMarkerOptions.Size = 20;
// Access the type-specific options of the diagram.
((XYDiagram)pointChart.Diagram).EnableAxisXZooming = true;
// Hide the legend (if necessary).
pointChart.Legend.Visible = true;
// Add a title to the chart (if necessary).
pointChart.Titles.Add(new ChartTitle());
pointChart.Titles[0].Text = "Doanh thu từng tháng";
// Add the chart to the form.
pointChart.Dock = DockStyle.Fill;
this.Controls.Add(pointChart);
}
public void laydulieu()
{
var dulieu = (from p in db.HopDongs
join b in db.GoiHopDongs
on p.MaGoiHD equals b.MaGoiHD
select new
{
MaHD = p.MaHD,
MucPhi = b.MucPhi,
NgayHieuLuc = p.NgayHieuLuc
}
).ToList();
foreach(var a in dulieu)
{
DoanhThu b = new DoanhThu();
b.MaHD = a.MaHD;
b.MucPhi = a.MucPhi;
b.NgayHieuLuc = a.NgayHieuLuc;
listdoanhthu.Add(b);
}
}
public void xulyradoanhthuhangthang()
{
for(int i=0;i<12;i++)
{
foreach(var a in listdoanhthu)
{
DateTime temp =(DateTime) a.NgayHieuLuc;
if(temp.Month==i+1)
{
doanhthutungthang[i] = (decimal)(doanhthutungthang[i] + a.MucPhi);
//doanhthutungthang[i] = 0;
}
}
}
}
public void showketquatest()
{
foreach(var a in doanhthutungthang)
{
System.Diagnostics.Debug.WriteLine(a);
}
}
}
} |
using UnityEngine;
namespace Game.AI.Health
{
public class Healthbox : MonoBehaviour {
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Smart.Distribution.Station.Domain
{
public class LowValtageEntity : EntityBase
{
public bool Ajx { get; set; }
public bool Drg { get; set; }
public bool QfOne { get; set; }
public bool QfTwo { get; set; }
public bool QfThree { get; set; }
public int Yellow { get; set; }
public int Green { get; set; }
public int Red { get; set; }
}
}
|
using DbRestify.Data;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.Http.SelfHost;
namespace DbRestify
{
class Program
{
static void Main(string[] args)
{
Dictionary<string, string> parameters = new Dictionary<string, string>()
{
{ "host", "http://127.0.0.1" },
{"port", "8080" },
{"connection", "" },
{"assembly", "" }
};
var app = new Microsoft.Extensions.CommandLineUtils.CommandLineApplication();
app.Option("--host|-h <host>", "Host. default 127.0.0.1", Microsoft.Extensions.CommandLineUtils.CommandOptionType.SingleValue);
app.Option("--connectionString | -cs <connection>", "Connection string.", Microsoft.Extensions.CommandLineUtils.CommandOptionType.SingleValue);
app.Option("--assembly | -a <assembly>", "Provider assembly name (without .dll).", Microsoft.Extensions.CommandLineUtils.CommandOptionType.SingleValue);
app.Option("--port | -p <port>", "port. default 8080", Microsoft.Extensions.CommandLineUtils.CommandOptionType.SingleValue);
app.HelpOption("-? | --help");
app.OnExecute(() =>
{
int result = 0;
app.Options.ForEach((o) =>
{
if (o.ValueName == null)
return;
if (o.HasValue())
parameters[o.ValueName] = o.Value();
else
result++;
});
if (result != 0)
app.ShowHelp();
return result;
});
if (app.Execute(args) == 0)
{
//Data Source=local_database.db;version=3"
Database.InitDatabase(parameters["assembly"], parameters["connection"]);
HttpSelfHostConfiguration config = new HttpSelfHostConfiguration(string.Format("{0}:{1}", parameters["host"], parameters["port"]));
DbRestify.Api.WebApiConfig.Register(config);
System.Web.Http.SelfHost.HttpSelfHostServer server = new System.Web.Http.SelfHost.HttpSelfHostServer(config);
server.OpenAsync().Wait();
Console.WriteLine("Listening on '{0}'", config.BaseAddress);
}
Console.Read();
}
}
}
|
namespace Standard
{
using System;
using System.Runtime.InteropServices;
[StructLayout(LayoutKind.Sequential)]
internal struct INPUT
{
public uint type;
public Standard.MOUSEINPUT mi;
}
}
|
namespace Altitude
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
public class Altitude
{
public static void Main(string[] args)
{
//read the input, split and convert to string array;
var input = Console.ReadLine().Split(' ').ToArray();
//var for altitude;
var altitude = double.Parse(input[0]);
//array for commands;
var commands = new string[input.Length - 1];
//fill the commands array;
for (int i = 1; i < input.Length; i++)
{
commands[i - 1] = input[i];
}
//Console.WriteLine(string.Join(" ", commands));
for (int i = 0; i < commands.Length - 1; i += 2)
{
//var command;
var command = commands[i];
//var for altitude of the command;
var height = commands[i + 1];
if (command == "up")
{
altitude += double.Parse(height);
}
else if (command == "down")
{
altitude -= double.Parse(height);
}
}
if (altitude > 0)
{
Console.WriteLine("got through safely. current altitude: {0}m", altitude);
}
else
{
Console.WriteLine("crashed");
}
}
}
}
|
using System;
namespace famoustimeapp.Models
{
public class HomeViewModel
{
public HomeViewModel()
{
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.AI;
public class EnemyController : MonoBehaviour
{
NavMeshAgent nav;
GameObject target;
public GameObject theSoldier;
void Start()
{
nav = GetComponent<NavMeshAgent>();
target = GameObject.Find("FirstPersonCharacter");
}
// Update is called once per frame
void Update()
{
if (nav.destination != target.transform.position)
{
nav.SetDestination(target.transform.position);
}
else
{
nav.SetDestination(transform.position);
}
if (nav.remainingDistance >= nav.stoppingDistance)
{
theSoldier.GetComponent<Animator>().Play("Walk");
}
if (nav.remainingDistance < nav.stoppingDistance)
{
if (nav.hasPath || nav.velocity.sqrMagnitude == 0f)
{
theSoldier.GetComponent<Animator>().Play("Idle");
}
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using DG.Tweening;
using TMPro;
public class HurtText : MonoBehaviour {
// Use this for initialization
void Start () {
Random.seed = System.Guid.NewGuid().GetHashCode();
int i = Random.Range(0, 150);
int y = Random.Range(30, 80);
Destroy(gameObject, 0.5f);
Sequence mySequence = DOTween.Sequence();
Tweener move1 = transform.DOMoveY(transform.position.y + y, 0.3f);
Tweener movex = transform.DOMoveX(transform.position.x + i, 0.3f);
Tweener scale1 = transform.DOScale(2f, 0.5f);
//Tweener move2 = transform.DOMoveY(transform.position.y + 80, 0.3f);
//Color c = gameObject.GetComponent<TextMeshProUGUI>().color;
//Tweener alpha1 = gameObject.GetComponent<TextMeshProUGUI>().DOFade(0, 0.5f);
mySequence.Append(move1);
mySequence.Join(scale1);
mySequence.Join(movex);
//mySequence.Append(alpha1);
// mySequence.AppendInterval(0.01f);
}
// Update is called once per frame
void Update ()
{
}
}
|
using System;
using System.Web;
using VkNet;
using VkNet.Enums.SafetyEnums;
namespace SuicideAlpha
{
class Wall
{
VkApi app;
VkNet.Model.WallGetObject wall;
public string GetTextWall()
{
string result = String.Empty;
foreach (var posts in wall.WallPosts)
{
if (posts.Text != "")
result += posts.Text + "\n\n";
foreach (var p in posts.CopyHistory)
if (p.Text != "")
result += p.Text + "\n\n";
}
return result;
}
public HtmlString GetText()
{
return new HtmlString("sda");
}
public Wall(VkApi app, long? ID)
{
this.app = app;
wall = app.Wall.Get(new VkNet.Model.RequestParams.WallGetParams
{
OwnerId = ID,
Count = 5,
Extended = true,
Filter = WallFilter.Owner
});
}
public Wall(VkApi app, string domain)
{
this.app = app;
wall = app.Wall.Get(new VkNet.Model.RequestParams.WallGetParams
{
Domain = domain,
Count = 99,
Extended = true,
Filter = WallFilter.Owner
});
}
}
}
|
using Library.Domain.Abstract;
using Library.Domain.Entities;
using Library.Models;
using Library.ViewModels;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Web;
using System.Web.Mvc;
namespace Library.Controllers
{
[Authorize(Roles = "Librarian, Admin")]
public class LibrarianController : Controller
{
private IBookRepository repository;
public LibrarianController(IBookRepository repositoryParam)
{
repository = repositoryParam;
}
public ActionResult Index()
{
IEnumerable<BooksViewModel> booksModel = repository.Books.
Select(x => new BooksViewModel
{
ID = x.BookID,
Title = x.Title,
Author = x.Author,
Description = x.Description.Length < 50 ? x.Description + "..." : x.Description.Substring(0, 50) + "...",
Classification = x.Classification
});
return View(booksModel);
}
public ActionResult Edit(int bookID)
{
Book book = repository.Books.FirstOrDefault(x => x.BookID == bookID);
return View(book);
}
[HttpPost]
public ActionResult Edit(Book book, HttpPostedFileBase image = null)
{
if (ModelState.IsValid)
{
if(image != null)
{
book.ImageMimeType = image.ContentType;
book.ImageData = new byte[image.ContentLength];
image.InputStream.Read(book.ImageData, 0, image.ContentLength);
}
else
{
FileInfo defaultImage = new FileInfo(Server.MapPath("~/Images/defaultCover.png"));
book.ImageMimeType = "image/png";
book.ImageData = new byte[defaultImage.Length];
using (FileStream fs = defaultImage.OpenRead())
{
fs.Read(book.ImageData, 0, book.ImageData.Length);
}
}
repository.SaveBook(book);
TempData["Message"] = new Message() { Text = "Success! <strong>You have successfully change book data.</strong>", ClassName = "alertMessage successful" };
return RedirectToAction("Index");
}
else
{
return View(book);
}
}
public ActionResult Create()
{
return View("Edit", new Book());
}
public ActionResult Delete(int bookID)
{
bool deleted = repository.DeleteBook(bookID);
if (deleted)
{
TempData["Message"] = new Message() { Text = "Success! <strong>You have successfully delete item.</strong>", ClassName = "alertMessage successful" };
}
else
{
TempData["Message"] = new Message() { Text = "Error! <strong>Cannot delete item!</strong>", ClassName = "alertMessage error" };
}
return RedirectToAction("Index");
}
}
} |
using DDClassLibrary1;
using System;
using System.Windows.Forms;
namespace DDWinFormApp1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Button1_Click(object sender, EventArgs e)
{
var platform = "Windows Forms(.NET Framework)";
DDExcel.Create(platform);
DDPdf.Create(platform);
}
}
}
|
using Microsoft.TeamFoundation.WorkItemTracking.Client;
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AnyconnectVSO
{
public class DBUploader
{
public void WriteToDb(WorkItemCollection collection, string connectionString)
{
foreach (WorkItem item in collection)
{
var query = "INSERT INTO Data_VSO_AnyConnect_Support (ID, [Work Item], Title, Priority, [Assigned To], State, Tags) values (@id,@workitem, @title, @priority, @assignedto,@state, @tags)";
using (var connection = new SqlConnection(connectionString))
{
connection.Open();
using (var command = new SqlCommand(query, connection))
{
command.Parameters.Add(new SqlParameter("id", item.Id));
command.Parameters.Add(new SqlParameter("workitem", item.Type.Name));
command.Parameters.Add(new SqlParameter("title", item.Title));
command.Parameters.Add(new SqlParameter("priority", item.Fields["Priority"].Value));
command.Parameters.Add(new SqlParameter("assignedto", item.Fields["Assigned To"].Value));
command.Parameters.Add(new SqlParameter("state", item.State));
command.Parameters.Add(new SqlParameter("tags", item.Tags));
command.ExecuteNonQuery();
}
}
}
}
}
} |
using System;
using System.Collections;
using System.IO;
using UpYunLibrary;
internal class UpYunSample
{
public void Sample()
{
UpYun upYun = new UpYun("bucket", "username", "password");
Hashtable hashtable = new Hashtable();
FileStream fileStream = new FileStream("..\\..\\test.jpeg", 3, 1);
BinaryReader binaryReader = new BinaryReader(fileStream);
byte[] data = binaryReader.ReadBytes((int)fileStream.get_Length());
Console.WriteLine("上传文件");
bool flag = upYun.writeFile("/a/test.jpg", data, true);
Console.WriteLine(flag);
Console.WriteLine("获取上传后的图片信息");
Console.WriteLine(upYun.getWritedFileInfo("x-upyun-width"));
Console.WriteLine(upYun.getWritedFileInfo("x-upyun-height"));
Console.WriteLine(upYun.getWritedFileInfo("x-upyun-frames"));
Console.WriteLine(upYun.getWritedFileInfo("x-upyun-file-type"));
Console.WriteLine("读取目录");
ArrayList arrayList = upYun.readDir("/a/");
using (IEnumerator enumerator = arrayList.GetEnumerator())
{
while (enumerator.MoveNext())
{
object current = enumerator.get_Current();
FolderItem folderItem = (FolderItem)current;
Console.WriteLine(folderItem.filename);
}
}
Console.WriteLine("获取某个目录的空间占用大小");
Console.WriteLine(upYun.getFolderUsage("/a/"));
Console.WriteLine("读取文件");
byte[] array = upYun.readFile("/a/test.jpg");
Console.WriteLine(array.Length);
Console.WriteLine("获取文件信息");
Hashtable fileInfo = upYun.getFileInfo("/a/test.jpg");
Console.WriteLine(fileInfo.get_Item("type"));
Console.WriteLine(fileInfo.get_Item("size"));
Console.WriteLine(fileInfo.get_Item("date"));
Console.Read();
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
namespace JoveZhao.Framework
{
/// <summary>
/// 自定义错误信息
/// </summary>
[DataContract]
public class CustomException : Exception
{
public int ErrorCode { get; private set; }
public CustomException( int errorCode,string message)
: base(message)
{
this.ErrorCode = errorCode;
}
}
}
|
using System.Collections.Generic;
using Abc.Data.Quantity;
using Microsoft.EntityFrameworkCore.Internal;
namespace Abc.Infra.Quantity
{
public static class QuantityDbInitializer
{
internal static List<MeasureData> measures => new List<MeasureData> {
new MeasureData {Id ="Time", Name = "Time", Code = "t",
Definition = "In physical science, time is defined as a measurement, "+
"or as what the clock face reads."},
new MeasureData {Id ="Length", Name = "Length", Code = "l",
Definition = "The measurement or extent of something from end to end."},
new MeasureData {Id ="Mass", Name = "Mass", Code = "m",
Definition = "The quantity of matter which a body contains, as measured by "+
"its acceleration under a given force or by the force exerted on "+
"it by a gravitational field"},
new MeasureData {Id ="Current", Name = "Electric Current", Code = "I",
Definition = "An electric current is the rate of flow of electric charge "+
"past a point or region. An electric current is said to exist "+
"when there is a net flow of electric charge through a region."+
"In electric circuits this charge is often carried by electrons "+
"moving through a wire. It can also be carried by ions in an "+
"electrolyte, or by both ions and electrons such as in an "+
"ionized gas (plasma)"},
new MeasureData {Id ="Temperature", Name = "Thermodynamic Temperature", Code = "T",
Definition = "Thermodynamic temperature is the absolute measure of temperature "+
"and is one of the principal parameters of thermodynamics."},
new MeasureData {Id ="Substance", Name = "Amount of Substance", Code = "n",
Definition = "In chemistry, the amount of substance in a given "+
"sample of matter is the number of discrete atomic-scale "+
"particles in it; where the particles may be molecules, "+
"atoms, ions, electrons, or other, depending on the context. "+
"It is sometimes referred to as the chemical amount."},
new MeasureData {Id ="Luminous", Name = "Luminous Intensity", Code = "Iv",
Definition = "In photometry, luminous intensity is a measure of the "+
"wavelength-weighted power emitted by a light source in a "+
"particular direction per unit solid angle, based on the "+
"luminosity function, a standardized model of the sensitivity "+
"of the human eye"}
};
public static void Initialize(QuantityDbContext db)
{
if (db.Measures.Any()) return;
db.Measures.AddRange(measures);
db.SaveChanges();
}
}
}
|
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ECommerceApp.Core.Interfaces;
using ECommerceApp.Core.Models;
using ECommerceApp.Infrastructure.DataContext;
namespace ECommerceApp.Infrastructure.Repositories
{
public class ProductRepository : IProductRepository
{
private ECommerceContext db = new ECommerceContext();
public void AddProduct(string article , string name , string description , decimal price , bool instock)
{
var addProduct = new Product();
addProduct.Article = article;
addProduct.ProductName = name;
addProduct.Description = description;
addProduct.Price = price;
addProduct.InStock = instock;
db.Products.Add(addProduct);
db.SaveChanges();
}
public void UpdateProduct(Guid Id , Product pr)
{
var updateProduct = db.Products.Find(Id);
db.Entry(updateProduct).CurrentValues.SetValues(pr);
db.SaveChanges();
}
public Product FindById(Guid Id)
{
var findProduct = db.Products.FirstOrDefault(x => x.Id == Id);
return findProduct;
}
public void RemoveProduct(Guid Id)
{
var removeProduct = db.Products.FirstOrDefault(x => x.Id == Id);
db.Products.Remove(removeProduct);
}
public IEnumerable GetProducts()
{
return db.Products;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Section01 {
class Program {
static void Main(string[] args) {
#region "①"
/*var person = new Person {
Name = "新井遥菜",
Birthday = new DateTime(1995, 11, 23),
PhoneNumber = "123-3456-7890",
};*/
#endregion
#region "②"
/*var list = new List<int> { 10, 20, 30, 40, };
var key = 50;
//1or0
var num = list.Contains(key);
Console.WriteLine(num);*/
//null合体演算時
/*string code = "12345";
var massage = GetMassage(code) ?? DefaultMassage();
Console.WriteLine(massage);"*/
#endregion
#region "③"
//var ret = GetProductA();
#endregion
/*
int count = 0;
//前置と後置では、加算するタイミングが違う
Console.WriteLine($"後置:{count++}");
Console.WriteLine($"前置:{++count}");*/
/*int height;
var str = "123";
if (int.TryParse(str,out height)) {
Console.WriteLine(height);
}
else {
Console.WriteLine("変換できません");
}*/
var Session = new Dictionary<string, object>();
Session["MyProduct"] = new Product();
var product = Session["MyProduct"] as Product;
if (product == null) {
Console.WriteLine("productが取得できなかった");
}
else {
Console.WriteLine("productが取得できた");
}
}
private static Product GetProductA() {
Sale sale =new Sale();
return sale?.Product;
}
}
#region "②"
/*private static object DefaultMassage() {
return "DefaultMassage";
}
private static object GetMassage(object code) {
return code;
}*/
#endregion
class Sale {
public string ShopName { get; set; } ="abcde";
public int Amount { get; set; } = 12345;
public Product Product{get; set;}
}
}
|
using UnityEngine;
using System.Collections;
public class LookAtMouse : MonoBehaviour {
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
Vector3 worldPos = Camera.main.ScreenToWorldPoint (Input.mousePosition);
Ray ray = Camera.main.ScreenPointToRay (Input.mousePosition);
int layerMask = LayerMask.GetMask(new string[]{GameManager.Instance.LayerNameGround});
RaycastHit hitInfo;
if(Physics.Raycast(ray, out hitInfo, 100, layerMask))
{
Vector3 lookPos = new Vector3(hitInfo.point.x, transform.position.y, hitInfo.point.z);
transform.LookAt (lookPos);
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PhysicsMgr : RuntimeMonoBehaviour
{
// ======================================================================================
protected override void StartPhase()
{
Physics2D.autoSimulation = true;
}
// ======================================================================================
protected override void OnPause()
{
Physics2D.autoSimulation = false;
}
// ======================================================================================
protected override void OnPlay()
{
Physics2D.autoSimulation = true;
}
}
|
//------------------------------------------------------------------------------
// The contents of this file are subject to the nopCommerce Public License Version 1.0 ("License"); you may not use this file except in compliance with the License.
// You may obtain a copy of the License at http://www.nopCommerce.com/License.aspx.
//
// Software distributed under the License is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or implied.
// See the License for the specific language governing rights and limitations under the License.
//
// The Original Code is nopCommerce.
// The Initial Developer of the Original Code is NopSolutions.
// All Rights Reserved.
//
// Contributor(s): _______.
//------------------------------------------------------------------------------
using System;
using System.Collections.Specialized;
using System.Configuration.Provider;
using System.Data;
using System.Data.Common;
using Microsoft.Practices.EnterpriseLibrary.Data;
namespace NopSolutions.NopCommerce.DataAccess.Directory
{
/// <summary>
/// Country provider for SQL Server
/// </summary>
public partial class SQLCountryProvider : DBCountryProvider
{
#region Fields
private string _sqlConnectionString;
#endregion
#region Utilities
private DBCountry GetCountryFromReader(IDataReader dataReader)
{
DBCountry country = new DBCountry();
country.CountryID = NopSqlDataHelper.GetInt(dataReader, "CountryID");
country.Name = NopSqlDataHelper.GetString(dataReader, "Name");
country.AllowsRegistration = NopSqlDataHelper.GetBoolean(dataReader, "AllowsRegistration");
country.AllowsBilling = NopSqlDataHelper.GetBoolean(dataReader, "AllowsBilling");
country.AllowsShipping = NopSqlDataHelper.GetBoolean(dataReader, "AllowsShipping");
country.TwoLetterISOCode = NopSqlDataHelper.GetString(dataReader, "TwoLetterISOCode");
country.ThreeLetterISOCode = NopSqlDataHelper.GetString(dataReader, "ThreeLetterISOCode");
country.NumericISOCode = NopSqlDataHelper.GetInt(dataReader, "NumericISOCode");
country.Published = NopSqlDataHelper.GetBoolean(dataReader, "Published");
country.DisplayOrder = NopSqlDataHelper.GetInt(dataReader, "DisplayOrder");
return country;
}
#endregion
#region Methods
/// <summary>
/// Initializes the provider with the property values specified in the application's configuration file. This method is not intended to be used directly from your code
/// </summary>
/// <param name="name">The name of the provider instance to initialize</param>
/// <param name="config">A NameValueCollection that contains the names and values of configuration options for the provider.</param>
public override void Initialize(string name, NameValueCollection config)
{
if (config == null)
{
throw new ArgumentNullException("config");
}
base.Initialize(name, config);
string connectionStringName = config["connectionStringName"];
if (String.IsNullOrEmpty(connectionStringName))
throw new ProviderException("Connection name not specified");
this._sqlConnectionString = NopSqlDataHelper.GetConnectionString(connectionStringName);
if ((this._sqlConnectionString == null) || (this._sqlConnectionString.Length < 1))
{
throw new ProviderException(string.Format("Connection string not found. {0}", connectionStringName));
}
config.Remove("connectionStringName");
if (config.Count > 0)
{
string key = config.GetKey(0);
if (!string.IsNullOrEmpty(key))
{
throw new ProviderException(string.Format("Provider unrecognized attribute. {0}", new object[] { key }));
}
}
}
/// <summary>
/// Deletes a country
/// </summary>
/// <param name="CountryID">Country identifier</param>
public override void DeleteCountry(int CountryID)
{
Database db = NopSqlDataHelper.CreateConnection(_sqlConnectionString);
DbCommand dbCommand = db.GetStoredProcCommand("Nop_CountryDelete");
db.AddInParameter(dbCommand, "CountryID", DbType.Int32, CountryID);
int retValue = db.ExecuteNonQuery(dbCommand);
}
/// <summary>
/// Gets all countries
/// </summary>
/// <returns>Country collection</returns>
public override DBCountryCollection GetAllCountries(bool showHidden)
{
DBCountryCollection countryCollection = new DBCountryCollection();
Database db = NopSqlDataHelper.CreateConnection(_sqlConnectionString);
DbCommand dbCommand = db.GetStoredProcCommand("Nop_CountryLoadAll");
db.AddInParameter(dbCommand, "ShowHidden", DbType.Boolean, showHidden);
using (IDataReader dataReader = db.ExecuteReader(dbCommand))
{
while (dataReader.Read())
{
DBCountry country = GetCountryFromReader(dataReader);
countryCollection.Add(country);
}
}
return countryCollection;
}
/// <summary>
/// Gets all countries that allow registration
/// </summary>
/// <returns>Country collection</returns>
public override DBCountryCollection GetAllCountriesForRegistration(bool showHidden)
{
DBCountryCollection countryCollection = new DBCountryCollection();
Database db = NopSqlDataHelper.CreateConnection(_sqlConnectionString);
DbCommand dbCommand = db.GetStoredProcCommand("Nop_CountryLoadAllForRegistration");
db.AddInParameter(dbCommand, "ShowHidden", DbType.Boolean, showHidden);
using (IDataReader dataReader = db.ExecuteReader(dbCommand))
{
while (dataReader.Read())
{
DBCountry country = GetCountryFromReader(dataReader);
countryCollection.Add(country);
}
}
return countryCollection;
}
/// <summary>
/// Gets all countries that allow billing
/// </summary>
/// <returns>Country collection</returns>
public override DBCountryCollection GetAllCountriesForBilling(bool showHidden)
{
DBCountryCollection countryCollection = new DBCountryCollection();
Database db = NopSqlDataHelper.CreateConnection(_sqlConnectionString);
DbCommand dbCommand = db.GetStoredProcCommand("Nop_CountryLoadAllForBilling");
db.AddInParameter(dbCommand, "ShowHidden", DbType.Boolean, showHidden);
using (IDataReader dataReader = db.ExecuteReader(dbCommand))
{
while (dataReader.Read())
{
DBCountry country = GetCountryFromReader(dataReader);
countryCollection.Add(country);
}
}
return countryCollection;
}
/// <summary>
/// Gets all countries that allow shipping
/// </summary>
/// <returns>Country collection</returns>
public override DBCountryCollection GetAllCountriesForShipping(bool showHidden)
{
DBCountryCollection countryCollection = new DBCountryCollection();
Database db = NopSqlDataHelper.CreateConnection(_sqlConnectionString);
DbCommand dbCommand = db.GetStoredProcCommand("Nop_CountryLoadAllForShipping");
db.AddInParameter(dbCommand, "ShowHidden", DbType.Boolean, showHidden);
using (IDataReader dataReader = db.ExecuteReader(dbCommand))
{
while (dataReader.Read())
{
DBCountry country = GetCountryFromReader(dataReader);
countryCollection.Add(country);
}
}
return countryCollection;
}
/// <summary>
/// Gets a country
/// </summary>
/// <param name="CountryID">Country identifier</param>
/// <returns>Country</returns>
public override DBCountry GetCountryByID(int CountryID)
{
DBCountry country = null;
Database db = NopSqlDataHelper.CreateConnection(_sqlConnectionString);
DbCommand dbCommand = db.GetStoredProcCommand("Nop_CountryLoadByPrimaryKey");
db.AddInParameter(dbCommand, "CountryID", DbType.Int32, CountryID);
using (IDataReader dataReader = db.ExecuteReader(dbCommand))
{
if (dataReader.Read())
{
country = GetCountryFromReader(dataReader);
}
}
return country;
}
/// <summary>
/// Gets a country by two letter ISO code
/// </summary>
/// <param name="TwoLetterISOCode">Country two letter ISO code</param>
/// <returns>Country</returns>
public override DBCountry GetCountryByTwoLetterISOCode(string TwoLetterISOCode)
{
DBCountry country = null;
Database db = NopSqlDataHelper.CreateConnection(_sqlConnectionString);
DbCommand dbCommand = db.GetStoredProcCommand("Nop_CountryLoadByTwoLetterISOCode");
db.AddInParameter(dbCommand, "TwoLetterISOCode", DbType.String, TwoLetterISOCode);
using (IDataReader dataReader = db.ExecuteReader(dbCommand))
{
if (dataReader.Read())
{
country = GetCountryFromReader(dataReader);
}
}
return country;
}
/// <summary>
/// Gets a country by three letter ISO code
/// </summary>
/// <param name="ThreeLetterISOCode">Country three letter ISO code</param>
/// <returns>Country</returns>
public override DBCountry GetCountryByThreeLetterISOCode(string ThreeLetterISOCode)
{
DBCountry country = null;
Database db = NopSqlDataHelper.CreateConnection(_sqlConnectionString);
DbCommand dbCommand = db.GetStoredProcCommand("Nop_CountryLoadByThreeLetterISOCode");
db.AddInParameter(dbCommand, "ThreeLetterISOCode", DbType.String, ThreeLetterISOCode);
using (IDataReader dataReader = db.ExecuteReader(dbCommand))
{
if (dataReader.Read())
{
country = GetCountryFromReader(dataReader);
}
}
return country;
}
/// <summary>
/// Inserts a country
/// </summary>
/// <param name="Name">The name</param>
/// <param name="AllowsRegistration">A value indicating whether registration is allowed to this country</param>
/// <param name="AllowsBilling">A value indicating whether billing is allowed to this country</param>
/// <param name="AllowsShipping">A value indicating whether shipping is allowed to this country</param>
/// <param name="TwoLetterISOCode">The two letter ISO code</param>
/// <param name="ThreeLetterISOCode">The three letter ISO code</param>
/// <param name="NumericISOCode">The numeric ISO code</param>
/// <param name="Published">A value indicating whether the entity is published</param>
/// <param name="DisplayOrder">The display order</param>
/// <returns>Country</returns>
public override DBCountry InsertCountry(string Name,
bool AllowsRegistration, bool AllowsBilling, bool AllowsShipping,
string TwoLetterISOCode, string ThreeLetterISOCode, int NumericISOCode,
bool Published, int DisplayOrder)
{
DBCountry country = null;
Database db = NopSqlDataHelper.CreateConnection(_sqlConnectionString);
DbCommand dbCommand = db.GetStoredProcCommand("Nop_CountryInsert");
db.AddOutParameter(dbCommand, "CountryID", DbType.Int32, 0);
db.AddInParameter(dbCommand, "Name", DbType.String, Name);
db.AddInParameter(dbCommand, "AllowsRegistration", DbType.Boolean, AllowsRegistration);
db.AddInParameter(dbCommand, "AllowsBilling", DbType.Boolean, AllowsBilling);
db.AddInParameter(dbCommand, "AllowsShipping", DbType.Boolean, AllowsShipping);
db.AddInParameter(dbCommand, "TwoLetterISOCode", DbType.String, TwoLetterISOCode);
db.AddInParameter(dbCommand, "ThreeLetterISOCode", DbType.String, ThreeLetterISOCode);
db.AddInParameter(dbCommand, "NumericISOCode", DbType.Int32, NumericISOCode);
db.AddInParameter(dbCommand, "Published", DbType.Boolean, Published);
db.AddInParameter(dbCommand, "DisplayOrder", DbType.Int32, DisplayOrder);
if (db.ExecuteNonQuery(dbCommand) > 0)
{
int CountryID = Convert.ToInt32(db.GetParameterValue(dbCommand, "@CountryID"));
country = GetCountryByID(CountryID);
}
return country;
}
/// <summary>
/// Updates the country
/// </summary>
/// <param name="CountryID">The country identifier</param>
/// <param name="Name">The name</param>
/// <param name="AllowsRegistration">A value indicating whether registration is allowed to this country</param>
/// <param name="AllowsBilling">A value indicating whether billing is allowed to this country</param>
/// <param name="AllowsShipping">A value indicating whether shipping is allowed to this country</param>
/// <param name="TwoLetterISOCode">The two letter ISO code</param>
/// <param name="ThreeLetterISOCode">The three letter ISO code</param>
/// <param name="NumericISOCode">The numeric ISO code</param>
/// <param name="Published">A value indicating whether the entity is published</param>
/// <param name="DisplayOrder">The display order</param>
/// <returns>Country</returns>
public override DBCountry UpdateCountry(int CountryID, string Name,
bool AllowsRegistration, bool AllowsBilling, bool AllowsShipping,
string TwoLetterISOCode, string ThreeLetterISOCode, int NumericISOCode,
bool Published, int DisplayOrder)
{
DBCountry country = null;
Database db = NopSqlDataHelper.CreateConnection(_sqlConnectionString);
DbCommand dbCommand = db.GetStoredProcCommand("Nop_CountryUpdate");
db.AddInParameter(dbCommand, "CountryID", DbType.Int32, CountryID);
db.AddInParameter(dbCommand, "Name", DbType.String, Name);
db.AddInParameter(dbCommand, "AllowsRegistration", DbType.Boolean, AllowsRegistration);
db.AddInParameter(dbCommand, "AllowsBilling", DbType.Boolean, AllowsBilling);
db.AddInParameter(dbCommand, "AllowsShipping", DbType.Boolean, AllowsShipping);
db.AddInParameter(dbCommand, "TwoLetterISOCode", DbType.String, TwoLetterISOCode);
db.AddInParameter(dbCommand, "ThreeLetterISOCode", DbType.String, ThreeLetterISOCode);
db.AddInParameter(dbCommand, "NumericISOCode", DbType.Int32, NumericISOCode);
db.AddInParameter(dbCommand, "Published", DbType.Boolean, Published);
db.AddInParameter(dbCommand, "DisplayOrder", DbType.Int32, DisplayOrder);
if (db.ExecuteNonQuery(dbCommand) > 0)
country = GetCountryByID(CountryID);
return country;
}
#endregion
}
}
|
using System;
using NUnit.Framework;
using Ninject;
namespace AdvancedIoCTechniques
{
public class OtherLifetimes
{
[Test]
public void Cache_And_Collect()
{
// unique feature of Ninject called "Cache-and-Collect"
var ninject = new StandardKernel();
// we define any object to be the "scope"
object scope = new object();
ninject.Bind<Third0>().ToSelf().InScope(_ => scope);
Assert.AreSame(
ninject.Get<Third0>(),
ninject.Get<Third0>());
scope = null;
GC.Collect();
GC.WaitForPendingFinalizers();
// since the scope has been garbage collected, these instances are no longer common
Assert.AreNotSame(
ninject.Get<Third0>(),
ninject.Get<Third0>());
}
}
} |
//using SynologyClient;
//namespace SynCommand
//{
// public class SynCommandCore
// {
// public SynologyResponse Injest()
// {
// return new SynologyResponse();
// }
// }
//} |
using System;
namespace PubSub
{
static public class PubSubExtensions
{
static private readonly Hub hub = new Hub();
static public bool Exists<T>(this object obj)
{
foreach (var h in hub.handlers)
{
if (Equals(h.Sender.Target, obj) &&
typeof(T) == h.Type)
{
return true;
}
}
return false;
}
static public void Publish<T>(this object obj, string routingKey = "")
{
hub.Publish(default(T), routingKey);
}
static public void Publish<T>(this object obj, T data, string routingKey = "")
{
hub.Publish(obj, routingKey, data);
}
static public void Subscribe<T>(this object obj, Action<T> handler, string routingKey = "")
{
hub.Subscribe(obj, handler, routingKey);
}
static public void Unsubscribe(this object obj)
{
hub.Unsubscribe(obj);
}
static public void Unsubscribe<T>(this object obj)
{
hub.Unsubscribe(obj, (Action<T>)null);
}
static public void Unsubscribe<T>(this object obj, Action<T> handler)
{
hub.Unsubscribe(obj, handler);
}
}
}
|
using System;
namespace Channel.Mine.API.Abstraction
{
public abstract class BaseFileSystemFilter<T> : Framework.Abstraction.BaseFilter<T> where T : Framework.Abstraction.BaseMedia
{
public String Query { get; internal set; }
public BaseFileSystemFilter(String query)
{
this.Query = query;
}
public override Boolean DoFilter(T item)
{
return item.File.FullName.IndexOf(this.Query, StringComparison.InvariantCultureIgnoreCase) >= 0;
}
}
} |
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using Microsoft.EntityFrameworkCore.Diagnostics;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Metadata.Internal;
using Microsoft.EntityFrameworkCore.Query.SqlExpressions;
using Microsoft.EntityFrameworkCore.Utilities;
namespace Microsoft.EntityFrameworkCore.Query
{
/// <summary>
/// <para>
/// A class that translates expressions to corresponding SQL representation.
/// </para>
/// <para>
/// This type is typically used by database providers (and other extensions). It is generally
/// not used in application code.
/// </para>
/// </summary>
public class RelationalSqlTranslatingExpressionVisitor : ExpressionVisitor
{
private const string RuntimeParameterPrefix = QueryCompilationContext.QueryParameterPrefix + "entity_equality_";
private static readonly MethodInfo _parameterValueExtractor =
typeof(RelationalSqlTranslatingExpressionVisitor).GetRequiredDeclaredMethod(nameof(ParameterValueExtractor));
private static readonly MethodInfo _parameterListValueExtractor =
typeof(RelationalSqlTranslatingExpressionVisitor).GetRequiredDeclaredMethod(nameof(ParameterListValueExtractor));
private static readonly MethodInfo _stringEqualsWithStringComparison
= typeof(string).GetRequiredRuntimeMethod(nameof(string.Equals), new[] { typeof(string), typeof(StringComparison) });
private static readonly MethodInfo _stringEqualsWithStringComparisonStatic
= typeof(string).GetRequiredRuntimeMethod(nameof(string.Equals), new[] { typeof(string), typeof(string), typeof(StringComparison) });
private static readonly MethodInfo _objectEqualsMethodInfo
= typeof(object).GetRequiredRuntimeMethod(nameof(object.Equals), new[] { typeof(object), typeof(object) });
private readonly QueryCompilationContext _queryCompilationContext;
private readonly IModel _model;
private readonly ISqlExpressionFactory _sqlExpressionFactory;
private readonly QueryableMethodTranslatingExpressionVisitor _queryableMethodTranslatingExpressionVisitor;
private readonly SqlTypeMappingVerifyingExpressionVisitor _sqlTypeMappingVerifyingExpressionVisitor;
/// <summary>
/// Creates a new instance of the <see cref="RelationalSqlTranslatingExpressionVisitor" /> class.
/// </summary>
/// <param name="dependencies"> Parameter object containing dependencies for this class. </param>
/// <param name="queryCompilationContext"> The query compilation context object to use. </param>
/// <param name="queryableMethodTranslatingExpressionVisitor"> A parent queryable method translating expression visitor to translate subquery. </param>
public RelationalSqlTranslatingExpressionVisitor(
RelationalSqlTranslatingExpressionVisitorDependencies dependencies,
QueryCompilationContext queryCompilationContext,
QueryableMethodTranslatingExpressionVisitor queryableMethodTranslatingExpressionVisitor)
{
Check.NotNull(dependencies, nameof(dependencies));
Check.NotNull(queryCompilationContext, nameof(queryCompilationContext));
Check.NotNull(queryableMethodTranslatingExpressionVisitor, nameof(queryableMethodTranslatingExpressionVisitor));
Dependencies = dependencies;
_sqlExpressionFactory = dependencies.SqlExpressionFactory;
_queryCompilationContext = queryCompilationContext;
_model = queryCompilationContext.Model;
_queryableMethodTranslatingExpressionVisitor = queryableMethodTranslatingExpressionVisitor;
_sqlTypeMappingVerifyingExpressionVisitor = new SqlTypeMappingVerifyingExpressionVisitor();
}
/// <summary>
/// Detailed information about errors encountered during translation.
/// </summary>
public virtual string? TranslationErrorDetails { get; private set; }
/// <summary>
/// Adds detailed information about error encountered during translation.
/// </summary>
/// <param name="details"> Detailed information about error encountered during translation. </param>
protected virtual void AddTranslationErrorDetails(string details)
{
Check.NotNull(details, nameof(details));
if (TranslationErrorDetails == null)
{
TranslationErrorDetails = details;
}
else
{
TranslationErrorDetails += Environment.NewLine + details;
}
}
/// <summary>
/// Parameter object containing service dependencies.
/// </summary>
protected virtual RelationalSqlTranslatingExpressionVisitorDependencies Dependencies { get; }
/// <summary>
/// Translates an expression to an equivalent SQL representation.
/// </summary>
/// <param name="expression"> An expression to translate. </param>
/// <returns> A SQL translation of the given expression. </returns>
public virtual SqlExpression? Translate(Expression expression)
{
Check.NotNull(expression, nameof(expression));
TranslationErrorDetails = null;
return TranslateInternal(expression);
}
private SqlExpression? TranslateInternal(Expression expression)
{
var result = Visit(expression);
if (result is SqlExpression translation)
{
if (translation is SqlUnaryExpression sqlUnaryExpression
&& sqlUnaryExpression.OperatorType == ExpressionType.Convert
&& sqlUnaryExpression.Type == typeof(object))
{
translation = sqlUnaryExpression.Operand;
}
translation = _sqlExpressionFactory.ApplyDefaultTypeMapping(translation);
if (translation.TypeMapping == null)
{
// The return type is not-mappable hence return null
return null;
}
_sqlTypeMappingVerifyingExpressionVisitor.Visit(translation);
return translation;
}
return null;
}
/// <summary>
/// Translates Average over an expression to an equivalent SQL representation.
/// </summary>
/// <param name="sqlExpression"> An expression to translate Average over. </param>
/// <returns> A SQL translation of Average over the given expression. </returns>
public virtual SqlExpression? TranslateAverage(SqlExpression sqlExpression)
{
Check.NotNull(sqlExpression, nameof(sqlExpression));
var inputType = sqlExpression.Type;
if (inputType == typeof(int)
|| inputType == typeof(long))
{
sqlExpression = sqlExpression is DistinctExpression distinctExpression
? new DistinctExpression(
_sqlExpressionFactory.ApplyDefaultTypeMapping(
_sqlExpressionFactory.Convert(distinctExpression.Operand, typeof(double))))
: _sqlExpressionFactory.ApplyDefaultTypeMapping(
_sqlExpressionFactory.Convert(sqlExpression, typeof(double)));
}
return inputType == typeof(float)
? _sqlExpressionFactory.Convert(
_sqlExpressionFactory.Function(
"AVG",
new[] { sqlExpression },
nullable: true,
argumentsPropagateNullability: new[] { false },
typeof(double)),
sqlExpression.Type,
sqlExpression.TypeMapping)
: (SqlExpression)_sqlExpressionFactory.Function(
"AVG",
new[] { sqlExpression },
nullable: true,
argumentsPropagateNullability: new[] { false },
sqlExpression.Type,
sqlExpression.TypeMapping);
}
/// <summary>
/// Translates Count over an expression to an equivalent SQL representation.
/// </summary>
/// <param name="sqlExpression"> An expression to translate Count over. </param>
/// <returns> A SQL translation of Count over the given expression. </returns>
public virtual SqlExpression? TranslateCount(SqlExpression sqlExpression)
{
Check.NotNull(sqlExpression, nameof(sqlExpression));
return _sqlExpressionFactory.ApplyDefaultTypeMapping(
_sqlExpressionFactory.Function(
"COUNT",
new[] { sqlExpression },
nullable: false,
argumentsPropagateNullability: new[] { false },
typeof(int)));
}
/// <summary>
/// Translates LongCount over an expression to an equivalent SQL representation.
/// </summary>
/// <param name="sqlExpression"> An expression to translate LongCount over. </param>
/// <returns> A SQL translation of LongCount over the given expression. </returns>
public virtual SqlExpression? TranslateLongCount(SqlExpression sqlExpression)
{
Check.NotNull(sqlExpression, nameof(sqlExpression));
return _sqlExpressionFactory.ApplyDefaultTypeMapping(
_sqlExpressionFactory.Function(
"COUNT",
new[] { sqlExpression },
nullable: false,
argumentsPropagateNullability: new[] { false },
typeof(long)));
}
/// <summary>
/// Translates Max over an expression to an equivalent SQL representation.
/// </summary>
/// <param name="sqlExpression"> An expression to translate Max over. </param>
/// <returns> A SQL translation of Max over the given expression. </returns>
public virtual SqlExpression? TranslateMax(SqlExpression sqlExpression)
{
Check.NotNull(sqlExpression, nameof(sqlExpression));
return sqlExpression != null
? _sqlExpressionFactory.Function(
"MAX",
new[] { sqlExpression },
nullable: true,
argumentsPropagateNullability: new[] { false },
sqlExpression.Type,
sqlExpression.TypeMapping)
: null;
}
/// <summary>
/// Translates Min over an expression to an equivalent SQL representation.
/// </summary>
/// <param name="sqlExpression"> An expression to translate Min over. </param>
/// <returns> A SQL translation of Min over the given expression. </returns>
public virtual SqlExpression? TranslateMin(SqlExpression sqlExpression)
{
Check.NotNull(sqlExpression, nameof(sqlExpression));
return sqlExpression != null
? _sqlExpressionFactory.Function(
"MIN",
new[] { sqlExpression },
nullable: true,
argumentsPropagateNullability: new[] { false },
sqlExpression.Type,
sqlExpression.TypeMapping)
: null;
}
/// <summary>
/// Translates Sum over an expression to an equivalent SQL representation.
/// </summary>
/// <param name="sqlExpression"> An expression to translate Sum over. </param>
/// <returns> A SQL translation of Sum over the given expression. </returns>
public virtual SqlExpression? TranslateSum(SqlExpression sqlExpression)
{
Check.NotNull(sqlExpression, nameof(sqlExpression));
var inputType = sqlExpression.Type;
return inputType == typeof(float)
? _sqlExpressionFactory.Convert(
_sqlExpressionFactory.Function(
"SUM",
new[] { sqlExpression },
nullable: true,
argumentsPropagateNullability: new[] { false },
typeof(double)),
inputType,
sqlExpression.TypeMapping)
: (SqlExpression)_sqlExpressionFactory.Function(
"SUM",
new[] { sqlExpression },
nullable: true,
argumentsPropagateNullability: new[] { false },
inputType,
sqlExpression.TypeMapping);
}
/// <inheritdoc />
protected override Expression VisitBinary(BinaryExpression binaryExpression)
{
Check.NotNull(binaryExpression, nameof(binaryExpression));
if (binaryExpression.Left.Type == typeof(object[])
&& binaryExpression.Left is NewArrayExpression
&& binaryExpression.NodeType == ExpressionType.Equal)
{
return Visit(ConvertObjectArrayEqualityComparison(binaryExpression.Left, binaryExpression.Right));
}
var left = TryRemoveImplicitConvert(binaryExpression.Left);
var right = TryRemoveImplicitConvert(binaryExpression.Right);
// Remove convert-to-object nodes if both sides have them, or if the other side is null constant
var isLeftConvertToObject = TryUnwrapConvertToObject(left, out var leftOperand);
var isRightConvertToObject = TryUnwrapConvertToObject(right, out var rightOperand);
if (isLeftConvertToObject && isRightConvertToObject)
{
left = leftOperand!;
right = rightOperand!;
}
else if (isLeftConvertToObject && right.IsNullConstantExpression())
{
left = leftOperand!;
}
else if (isRightConvertToObject && left.IsNullConstantExpression())
{
right = rightOperand!;
}
var visitedLeft = Visit(left);
var visitedRight = Visit(right);
if ((binaryExpression.NodeType == ExpressionType.Equal
|| binaryExpression.NodeType == ExpressionType.NotEqual)
// Visited expression could be null, We need to pass MemberInitExpression
&& TryRewriteEntityEquality(
binaryExpression.NodeType,
visitedLeft == QueryCompilationContext.NotTranslatedExpression ? left : visitedLeft,
visitedRight == QueryCompilationContext.NotTranslatedExpression ? right : visitedRight,
equalsMethod: false, out var result))
{
return result;
}
var uncheckedNodeTypeVariant = binaryExpression.NodeType switch
{
ExpressionType.AddChecked => ExpressionType.Add,
ExpressionType.SubtractChecked => ExpressionType.Subtract,
ExpressionType.MultiplyChecked => ExpressionType.Multiply,
_ => binaryExpression.NodeType
};
return TranslationFailed(binaryExpression.Left, visitedLeft, out var sqlLeft)
|| TranslationFailed(binaryExpression.Right, visitedRight, out var sqlRight)
? QueryCompilationContext.NotTranslatedExpression
: uncheckedNodeTypeVariant == ExpressionType.Coalesce
? _sqlExpressionFactory.Coalesce(sqlLeft!, sqlRight!)
: _sqlExpressionFactory.MakeBinary(
uncheckedNodeTypeVariant,
sqlLeft!,
sqlRight!,
null) ?? QueryCompilationContext.NotTranslatedExpression;
static bool TryUnwrapConvertToObject(Expression expression, out Expression? operand)
{
if (expression is UnaryExpression convertExpression
&& (convertExpression.NodeType == ExpressionType.Convert
|| convertExpression.NodeType == ExpressionType.ConvertChecked)
&& expression.Type == typeof(object))
{
operand = convertExpression.Operand;
return true;
}
operand = null;
return false;
}
}
/// <inheritdoc />
protected override Expression VisitConditional(ConditionalExpression conditionalExpression)
{
Check.NotNull(conditionalExpression, nameof(conditionalExpression));
var test = Visit(conditionalExpression.Test);
var ifTrue = Visit(conditionalExpression.IfTrue);
var ifFalse = Visit(conditionalExpression.IfFalse);
return TranslationFailed(conditionalExpression.Test, test, out var sqlTest)
|| TranslationFailed(conditionalExpression.IfTrue, ifTrue, out var sqlIfTrue)
|| TranslationFailed(conditionalExpression.IfFalse, ifFalse, out var sqlIfFalse)
? QueryCompilationContext.NotTranslatedExpression
: _sqlExpressionFactory.Case(new[] { new CaseWhenClause(sqlTest!, sqlIfTrue!) }, sqlIfFalse);
}
/// <inheritdoc />
protected override Expression VisitConstant(ConstantExpression constantExpression)
=> new SqlConstantExpression(Check.NotNull(constantExpression, nameof(constantExpression)), null);
/// <inheritdoc />
protected override Expression VisitExtension(Expression extensionExpression)
{
Check.NotNull(extensionExpression, nameof(extensionExpression));
switch (extensionExpression)
{
case EntityProjectionExpression _:
case EntityReferenceExpression _:
case SqlExpression _:
return extensionExpression;
case EntityShaperExpression entityShaperExpression:
return new EntityReferenceExpression(entityShaperExpression);
case ProjectionBindingExpression projectionBindingExpression:
return ((SelectExpression)projectionBindingExpression.QueryExpression)
.GetProjection(projectionBindingExpression);
case GroupByShaperExpression groupByShaperExpression:
return new GroupingElementExpression(groupByShaperExpression.ElementSelector);
case ShapedQueryExpression shapedQueryExpression:
if (shapedQueryExpression.ResultCardinality == ResultCardinality.Enumerable)
{
return QueryCompilationContext.NotTranslatedExpression;
}
var shaperExpression = shapedQueryExpression.ShaperExpression;
ProjectionBindingExpression? mappedProjectionBindingExpression = null;
var innerExpression = shaperExpression;
Type? convertedType = null;
if (shaperExpression is UnaryExpression unaryExpression
&& unaryExpression.NodeType == ExpressionType.Convert)
{
convertedType = unaryExpression.Type;
innerExpression = unaryExpression.Operand;
}
if (innerExpression is EntityShaperExpression ese
&& (convertedType == null
|| convertedType.IsAssignableFrom(ese.Type)))
{
return new EntityReferenceExpression(shapedQueryExpression.UpdateShaperExpression(innerExpression));
}
if (innerExpression is ProjectionBindingExpression pbe
&& (convertedType == null
|| convertedType.MakeNullable() == innerExpression.Type))
{
mappedProjectionBindingExpression = pbe;
}
if (mappedProjectionBindingExpression == null
&& shaperExpression is BlockExpression blockExpression
&& blockExpression.Expressions.Count == 2
&& blockExpression.Expressions[0] is BinaryExpression binaryExpression
&& binaryExpression.NodeType == ExpressionType.Assign
&& binaryExpression.Right is ProjectionBindingExpression pbe2)
{
mappedProjectionBindingExpression = pbe2;
}
if (mappedProjectionBindingExpression == null)
{
return QueryCompilationContext.NotTranslatedExpression;
}
var subquery = (SelectExpression)shapedQueryExpression.QueryExpression;
var projection = subquery.GetProjection(mappedProjectionBindingExpression);
if (projection is not SqlExpression sqlExpression)
{
return QueryCompilationContext.NotTranslatedExpression;
}
if (subquery.Tables.Count == 0)
{
return sqlExpression;
}
subquery.ReplaceProjection(new List<Expression>());
subquery.AddToProjection(sqlExpression);
SqlExpression scalarSubqueryExpression = new ScalarSubqueryExpression(subquery);
if (shapedQueryExpression.ResultCardinality == ResultCardinality.SingleOrDefault
&& !shaperExpression.Type.IsNullableType())
{
scalarSubqueryExpression = _sqlExpressionFactory.Coalesce(
scalarSubqueryExpression,
(SqlExpression)Visit(shaperExpression.Type.GetDefaultValueConstant()));
}
return scalarSubqueryExpression;
default:
return QueryCompilationContext.NotTranslatedExpression;
}
}
/// <inheritdoc />
protected override Expression VisitInvocation(InvocationExpression invocationExpression)
=> QueryCompilationContext.NotTranslatedExpression;
/// <inheritdoc />
protected override Expression VisitLambda<T>(Expression<T> lambdaExpression)
=> throw new InvalidOperationException(CoreStrings.TranslationFailed(lambdaExpression.Print()));
/// <inheritdoc />
protected override Expression VisitListInit(ListInitExpression listInitExpression)
=> QueryCompilationContext.NotTranslatedExpression;
/// <inheritdoc />
protected override Expression VisitMember(MemberExpression memberExpression)
{
Check.NotNull(memberExpression, nameof(memberExpression));
var innerExpression = Visit(memberExpression.Expression);
return TryBindMember(innerExpression, MemberIdentity.Create(memberExpression.Member))
?? (TranslationFailed(memberExpression.Expression, Visit(memberExpression.Expression), out var sqlInnerExpression)
? QueryCompilationContext.NotTranslatedExpression
: Dependencies.MemberTranslatorProvider.Translate(
sqlInnerExpression, memberExpression.Member, memberExpression.Type, _queryCompilationContext.Logger))
?? QueryCompilationContext.NotTranslatedExpression;
}
/// <inheritdoc />
protected override Expression VisitMemberInit(MemberInitExpression memberInitExpression)
=> GetConstantOrNotTranslated(Check.NotNull(memberInitExpression, nameof(memberInitExpression)));
/// <inheritdoc />
protected override Expression VisitMethodCall(MethodCallExpression methodCallExpression)
{
Check.NotNull(methodCallExpression, nameof(methodCallExpression));
// EF.Property case
if (methodCallExpression.TryGetEFPropertyArguments(out var source, out var propertyName))
{
return TryBindMember(Visit(source), MemberIdentity.Create(propertyName))
?? throw new InvalidOperationException(CoreStrings.QueryUnableToTranslateEFProperty(methodCallExpression.Print()));
}
// EF Indexer property
if (methodCallExpression.TryGetIndexerArguments(_model, out source, out propertyName))
{
var result = TryBindMember(Visit(source), MemberIdentity.Create(propertyName));
if (result != null)
{
return result;
}
}
// GroupBy Aggregate case
if (methodCallExpression.Object == null
&& methodCallExpression.Method.DeclaringType == typeof(Enumerable)
&& methodCallExpression.Arguments.Count > 0)
{
if (methodCallExpression.Arguments[0].Type.TryGetElementType(typeof(IQueryable<>)) == null
&& Visit(methodCallExpression.Arguments[0]) is GroupingElementExpression groupingElementExpression)
{
Expression? result;
switch (methodCallExpression.Method.Name)
{
case nameof(Enumerable.Average):
if (methodCallExpression.Arguments.Count == 2)
{
groupingElementExpression = ApplySelector(
groupingElementExpression, methodCallExpression.Arguments[1].UnwrapLambdaFromQuote());
}
result = GetExpressionForAggregation(groupingElementExpression) is SqlExpression averageExpression
? TranslateAverage(averageExpression)
: null;
break;
case nameof(Enumerable.Count):
if (methodCallExpression.Arguments.Count == 2)
{
var newGroupingElementExpression = ApplyPredicate(
groupingElementExpression, methodCallExpression.Arguments[1].UnwrapLambdaFromQuote());
if (newGroupingElementExpression == null)
{
result = null;
break;
}
groupingElementExpression = newGroupingElementExpression;
}
result = TranslateCount(GetExpressionForAggregation(groupingElementExpression, starProjection: true)!);
break;
case nameof(Enumerable.Distinct):
result = groupingElementExpression.Element is EntityShaperExpression
? groupingElementExpression
: groupingElementExpression.IsDistinct
? null
: groupingElementExpression.ApplyDistinct();
break;
case nameof(Enumerable.LongCount):
if (methodCallExpression.Arguments.Count == 2)
{
var newGroupingElementExpression = ApplyPredicate(
groupingElementExpression, methodCallExpression.Arguments[1].UnwrapLambdaFromQuote());
if (newGroupingElementExpression == null)
{
result = null;
break;
}
groupingElementExpression = newGroupingElementExpression;
}
result = TranslateLongCount(GetExpressionForAggregation(groupingElementExpression, starProjection: true)!);
break;
case nameof(Enumerable.Max):
if (methodCallExpression.Arguments.Count == 2)
{
groupingElementExpression = ApplySelector(
groupingElementExpression, methodCallExpression.Arguments[1].UnwrapLambdaFromQuote());
}
result = GetExpressionForAggregation(groupingElementExpression) is SqlExpression maxExpression
? TranslateMax(maxExpression)
: null;
break;
case nameof(Enumerable.Min):
if (methodCallExpression.Arguments.Count == 2)
{
groupingElementExpression = ApplySelector(
groupingElementExpression, methodCallExpression.Arguments[1].UnwrapLambdaFromQuote());
}
result = GetExpressionForAggregation(groupingElementExpression) is SqlExpression minExpression
? TranslateMin(minExpression)
: null;
break;
case nameof(Enumerable.Select):
result = ApplySelector(groupingElementExpression, methodCallExpression.Arguments[1].UnwrapLambdaFromQuote());
break;
case nameof(Enumerable.Sum):
if (methodCallExpression.Arguments.Count == 2)
{
groupingElementExpression = ApplySelector(
groupingElementExpression, methodCallExpression.Arguments[1].UnwrapLambdaFromQuote());
}
result = GetExpressionForAggregation(groupingElementExpression) is SqlExpression sumExpression
? TranslateSum(sumExpression)
: null;
break;
case nameof(Enumerable.Where):
result = ApplyPredicate(groupingElementExpression, methodCallExpression.Arguments[1].UnwrapLambdaFromQuote());
break;
default:
result = null;
break;
}
return result ?? throw new InvalidOperationException(CoreStrings.TranslationFailed(methodCallExpression.Print()));
GroupingElementExpression? ApplyPredicate(GroupingElementExpression groupingElement, LambdaExpression lambdaExpression)
{
var predicate = TranslateInternal(RemapLambda(groupingElement, lambdaExpression));
return predicate == null
? null
: groupingElement.ApplyPredicate(predicate);
}
static GroupingElementExpression ApplySelector(
GroupingElementExpression groupingElement,
LambdaExpression lambdaExpression)
{
var selector = RemapLambda(groupingElement, lambdaExpression);
return groupingElement.ApplySelector(selector);
}
static Expression RemapLambda(GroupingElementExpression groupingElement, LambdaExpression lambdaExpression)
=> ReplacingExpressionVisitor.Replace(
lambdaExpression.Parameters[0], groupingElement.Element, lambdaExpression.Body);
SqlExpression? GetExpressionForAggregation(GroupingElementExpression groupingElement, bool starProjection = false)
{
var selector = TranslateInternal(groupingElement.Element);
if (selector == null)
{
if (starProjection)
{
selector = _sqlExpressionFactory.Fragment("*");
}
else
{
return null;
}
}
if (groupingElement.Predicate != null)
{
if (selector is SqlFragmentExpression)
{
selector = _sqlExpressionFactory.Constant(1);
}
selector = _sqlExpressionFactory.Case(
new List<CaseWhenClause> { new(groupingElement.Predicate, selector) },
elseResult: null);
}
if (groupingElement.IsDistinct
&& !(selector is SqlFragmentExpression))
{
selector = new DistinctExpression(selector);
}
return selector;
}
}
}
// Subquery case
var subqueryTranslation = _queryableMethodTranslatingExpressionVisitor.TranslateSubquery(methodCallExpression);
if (subqueryTranslation != null)
{
return Visit(subqueryTranslation);
}
SqlExpression? sqlObject = null;
SqlExpression[] arguments;
var method = methodCallExpression.Method;
if (method.Name == nameof(object.Equals)
&& methodCallExpression.Object != null
&& methodCallExpression.Arguments.Count == 1)
{
var left = Visit(methodCallExpression.Object);
var right = Visit(RemoveObjectConvert(methodCallExpression.Arguments[0]));
if (TryRewriteEntityEquality(
ExpressionType.Equal,
left == QueryCompilationContext.NotTranslatedExpression ? methodCallExpression.Object : left,
right == QueryCompilationContext.NotTranslatedExpression ? methodCallExpression.Arguments[0] : right,
equalsMethod: true,
out var result))
{
return result;
}
if (left is SqlExpression leftSql
&& right is SqlExpression rightSql)
{
sqlObject = leftSql;
arguments = new SqlExpression[1] { rightSql };
}
else
{
return QueryCompilationContext.NotTranslatedExpression;
}
}
else if (method.Name == nameof(object.Equals)
&& methodCallExpression.Object == null
&& methodCallExpression.Arguments.Count == 2)
{
if (methodCallExpression.Arguments[0].Type == typeof(object[])
&& methodCallExpression.Arguments[0] is NewArrayExpression)
{
return Visit(
ConvertObjectArrayEqualityComparison(
methodCallExpression.Arguments[0], methodCallExpression.Arguments[1]));
}
var left = Visit(RemoveObjectConvert(methodCallExpression.Arguments[0]));
var right = Visit(RemoveObjectConvert(methodCallExpression.Arguments[1]));
if (TryRewriteEntityEquality(
ExpressionType.Equal,
left == QueryCompilationContext.NotTranslatedExpression ? methodCallExpression.Arguments[0] : left,
right == QueryCompilationContext.NotTranslatedExpression ? methodCallExpression.Arguments[1] : right,
equalsMethod: true,
out var result))
{
return result;
}
if (left is SqlExpression leftSql
&& right is SqlExpression rightSql)
{
arguments = new SqlExpression[2] { leftSql, rightSql };
}
else
{
return QueryCompilationContext.NotTranslatedExpression;
}
}
else if (method.IsGenericMethod
&& method.GetGenericMethodDefinition().Equals(EnumerableMethods.Contains))
{
var enumerable = Visit(methodCallExpression.Arguments[0]);
var item = Visit(methodCallExpression.Arguments[1]);
if (TryRewriteContainsEntity(enumerable,
item == QueryCompilationContext.NotTranslatedExpression ? methodCallExpression.Arguments[1] : item, out var result))
{
return result;
}
if (enumerable is SqlExpression sqlEnumerable
&& item is SqlExpression sqlItem)
{
arguments = new SqlExpression[2] { sqlEnumerable, sqlItem };
}
else
{
return QueryCompilationContext.NotTranslatedExpression;
}
}
else if (methodCallExpression.Arguments.Count == 1
&& method.IsContainsMethod())
{
var enumerable = Visit(methodCallExpression.Object);
var item = Visit(methodCallExpression.Arguments[0]);
if (TryRewriteContainsEntity(enumerable!,
item == QueryCompilationContext.NotTranslatedExpression ? methodCallExpression.Arguments[0] : item, out var result))
{
return result;
}
if (enumerable is SqlExpression sqlEnumerable
&& item is SqlExpression sqlItem)
{
sqlObject = sqlEnumerable;
arguments = new SqlExpression[1] { sqlItem };
}
else
{
return QueryCompilationContext.NotTranslatedExpression;
}
}
else
{
if (TranslationFailed(methodCallExpression.Object, Visit(methodCallExpression.Object), out sqlObject))
{
return QueryCompilationContext.NotTranslatedExpression;
}
arguments = new SqlExpression[methodCallExpression.Arguments.Count];
for (var i = 0; i < arguments.Length; i++)
{
var argument = methodCallExpression.Arguments[i];
if (TranslationFailed(argument, Visit(argument), out var sqlArgument))
{
return QueryCompilationContext.NotTranslatedExpression;
}
arguments[i] = sqlArgument!;
}
}
var translation = Dependencies.MethodCallTranslatorProvider.Translate(
_model, sqlObject, methodCallExpression.Method, arguments, _queryCompilationContext.Logger);
if (translation == null)
{
if (methodCallExpression.Method == _stringEqualsWithStringComparison
|| methodCallExpression.Method == _stringEqualsWithStringComparisonStatic)
{
AddTranslationErrorDetails(CoreStrings.QueryUnableToTranslateStringEqualsWithStringComparison);
}
else
{
AddTranslationErrorDetails(
CoreStrings.QueryUnableToTranslateMethod(
methodCallExpression.Method.DeclaringType?.DisplayName(),
methodCallExpression.Method.Name));
}
}
return translation ?? QueryCompilationContext.NotTranslatedExpression;
}
/// <inheritdoc />
protected override Expression VisitNew(NewExpression newExpression)
=> GetConstantOrNotTranslated(Check.NotNull(newExpression, nameof(newExpression)));
/// <inheritdoc />
protected override Expression VisitNewArray(NewArrayExpression newArrayExpression)
=> QueryCompilationContext.NotTranslatedExpression;
/// <inheritdoc />
protected override Expression VisitParameter(ParameterExpression parameterExpression)
=> parameterExpression.Name?.StartsWith(QueryCompilationContext.QueryParameterPrefix, StringComparison.Ordinal) == true
? new SqlParameterExpression(Check.NotNull(parameterExpression, nameof(parameterExpression)), null)
: throw new InvalidOperationException(CoreStrings.TranslationFailed(parameterExpression.Print()));
/// <inheritdoc />
protected override Expression VisitTypeBinary(TypeBinaryExpression typeBinaryExpression)
{
Check.NotNull(typeBinaryExpression, nameof(typeBinaryExpression));
var innerExpression = Visit(typeBinaryExpression.Expression);
if (typeBinaryExpression.NodeType == ExpressionType.TypeIs
&& innerExpression is EntityReferenceExpression entityReferenceExpression)
{
var entityType = entityReferenceExpression.EntityType;
if (entityType.GetAllBaseTypesInclusive().Any(et => et.ClrType == typeBinaryExpression.TypeOperand))
{
return _sqlExpressionFactory.Constant(true);
}
var derivedType = entityType.GetDerivedTypes().SingleOrDefault(et => et.ClrType == typeBinaryExpression.TypeOperand);
if (derivedType != null)
{
var discriminatorProperty = entityType.FindDiscriminatorProperty();
if (discriminatorProperty == null)
{
// TPT
var discriminatorValues = derivedType.GetTptDiscriminatorValues();
if (entityReferenceExpression.SubqueryEntity != null)
{
var entityShaper = (EntityShaperExpression)entityReferenceExpression.SubqueryEntity.ShaperExpression;
var entityProjection = (EntityProjectionExpression)Visit(entityShaper.ValueBufferExpression);
var subSelectExpression = (SelectExpression)entityReferenceExpression.SubqueryEntity.QueryExpression;
var predicate = GeneratePredicateTPT(entityProjection);
subSelectExpression.ApplyPredicate(predicate);
subSelectExpression.ReplaceProjection(new Dictionary<ProjectionMember, Expression>());
if (subSelectExpression.Limit == null
&& subSelectExpression.Offset == null)
{
subSelectExpression.ClearOrdering();
}
return _sqlExpressionFactory.Exists(subSelectExpression, false);
}
if (entityReferenceExpression.ParameterEntity != null)
{
var entityProjection = (EntityProjectionExpression)Visit(
entityReferenceExpression.ParameterEntity.ValueBufferExpression);
return GeneratePredicateTPT(entityProjection);
}
SqlExpression GeneratePredicateTPT(EntityProjectionExpression entityProjectionExpression)
{
if (entityProjectionExpression.DiscriminatorExpression is CaseExpression caseExpression)
{
var matchingCaseWhenClauses = caseExpression.WhenClauses
.Where(wc => discriminatorValues.Contains((string)((SqlConstantExpression)wc.Result).Value!))
.ToList();
return matchingCaseWhenClauses.Count == 1
? matchingCaseWhenClauses[0].Test
: matchingCaseWhenClauses.Select(e => e.Test)
.Aggregate((l, r) => _sqlExpressionFactory.OrElse(l, r));
}
return discriminatorValues.Count == 1
? _sqlExpressionFactory.Equal(
entityProjectionExpression.DiscriminatorExpression!,
_sqlExpressionFactory.Constant(discriminatorValues[0]))
: (SqlExpression)_sqlExpressionFactory.In(
entityProjectionExpression.DiscriminatorExpression!,
_sqlExpressionFactory.Constant(discriminatorValues),
negated: false);
}
}
else
{
if (!derivedType.GetRootType().GetIsDiscriminatorMappingComplete()
|| !derivedType.GetAllBaseTypesInclusiveAscending()
.All(e => (e == derivedType || e.IsAbstract()) && !HasSiblings(e)))
{
var concreteEntityTypes = derivedType.GetConcreteDerivedTypesInclusive().ToList();
var discriminatorColumn = BindProperty(entityReferenceExpression, discriminatorProperty);
if (discriminatorColumn != null)
{
return concreteEntityTypes.Count == 1
? _sqlExpressionFactory.Equal(
discriminatorColumn,
_sqlExpressionFactory.Constant(concreteEntityTypes[0].GetDiscriminatorValue()))
: (Expression)_sqlExpressionFactory.In(
discriminatorColumn,
_sqlExpressionFactory.Constant(
concreteEntityTypes.Select(et => et.GetDiscriminatorValue()).ToList()),
negated: false);
}
}
else
{
return _sqlExpressionFactory.Constant(true);
}
}
}
}
return QueryCompilationContext.NotTranslatedExpression;
static bool HasSiblings(IEntityType entityType)
=> entityType.BaseType?.GetDirectlyDerivedTypes().Any(i => i != entityType) == true;
}
/// <inheritdoc />
protected override Expression VisitUnary(UnaryExpression unaryExpression)
{
Check.NotNull(unaryExpression, nameof(unaryExpression));
var operand = Visit(unaryExpression.Operand);
if (operand is EntityReferenceExpression entityReferenceExpression
&& (unaryExpression.NodeType == ExpressionType.Convert
|| unaryExpression.NodeType == ExpressionType.ConvertChecked
|| unaryExpression.NodeType == ExpressionType.TypeAs))
{
return entityReferenceExpression.Convert(unaryExpression.Type);
}
if (TranslationFailed(unaryExpression.Operand, operand, out var sqlOperand))
{
return QueryCompilationContext.NotTranslatedExpression;
}
switch (unaryExpression.NodeType)
{
case ExpressionType.Not:
return _sqlExpressionFactory.Not(sqlOperand!);
case ExpressionType.Negate:
case ExpressionType.NegateChecked:
return _sqlExpressionFactory.Negate(sqlOperand!);
case ExpressionType.Convert:
case ExpressionType.ConvertChecked:
case ExpressionType.TypeAs:
// Object convert needs to be converted to explicit cast when mismatching types
if (operand.Type.IsInterface
&& unaryExpression.Type.GetInterfaces().Any(e => e == operand.Type)
|| unaryExpression.Type.UnwrapNullableType() == operand.Type.UnwrapNullableType()
|| unaryExpression.Type.UnwrapNullableType() == typeof(Enum))
{
return sqlOperand!;
}
// Introduce explicit cast only if the target type is mapped else we need to client eval
if (unaryExpression.Type == typeof(object)
|| Dependencies.TypeMappingSource.FindMapping(unaryExpression.Type) != null)
{
sqlOperand = _sqlExpressionFactory.ApplyDefaultTypeMapping(sqlOperand);
return _sqlExpressionFactory.Convert(sqlOperand!, unaryExpression.Type);
}
break;
case ExpressionType.Quote:
return operand;
}
return QueryCompilationContext.NotTranslatedExpression;
}
private Expression? TryBindMember(Expression? source, MemberIdentity member)
{
if (!(source is EntityReferenceExpression entityReferenceExpression))
{
return null;
}
var entityType = entityReferenceExpression.EntityType;
var property = member.MemberInfo != null
? entityType.FindProperty(member.MemberInfo)
: entityType.FindProperty(member.Name!);
if (property != null)
{
return BindProperty(entityReferenceExpression, property);
}
AddTranslationErrorDetails(
CoreStrings.QueryUnableToTranslateMember(
member.Name,
entityReferenceExpression.EntityType.DisplayName()));
return null;
}
private SqlExpression? BindProperty(EntityReferenceExpression entityReferenceExpression, IProperty property)
{
if (entityReferenceExpression.ParameterEntity != null)
{
var valueBufferExpression = Visit(entityReferenceExpression.ParameterEntity.ValueBufferExpression);
if (valueBufferExpression == QueryCompilationContext.NotTranslatedExpression)
{
return null;
}
return ((EntityProjectionExpression)valueBufferExpression).BindProperty(property);
}
if (entityReferenceExpression.SubqueryEntity != null)
{
var entityShaper = (EntityShaperExpression)entityReferenceExpression.SubqueryEntity.ShaperExpression;
var subSelectExpression = (SelectExpression)entityReferenceExpression.SubqueryEntity.QueryExpression;
SqlExpression innerProjection;
var projectionBindingExpression = (ProjectionBindingExpression)entityShaper.ValueBufferExpression;
var entityProjectionExpression = (EntityProjectionExpression)subSelectExpression.GetProjection(projectionBindingExpression);
innerProjection = entityProjectionExpression.BindProperty(property);
subSelectExpression.ReplaceProjection(new List<Expression>());
subSelectExpression.AddToProjection(innerProjection);
return new ScalarSubqueryExpression(subSelectExpression);
}
return null;
}
private static Expression TryRemoveImplicitConvert(Expression expression)
{
if (expression is UnaryExpression unaryExpression
&& (unaryExpression.NodeType == ExpressionType.Convert
|| unaryExpression.NodeType == ExpressionType.ConvertChecked))
{
var innerType = unaryExpression.Operand.Type.UnwrapNullableType();
if (innerType.IsEnum)
{
innerType = Enum.GetUnderlyingType(innerType);
}
var convertedType = expression.Type.UnwrapNullableType();
if (innerType == convertedType
|| (convertedType == typeof(int)
&& (innerType == typeof(byte)
|| innerType == typeof(sbyte)
|| innerType == typeof(char)
|| innerType == typeof(short)
|| innerType == typeof(ushort))))
{
return TryRemoveImplicitConvert(unaryExpression.Operand);
}
}
return expression;
}
private static Expression RemoveObjectConvert(Expression expression)
=> expression is UnaryExpression unaryExpression
&& (unaryExpression.NodeType == ExpressionType.Convert || unaryExpression.NodeType == ExpressionType.ConvertChecked)
&& unaryExpression.Type == typeof(object)
? unaryExpression.Operand
: expression;
private static Expression ConvertObjectArrayEqualityComparison(Expression left, Expression right)
{
var leftExpressions = ((NewArrayExpression)left).Expressions;
var rightExpressions = ((NewArrayExpression)right).Expressions;
return leftExpressions.Zip(
rightExpressions,
(l, r) => (Expression)Expression.Call(_objectEqualsMethodInfo, l, r))
.Aggregate((a, b) => Expression.AndAlso(a, b));
}
private static Expression GetConstantOrNotTranslated(Expression expression)
=> CanEvaluate(expression)
? new SqlConstantExpression(
Expression.Constant(
Expression.Lambda<Func<object>>(Expression.Convert(expression, typeof(object))).Compile().Invoke(),
expression.Type),
null)
: QueryCompilationContext.NotTranslatedExpression;
private bool TryRewriteContainsEntity(Expression source, Expression item, [NotNullWhen(true)] out Expression? result)
{
result = null;
if (!(item is EntityReferenceExpression itemEntityReference))
{
return false;
}
var entityType = itemEntityReference.EntityType;
var primaryKeyProperties = entityType.FindPrimaryKey()?.Properties;
if (primaryKeyProperties == null)
{
throw new InvalidOperationException(CoreStrings.EntityEqualityOnKeylessEntityNotSupported(
nameof(Queryable.Contains), entityType.DisplayName()));
}
if (primaryKeyProperties.Count > 1)
{
throw new InvalidOperationException(
CoreStrings.EntityEqualityOnCompositeKeyEntitySubqueryNotSupported(nameof(Queryable.Contains), entityType.DisplayName()));
}
var property = primaryKeyProperties[0];
Expression rewrittenSource;
switch (source)
{
case SqlConstantExpression sqlConstantExpression:
var values = (IEnumerable)sqlConstantExpression.Value!;
var propertyValueList =
(IList)Activator.CreateInstance(typeof(List<>).MakeGenericType(property.ClrType.MakeNullable()))!;
var propertyGetter = property.GetGetter();
foreach (var value in values)
{
propertyValueList.Add(propertyGetter.GetClrValue(value));
}
rewrittenSource = Expression.Constant(propertyValueList);
break;
case SqlParameterExpression sqlParameterExpression
when sqlParameterExpression.Name.StartsWith(QueryCompilationContext.QueryParameterPrefix, StringComparison.Ordinal):
var lambda = Expression.Lambda(
Expression.Call(
_parameterListValueExtractor.MakeGenericMethod(entityType.ClrType, property.ClrType.MakeNullable()),
QueryCompilationContext.QueryContextParameter,
Expression.Constant(sqlParameterExpression.Name, typeof(string)),
Expression.Constant(property, typeof(IProperty))),
QueryCompilationContext.QueryContextParameter
);
var newParameterName =
$"{RuntimeParameterPrefix}"
+ $"{sqlParameterExpression.Name[QueryCompilationContext.QueryParameterPrefix.Length..]}_{property.Name}";
rewrittenSource = _queryCompilationContext.RegisterRuntimeParameter(newParameterName, lambda);
break;
default:
return false;
}
result = Visit(
Expression.Call(
EnumerableMethods.Contains.MakeGenericMethod(property.ClrType.MakeNullable()),
rewrittenSource,
CreatePropertyAccessExpression(item, property)));
return true;
}
private bool TryRewriteEntityEquality(
ExpressionType nodeType, Expression left, Expression right, bool equalsMethod, [NotNullWhen(true)] out Expression? result)
{
var leftEntityReference = left as EntityReferenceExpression;
var rightEntityReference = right as EntityReferenceExpression;
if (leftEntityReference == null
&& rightEntityReference == null)
{
result = null;
return false;
}
if (IsNullSqlConstantExpression(left)
|| IsNullSqlConstantExpression(right))
{
var nonNullEntityReference = (IsNullSqlConstantExpression(left) ? rightEntityReference : leftEntityReference)!;
var entityType1 = nonNullEntityReference.EntityType;
var table = entityType1.GetViewOrTableMappings().FirstOrDefault()?.Table;
if (table?.IsOptional(entityType1) == true)
{
Expression? condition = null;
// Optional dependent sharing table
var requiredNonPkProperties = entityType1.GetProperties().Where(p => !p.IsNullable && !p.IsPrimaryKey()).ToList();
if (requiredNonPkProperties.Count > 0)
{
condition = requiredNonPkProperties.Select(
p =>
{
var comparison = Expression.Call(
_objectEqualsMethodInfo,
Expression.Convert(CreatePropertyAccessExpression(nonNullEntityReference, p), typeof(object)),
Expression.Convert(Expression.Constant(null, p.ClrType.MakeNullable()), typeof(object)));
return nodeType == ExpressionType.Equal
? (Expression)comparison
: Expression.Not(comparison);
})
.Aggregate((l, r) => nodeType == ExpressionType.Equal ? Expression.OrElse(l, r) : Expression.AndAlso(l, r));
}
var allNonPrincipalSharedNonPkProperties = entityType1.GetNonPrincipalSharedNonPkProperties(table);
// We don't need condition for nullable property if there exist at least one required property which is non shared.
if (allNonPrincipalSharedNonPkProperties.Count != 0
&& allNonPrincipalSharedNonPkProperties.All(p => p.IsNullable))
{
var atLeastOneNonNullValueInNullablePropertyCondition = allNonPrincipalSharedNonPkProperties
.Select(
p =>
{
var comparison = Expression.Call(
_objectEqualsMethodInfo,
Expression.Convert(CreatePropertyAccessExpression(nonNullEntityReference, p), typeof(object)),
Expression.Convert(Expression.Constant(null, p.ClrType.MakeNullable()), typeof(object)));
return nodeType == ExpressionType.Equal
? (Expression)comparison
: Expression.Not(comparison);
})
.Aggregate((l, r) => nodeType == ExpressionType.Equal ? Expression.AndAlso(l, r) : Expression.OrElse(l, r));
condition = condition == null
? atLeastOneNonNullValueInNullablePropertyCondition
: nodeType == ExpressionType.Equal
? Expression.OrElse(condition, atLeastOneNonNullValueInNullablePropertyCondition)
: Expression.AndAlso(condition, atLeastOneNonNullValueInNullablePropertyCondition);
}
if (condition != null)
{
result = Visit(condition);
return true;
}
result = null;
return false;
}
var primaryKeyProperties1 = entityType1.FindPrimaryKey()?.Properties;
if (primaryKeyProperties1 == null)
{
throw new InvalidOperationException(CoreStrings.EntityEqualityOnKeylessEntityNotSupported(
nodeType == ExpressionType.Equal
? equalsMethod ? nameof(object.Equals) : "=="
: equalsMethod ? "!" + nameof(object.Equals) : "!=",
entityType1.DisplayName()));
}
result = Visit(
primaryKeyProperties1.Select(
p =>
{
var comparison = Expression.Call(
_objectEqualsMethodInfo,
Expression.Convert(CreatePropertyAccessExpression(nonNullEntityReference, p), typeof(object)),
Expression.Convert(Expression.Constant(null, p.ClrType.MakeNullable()), typeof(object)));
return nodeType == ExpressionType.Equal
? (Expression)comparison
: Expression.Not(comparison);
}).Aggregate((l, r) => nodeType == ExpressionType.Equal ? Expression.OrElse(l, r) : Expression.AndAlso(l, r)));
return true;
}
var leftEntityType = leftEntityReference?.EntityType;
var rightEntityType = rightEntityReference?.EntityType;
var entityType = leftEntityType ?? rightEntityType;
Debug.Assert(entityType != null, "At least one side should be entityReference so entityType should be non-null.");
if (leftEntityType != null
&& rightEntityType != null
&& leftEntityType.GetRootType() != rightEntityType.GetRootType())
{
result = _sqlExpressionFactory.Constant(false);
return true;
}
var primaryKeyProperties = entityType.FindPrimaryKey()?.Properties;
if (primaryKeyProperties == null)
{
throw new InvalidOperationException(CoreStrings.EntityEqualityOnKeylessEntityNotSupported(
nodeType == ExpressionType.Equal
? equalsMethod ? nameof(object.Equals) : "=="
: equalsMethod ? "!" + nameof(object.Equals) : "!=",
entityType.DisplayName()));
}
if (primaryKeyProperties.Count > 1
&& (leftEntityReference?.SubqueryEntity != null
|| rightEntityReference?.SubqueryEntity != null))
{
throw new InvalidOperationException(CoreStrings.EntityEqualityOnCompositeKeyEntitySubqueryNotSupported(
nodeType == ExpressionType.Equal
? equalsMethod ? nameof(object.Equals) : "=="
: equalsMethod ? "!" + nameof(object.Equals) : "!=",
entityType.DisplayName()));
}
result = Visit(
primaryKeyProperties.Select(
p =>
{
var comparison = Expression.Call(
_objectEqualsMethodInfo,
Expression.Convert(CreatePropertyAccessExpression(left, p), typeof(object)),
Expression.Convert(CreatePropertyAccessExpression(right, p), typeof(object)));
return nodeType == ExpressionType.Equal
? (Expression)comparison
: Expression.Not(comparison);
}).Aggregate((l, r) => nodeType == ExpressionType.Equal
? Expression.AndAlso(l, r)
: Expression.OrElse(l, r)));
return true;
}
private Expression CreatePropertyAccessExpression(Expression target, IProperty property)
{
switch (target)
{
case SqlConstantExpression sqlConstantExpression:
return Expression.Constant(
sqlConstantExpression.Value is null
? null
: property.GetGetter().GetClrValue(sqlConstantExpression.Value),
property.ClrType.MakeNullable());
case SqlParameterExpression sqlParameterExpression
when sqlParameterExpression.Name.StartsWith(QueryCompilationContext.QueryParameterPrefix, StringComparison.Ordinal):
var lambda = Expression.Lambda(
Expression.Call(
_parameterValueExtractor.MakeGenericMethod(property.ClrType.MakeNullable()),
QueryCompilationContext.QueryContextParameter,
Expression.Constant(sqlParameterExpression.Name, typeof(string)),
Expression.Constant(property, typeof(IProperty))),
QueryCompilationContext.QueryContextParameter);
var newParameterName =
$"{RuntimeParameterPrefix}"
+ $"{sqlParameterExpression.Name.Substring(QueryCompilationContext.QueryParameterPrefix.Length)}_{property.Name}";
return _queryCompilationContext.RegisterRuntimeParameter(newParameterName, lambda);
case MemberInitExpression memberInitExpression
when memberInitExpression.Bindings.SingleOrDefault(
mb => mb.Member.Name == property.Name) is MemberAssignment memberAssignment:
return memberAssignment.Expression;
default:
return target.CreateEFPropertyExpression(property);
}
}
private static T? ParameterValueExtractor<T>(QueryContext context, string baseParameterName, IProperty property)
{
var baseParameter = context.ParameterValues[baseParameterName];
return baseParameter == null ? (T?)(object?)null : (T?)property.GetGetter().GetClrValue(baseParameter);
}
private static List<TProperty?>? ParameterListValueExtractor<TEntity, TProperty>(
QueryContext context,
string baseParameterName,
IProperty property)
{
if (!(context.ParameterValues[baseParameterName] is IEnumerable<TEntity> baseListParameter))
{
return null;
}
var getter = property.GetGetter();
return baseListParameter.Select(e => e != null ? (TProperty?)getter.GetClrValue(e) : (TProperty?)(object?)null).ToList();
}
private static bool CanEvaluate(Expression expression)
{
#pragma warning disable IDE0066 // Convert switch statement to expression
switch (expression)
#pragma warning restore IDE0066 // Convert switch statement to expression
{
case ConstantExpression constantExpression:
return true;
case NewExpression newExpression:
return newExpression.Arguments.All(e => CanEvaluate(e));
case MemberInitExpression memberInitExpression:
return CanEvaluate(memberInitExpression.NewExpression)
&& memberInitExpression.Bindings.All(
mb => mb is MemberAssignment memberAssignment && CanEvaluate(memberAssignment.Expression));
default:
return false;
}
}
private static bool IsNullSqlConstantExpression(Expression expression)
=> expression is SqlConstantExpression sqlConstant && sqlConstant.Value == null;
[DebuggerStepThrough]
private static bool TranslationFailed(Expression? original, Expression? translation, out SqlExpression? castTranslation)
{
if (original != null
&& !(translation is SqlExpression))
{
castTranslation = null;
return true;
}
castTranslation = translation as SqlExpression;
return false;
}
private sealed class EntityReferenceExpression : Expression
{
public EntityReferenceExpression(EntityShaperExpression parameter)
{
ParameterEntity = parameter;
EntityType = parameter.EntityType;
}
public EntityReferenceExpression(ShapedQueryExpression subquery)
{
SubqueryEntity = subquery;
EntityType = ((EntityShaperExpression)subquery.ShaperExpression).EntityType;
}
private EntityReferenceExpression(EntityReferenceExpression entityReferenceExpression, IEntityType entityType)
{
ParameterEntity = entityReferenceExpression.ParameterEntity;
SubqueryEntity = entityReferenceExpression.SubqueryEntity;
EntityType = entityType;
}
public EntityShaperExpression? ParameterEntity { get; }
public ShapedQueryExpression? SubqueryEntity { get; }
public IEntityType EntityType { get; }
public override Type Type
=> EntityType.ClrType;
public override ExpressionType NodeType
=> ExpressionType.Extension;
public Expression Convert(Type type)
{
if (type == typeof(object) // Ignore object conversion
|| type.IsAssignableFrom(Type)) // Ignore casting to base type/interface
{
return this;
}
var derivedEntityType = EntityType.GetDerivedTypes().FirstOrDefault(et => et.ClrType == type);
return derivedEntityType == null
? QueryCompilationContext.NotTranslatedExpression
: new EntityReferenceExpression(this, derivedEntityType);
}
}
private sealed class GroupingElementExpression : Expression
{
public GroupingElementExpression(Expression element)
{
Element = element;
}
public Expression Element { get; private set; }
public bool IsDistinct { get; private set; }
public SqlExpression? Predicate { get; private set; }
public GroupingElementExpression ApplyDistinct()
{
IsDistinct = true;
return this;
}
public GroupingElementExpression ApplySelector(Expression expression)
{
Element = expression;
return this;
}
public GroupingElementExpression ApplyPredicate(SqlExpression expression)
{
Check.NotNull(expression, nameof(expression));
if (expression is SqlConstantExpression sqlConstant
&& sqlConstant.Value is bool boolValue
&& boolValue)
{
return this;
}
Predicate = Predicate == null
? expression
: new SqlBinaryExpression(
ExpressionType.AndAlso,
Predicate,
expression,
typeof(bool),
expression.TypeMapping);
return this;
}
public override Type Type
=> typeof(IEnumerable<>).MakeGenericType(Element.Type);
public override ExpressionType NodeType
=> ExpressionType.Extension;
}
private sealed class SqlTypeMappingVerifyingExpressionVisitor : ExpressionVisitor
{
protected override Expression VisitExtension(Expression extensionExpression)
{
Check.NotNull(extensionExpression, nameof(extensionExpression));
if (extensionExpression is SqlExpression sqlExpression
&& !(extensionExpression is SqlFragmentExpression))
{
if (sqlExpression.TypeMapping == null)
{
throw new InvalidOperationException(RelationalStrings.NullTypeMappingInSqlTree(sqlExpression.Print()));
}
}
return base.VisitExtension(extensionExpression);
}
}
}
}
|
using FindSelf.Application.Configuration.Database;
using FindSelf.Application.Configuration.Queries;
using System.Data;
using System.Threading;
using System.Threading.Tasks;
using System;
namespace FindSelf.Application.Users.GetUser
{
public abstract class QueryHandlerBase<TQuery, TResponse> : IQueryHandler<TQuery, TResponse> , IDisposable
where TQuery : IQuery<TResponse>
{
protected IDbConnection connection => db.Connection;
protected readonly IDbFactory db;
public QueryHandlerBase(IDbFactory db)
{
this.db = db;
}
public abstract Task<TResponse> Handle(TQuery request, CancellationToken cancellationToken);
public void Dispose()
{
connection.Dispose();
}
}
} |
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="CruiseControlStatusViewModel.cs" company="Soloplan GmbH">
// Copyright (c) Soloplan GmbH. All rights reserved.
// Licensed under the MIT License. See License-file in the project root for license information.
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
namespace Soloplan.WhatsON.CruiseControl.GUI
{
using System;
using Soloplan.WhatsON.GUI.Common.BuildServer;
using Soloplan.WhatsON.GUI.Common.ConnectorTreeView;
using Soloplan.WhatsON.Model;
public class CruiseControlStatusViewModel : BuildStatusViewModel
{
/// <summary>
/// The backing field for <see cref="BuildTimeUnknown"/>.
/// </summary>
private bool buildTimeUnknown;
public CruiseControlStatusViewModel(ConnectorViewModel model)
: base(model)
{
}
/// <summary>
/// Gets or sets a value indicating whether estimated build time is known.
/// </summary>
public bool BuildTimeUnknown
{
get => this.buildTimeUnknown;
set
{
if (this.buildTimeUnknown != value)
{
this.buildTimeUnknown = value;
this.OnPropertyChanged();
}
}
}
public override void Update(Status newStatus)
{
base.Update(newStatus);
var ccStatus = newStatus as CruiseControlStatus;
if (ccStatus == null)
{
return;
}
if (this.State == ObservationState.Running && this.EstimatedDuration.TotalSeconds > 0)
{
var elapsedSinceStart = (DateTime.Now - ccStatus.NextBuildTime).TotalSeconds;
this.RawProgress = (int)((100 * elapsedSinceStart) / this.EstimatedDuration.TotalSeconds);
}
else
{
this.RawProgress = 0;
}
this.Culprits.Clear();
foreach (var culprit in ccStatus.Culprits)
{
var culpritModel = new UserViewModel();
culpritModel.FullName = culprit.Name;
this.Culprits.Add(culpritModel);
}
this.UpdateCalculatedFields();
if (this.State == ObservationState.Running && this.EstimatedDuration.TotalSeconds < 1)
{
this.BuildingLongerThenExpected = false;
this.BuildingNoLongerThenExpected = false;
this.BuildTimeUnknown = true;
}
else
{
this.BuildTimeUnknown = false;
}
}
}
} |
using System.Collections.Generic;
using DDDSouthWest.Domain.Features.Public.News.ListNews;
namespace DDDSouthWest.Website.Features.Public.News
{
public class NewsListViewModel
{
public IList<NewsListModel> News { get; set; }
}
} |
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MyBlog.Entities.Models
{
// Represent a Comments entity
public class Comment
{
[Key]
public int CommentId { get; set; }
[Display(Name = "Enter post id ")]
public int PostID { get; set; }
[Required]
[Display(Name = " Name ")]
public string CommentAuthorName { get; set; }
[DataType(DataType.Date, ErrorMessage = "Please enter a proper date.")]
[DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
[Required]
[Display(Name = " Date ")]
public DateTime CommentDate { get; set; }
[Required]
[Display(Name = "Text ")]
public string CommentBody { get; set; }
public ICollection<Post> Posts { get; set; }
}
} |
using LuaInterface;
using SLua;
using System;
public class Lua_UICustomScrollBar : LuaObject
{
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int constructor(IntPtr l)
{
int result;
try
{
UICustomScrollBar o = new UICustomScrollBar();
LuaObject.pushValue(l, true);
LuaObject.pushValue(l, o);
result = 2;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int get_isDragging(IntPtr l)
{
int result;
try
{
UICustomScrollBar uICustomScrollBar = (UICustomScrollBar)LuaObject.checkSelf(l);
LuaObject.pushValue(l, true);
LuaObject.pushValue(l, uICustomScrollBar.isDragging);
result = 2;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
public static void reg(IntPtr l)
{
LuaObject.getTypeTable(l, "UICustomScrollBar");
LuaObject.addMember(l, "isDragging", new LuaCSFunction(Lua_UICustomScrollBar.get_isDragging), null, true);
LuaObject.createTypeMetatable(l, new LuaCSFunction(Lua_UICustomScrollBar.constructor), typeof(UICustomScrollBar), typeof(UIScrollBar));
}
}
|
using System.Web.Routing;
namespace NuGet.Lucene.Web
{
public static class RouteNames
{
public const string PackageFeed = "OData Package Feed";
public static readonly RouteValueDictionary PackageFeedRouteValues = new RouteValueDictionary { { "serviceType", "odata" } };
public const string Home = "Home";
public const string IndexingStatus = "Status";
public const string UserApi = "UserApi";
public const string PackageApi = "PackageApi";
public const string PackageInfo = "Package Info";
public const string PackageDownload = "Download Package";
public const string PackageDownloadAnyVersion = "Package Download - Latest Version";
public const string PackageSearch = "Package Search";
public const string TabCompletionPackageIds = "Package Manager Console Tab Completion - Package IDs";
public const string TabCompletionPackageVersions = "Package Manager Console Tab Completion - Package Versions";
}
} |
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="AuditInfoFactory.cs" company="CGI">
// Copyright (c) CGI. All rights reserved.
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using CGI.Reflex.Core.Entities;
namespace CGI.Reflex.Core.Tests.Factories
{
public class AuditInfoFactory : BaseFactory<AuditInfo>
{
public AuditInfoFactory(AllFactories factories)
: base(factories)
{
}
protected override AuditInfo CreateImpl()
{
return new AuditInfo
{
EntityType = Rand.String(),
EntityId = Rand.Int(10000),
ConcurrencyVersion = Rand.Int(10),
Timestamp = Rand.DateTime(),
Action = Rand.Enum<AuditInfoAction>(),
User = Factories.User.Save()
};
}
}
}
|
using System;
namespace LuaInterface
{
public delegate int LuaCSFunction(IntPtr luaState);
}
|
using Dashboard.API.Persistence.Entities;
using System;
namespace Dashboard.API.Domain.Models
{
public class ClientServiceModel
{
public Guid Id { get; set; }
public string Name { get; set; }
public string Key { get; set; }
public string DefaultValue { get; set; }
public string Description { get; set; }
public bool Subscribed { get; set; }
public static ClientServiceModel Create(ClientService clientService)
{
return new ClientServiceModel
{
Id = clientService.Id,
Name = clientService.Name,
Description = clientService.Description,
Key = clientService.Key,
DefaultValue = clientService.DefaultValue
};
}
}
} |
using System;
using UnityEngine;
[AddComponentMenu("NGUI/UI/Stretch"), ExecuteInEditMode]
public class UIStretch : MonoBehaviour
{
public enum Style
{
None,
Horizontal,
Vertical,
Both,
BasedOnHeight,
FillKeepingRatio,
FitInternalKeepingRatio
}
public Camera uiCamera;
public GameObject container;
public UIStretch.Style style;
public bool runOnlyOnce = true;
public Vector2 relativeSize = Vector2.get_one();
public Vector2 initialSize = Vector2.get_one();
public Vector2 borderPadding = Vector2.get_zero();
[HideInInspector, SerializeField]
private UIWidget widgetContainer;
private Transform mTrans;
private UIWidget mWidget;
private UISprite mSprite;
private UIPanel mPanel;
private UIRoot mRoot;
private Animation mAnim;
private Rect mRect;
private bool mStarted;
private void Awake()
{
this.mAnim = base.GetComponent<Animation>();
this.mRect = default(Rect);
this.mTrans = base.get_transform();
this.mWidget = base.GetComponent<UIWidget>();
this.mSprite = base.GetComponent<UISprite>();
this.mPanel = base.GetComponent<UIPanel>();
UICamera.onScreenResize = (UICamera.OnScreenResize)Delegate.Combine(UICamera.onScreenResize, new UICamera.OnScreenResize(this.ScreenSizeChanged));
}
private void OnDestroy()
{
UICamera.onScreenResize = (UICamera.OnScreenResize)Delegate.Remove(UICamera.onScreenResize, new UICamera.OnScreenResize(this.ScreenSizeChanged));
}
private void ScreenSizeChanged()
{
if (this.mStarted && this.runOnlyOnce)
{
this.Update();
}
}
private void Start()
{
if (this.container == null && this.widgetContainer != null)
{
this.container = this.widgetContainer.get_gameObject();
this.widgetContainer = null;
}
if (this.uiCamera == null)
{
this.uiCamera = NGUITools.FindCameraForLayer(base.get_gameObject().get_layer());
}
this.mRoot = NGUITools.FindInParents<UIRoot>(base.get_gameObject());
this.Update();
this.mStarted = true;
}
private void Update()
{
if (this.mAnim != null && this.mAnim.get_isPlaying())
{
return;
}
if (this.style != UIStretch.Style.None)
{
UIWidget uIWidget = (!(this.container == null)) ? this.container.GetComponent<UIWidget>() : null;
UIPanel uIPanel = (!(this.container == null) || !(uIWidget == null)) ? this.container.GetComponent<UIPanel>() : null;
float num = 1f;
if (uIWidget != null)
{
Bounds bounds = uIWidget.CalculateBounds(base.get_transform().get_parent());
this.mRect.set_x(bounds.get_min().x);
this.mRect.set_y(bounds.get_min().y);
this.mRect.set_width(bounds.get_size().x);
this.mRect.set_height(bounds.get_size().y);
}
else if (uIPanel != null)
{
if (uIPanel.clipping == UIDrawCall.Clipping.None)
{
float num2 = (!(this.mRoot != null)) ? 0.5f : ((float)this.mRoot.activeHeight / (float)Screen.get_height() * 0.5f);
this.mRect.set_xMin((float)(-(float)Screen.get_width()) * num2);
this.mRect.set_yMin((float)(-(float)Screen.get_height()) * num2);
this.mRect.set_xMax(-this.mRect.get_xMin());
this.mRect.set_yMax(-this.mRect.get_yMin());
}
else
{
Vector4 finalClipRegion = uIPanel.finalClipRegion;
this.mRect.set_x(finalClipRegion.x - finalClipRegion.z * 0.5f);
this.mRect.set_y(finalClipRegion.y - finalClipRegion.w * 0.5f);
this.mRect.set_width(finalClipRegion.z);
this.mRect.set_height(finalClipRegion.w);
}
}
else if (this.container != null)
{
Transform parent = base.get_transform().get_parent();
Bounds bounds2 = (!(parent != null)) ? NGUIMath.CalculateRelativeWidgetBounds(this.container.get_transform()) : NGUIMath.CalculateRelativeWidgetBounds(parent, this.container.get_transform());
this.mRect.set_x(bounds2.get_min().x);
this.mRect.set_y(bounds2.get_min().y);
this.mRect.set_width(bounds2.get_size().x);
this.mRect.set_height(bounds2.get_size().y);
}
else
{
if (!(this.uiCamera != null))
{
return;
}
this.mRect = this.uiCamera.get_pixelRect();
if (this.mRoot != null)
{
num = this.mRoot.pixelSizeAdjustment;
}
}
float num3 = this.mRect.get_width();
float num4 = this.mRect.get_height();
if (num != 1f && num4 > 1f)
{
float num5 = (float)this.mRoot.activeHeight / num4;
num3 *= num5;
num4 *= num5;
}
Vector3 vector = (!(this.mWidget != null)) ? this.mTrans.get_localScale() : new Vector3((float)this.mWidget.width, (float)this.mWidget.height);
if (this.style == UIStretch.Style.BasedOnHeight)
{
vector.x = this.relativeSize.x * num4;
vector.y = this.relativeSize.y * num4;
}
else if (this.style == UIStretch.Style.FillKeepingRatio)
{
float num6 = num3 / num4;
float num7 = this.initialSize.x / this.initialSize.y;
if (num7 < num6)
{
float num8 = num3 / this.initialSize.x;
vector.x = num3;
vector.y = this.initialSize.y * num8;
}
else
{
float num9 = num4 / this.initialSize.y;
vector.x = this.initialSize.x * num9;
vector.y = num4;
}
}
else if (this.style == UIStretch.Style.FitInternalKeepingRatio)
{
float num10 = num3 / num4;
float num11 = this.initialSize.x / this.initialSize.y;
if (num11 > num10)
{
float num12 = num3 / this.initialSize.x;
vector.x = num3;
vector.y = this.initialSize.y * num12;
}
else
{
float num13 = num4 / this.initialSize.y;
vector.x = this.initialSize.x * num13;
vector.y = num4;
}
}
else
{
if (this.style != UIStretch.Style.Vertical)
{
vector.x = this.relativeSize.x * num3;
}
if (this.style != UIStretch.Style.Horizontal)
{
vector.y = this.relativeSize.y * num4;
}
}
if (this.mSprite != null)
{
float num14 = (!(this.mSprite.atlas != null)) ? 1f : this.mSprite.atlas.pixelSize;
vector.x -= this.borderPadding.x * num14;
vector.y -= this.borderPadding.y * num14;
if (this.style != UIStretch.Style.Vertical)
{
this.mSprite.width = Mathf.RoundToInt(vector.x);
}
if (this.style != UIStretch.Style.Horizontal)
{
this.mSprite.height = Mathf.RoundToInt(vector.y);
}
vector = Vector3.get_one();
}
else if (this.mWidget != null)
{
if (this.style != UIStretch.Style.Vertical)
{
this.mWidget.width = Mathf.RoundToInt(vector.x - this.borderPadding.x);
}
if (this.style != UIStretch.Style.Horizontal)
{
this.mWidget.height = Mathf.RoundToInt(vector.y - this.borderPadding.y);
}
vector = Vector3.get_one();
}
else if (this.mPanel != null)
{
Vector4 baseClipRegion = this.mPanel.baseClipRegion;
if (this.style != UIStretch.Style.Vertical)
{
baseClipRegion.z = vector.x - this.borderPadding.x;
}
if (this.style != UIStretch.Style.Horizontal)
{
baseClipRegion.w = vector.y - this.borderPadding.y;
}
this.mPanel.baseClipRegion = baseClipRegion;
vector = Vector3.get_one();
}
else
{
if (this.style != UIStretch.Style.Vertical)
{
vector.x -= this.borderPadding.x;
}
if (this.style != UIStretch.Style.Horizontal)
{
vector.y -= this.borderPadding.y;
}
}
if (this.mTrans.get_localScale() != vector)
{
this.mTrans.set_localScale(vector);
}
if (this.runOnlyOnce && Application.get_isPlaying())
{
base.set_enabled(false);
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Text;
using System.Xml;
namespace UpdateExecutableCommon.Utilities
{
public static class ConfigUtility
{
/// <summary>
/// Gets the connection string that matches connectionStringName from the specified web.config.
/// </summary>
/// <param name="webConfigPath">Path to the web.config</param>
/// <param name="connectionStringName">Name attribute of the connectionString in the web.config</param>
/// <returns></returns>
public static string GetConnectionStringFromWebConfig(string webConfigPath, string connectionStringName)
{
try
{
var webConfigContents = File.ReadAllText(webConfigPath);
using (XmlReader reader = XmlReader.Create(new StringReader(webConfigContents)))
{
reader.ReadToFollowing("connectionStrings");
using (XmlReader rdr = reader.ReadSubtree())
{
while (reader.Read())
{
if (reader.NodeType == XmlNodeType.Element)
{
reader.MoveToAttribute("name");
if (reader.Value.ToLower() == connectionStringName.ToLower())
{
reader.MoveToAttribute("connectionString");
return reader.Value;
}
}
}
}
}
}
catch {}
return string.Empty;
}
}
}
|
//_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/.
// VisualNovelToolkit /_/_/_/_/_/_/_/_/_/.
// Copyright ©2013 - Sol-tribe. /_/_/_/_/_/_/_/_/_/.
//_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/.
using UnityEngine;
using System.Collections;
/// <summary>
/// I Script Engine.
/// </summary>
public class IScriptEngine : ScriptEngineBehaviour {
static private IScriptEngine instance = null;
public static IScriptEngine Instance {
get { return IScriptEngine.instance; }
}
/// <summary>
/// Create a script bind Object.
/// </summary>
/// <returns>
/// The script bind.
/// </returns>
/// <param name='scriptBindObj'>
/// Script bind object.
/// </param>
virtual public IScriptBinder CreateScriptBind( GameObject scriptBindObj ) {
return null;
}
static public void NextMessage(){
if( ! m_LockNextMessage ){
VM vm = VM.Instance;
if( vm != null ){
vm.TextProgress();
}
}
}
void Awake( ){
if( instance == null){
instance = this;
Init ();
ViNoDebugger.m_LogEnabled = true;
// Create Default VM with Default Settings.
VM vm = CreateVM();
GameObject scriptBindObj = new GameObject( "_ScriptBinder" );
scriptBindObj.transform.parent = transform;
scriptBindObj.hideFlags = HideFlags.HideInHierarchy;
// Create a ScriptBinder.
m_ScriptBinder = CreateScriptBind( scriptBindObj );
// Attach Script Binder To VM.
vm.scriptBinder = m_ScriptBinder;
}
else{
Destroy( this.gameObject );
}
}
// Protected Functions.
protected VM CreateVM(){
Transform thisTra = transform;
GameObject msgHandObj = new GameObject( "_MessagingHandler" );
MessagingHandler msgHnd = msgHandObj.AddComponent<MessagingHandler>();
msgHandObj.transform.parent = thisTra;
GameObject vmObj = new GameObject( "_VM" );
vmObj.transform.parent = thisTra;
VM vm = vmObj.AddComponent<VM>();
vm.m_MessagingHandler = msgHnd;
vm.scriptEngineBehaviour = this;
// Dont Show in Hierarchy these objects.
msgHandObj.hideFlags = HideFlags.HideInHierarchy;
vmObj.hideFlags = HideFlags.HideInHierarchy;
return vm;
}
void OnLevelWasLoaded( int index ){
if( loadLevelAndClearBackLog ){
ViNoBackLog.Clear();
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class NPCTextTrigger : MonoBehaviour
{
private SpriteRenderer SR;
// Start is called before the first frame update
void Start()
{
SR = GetComponent<SpriteRenderer>();
SR.sortingLayerName = "Default";
}
// Update is called once per frame
void Update()
{
}
void OnTriggerEnter2D(Collider2D other)
{
if (other.gameObject.CompareTag("Player"))
{
SR.sortingLayerName = "foreground";
}
}
void OnTriggerExit2D(Collider2D other)
{
if (other.gameObject.CompareTag("Player"))
{
SR.sortingLayerName = "Default";
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using rclcs;
using rosgraph_msgs.msg;
public class ClockPublisher : MonoBehaviourRosNode
{
private string currentNodeName = "unityTimer";
private string clockTopic = "clock";
// private Publisher<builtin_interfaces.msg.Time> timePublisher;
// private builtin_interfaces.msg.Time timeMessage;
private Publisher<rosgraph_msgs.msg.Clock> timePublisher;
private rosgraph_msgs.msg.Clock timeMessage;
protected override string nodeName{
get{
return currentNodeName;
}
}
protected override void StartRos(){
// timePublisher = node.CreatePublisher<builtin_interfaces.msg.Time>(clockTopic);
// timeMessage = new builtin_interfaces.msg.Time();
timePublisher = node.CreatePublisher<rosgraph_msgs.msg.Clock>(clockTopic);
timeMessage = new rosgraph_msgs.msg.Clock();
}
private void FixedUpdate(){
float time = Time.realtimeSinceStartup;
// timeMessage.Sec = (int)time;
// timeMessage.Nanosec = (uint)(1e9 * (time - timeMessage.Sec));
timeMessage.Clock_.Sec = (int)time;
timeMessage.Clock_.Nanosec = (uint)(1e9 * (time - timeMessage.Clock_.Sec));
timePublisher.Publish(timeMessage);
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CursorArrowLinks : MonoBehaviour {
public int ClickLeft;
public int CharacterArrowClickLeft;
public AudioSource click;
void OnSelect()
{
click.Play();
//Debug.Log("Arrow Links Clicked");
var menuController = GameObject.Find("MenuController").GetComponent<MenuController>();
menuController.Left = true;
menuController.right = false;
if (menuController.ObjectCounter >= 1)
{
ClickLeft++;
menuController.ObjectCounter = menuController.ObjectCounter - 3;
}
if (menuController.CharacterObjectCounter >= 1)
{
CharacterArrowClickLeft++;
menuController.CharacterObjectCounter = menuController.CharacterObjectCounter - 3;
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.