text stringlengths 13 6.01M |
|---|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading.Tasks;
namespace St.Eg.M1.Ex1.OOP.Model8
{
public interface IRepository
{
T Retrieve<T>(string id) where T : EntityBase;
void Save<T>(T theItem) where T : EntityBase;
IEnumerable<Order> GetOrdersForCustomer(string customerID);
}
}
|
using System.Linq;
using System.Collections.Generic;
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using StringReplicator.Core.Helpers;
using StringReplicator.Core.Operations.History;
using Voodoo.Messages;
namespace StringReplicator.Tests.Operations.History
{
[TestClass()]
public class FormatRequestQueryTests
{
private TestContext testContextInstance;
public TestContext TestContext
{
get
{
return testContextInstance;
}
set
{
testContextInstance = value;
}
}
public FormatRequestQueryTests()
{
var config = new TestConfig(TestContext);
Config.RegisterConfig(config);
}
[TestMethod()]
public void FormatRequestQueryTest()
{
var response = new LastFormatRequestQuery(new EmptyRequest()).Execute();
Assert.AreEqual(null, response.Message);
Assert.AreEqual(true, response.IsOk);
Assert.AreNotEqual(null, response.Data.DataString);
Assert.AreNotEqual(null, response.Data.DataString);
}
}
}
|
using System;
using System.Collections.Generic;
using ContentPatcher.Framework.Conditions;
using ContentPatcher.Framework.Constants;
using Pathoschild.Stardew.Common.Utilities;
using StardewValley;
namespace ContentPatcher.Framework.Tokens.ValueProviders
{
/// <summary>A value provider for the player's professions.</summary>
internal class HasProfessionValueProvider : BaseValueProvider
{
/*********
** Fields
*********/
/// <summary>Get whether the player data is available in the current context.</summary>
private readonly Func<bool> IsPlayerDataAvailable;
/// <summary>The player's current professions.</summary>
private readonly HashSet<Profession> Professions = new HashSet<Profession>();
/*********
** Public methods
*********/
/// <summary>Construct an instance.</summary>
/// <param name="isPlayerDataAvailable">Get whether the player data is available in the current context.</param>
public HasProfessionValueProvider(Func<bool> isPlayerDataAvailable)
: base(ConditionType.HasProfession, canHaveMultipleValuesForRoot: true)
{
this.IsPlayerDataAvailable = isPlayerDataAvailable;
this.EnableInputArguments(required: false, canHaveMultipleValues: false);
}
/// <summary>Update the instance when the context changes.</summary>
/// <param name="context">Provides access to contextual tokens.</param>
/// <returns>Returns whether the instance changed.</returns>
public override bool UpdateContext(IContext context)
{
return this.IsChanged(this.Professions, () =>
{
this.Professions.Clear();
this.IsReady = this.IsPlayerDataAvailable();
if (this.IsReady)
{
foreach (int professionID in Game1.player.professions)
this.Professions.Add((Profession)professionID);
}
});
}
/// <summary>Get the allowed values for a token name (or <c>null</c> if any value is allowed).</summary>
/// <param name="input">The input argument, if applicable.</param>
/// <exception cref="InvalidOperationException">The input argument doesn't match this token, or does not respect <see cref="IValueProvider.AllowsInput"/> or <see cref="IValueProvider.RequiresInput"/>.</exception>
public override InvariantHashSet GetAllowedValues(string input)
{
return input != null
? InvariantHashSet.Boolean()
: null;
}
/// <summary>Get the current values.</summary>
/// <param name="input">The input argument, if applicable.</param>
/// <exception cref="InvalidOperationException">The input argument doesn't match this token, or does not respect <see cref="IValueProvider.AllowsInput"/> or <see cref="IValueProvider.RequiresInput"/>.</exception>
public override IEnumerable<string> GetValues(string input)
{
this.AssertInputArgument(input);
if (input != null)
{
bool hasProfession = this.TryParseEnum(input, out Profession profession, mustBeNamed: false) && this.Professions.Contains(profession);
yield return hasProfession.ToString();
}
else
{
foreach (Profession profession in this.Professions)
yield return profession.ToString();
}
}
/// <summary>Validate that the provided value is valid for an input argument (regardless of whether they match).</summary>
/// <param name="input">The input argument, if applicable.</param>
/// <param name="value">The value to validate.</param>
/// <param name="error">The validation error, if any.</param>
/// <returns>Returns whether validation succeeded.</returns>
protected override bool TryValidate(string input, string value, out string error)
{
if (!base.TryValidate(input, value, out error))
return false;
// validate profession IDs
string profession = input ?? value;
if (!this.TryParseEnum(profession, out Profession _, mustBeNamed: false))
{
error = $"can't parse '{profession}' as a profession ID; must be one of [{string.Join(", ", Enum.GetNames(typeof(Profession)).OrderByIgnoreCase(p => p))}] or an integer ID.";
return false;
}
error = null;
return true;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Android.App;
using Android.Content;
using Android.Graphics;
using Android.Graphics.Drawables;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Cashflow9000.Adapters;
using Cashflow9000.Fragments;
using Cashflow9000.Models;
using ListFragment = Cashflow9000.Fragments.ListFragment;
namespace Cashflow9000
{
[Activity(Label = "MilestoneListFragmentActivity")]
public class MilestoneListFragmentActivity : ListFragmentActivity<MilestoneActivity, Milestone>
{
protected override int GetTitleId()
{
return Resource.String.milestone;
}
protected override IListAdapter GetListAdapter()
{
return new MilestoneAdapter(this, false);
}
protected override Fragment GetItemFragment(int id = -1)
{
return new MilestoneFragment(id);
}
protected override string GetExtraId()
{
return MilestoneActivity.ExtraMilestoneId;
}
}
} |
namespace Igorious.StardewValley.DynamicApi2.Constants
{
public enum ToolID
{
ReturnScepter = 2,
MilkPail = 6,
Shears = 7,
Pan = 12,
WateringCan = 296,
}
} |
using IPA.Utilities;
using MultiplayerExtensions.Environments;
using MultiplayerExtensions.OverrideClasses;
using MultiplayerExtensions.UI;
using UnityEngine;
using Zenject;
namespace MultiplayerExtensions.Installers
{
class MPMenuInstaller : MonoInstaller
{
public override void InstallBindings()
{
Container.BindInterfacesAndSelfTo<LobbyPlaceManager>().AsSingle();
Container.BindInterfacesAndSelfTo<LobbyEnvironmentManager>().AsSingle();
}
public override void Start()
{
Plugin.Log?.Info("Installing Interface");
HostLobbySetupViewController hostViewController = Container.Resolve<HostLobbySetupViewController>();
HostLobbySetupPanel hostSetupPanel = hostViewController.gameObject.AddComponent<HostLobbySetupPanel>();
Container.Inject(hostSetupPanel);
ClientLobbySetupViewController clientViewController = Container.Resolve<ClientLobbySetupViewController>();
ClientLobbySetupPanel clientSetupPanel = clientViewController.gameObject.AddComponent<ClientLobbySetupPanel>();
Container.Inject(clientSetupPanel);
CenterStageScreenController centerScreenController = Container.Resolve<CenterStageScreenController>();
CenterScreenLoadingPanel loadingPanel = centerScreenController.gameObject.AddComponent<CenterScreenLoadingPanel>();
Container.Inject(loadingPanel);
ServerPlayerListController playerListController = Container.Resolve<ServerPlayerListController>();
GameServerPlayersTableView playersTableView = playerListController.GetField<GameServerPlayersTableView, ServerPlayerListController>("_gameServerPlayersTableView");
GameServerPlayerTableCell playerTableCell = playersTableView.GetField<GameServerPlayerTableCell, GameServerPlayersTableView>("_gameServerPlayerCellPrefab");
GameServerPlayerTableCell newPlayerTableCell = GameObject.Instantiate(playerTableCell);
newPlayerTableCell.gameObject.SetActive(false);
PlayerTableCellStub playerTableCellStub = newPlayerTableCell.gameObject.AddComponent<PlayerTableCellStub>();
playerTableCellStub.Construct(newPlayerTableCell);
Destroy(newPlayerTableCell.GetComponent<GameServerPlayerTableCell>());
playersTableView.SetField<GameServerPlayersTableView, GameServerPlayerTableCell>("_gameServerPlayerCellPrefab", playerTableCellStub);
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.SceneManagement;
public class Experiment_Ctrl : MonoBehaviour
{
public GameObject SMI_Prefab;
float stimulus_eye_dist = 57.2285103656461f;
public float sample_rate;
public float stimulus_interval;
public string user_name = "";
public bool show_gaze_cursor;
public GameObject cam;
public GameObject UI_Cam;
GameObject stimulus_prefab;
GameObject stimulus;
GameObject eyeball_prefab;
GameObject leftEye, rightEye;
public float stimulus_cur_rot;
float[] stimulus_rotation_input = new float[] { -40, -30, -20, -10, 10, 20, 30, 40 };
int[] stimulus_rotation_weights = new int[] { 12, 12, 12, 12, 12, 12, 12, 12 };
public float[] stimulus_rotations_arr;
public Vector3 gaze_l;
public Vector3 gaze_r;
public ulong SMI_timestamp;
public int session_num = 0;
public int customTagSize;
public InputStringPair[] usrTags;
public bool[] usrTagBools;
DataLogger logger;
GameObject gaze_cursor;
Ctrl_STATUS ctrl_status;
void Start()
{
Start_Configuration();
}
void Start_Configuration()
{
ctrl_status = Ctrl_STATUS.CONFIG;
UI_Cam = new GameObject("UI_Camera");
UI_Cam.AddComponent<Camera>();
UI_Cam.GetComponent<Camera>().backgroundColor = Color.black;
GameObject.Find("Experiment_UI").GetComponent<Canvas>().worldCamera = UI_Cam.GetComponent<Camera>();
GameObject.Find("Menu").GetComponent<Canvas>().worldCamera = UI_Cam.GetComponent<Camera>();
}
public void Finish_Configuration()
{
cam = GetComponent<Experiment_Config>().Instantiate_SMI();
GameObject.Find("Menu").SetActive(false);
GameObject.Destroy(UI_Cam);
Start_Experiment();
ctrl_status = Ctrl_STATUS.WAITING;
}
void Start_Experiment()
{
load_stimulus_prefab();
load_eyeball_prefab();
Init_Stimulus();
Init_Gaze_Cursor();
usrTagBools = new bool[usrTags.Length];
logger = new DataLogger(this);
logger.usrTags = usrTags;
logger.usr_name = user_name;
logger.init_writing();
Init_Trial();
InvokeRepeating("Update_Data", 0, 1 / sample_rate);
}
void Update()
{
Process_Input();
Update_Cursor_Position();
}
void Process_Input()
{
if (Input.GetKeyDown(KeyCode.S) && ctrl_status == Ctrl_STATUS.WAITING)
{
Start_Trial();
ctrl_status = Ctrl_STATUS.RUNNING;
InvokeRepeating("Write_Data", 0, 1 / sample_rate);
}
if (Input.GetKeyDown(KeyCode.Escape))
{
Application.Quit();
}
if (Input.GetKeyDown(KeyCode.I))
{
show_gaze_cursor = !show_gaze_cursor;
gaze_cursor.GetComponent<Camera_Facing_Sprite>().amActive = show_gaze_cursor;
}
for (int i = 0; i < usrTags.Length; i++)
{
if (Input.GetKey(usrTags[i].input))
{
usrTagBools[i] = true;
}
else
{
usrTagBools[i] = false;
}
}
}
void Init_Gaze_Cursor()
{
gaze_cursor = GameObject.Instantiate(Resources.Load<GameObject>("Prefabs/SMI_Gaze_Sprite_Prefab"));
gaze_cursor.name = "SMI_Gaze_Sprite_Prefab";
gaze_cursor.GetComponent<Camera_Facing_Sprite>().amActive = show_gaze_cursor;
}
void Update_Cursor_Position()
{
if (gaze_cursor != null)
{
gaze_cursor.transform.position = cam.transform.position + cam.transform.rotation * (gaze_l + gaze_r) / 2 * 20;
}
}
void Start_Trial()
{
//display play button
Toggle_PlayButton();
//play audio
AudioSource audio = GetComponent<AudioSource>();
audio.Play();
InvokeRepeating("Next_Stimulus", 2, stimulus_interval);
}
void Toggle_PlayButton()
{
try
{
GameObject.Find("Experiment_UI").GetComponent<Canvas>().worldCamera = cam.GetComponent<Camera>();
Image playButton = GameObject.Find("PlayButton").GetComponent<Image>();
playButton.enabled = true;
Invoke("Disable_PlayButton", 1);
}
catch (System.Exception e)
{
Debug.LogWarning("No playbutton found, will only play sound, " + e.Message);
}
}
void Disable_PlayButton()
{
Image playButton = GameObject.Find("PlayButton").GetComponent<Image>();
if (playButton != null)
{
playButton.enabled = false;
}
}
/// <summary>
/// Update SMI data and call logger to writer data to files
/// </summary>
void Update_Data()
{
Update_SMI_Data();
}
void Write_Data()
{
logger.writeData();
}
/// <summary>
/// load stimulus prefab from resources file
/// </summary>
void load_stimulus_prefab()
{
//Load stimulus prefab
stimulus_prefab = (GameObject)Resources.Load("Prefabs/Stimulus");
if (stimulus_prefab == null)
{
Debug.LogError("No stimulus prefab found, check Assets/Resources/Prefabs/Stimulus.prefab");
Application.Quit();
}
}
/// <summary>
/// load eyeball prefab from resources file
/// </summary>
void load_eyeball_prefab()
{
eyeball_prefab = Resources.Load("Prefabs/eyeball") as GameObject;
if (eyeball_prefab == null)
{
Debug.LogError(
"No eyeball prefabs found, check Asset/Resources/Prefabs/eyeball.prefab"
);
Application.Quit();
}
leftEye = GameObject.Instantiate(eyeball_prefab, cam.transform);
leftEye.name = "leftEye";
rightEye = GameObject.Instantiate(eyeball_prefab, cam.transform);
rightEye.name = "rightEye";
}
/// <summary>
/// update all data from SMI instance
/// </summary>
void Update_SMI_Data()
{
var leftEyePos = SMI.SMIEyeTrackingUnity.Instance.smi_GetLeftGazeBase();
var rightEyePos = SMI.SMIEyeTrackingUnity.Instance.smi_GetRightGazeBase();
if (SMI.SMIEyeTrackingUnity.smi_IsValid(leftEyePos))
{
leftEye.transform.localPosition = leftEyePos + cam.transform.position;
}
if (SMI.SMIEyeTrackingUnity.smi_IsValid(rightEyePos))
{
rightEye.transform.localPosition = rightEyePos + cam.transform.position;
}
var SMI_leftEyeGaze = SMI.SMIEyeTrackingUnity.Instance.smi_GetLeftGazeDirection();
var SMI_rightEyeGaze = SMI.SMIEyeTrackingUnity.Instance.smi_GetRightGazeDirection();
if (SMI.SMIEyeTrackingUnity.smi_IsValid(SMI_leftEyeGaze))
{
gaze_l = SMI_leftEyeGaze;
}
else
{
gaze_l.Set(-1, -1, -1);
}
if (SMI.SMIEyeTrackingUnity.smi_IsValid(SMI_rightEyeGaze))
{
gaze_r = SMI_rightEyeGaze;
}
else
{
gaze_r.Set(-1, -1, -1);
}
SMI_timestamp = SMI.SMIEyeTrackingUnity.Instance.smi_GetTimeStamp();
}
/// <summary>
/// Instantiate stimulus at 0 degree
/// </summary>
void Init_Stimulus()
{
Transform camTrans = cam.transform;
Vector3 targetPos = camTrans.position + camTrans.forward * stimulus_eye_dist;
stimulus = GameObject.Instantiate(stimulus_prefab, camTrans);
stimulus.transform.position = targetPos;
}
/// <summary>
/// Generate random trial
/// </summary>
void Init_Trial()
{
stimulus_rotations_arr = Random_Trial_Generator.generate(stimulus_rotation_input, stimulus_rotation_weights, -30, 30);
string s = "";
foreach (float x in stimulus_rotations_arr)
{
s += x + ",";
}
Debug.Log(s);
}
/// <summary>
/// Proceed to next stimulus in trial
/// </summary>
void Next_Stimulus()
{
if (session_num < stimulus_rotations_arr.Length)
{
Set_Stimulus_Rotation_In_Head(stimulus_cur_rot + stimulus_rotations_arr[session_num]);
stimulus_cur_rot += stimulus_rotations_arr[session_num];
session_num++;
}
else
{
CancelInvoke("Next_Stimulus");
}
}
/// <summary>
/// Change stimulus location in degree relative to head
/// </summary>
/// <param name="degree"></param>
void Set_Stimulus_Rotation_In_Head(float degree)
{
stimulus.transform.localRotation = Quaternion.identity;
Transform camTrans = cam.transform;
Vector3 eyeball_Center = (leftEye.transform.position + rightEye.transform.position) / 2;
Vector3 targetPos = eyeball_Center + camTrans.forward * stimulus_eye_dist;
stimulus.transform.position = targetPos;
stimulus.transform.RotateAround(eyeball_Center, camTrans.up, degree);
}
/// <summary>
/// Debug: draw gaze ray for debug
/// </summary>
private void OnApplicationQuit()
{
logger.closeLogger();
}
}
enum Ctrl_STATUS
{
CONFIG, WAITING, RUNNING
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayAnimation : MonoBehaviour
{
// This script file uses for single object with single animation.
// The name of the animation should be the same as the object name.
private Animator anim;
private string animName;
// Start is called before the first frame update
void Start()
{
anim = GetComponent<Animator>();
animName = gameObject.name;
Debug.Log(anim);
Debug.Log(animName);
}
// Update is called once per frame
void Update()
{
}
public void PlayInteraction()
{
anim.Play(animName);
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Dapper.DBContext;
using System.Security.Cryptography;
using EBS.Infrastructure.Extension;
using EBS.Domain.Entity;
using EBS.Infrastructure.Caching;
namespace EBS.Domain.Service
{
public class AccessTokenService
{
IDBContext _db;
ICacheManager _cacheManager;
public AccessTokenService(IDBContext dbcontext, ICacheManager cacheManager)
{
this._db = dbcontext;
_cacheManager = cacheManager;
}
public void ValidateCDkey(int storeId, int posId, string cdkey)
{
string cacheKey = "EBS.AccessToken.All";
var accessTokens = _cacheManager.Get<IEnumerable<AccessToken>>(cacheKey, () =>
{
return _db.Table.FindAll<AccessToken>();
});
MD5 md5Prider = MD5.Create();
string clientCDKEY = string.Format("{0}{1}{2}", storeId, posId, cdkey);
//加密
string clientCDKeyMd5 = md5Prider.GetMd5Hash(clientCDKEY);
// var entity= _db.Table.Find<AccessToken>(n=>n.CDKey==clientCDKeyMd5);
var entity = accessTokens.FirstOrDefault(n => n.CDKey == clientCDKeyMd5);
if (entity == null)
{
throw new Exception("cdkey 不存在");
}
if (entity.StoreId == storeId && entity.PosId == posId)
{
//匹配成功,不处理
}
else
{
throw new Exception("cdkey 错误");
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Text;
using System.Linq;
namespace EntityLayer
{
public class DebitCardValidator
{
[CreditCard]
public string DebitCardNumber { get; set; }
/// <summary>
/// This class uses Luhr's algorithm to test generated debit card numbers, whether they are valid or not.
/// </summary>
/// <param name="Generators"></param>
/// <returns></returns>
public static bool ValidateDebitCard(string Generators)
{
if( Generators == null)
{
throw new ArgumentNullException();
}
if(Generators.Length != 16)
{
throw new ArgumentException();
}
var splittedValues = Generators.ToCharArray().ToList().Skip(1).Take(1).ToList();
int summation = default;
for (int index = 0; index < splittedValues.Count; index ++)
{
var currentValue = splittedValues[index] * 2;
if (currentValue > 9)
{
currentValue = currentValue - 9;
}
summation += currentValue;
}
var splittedValue2 = Generators.ToCharArray();
int summation2 = default;
for (int i = 0; i < splittedValue2.Length; i+=2)
{
var currentValue2 = splittedValue2[i];
summation2 += currentValue2;
}
var aggregate = (summation + summation2) % 10 == 0;
return aggregate;
}
public string CardGenerator(CardType cardType)
{
string card = default;
switch (cardType)
{
case CardType.VISA:
card =CardEngine("4");
break;
case CardType.MASTERCARD:
card = CardEngine("5");
break;
default:
break;
}
return card;
}
/// <summary>
/// This class validates the numbers generated and confirms whether it is a valid debit card. The loop continues to run until a valid number is generated.
/// </summary>
/// <param name="card"></param>
/// <returns></returns>
private static string CardEngine(string card)
{
var returnCard = Randomizer(card);
var isValid = ValidateDebitCard(returnCard);
while (!isValid)
{
returnCard = Randomizer(card);
isValid = ValidateDebitCard(returnCard);
}
return returnCard;
}
/// <summary>
/// The purpose of this class is to generate random strings that contains numbers that are upto 16 character long.
/// </summary>
/// <param name="card"></param>
/// <returns></returns>
private static string Randomizer(string card)
{
var randomNumbers = new Random();
var randomNumbers2 = new Random();
string cardNumber = $"{card}{randomNumbers.Next(1000000, 9999999)}{randomNumbers2.Next(10000000, 99999999)}";
return cardNumber;
}
}
public enum CardType
{
VISA,
MASTERCARD
}
}
|
using System;
using System.Collections.Generic;
using System.Drawing;
using Painter.WinForms.Tools.DrawingTools;
using Rectangle = Painter.WinForms.Tools.DrawingTools.Rectangle;
namespace Painter.WinForms
{
/// <summary>
/// Represent application settings
/// </summary>
public class StartupParams
{
#region Singleton
private static readonly Lazy<StartupParams> _instance = new Lazy<StartupParams>(() => new StartupParams());
public static StartupParams Instance() => _instance.Value;
#endregion
/// <summary>
/// Border figure color
/// </summary>
public Color CurrentBorderColor { get; set; } = Color.Black;
/// <summary>
/// Back figure color
/// </summary>
public Color CurrentBackgroundColor { get; set; } = Color.AliceBlue;
/// <summary>
/// Selected drawing tool
/// </summary>
public ToolsBase CurrentTool { get; set; }
/// <summary>
/// All <see cref="ToolsBase"/> tools
/// </summary>
public IEnumerable<ToolsBase> Tools { get; } = new List<ToolsBase> { new Pencil(), new Line(), new Rectangle(), new Circle() };
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
/* Displays the name of the chracter
/* References the players neck for display location */
public class NameLabel : MonoBehaviour {
public GameObject playerRef;
public float distanceAboveHead; // 0.33 is good
public float movementSpeed = 50;
private Text statusText;
private bool statusInitialized = false;
// Use this for initialization
void Start () {
statusText = GetComponentInChildren<Text>();
}
// Update is called once per frame
void Update () {
if (GameManager.Instance.isGameRunning)
{
Vector3 location = new Vector3(playerRef.transform.position.x,
playerRef.transform.position.y + distanceAboveHead, playerRef.transform.position.z);
transform.position = Vector3.MoveTowards(transform.position,
Camera.main.WorldToScreenPoint(location), movementSpeed * Time.deltaTime);
}
if (GameManager.Instance.isGameRunning && !statusInitialized)
{
statusInitialized = true;
statusText.text = "Type: !task to start working";
}
}
}
|
using Def;
using NStandard.Flows;
using System;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using Xunit;
namespace NStandard.Test
{
public class StringExtensionsTests
{
[Fact]
public void CommonTest()
{
var ds = "123";
Assert.Equal("123123123", ds.Repeat(3));
Assert.Equal("12", ds.Slice(0, -1));
Assert.Equal("1", ds.Slice(0, 1));
Assert.Equal("23", ds.Substring(1));
Assert.Equal("23", ds.Slice(-2));
Assert.Throws<ArgumentOutOfRangeException>(() => ds.Slice(3, 2));
Assert.Equal('1', ds.CharAt(0));
Assert.Equal('3', ds.CharAt(-1));
Assert.Equal("zmjack", "zmjack".Center(5));
Assert.Equal("zmjack", "zmjack".Center(6));
Assert.Equal(" zmjack", "zmjack".Center(7));
Assert.Equal(" zmjack ", "zmjack".Center(8));
}
[Fact]
public void GetBytesTest1()
{
var str = "你好";
Assert.Equal(Encoding.UTF8.GetBytes(str), str.Bytes(Encoding.UTF8));
Assert.Equal(Encoding.UTF8.GetBytes(str), str.Bytes("utf-8"));
Assert.NotEqual(Encoding.ASCII.GetBytes(str), str.Bytes(Encoding.UTF8));
Assert.NotEqual(Encoding.ASCII.GetBytes(str), str.Bytes("utf-8"));
}
[Fact]
public void GetBytesTest2()
{
var hexString = "0c66182ec710840065ebaa47c5e6ce90";
var hexString_Base64 = "MGM2NjE4MmVjNzEwODQwMDY1ZWJhYTQ3YzVlNmNlOTA=";
var hexString_Bytes = new byte[]
{
0x0C, 0x66, 0x18, 0x2E, 0xC7, 0x10, 0x84, 0x00, 0x65, 0xEB, 0xAA, 0x47, 0xC5, 0xE6, 0xCE, 0x90
};
Assert.Equal(hexString_Bytes, hexString.Pipe(StringFlow.BytesFromHexString));
Assert.Equal(hexString, hexString_Bytes.Pipe(BytesFlow.HexString));
Assert.Equal(hexString, hexString_Base64.Pipe(StringFlow.BytesFromBase64).String(Encoding.Default));
}
[Fact]
public void NormalizeNewLineTest()
{
Assert.Equal($"123{Environment.NewLine}456", "123\r456".NormalizeNewLine());
Assert.Equal($"123{Environment.NewLine}456", "123\n456".NormalizeNewLine());
Assert.Equal($"123{Environment.NewLine}456", "123\r\n456".NormalizeNewLine());
Assert.Equal($"123{Environment.NewLine}{Environment.NewLine}456", "123\n\r456".NormalizeNewLine());
Assert.Equal($"123{Environment.NewLine}{Environment.NewLine}456", "123\n\r\n456".NormalizeNewLine());
Assert.Equal($"123{Environment.NewLine}{Environment.NewLine}456", "123\r\r\n456".NormalizeNewLine());
Assert.Equal($"123{Environment.NewLine}{Environment.NewLine}456", "123\r\n\r456".NormalizeNewLine());
Assert.Equal($"123{Environment.NewLine}{Environment.NewLine}456", "123\r\n\n456".NormalizeNewLine());
}
[Fact]
public void GetLinesTest()
{
string nullString = null;
Assert.Equal(Array.Empty<string>(), nullString.GetLines());
Assert.Equal(new[] { "1", "2" }, $"1{Environment.NewLine}2".GetLines());
Assert.Equal(new[] { "1", "2" }, $"1{Environment.NewLine}2{Environment.NewLine}".GetLines());
Assert.Equal(new[] { "1", " " }, $"1{Environment.NewLine} ".GetLines());
Assert.Equal(new[] { "", "1", " " }, $"{Environment.NewLine}1{Environment.NewLine} ".GetLines());
Assert.Equal(Array.Empty<string>(), nullString.GetLines());
Assert.Equal(new[] { "1", "2" }, $"1{ControlChars.Lf}2".GetLines(true));
Assert.Equal(new[] { "1", "2" }, $"1{ControlChars.CrLf}2".GetLines(true));
}
[Fact]
public void GetPureLinesTest()
{
string nullString = null;
Assert.Equal(Array.Empty<string>(), nullString.GetPureLines());
Assert.Equal(new[] { "1", "2" }, $"1{Environment.NewLine}2".GetPureLines());
Assert.Equal(new[] { "1", "2" }, $"1{Environment.NewLine}2{Environment.NewLine}".GetPureLines());
Assert.Equal(new[] { "1" }, $"1{Environment.NewLine} ".GetPureLines());
Assert.Equal(new[] { "1" }, $"{Environment.NewLine}1{Environment.NewLine} ".GetPureLines());
}
[Fact]
public void UniqueTest()
{
Assert.Null(((string)null).Unique());
Assert.Equal("123 456 7890", " 123 456 7890 ".Unique());
Assert.Equal("123 456 7890", " 123 456 7890".Unique());
Assert.Equal("123 456 7890", " 123\r\n456 7890".Unique());
Assert.Equal("123 456 7890", " 123\r\n 456 7890".Unique());
}
[Fact]
public void ExtractTest()
{
var regex = new Regex(@"^(.+?)\s*(?:\(\d+\))?$");
Assert.Equal("zmjack", "zmjack".Extract(regex).First());
Assert.Equal("zmjack", "zmjack(1)".Extract(regex).First());
Assert.Equal("zmjack", "zmjack (1)".Extract(regex).First());
Assert.Equal("ja", "zmjack".Extract(new Regex(@"(ja)"), "$1").First());
Assert.Equal("zmjack", "zmjack".ExtractFirst(regex));
Assert.Equal("zmjack", "zmjack(1)".ExtractFirst(regex));
Assert.Equal("zmjack", "zmjack (1)".ExtractFirst(regex));
Assert.Equal("ja", "zmjack".ExtractFirst(new Regex(@"(ja)"), "$1"));
}
[Fact]
public void ProjectToArrayTest1()
{
Assert.Throws<ArgumentNullException>(() => "ABC".Resolve(new Regex(@"^$")));
}
[Fact]
public void ProjectToArrayTest2()
{
var result = "A|1|11|B|2|22".Resolve(new Regex(@"(?:(?:^|\|)(.+?\|.+?\|.+?)(?=\||$))*"));
Assert.Equal(new string[][]
{
new [] { "A|1|11|B|2|22" },
new [] { "A|1|11", "B|2|22" },
}, result);
}
[Fact]
public void ProjectToArrayTest3()
{
var declRegex = new Regex(@"(.+)? (.+?)\((?:(?:\[In\] )?(.+?) (.+?)(?:, |(?=\))))*\);");
{
var result = "void F(short a, [In] int b);".Resolve(declRegex);
Assert.Equal(new string[][]
{
new[] { "void F(short a, [In] int b);" },
new[] { "void" },
new[] { "F" },
new[] { "short", "int" },
new[] { "a", "b" },
}, result);
}
{
var result = "void F();".Resolve(declRegex);
Assert.Equal(new string[][]
{
new[] { "void F();" },
new[] { "void" },
new[] { "F" },
Array.Empty<string>(),
Array.Empty<string>(),
}, result);
}
}
[Fact]
public void Insert()
{
Assert.Equal("", "".UnitInsert(4, " "));
Assert.Equal("", "".UnitInsert(4, " ", true));
Assert.Equal("1 2345", "12345".UnitInsert(4, " "));
Assert.Equal("1234 5", "12345".UnitInsert(4, " ", true));
Assert.Equal("1234 5678", "12345678".UnitInsert(4, " "));
Assert.Equal("1234 5678", "12345678".UnitInsert(4, " ", true));
Assert.Equal("1 2345 6789", "123456789".UnitInsert(4, " "));
Assert.Equal("1234 5678 9", "123456789".UnitInsert(4, " ", true));
}
[Fact]
public void CapitalizeFirst()
{
Assert.Equal("zmjack", "Zmjack".CapitalizeFirst(false));
Assert.Equal("Zmjack", "zmjack".CapitalizeFirst());
}
[Fact]
public void ConsoleWidth()
{
Assert.Equal(7, "English".GetLengthA());
Assert.Equal(4, "中文".GetLengthA());
}
[Fact]
public void PadLeftUTest()
{
Assert.Equal("English", "English".PadLeftA(1));
Assert.Equal(" English", "English".PadLeftA(8));
Assert.Equal("中文", "中文".PadLeftA(1));
Assert.Equal(" 中文", "中文".PadLeftA(5));
Assert.Equal(" 中文", "中文".PadLeftA(5, '嗯'));
Assert.Equal("嗯中文", "中文".PadLeftA(6, '嗯'));
Assert.Equal(".中文", "中文".PadLeftA(5, '.'));
Assert.Equal("..中文", "中文".PadLeftA(6, '.'));
}
[Fact]
public void PadRightUTest()
{
Assert.Equal("English", "English".PadRightA(1));
Assert.Equal("English ", "English".PadRightA(8));
Assert.Equal("中文", "中文".PadRightA(1));
Assert.Equal("中文 ", "中文".PadRightA(5));
Assert.Equal("中文 ", "中文".PadRightA(5, '嗯'));
Assert.Equal("中文嗯", "中文".PadRightA(6, '嗯'));
Assert.Equal("中文.", "中文".PadRightA(5, '.'));
Assert.Equal("中文..", "中文".PadRightA(6, '.'));
}
[Fact]
public void IndexOfTest()
{
Assert.Equal(3, "1110101".IndexOf(c => c == '0'));
Assert.Equal(5, "1110101".IndexOf(c => c == '0', 4));
Assert.Equal(-1, "1110101".IndexOf(c => c == '0', 4, 1));
}
[Fact]
public void IsMatchTest()
{
Assert.True("你好".IsMatch(new Regex($"^{Unicode.Chinese}+$")));
Assert.True("こんにちは".IsMatch(new Regex($"^{Unicode.Japanese}+$")));
Assert.True("안녕".IsMatch(new Regex($"^{Unicode.Korean}+$")));
}
}
}
|
using DataAccess.Context;
using DataAccess.Repository;
using Ninject.Modules;
namespace Services.DependencyInjection
{
public class BlogModule : NinjectModule
{
public override void Load()
{
Bind<IBlogRepository>().To<BlogRepository>();
Bind<IContextFactory>().To<ContextFactory>();
Bind<IBlogService>().To<BlogService>();
Bind<IEntryRepository>().To<EntryRepository>();
Bind<IEntryService>().To<EntryService>();
}
}
}
|
using System;
using System.ComponentModel;
using System.Windows.Forms;
using System.Xml;
namespace TemplateEditor
{
public partial class Form1 : Form
{
bool Saved = false;
string filename="";
public Form1()
{
InitializeComponent();
}
public Form1(string filename)
{
this.filename = filename;
InitializeComponent();
}
private void Save(string Filename)
{
XmlDocument doc = new XmlDocument();
XmlNode root = doc.CreateElement("root");
for (int i = 0; i < this.dataGridView1.RowCount; i++)
{
if (dataGridView1.Rows[i].Cells[1].Value != null && dataGridView1.Rows[i].Cells[0].Value != null)
{
XmlElement node = doc.CreateElement("word");
XmlAttribute name = doc.CreateAttribute("name");
name.Value = dataGridView1.Rows[i].Cells[0].Value.ToString();
XmlAttribute color = doc.CreateAttribute("color");
color.Value = dataGridView1.Rows[i].Cells[1].Value.ToString();
node.Attributes.Append(name);
node.Attributes.Append(color);
root.AppendChild(node);
}
}
doc.AppendChild(root);
if (Filename == "")
{
saveFileDialog1.ShowDialog();
doc.Save(saveFileDialog1.FileName);
}
else
{
doc.Save(Filename);
}
}
private void Save()
{
XmlDocument doc = new XmlDocument();
XmlNode root = doc.CreateElement("root");
for (int i = 0; i < dataGridView1.RowCount; i++)
{
if (dataGridView1.Rows[i].Cells[1].Value != null && dataGridView1.Rows[i].Cells[0].Value != null)
{
XmlElement node = doc.CreateElement("word");
XmlAttribute name = doc.CreateAttribute("name");
name.Value = dataGridView1.Rows[i].Cells[0].Value.ToString();
XmlAttribute color = doc.CreateAttribute("color");
color.Value = dataGridView1.Rows[i].Cells[1].Value.ToString();
node.Attributes.Append(name);
node.Attributes.Append(color);
root.AppendChild(node);
}
}
doc.AppendChild(root);
saveFileDialog1.ShowDialog();
if (saveFileDialog1.FileName != "")
{
doc.Save(saveFileDialog1.FileName);
}
}
private void saveToolStripMenuItem_Click(object sender, EventArgs e)
{
Save(filename);
}
private void saveFileDialog1_FileOk(object sender, CancelEventArgs e)
{
}
private void openToolStripMenuItem_Click(object sender, EventArgs e)
{
openFileDialog1.ShowDialog();
XmlDocument doc = new XmlDocument();
doc.Load(openFileDialog1.FileName);
XmlNode root = doc.DocumentElement;
foreach (XmlNode node in root)
{
dataGridView1.Rows.Add();
if (((dataGridView1.RowCount) >= 0))
{
if (node.Attributes.GetNamedItem("name") != null && node.Attributes.GetNamedItem("color") != null)
{
dataGridView1.Rows.Add(new object[] { node.Attributes.GetNamedItem("name").Value, node.Attributes.GetNamedItem("color").Value });
}
}
}
filename = openFileDialog1.FileName;
}
private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
}
private void Form1_Load(object sender, EventArgs e)
{
if (filename != "")
{
XmlDocument doc = new XmlDocument();
doc.Load(filename);
XmlNode root = doc.DocumentElement;
foreach (XmlNode node in root)
{
dataGridView1.Rows.Add();
if (((dataGridView1.RowCount) >= 0))
{
if (node.Attributes.GetNamedItem("name") != null && node.Attributes.GetNamedItem("color") != null)
{
dataGridView1.Rows.Add(new object[] { node.Attributes.GetNamedItem("name").Value, node.Attributes.GetNamedItem("color").Value });
}
}
}
}
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
if(Saved==false)
{
DialogResult res = MessageBox.Show("Do you want to save?", "File isn't saved",MessageBoxButtons.YesNoCancel);
if(res==DialogResult.Yes)
{
if (filename != "") Save(filename);
else Save();
}
if(res==DialogResult.No)
{
}
if(res==DialogResult.Cancel)
{
e.Cancel = true;
}
}
}
private void saveAsToolStripMenuItem_Click(object sender, EventArgs e)
{
Save();
}
private void dataGridView1_CellBeginEdit(object sender, DataGridViewCellCancelEventArgs e)
{
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.Reflection;
using System;
using System.Linq;
public static class Blocks
{
public const int Air = 0,
Dirt = 1,
Grass = 2,
Stone = 3,
Sand = 4,
Log = 5,
Leaves = 6,
Water = 7,
DryGrass = 8;
}
public static class BlockRegistrar
{
public static Dictionary<int, Block> Blocks = new Dictionary<int, Block>();
static bool isInited;
public static int MaxSubmeshes { get; set; }
public static void Init()
{
if (isInited) return;
foreach (Type t in Assembly.GetAssembly(typeof(Block)).GetTypes().Where(x => x.IsClass && x.IsSubclassOf(typeof(Block))))
{
var block = (Block)Activator.CreateInstance(t);
if(block.Submesh > MaxSubmeshes)
{
MaxSubmeshes = block.Submesh;
}
Blocks.Add(block.BlockID, block);
}
Blocks = Blocks.OrderBy(x => x.Key).ToDictionary(x => x.Key, x => x.Value);
isInited = true;
}
public static Block GetBlock(int i)
{
if(Blocks.ContainsKey(i))
{
return Blocks[i];
}
return null;
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using Lussatite.FeatureManagement.SessionManagers;
namespace RimDev.AspNetCore.FeatureFlags
{
public class FeatureFlagsSettings
{
public FeatureFlagsSettings(IEnumerable<Assembly> featureFlagAssemblies)
{
FeatureFlagTypes = featureFlagAssemblies.GetFeatureTypesInAssemblies().ToList();
}
/// <summary>A SQL connection string which can be used to SELECT/INSERT/UPDATE
/// from the feature flag values table.</summary>
public string ConnectionString { get; set; }
/// <summary>A SQL connection string which can be used to create a missing feature
/// flag values table.</summary>
public string InitializationConnectionString { get; set; }
/// <summary>The list of types found by initial assembly scanning.</summary>
public IReadOnlyCollection<Type> FeatureFlagTypes { get; }
public Type GetFeatureType(
string featureName
)
{
return FeatureFlagTypes.SingleOrDefault(x =>
x.Name.Equals(featureName, StringComparison.OrdinalIgnoreCase));
}
/// <summary>How long a cache entry will be valid until it is forced to
/// refresh from the database. Defaults to 60 seconds.</summary>
public TimeSpan CacheTime { get; set; } = TimeSpan.FromSeconds(60.0);
/// <summary>The <see cref="SqlSessionManagerSettings"/> object which lets the
/// <see cref="FeatureFlagsSessionManager"/> communicate with a database backend.
/// </summary>
public SqlSessionManagerSettings SqlSessionManagerSettings { get; set; }
}
}
|
using System.Web.Mvc;
namespace LiveTest.Controllers
{
public class EmptyController : Controller
{
// GET: Empty
public ActionResult Index()
{
return View();
}
}
} |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using WinFormsWCF_TournamentGenerator.ServiceReference1;
using System.Linq;
namespace WinFormsWCF_TournamentGenerator
{
public partial class FormUpdate : Form
{
Player playerToUpdate;
public FormUpdate()
{
InitializeComponent();
}
private void FormUpdate_Load(object sender, EventArgs e)
{
playerToUpdate = Form1.currentSelectedPlayer;
textBoxFirstName.Text = playerToUpdate.FirstName;
textBoxLastName.Text = playerToUpdate.LastName;
numericUpDownAge.Value = playerToUpdate.Age;
numericUpDownSkill.Value = playerToUpdate.Skill;
numericUpDownSpeed.Value = playerToUpdate.Speed;
numericUpDownStrength.Value = playerToUpdate.Strength;
}
private void buttonUpdatePlayer_Click(object sender, EventArgs e)
{
Player player = new Player();
player.Id = playerToUpdate.Id;
player.FirstName = textBoxFirstName.Text;
player.LastName = textBoxLastName.Text;
player.Age = Convert.ToInt32(numericUpDownAge.Value);
player.Speed = Convert.ToInt32(numericUpDownSpeed.Value);
player.Strength = Convert.ToInt32(numericUpDownStrength.Value);
player.Skill = Convert.ToInt32(numericUpDownSkill.Value);
Service1Client serviceClient = new Service1Client();
if (serviceClient.UpdatePlayer(player) == 1)
{
Form1.playerList.Remove(playerToUpdate);
Form1.playerList.Add(player);
Form1.dataGridViewForm1.DataSource = serviceClient.GetAllPlayers();
this.Close();
}
}
#region VALIDATION
private void textBoxFirstName_TextChanged(object sender, EventArgs e)
{
if (textBoxLastName.Text != "" && textBoxFirstName.Text != "")
buttonUpdatePlayer.Enabled = true;
else
buttonUpdatePlayer.Enabled = false;
}
private void textBoxLastName_TextChanged(object sender, EventArgs e)
{
if (textBoxLastName.Text != "" && textBoxFirstName.Text != "")
buttonUpdatePlayer.Enabled = true;
else
buttonUpdatePlayer.Enabled = false;
}
#endregion
}
}
|
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Text;
using UnityEditor;
using UnityEngine;
namespace TG.AssetBundleRM
{
public class AssetBundleEditor : Editor
{
private static string DependenciesDirectory = Path.Combine(Application.dataPath, "Dependencies");
private static string CsvAssetPath = "Assets/L10N";
private static string PrefabAssetPath = "Assets/Res/Prefabs";
private static string dependenciesMapName = "dependenciesMap.ab";
private static string dependenciesMapDir = Path.Combine(Application.dataPath, "../DependenciesMap/");
/// <summary>
/// asset bundle 导出路径
/// </summary>
private static string absDataOutPath = Path.Combine(Application.dataPath, "../AssetBundles");
// abPath for key
private static Dictionary<string, ABUnitModel> abDic = new Dictionary<string, ABUnitModel>();
/// <summary>
/// 设置资源ab名字
/// </summary>
/// <param name="assetPath">eg:Assets/Res/UI/Main/MainWindow.prefab</param>
/// <returns></returns>
private static bool SetABNameByAssetPath(string assetPath)
{
if (!IsAssetPathIllegality(assetPath))
{
//Utility.Log(Utility.LogLevel.Error, $"SetABNameByAssetPath::illegality assetPath = {assetPath}");
return false;
}
string fullPath = Path.GetFullPath(assetPath);
if (!File.Exists(fullPath))
return false;
if (assetPath.Contains(" "))
{
Utility.Log(Utility.LogLevel.Warning, $"SetABNameByAssetPath::ab name contain blank space,assetPath = {assetPath}");
return false;
}
AssetImporter assetImporter = AssetImporter.GetAtPath(assetPath);
if (assetImporter != null)
{
string abPath = Utility.ConvertAssetPath2ABPath(assetImporter.assetPath);
//去除Assets/ 和 文件后缀
//string assetName = Utility.ConvertAssetPath2AssetName(assetImporter.assetPath);
ABUnitModel abUnitModel = null;
if (abDic.TryGetValue(abPath, out abUnitModel))
{
abUnitModel.AddAsset(assetImporter.assetPath, abPath);
}
else
{
abUnitModel = new ABUnitModel(assetImporter.assetPath, abPath);
abDic.Add(abPath, abUnitModel);
}
assetImporter.assetBundleName = abPath;
string[] depencies = AssetDatabase.GetDependencies(assetPath, false);
if (depencies != null && depencies.Length > 0)
{
foreach (var dep in depencies)
{
SetABNameByAssetPath(dep);
}
}
}
else
{
Utility.Log(Utility.LogLevel.Error, $"SetABNameByAssetPath::get assetImporter is null ,assetPath = {assetPath}");
}
return true;
}
/// <summary>
/// 设置所有prefab asset bundle name
/// </summary>
private static void SetAllPrefabABName()
{
if (!Directory.Exists(PrefabAssetPath))
return;
var files = Directory.GetFiles(PrefabAssetPath, "*.prefab", SearchOption.AllDirectories);
foreach (var file in files)
{
SetABNameByAssetPath(file.Replace(@"\", @"/"));
}
}
/// <summary>
/// 设置所有csv/txt 文件asset bundle name
/// </summary>
private static void SetAllCsvABName()
{
if (!Directory.Exists(CsvAssetPath))
return;
var files = Directory.GetFiles(CsvAssetPath, "*.txt", SearchOption.AllDirectories);
foreach (var file in files)
{
SetABNameByAssetPath(file.Replace(@"\", @"/"));
}
}
/// <summary>
/// 设置游戏内所有资源asset bundle name
/// </summary>
public static void SetAllABName()
{
Clear();
SetAllCsvABName();
SetAllPrefabABName();
AssetDatabase.Refresh();
Utility.Log(Utility.LogLevel.Info, $"Set All AB Name Finished , dependenciesMapDir = {dependenciesMapDir}");
}
/// <summary>
/// 清理所有asset bundle name
/// </summary>
public static void ClearAllABName()
{
Clear();
string[] allABNames = AssetDatabase.GetAllAssetBundleNames();
if (allABNames != null)
{
foreach (var name in allABNames)
{
AssetDatabase.RemoveAssetBundleName(name, true);
}
}
AssetDatabase.RemoveUnusedAssetBundleNames();
AssetDatabase.Refresh();
}
/// <summary>
/// 生成资源依赖关系表
/// </summary>
public static void GenerateDepFile()
{
SetAllABName();
WriteABDependenies2File();
}
/// <summary>
/// 设置所有AB依赖关系
/// </summary>
private static void WriteABDependenies2File()
{
Dictionary<string, HashSet<string>> depsMap = GenerateAllABDependencies();
WriteABInfo2ByteFile(depsMap);
WriteABInfo2File(depsMap);
}
/// <summary>
/// 清理
/// </summary>
private static void Clear()
{
if (abDic != null)
{
abDic.Clear();
}
}
/// <summary>
/// 获取ab依赖关系
/// </summary>
/// <returns></returns>
private static Dictionary<string, HashSet<string>> GenerateAllABDependencies()
{
if (!Directory.Exists(DependenciesDirectory))
{
Directory.CreateDirectory(DependenciesDirectory);
}
//assetPath for key ; dependenies assetPath list for value
Dictionary<string, HashSet<string>> dependenciesSet = new Dictionary<string, HashSet<string>>();
foreach (var keyValue in abDic)
{
string abPath = keyValue.Key;
List<AssetUnitModel> assetList = keyValue.Value.assetList;
if (abPath.StartsWith("assets/dependencies") || abPath.Equals("assets"))
{
continue;
}
if (assetList != null && assetList.Count > 0)
{
foreach (var assetInfo in assetList)
{
AssetImporter assetImporter = AssetImporter.GetAtPath(assetInfo.assetPath);
if (assetImporter != null)
{
ABUnitModel model = keyValue.Value;
HashSet<string> tempSet;
if (!dependenciesSet.TryGetValue(assetInfo.assetPath, out tempSet))
{
dependenciesSet.Add(assetInfo.assetPath, tempSet = new HashSet<string>());
}
HashSet<string> tempDependenciesSet = new HashSet<string>();
GetDependenciesRecursive(assetInfo.assetPath, tempDependenciesSet);
if (tempDependenciesSet.Count > 0)
{
foreach (string depAssetPath in tempDependenciesSet)
{
var depAssetImporter = AssetImporter.GetAtPath(depAssetPath);
if (depAssetImporter != null)
{
tempSet.Add(depAssetPath);
}
else
{
Utility.Log(Utility.LogLevel.Error, $"GenerateAllABDependencies::dep asset importer is null,assetPath = {depAssetPath}");
}
}
}
}
else
{
Utility.Log(Utility.LogLevel.Error, $"GenerateAllABDependencies::asset importer is null,assetPath = {assetInfo}");
}
}
}
}
return dependenciesSet;
}
/// <summary>
/// 递归获取依赖
/// </summary>
/// <param name="assetPath"></param>
/// <param name="resultSet"></param>
private static void GetDependenciesRecursive(string assetPath, HashSet<string> resultSet)
{
string[] dependencies = AssetDatabase.GetDependencies(assetPath);
if (dependencies == null || dependencies.Length == 0)
{
return;
}
foreach (var depAssetPath in dependencies)
{
if (IsAssetPathIllegality(depAssetPath) && !resultSet.Contains(depAssetPath))
{
resultSet.Add(depAssetPath);
if (depAssetPath != assetPath)
{
GetDependenciesRecursive(depAssetPath, resultSet);
}
}
}
}
/// <summary>
/// 依赖关系保存为2进制文件
/// </summary>
/// <param name="depsMap">assetPath for key , assetPath list for value</param>
private static void WriteABInfo2ByteFile(Dictionary<string, HashSet<string>> depsMap)
{
//abPath list
List<string> allABPathList = new List<string>();
//abPath for key , index for value
Dictionary<string, int> abPath2IndexDic = new Dictionary<string, int>();
//abPath for key , dependencies for value
Dictionary<string, string[]> abPathDependenciesDic = new Dictionary<string, string[]>();
foreach (var dep in depsMap)
{
string abPath = Utility.ConvertAssetPath2ABPath(dep.Key);
if (abDic.ContainsKey(abPath))
{
//ABUnitModel model = abDic[abPath];
if (!abPathDependenciesDic.ContainsKey(abPath))
{
//依赖
List<string> dependencies = new List<string>();
foreach (var assetPath in dep.Value)
{
string depABPath = Utility.ConvertAssetPath2ABPath(assetPath);
if (!dependencies.Contains(depABPath))
{
dependencies.Add(depABPath);
}
}
abPathDependenciesDic.Add(abPath, dependencies.ToArray());
}
}
}
foreach (var dep in abPathDependenciesDic)
{
if (!abPath2IndexDic.ContainsKey(dep.Key))
{
allABPathList.Add(dep.Key);
abPath2IndexDic.Add(dep.Key, allABPathList.Count - 1);
}
}
string dependenciesMapPath = Path.Combine(dependenciesMapDir, dependenciesMapName);
if (!Directory.Exists(dependenciesMapDir))
{
Directory.CreateDirectory(dependenciesMapDir);
}
using (Stream stream = new FileStream(dependenciesMapPath, FileMode.Create, FileAccess.Write))
{
using (BinaryWriter writer = new BinaryWriter(stream, Encoding.UTF8))
{
int allABLength = allABPathList.Count;
string abPath;
writer.Write(allABLength);
for (int i = 0; i < allABLength; i++)
{
abPath = allABPathList[i];
writer.Write(abPath);
if (abPathDependenciesDic.ContainsKey(abPath))
{
int depCount = 0;
string[] dependencies = abPathDependenciesDic[abPath];
if (dependencies != null)
{
depCount = dependencies.Length;
writer.Write(depCount);
if (depCount > 0)
{
for (int j = 0; j < depCount; j++)
{
int index = abPath2IndexDic[dependencies[j]];
writer.Write(index);
}
}
}
else
{
writer.Write(depCount);
}
}
}
List<AssetUnitModel> tempAssetList = new List<AssetUnitModel>();
foreach (var abInfo in abDic)
{
if (abInfo.Value.assetList != null && abInfo.Value.assetList.Count > 0)
{
foreach (var assetInfo in abInfo.Value.assetList)
{
if (!Utility.IsContains<AssetUnitModel>(tempAssetList, assetInfo, (a, b) => { return a.abPath == b.abPath && a.assetPath == b.assetPath ? true : false; }))
tempAssetList.Add(assetInfo);
}
}
}
writer.Write(tempAssetList.Count);
foreach (var assetInfo in tempAssetList)
{
int assetPathHash = assetInfo.assetPathHash;
string assetBundlePath = assetInfo.abPath;
writer.Write(assetPathHash);
writer.Write(abPath2IndexDic[assetBundlePath]);
}
writer.Flush();
writer.Dispose();
writer.Close();
}
stream.Dispose();
stream.Close();
}
}
/// <summary>
/// 依赖关系保存为普通文本
/// </summary>
/// <param name="depsMap"></param>
private static void WriteABInfo2File(Dictionary<string, HashSet<string>> depsMap)
{
//abPath list
List<string> allABPathList = new List<string>();
//abPath for key , index for value
Dictionary<string, int> abPath2IndexDic = new Dictionary<string, int>();
//abPath for key , dependencies for value
Dictionary<string, string[]> abPathDependenciesDic = new Dictionary<string, string[]>();
foreach (var dep in depsMap)
{
string abPath = Utility.ConvertAssetPath2ABPath(dep.Key);
if (abDic.ContainsKey(abPath))
{
ABUnitModel model = abDic[abPath];
if (!abPathDependenciesDic.ContainsKey(model.abPath))
{
List<string> dependencies = new List<string>();
foreach (var assetPath in dep.Value)
{
abPath = Utility.ConvertAssetPath2ABPath(assetPath);
if (!dependencies.Contains(abPath))
{
dependencies.Add(abPath);
}
}
abPathDependenciesDic.Add(model.abPath, dependencies.ToArray());
}
}
}
foreach (var dep in abPathDependenciesDic)
{
if (!abPath2IndexDic.ContainsKey(dep.Key))
{
allABPathList.Add(dep.Key);
abPath2IndexDic.Add(dep.Key, allABPathList.Count - 1);
}
}
string dependenciesMapPath = Path.Combine(dependenciesMapDir, "dependenciesMap.txt");
if (!Directory.Exists(dependenciesMapDir))
{
Directory.CreateDirectory(dependenciesMapDir);
}
using (Stream stream = new FileStream(dependenciesMapPath, FileMode.Create, FileAccess.Write))
{
using (StreamWriter writer = new StreamWriter(stream, Encoding.UTF8))
{
int allABLength = allABPathList.Count;
string abPath;
writer.WriteLine(allABLength);
for (int i = 0; i < allABLength; i++)
{
abPath = allABPathList[i];
writer.WriteLine(abPath);
if (abPathDependenciesDic.ContainsKey(abPath))
{
int depCount = 0;
string[] dependencies = abPathDependenciesDic[abPath];
if (dependencies != null)
{
depCount = dependencies.Length;
writer.WriteLine(depCount);
if (depCount > 0)
{
for (int j = 0; j < depCount; j++)
{
int index = abPath2IndexDic[dependencies[j]];
writer.Write($"{index},");
}
}
}
else
{
writer.WriteLine(depCount);
}
writer.WriteLine();
}
}
List<AssetUnitModel> tempAssetList = new List<AssetUnitModel>();
foreach (var abInfo in abDic)
{
if (abInfo.Value.assetList != null && abInfo.Value.assetList.Count > 0)
{
foreach (var assetInfo in abInfo.Value.assetList)
{
if (!Utility.IsContains<AssetUnitModel>(tempAssetList, assetInfo, (a, b) => { return a.abPath == b.abPath && a.assetPath == b.assetPath ? true : false; }))
tempAssetList.Add(assetInfo);
}
}
}
writer.WriteLine(tempAssetList.Count);
foreach (var assetInfo in tempAssetList)
{
int assetPathHash = assetInfo.assetPathHash;
string assetBundlePath = assetInfo.abPath;
writer.WriteLine($"{assetInfo.assetPath},{assetPathHash},{assetInfo.abPath},{abPath2IndexDic[assetBundlePath]}");
}
writer.Flush();
writer.Dispose();
writer.Close();
}
stream.Dispose();
stream.Close();
}
}
/// <summary>
/// 判断资源路径是否合法
/// </summary>
/// <param name="assetPath"></param>
/// <returns></returns>
private static bool IsAssetPathIllegality(string assetPath)
{
if (assetPath.EndsWith(".cs") || assetPath.EndsWith(".meta") || assetPath.StartsWith("Assets/Plugins") || assetPath.Contains("Scripts") || assetPath.Contains("Packages"))
return false;
return true;
}
/// <summary>
/// build android asset bundle
/// </summary>
public static void BuildForAndroid()
{
BuildAB(BuildTarget.Android, absDataOutPath);
}
/// <summary>
/// build window asset bundle
/// </summary>
public static void BuildForWindow()
{
BuildAB(BuildTarget.StandaloneWindows64, absDataOutPath);
}
/// <summary>
/// build platform asset bundle
/// </summary>
/// <param name="target">平台</param>
/// <param name="outPutDir">asset bundle输出的目录</param>
private static void BuildAB(BuildTarget target, string outPutDir)
{
BuildTargetGroup targetGroup = BuildTargetGroup.Unknown;
switch (target)
{
case BuildTarget.StandaloneOSX:
targetGroup = BuildTargetGroup.Standalone;
break;
case BuildTarget.StandaloneOSXIntel:
targetGroup = BuildTargetGroup.Standalone;
break;
case BuildTarget.StandaloneWindows:
targetGroup = BuildTargetGroup.Standalone;
break;
case BuildTarget.StandaloneLinux:
targetGroup = BuildTargetGroup.Standalone;
break;
case BuildTarget.StandaloneWindows64:
targetGroup = BuildTargetGroup.Standalone;
break;
case BuildTarget.StandaloneLinux64:
targetGroup = BuildTargetGroup.Standalone;
break;
case BuildTarget.StandaloneLinuxUniversal:
targetGroup = BuildTargetGroup.Standalone;
break;
case BuildTarget.StandaloneOSXIntel64:
targetGroup = BuildTargetGroup.Standalone;
break;
case BuildTarget.iOS:
targetGroup = BuildTargetGroup.iOS;
break;
case BuildTarget.Android:
targetGroup = BuildTargetGroup.Android;
break;
default:
Utility.Log(Utility.LogLevel.Error, $"BuildAB::Unsupported build target {target}!");
break;
}
if (targetGroup == BuildTargetGroup.Unknown || !EditorUserBuildSettings.SwitchActiveBuildTarget(targetGroup, target))
{
Utility.Log(Utility.LogLevel.Error, $"BuildAB::build target {target} Failed!");
return;
}
//if (!string.IsNullOrEmpty(outPutDir) && Directory.Exists(outPutDir))
//{
// Directory.CreateDirectory(outPutDir);
//}
string finalOutPutDir = Path.Combine(outPutDir, EditorUserBuildSettings.activeBuildTarget.ToString()).Replace("\\", "/");
Utility.Log(Utility.LogLevel.Info, $"BuildAB::outPutDir = {finalOutPutDir}");
if (!string.IsNullOrEmpty(finalOutPutDir) && !Directory.Exists(finalOutPutDir))
{
Directory.CreateDirectory(finalOutPutDir);
}
List<string> tempSceneList = new List<string>();
for (int i = 0; i < EditorBuildSettings.scenes.Length; i++)
{
if (EditorBuildSettings.scenes[i].enabled)
{
tempSceneList.Add(EditorBuildSettings.scenes[i].path);
}
}
SetAllABName();
WriteABDependenies2File();
try
{
List<AssetBundleBuild> tempABBList = new List<AssetBundleBuild>();
foreach (var abInfo in abDic.Values)
{
if (abInfo != null)
{
AssetBundleBuild abb = new AssetBundleBuild();
abb.assetBundleName = abInfo.abPath;
abb.assetBundleVariant = "";
abb.assetNames = new string[abInfo.assetList.Count];
for (int i = 0; i < abInfo.assetList.Count; i++)
{
abb.assetNames[i] = abInfo.assetList[i].assetPath;
//Debug.Log(abInfo.assetList[i].assetPath);
//if (abInfo.assetList[i].assetPath.Contains("HeroGiftsActivityItem"))
//{
// Utility.Log(Utility.LogLevel.Error, $"BuildAB::Same Asset Bundle more then once , assetPath = {abInfo.assetList[i].assetPath} ,abPath = {abInfo.assetList[i].abPath}");
//}
}
tempABBList.Add(abb);
}
}
BuildPipeline.BuildAssetBundles(finalOutPutDir, tempABBList.ToArray(), BuildAssetBundleOptions.DeterministicAssetBundle | BuildAssetBundleOptions.ChunkBasedCompression, EditorUserBuildSettings.activeBuildTarget);
}
catch (Exception e)
{
Utility.Log(Utility.LogLevel.Error, $"BuildAB::Build AssetBundle Failed, error = {e.Message}");
}
Utility.Log(Utility.LogLevel.Info, $"BuildAB::Build AssetBundle Finished!!!");
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace MVC_Music.Controllers
{
public class CookieController : Controller
{
// GET: Cookie
public ActionResult Index(string val)
{
HttpCookie c = Request.Cookies.Get("mycookie");
if (c == null)
{
ViewBag.State = "Add";
}
else
{
ViewBag.State = "Expire";
}
if (!string.IsNullOrEmpty(val))
{
if (val == "Add")
{
c = new HttpCookie("mycookie", "Hello there");
c["username"] = "someuser";
ViewBag.State = "Persist";
}
else if (val == "Persist")
{
c.Expires = DateTime.Now.AddHours(5);
ViewBag.State = "Expire";
}
else
{
c.Expires = DateTime.Now.AddHours(-5);
ViewBag.State = "Add";
}
Response.Cookies.Add(c);
}
return View();
}
}
} |
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using M220N.Models;
using MongoDB.Bson;
using MongoDB.Bson.Serialization.Conventions;
using MongoDB.Driver;
using NUnit.Framework;
namespace M220NLessons
{
/// <summary>
/// This Test Class shows the code used in the Basic Writes lesson.
///
/// Welcome back. In this lesson, we'll explore writing new
/// documents to a MongoDB collection.
///
/// </summary>
public class BasicWrites
{
private IMongoCollection<Theater> _theatersCollection;
[SetUp]
public void Setup()
{
var camelCaseConvention = new ConventionPack { new CamelCaseElementNameConvention() };
ConventionRegistry.Register("CamelCase", camelCaseConvention, type => true);
var client = new MongoClient(Constants.MongoDbConnectionUri());
_theatersCollection = client.GetDatabase("sample_mflix").GetCollection<Theater>("theaters");
}
[Test]
public async Task CreateMovieAsync()
{
/* There are two methods for writing documents with the MongoDB
* driver: InsertOne and InsertMany, as well as the Async versions
* of those two methods. In this lesson, I'll show you how to use
* the Async methods in a couple of different ways.
*
* Let's start with a simple example. We want to add a new movie
* theater to the "theaters" collection. Let's first take a look at
* the Theater mapping class. It has Id, TheaterId, and Location
* properties. The Location property is an object that contains an
* Address object and Geo information, which we won't worry about
* in this lesson.
*
* With that bit of information, let's create a new instance of the
* Theater class, using the constructor that takes in a TheaterId and
* various Address components:
*
*/
var newTheater = new Theater(27777,
"4 Privet Drive",
"Little Whinging",
"LA",
"343434");
// And now we call InsertOneAsync() to add it to the collection:
await _theatersCollection.InsertOneAsync(newTheater);
/* Here's something you should be aware of. In the constructor for
* the Theater object, we don't set the Id property. Instead,
* we let MongoDB create one and assign it for us as part of the
* Insert call. We can check that property as soon as the InsertOne
* returns:
*/
Assert.IsNotEmpty(newTheater.Id.ToString());
/* Adding multiple theaters to the collection is just as easy.
* Let's add a group of 3 new theaters that have just been built.
* First, we create the Theater objects:
*/
var theater1 = new Theater(27017, "1 Foo Street", "Dingledongle", "DE", "45678");
var theater2 = new Theater(27018, "234 Bar Ave.", "Wishywashy", "WY", "87654");
var theater3 = new Theater(27019, "75 Birthday Road", "Viejo Amigo", "CA", "99887");
/* And then we call InsertManyAsync, passing in a new List of
* those Theater objects:
*/
await _theatersCollection.InsertManyAsync(
new List<Theater>()
{
theater1, theater2, theater3
}
);
/* Let's make sure everything worked. */
var newTheaters = await _theatersCollection.Find<Theater>(
Builders<Theater>.Filter.Gte(t => t.TheaterId, 27017)
& Builders<Theater>.Filter.Lte(t => t.TheaterId, 27019))
.ToListAsync();
Assert.AreEqual(3, newTheaters.Count);
Assert.AreEqual("1 Foo Street",
newTheaters.First().Location.Address.Street1);
Assert.AreEqual("Viejo Amigo",
newTheaters.Last().Location.Address.City);
/* So that's all there is to writing new documents to a MongoDB
* collection. In the next lesson, we'll look at updating
* existing documents.
*/
}
[TearDown]
public void Cleanup()
{
_theatersCollection.DeleteMany(t => t.TheaterId >= 27017);
}
}
}
|
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace EquationSolver
{
class Utilities
{
static char[] numberChars = { '-', '+', '.', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' };
/// <summary>
/// For debug timing tests
/// </summary>
public static DateTime d1;
/// <summary>
/// Useless constructor.
/// </summary>
public Utilities()
{
}
#region Relative path munging
/// <summary>
/// Outputs the relative path supplied as an absolute path using the basepath supplied.
/// </summary>
/// <param name="sPath">The path to output</param>
/// <param name="sBasepath">the base path to compare to</param>
/// <param name="sRelpath">the relative path</param>
public static void RelativeToAbsolutePath(out string sPath, string sBasepath, string sRelpath)
{
// determine relative child to parent distance
StringBuilder sb = new StringBuilder();
char[] chars = sRelpath.ToCharArray();
bool bADot = false;
int iUpDirs = 0;
int iStartNdx = 0;
for (int i = 0; i < chars.Length; i++)
{
char c = chars[i];
if (c == '.')
{
if (bADot)
{
iUpDirs++;
}
bADot = true;
}
else if (c == '\\')
{
bADot = false;
}
else
{
iStartNdx = i;
bADot = false;
break;
}
}
if (iUpDirs > 0)
{
string sDir = sBasepath;
for (int d = 0; d < iUpDirs; d++)
{
DirectoryInfo di = Directory.GetParent(sDir);
sDir = di.FullName;
}
}
sPath = sBasepath + sRelpath.Substring(iStartNdx - 1);
}
/// <summary>
/// Ouputs the relative path from the absolute path supplied
/// </summary>
/// <param name="sPath">the output path</param>
/// <param name="sAbsPath">the absolute path</param>
/// <param name="sBasepath">the base path to compare to</param>
/// <returns>true is successful</returns>
public static bool AbsPathMunge(out string sPath, string sAbsPath, string sBasepath)
{
string strAbs = sAbsPath.ToLower();
string strBase = sBasepath.ToLower();
if (strAbs.StartsWith(strBase))
{
string str = "." + sAbsPath.Substring(sBasepath.Length);
sPath = str;
return true;
}
else
{
sPath = sAbsPath;
return false;
}
}
#endregion
#region Date Munging
/// <summary>
/// Ouputs a DateTime object from the string supplied.
/// </summary>
/// <param name="oDateTime">the DateTime object ouput</param>
/// <param name="sDate">the string of the date</param>
/// <returns>true if successful</returns>
public static bool MakeDateFromString(out DateTime oDateTime, string sDate)
{
try
{
System.Text.RegularExpressions.Regex regEx = new System.Text.RegularExpressions.Regex("^{n}/{n}/{n:4}");
if (regEx.IsMatch(sDate))
{
oDateTime = DateTime.Parse(sDate);
return true;
}
else
{
oDateTime = DateTime.Now;
return false;
}
}
catch
{
oDateTime = DateTime.Now;
return false;
}
}
#endregion
#region Number munging
public static int Factorial(int n)
{
return (n == 1 || n == 0) ? 1 : n * Factorial(n - 1);
}
/// <summary>
/// Outputs the integer equivalent of the string
/// </summary>
/// <param name="strI">the Integer string</param>
/// <param name="iNumber">the int output</param>
/// <returns>true if successful</returns>
public static bool StringToInteger(string strI, out int iNumber)
{
try
{
if (IsANumber(strI))
{
iNumber = int.Parse(strI.Trim());
return true;
}
else
{
iNumber = 0;
return false;
}
}
catch
{
iNumber = 0;
return false;
}
}
/// <summary>
/// Outputs the double value of the string supplied
/// </summary>
/// <param name="str">the string of the double</param>
/// <param name="dNumber">the double ouput</param>
/// <returns>true if successful</returns>
public static bool StringToDouble(string str, out double dNumber)
{
try
{
if (IsANumber(str))
{
dNumber = double.Parse(str.Trim());
return true;
}
else
{
dNumber = 0;
return false;
}
}
catch
{
dNumber = 0;
return false;
}
}
/// <summary>
/// Outputs the double value of the string supplied
/// </summary>
/// <param name="str">the string of the double</param>
/// <param name="dNumber">the double ouput</param>
/// <returns>true if successful</returns>
public static bool StringToDecimal(string str, out decimal dNumber)
{
try
{
if (IsANumber(str))
{
dNumber = decimal.Parse(str.Trim());
return true;
}
else
{
dNumber = 0;
return false;
}
}
catch
{
dNumber = 0;
return false;
}
}
/// <summary>
/// Verifies that the string is composed of digits and signs exclusively.
/// </summary>
/// <param name="str">string to check</param>
/// <returns>True if it is a number, false otherwise</returns>
public static bool IsANumber(string str)
{
char[] chrs = str.ToCharArray();
foreach (char c in chrs)
{
if (!IsADigit(c))
{
return false;
}
}
return true;
}
static bool IsADigit(char c)
{
bool isOne = false;
foreach (char x in numberChars)
{
if (c.CompareTo(x) == 0)
{
isOne = true;
}
}
return isOne;
}
/// <summary>
/// Determines if the string is a representation of a whole number greater than zero
/// </summary>
/// <param name="str">the string of the number</param>
/// <returns>true if successful</returns>
public static bool IsPositiveWholeNumber(string str)
{
bool bIsPos = false;
char[] chars = str.Trim().ToCharArray();
for (int i = 0; i < chars.Length; i++)
{
char c = chars[i];
if (c == '.' || c == '-')
{
bIsPos = false;
break;
}
else if (!char.IsDigit(c))
{
bIsPos = false;
break;
}
else
{
bIsPos = true;
}
}
return bIsPos;
}
#endregion
#region Normalizing
/// <summary>
/// Converts characters reserved for XML syntax to equvalent values that can be used by XML.
/// </summary>
/// <example>
/// Utilities.NormalizeXML("<SomeXmlNode expression="5<6"></SomeXmlNode><br/>
/// Outputs<br/>
/// 5<6<br/>
/// </example>
/// <param name="str"></param>
/// <returns></returns>
public static string NormalizeXML(string str)
{
try
{
string strRet;
string lt = "<";
string strLt = "<";
string gt = ">";
string strGt = ">";
string amp = "&";
string strAmp = "&";
strRet = str.Replace(amp, strAmp);
string strOne = strRet.Replace(lt, strLt);
string strTwo = strOne.Replace(gt, strGt);
return strTwo;
}
catch
{
return "";
}
}
/// <summary>
/// Checks for characters reserved for XML Syntax and encloses the string in a CDATA section.
/// </summary>
/// <param name="sString"></param>
/// <returns></returns>
public static string MakeAppropriateCDATA(string sString)
{
string sRet = sString;
char[] checks = { '<', '>', '&', '\"' };
if (sString.IndexOfAny(checks, 0) > -1)
{
sRet = "<![CDATA[" + sString + "]]>";
}
return sRet;
}
#endregion
#region Directory/File copying
/// <summary>
/// Copies file and folders from the source location to the destination location.
/// </summary>
/// <param name="src">the source location</param>
/// <param name="dest">the destination location</param>
public static void CopyLocation(string src, string dest)
{
try
{
string[] srcDirs = Directory.GetDirectories(src);
string[] srcFiles = Directory.GetFiles(src);
if (!Directory.Exists(dest))
{
Directory.CreateDirectory(dest);
}
for (int f = 0; f < srcFiles.Length; f++)
{
string srcFilename = srcFiles[f];
FileInfo fi = new FileInfo(srcFilename);
string destFilename = dest + "\\" + fi.Name;
File.Copy(srcFilename, destFilename, true);
}
for (int d = 0; d < srcDirs.Length; d++)
{
string sDir = srcDirs[d];
DirectoryInfo di = new DirectoryInfo(sDir);
string dirParent = di.Parent.FullName;
int parentLen = dirParent.Length;
string newDestDir = dest + sDir.Substring(parentLen);
CopyLocation(sDir, newDestDir);
}
}
catch
{
}
}
/// <summary>
/// Copies the directory contents from the source directory to the destination directory.
/// </summary>
/// <param name="srcDir">the source directory</param>
/// <param name="destDir">the destination directory</param>
public static void CopyDirectory(string srcDir, string destDir)
{
string[] srcDirs = Directory.GetDirectories(srcDir);
string[] srcFiles = Directory.GetFiles(srcDir);
if (!Directory.Exists(destDir))
{
Directory.CreateDirectory(destDir);
}
for (int f = 0; f < srcFiles.Length; f++)
{
string srcFilename = srcFiles[f];
FileInfo fi = new FileInfo(srcFilename);
string destFilename = destDir + "\\" + fi.Name;
File.Copy(srcFilename, destFilename, true);
}
for (int d = 0; d < srcDirs.Length; d++)
{
string sDir = srcDirs[d];
DirectoryInfo di = new DirectoryInfo(sDir);
string dirParent = di.Parent.FullName;
int parentLen = dirParent.Length;
string newDestDir = destDir + sDir.Substring(parentLen);
CopyDirectory(sDir, newDestDir);
}
}
/// <summary>
/// Copies all subdirectories from the source directory to the destination directory
/// </summary>
/// <param name="srcParentDir">the "Parent" directory</param>
/// <param name="destDir">the destination directory</param>
public static void CopySubDirectories(string srcParentDir, string destDir)
{
string[] srcDirs = Directory.GetDirectories(srcParentDir);
if (!Directory.Exists(destDir))
{
Directory.CreateDirectory(destDir);
}
for (int d = 0; d < srcDirs.Length; d++)
{
string sDir = srcDirs[d];
DirectoryInfo di = new DirectoryInfo(sDir);
string dirParent = di.Parent.FullName;
int parentLen = dirParent.Length;
string newDestDir = destDir + sDir.Substring(parentLen);
CopyDirectory(sDir, newDestDir);
}
}
#endregion
#region Text Recognition (True false knowing)
/// <summary>
/// Determines if the supplied string corresponds to a word that means true or false.
/// </summary>
/// <param name="bIsTrue">Ouput of boolean resolved from the string</param>
/// <param name="str">string to examine</param>
/// <returns>true if successful and false otherwise</returns>
public static bool IsStringBoolean(out bool bIsTrue, string str)
{
string strLower = str.Trim().ToLower();
if (strLower.CompareTo("true") == 0)
{
bIsTrue = true;
return true;
}
else if (strLower.CompareTo("false") == 0)
{
bIsTrue = false;
return true;
}
else
{
bIsTrue = false;
return false;
}
}
/// <summary>
/// Determines if the supplied string represents a True boolean
/// </summary>
/// <param name="str">the string of the boolean</param>
/// <returns>true if the string is correct for true and false otherwise</returns>
public static bool IsStringTrue(string str)
{
string strLower = str.Trim().ToLower();
if (strLower.CompareTo("true") == 0)
{
return true;
}
else
{
return false;
}
}
#endregion
#region Debug
/// <summary>
/// Sets a starting TimeDate object.
/// </summary>
public static void SetTimeStart()
{
d1 = DateTime.Now;
}
/// <summary>
/// returns the elasped time since the SetTimeStart() has been called.
/// </summary>
/// <returns>the elasped time in milliseconds</returns>
public static string GetElaspedTime()
{
DateTime d2 = DateTime.Now;
TimeSpan dElasped = d2 - d1;
return "" + dElasped.TotalMilliseconds;
}
#endregion
}
}
|
using System.Collections.Generic;
using Atc.Rest.Extended.Options;
using AutoFixture.Xunit2;
using FluentAssertions;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.Extensions.Options;
using Xunit;
namespace Atc.Rest.Extended.Tests.Options
{
public class ConfigureAuthorizationOptionsTests
{
[Fact]
public void Implements_IPostConfigureOptions_JwtBearerOptions()
=> typeof(ConfigureAuthorizationOptions)
.Should()
.Implement<IPostConfigureOptions<JwtBearerOptions>>();
[Fact]
public void Implements_IPostConfigureOptions_AuthenticationOptions()
=> typeof(ConfigureAuthorizationOptions)
.Should()
.Implement<IPostConfigureOptions<AuthenticationOptions>>();
[Theory, AutoData]
public void PostConfigure_JwtBearerOptions_Sets_Authority(RestApiExtendedOptions apiOptions)
{
var options = new JwtBearerOptions();
new ConfigureAuthorizationOptions(apiOptions, null).PostConfigure(string.Empty, options);
options.Authority.Should().NotBeNullOrWhiteSpace();
}
[Theory, AutoData]
public void PostConfigure_JwtBearerOptions_Sets_TokenValidationParameters(RestApiExtendedOptions apiOptions)
{
var options = new JwtBearerOptions();
new ConfigureAuthorizationOptions(apiOptions, null).PostConfigure(string.Empty, options);
options.TokenValidationParameters.Should().NotBeNull();
}
[Theory, AutoData]
public void PostConfigure_JwtBearerOptions_Sets_TokenValidationParameters_ValidateAudience(RestApiExtendedOptions apiOptions)
{
var options = new JwtBearerOptions();
new ConfigureAuthorizationOptions(apiOptions, null).PostConfigure(string.Empty, options);
options.TokenValidationParameters.ValidateAudience.Should().BeTrue();
}
[Theory, AutoData]
public void PostConfigure_JwtBearerOptions_Sets_TokenValidationParameters_ValidAudience(RestApiExtendedOptions apiOptions)
{
var options = new JwtBearerOptions();
new ConfigureAuthorizationOptions(apiOptions, null).PostConfigure(string.Empty, options);
options.TokenValidationParameters.ValidAudience.Should().NotBeNullOrWhiteSpace();
}
[Theory, AutoData]
public void PostConfigure_JwtBearerOptions_Sets_TokenValidationParameters_ValidAudiences(RestApiExtendedOptions apiOptions)
{
var options = new JwtBearerOptions();
new ConfigureAuthorizationOptions(apiOptions, null).PostConfigure(string.Empty, options);
options.TokenValidationParameters.ValidAudiences.Should().NotBeNullOrEmpty();
}
[Theory, AutoData]
public void PostConfigure_AuthenticationOptions_Sets_DefaultScheme(RestApiExtendedOptions apiOptions)
{
var options = new AuthenticationOptions();
new ConfigureAuthorizationOptions(apiOptions, null).PostConfigure(string.Empty, options);
options.DefaultScheme.Should().Be(JwtBearerDefaults.AuthenticationScheme);
}
[Theory, AutoData]
public void PostConfigure_JwtBearerOptions_ValidateIssuer_False_If_No_Issuers(RestApiExtendedOptions apiOptions)
{
apiOptions.Authorization.Issuer = null;
apiOptions.Authorization.ValidIssuers = new List<string>();
var options = new JwtBearerOptions();
new ConfigureAuthorizationOptions(apiOptions, null).PostConfigure(string.Empty, options);
options.TokenValidationParameters.ValidateIssuer.Should().BeFalse();
}
[Theory, AutoData]
public void PostConfigure_JwtBearerOptions_ValidateIssuer_True_With_ValidIssuers(RestApiExtendedOptions apiOptions)
{
apiOptions.Authorization.Issuer = null;
var options = new JwtBearerOptions();
new ConfigureAuthorizationOptions(apiOptions, null).PostConfigure(string.Empty, options);
options.TokenValidationParameters.ValidateIssuer.Should().BeTrue();
}
[Theory, AutoData]
public void PostConfigure_JwtBearerOptions_ValidateIssuer_True_With_Issuer(RestApiExtendedOptions apiOptions)
{
apiOptions.Authorization.ValidIssuers = new List<string>();
var options = new JwtBearerOptions();
new ConfigureAuthorizationOptions(apiOptions, null).PostConfigure(string.Empty, options);
options.TokenValidationParameters.ValidateIssuer.Should().BeTrue();
}
[Theory, AutoData]
public void PostConfigure_JwtBearerOptions_ValidateIssuer_False_With_ValidIssuers_Null(RestApiExtendedOptions apiOptions)
{
apiOptions.Authorization.Issuer = null;
apiOptions.Authorization.ValidIssuers = null;
var options = new JwtBearerOptions();
new ConfigureAuthorizationOptions(apiOptions, null).PostConfigure(string.Empty, options);
options.TokenValidationParameters.ValidateIssuer.Should().BeFalse();
}
}
} |
using AutoMapper;
using Efa.Application.Interfaces;
using Efa.Application.ViewModels;
using Efa.Domain.Entities;
using Efa.Domain.Interfaces.Services;
using Efa.Infra.Data.Context;
using System;
using System.Collections.Generic;
namespace Efa.Application.AppService
{
public class NotasAppService : AppServiceBase<EfaContext>, INotasAppService
{
private readonly INotasService _notasService;
public NotasAppService(INotasService notasService)
{
_notasService = notasService;
}
public NotasViewModel GetById(Guid id)
{
return Mapper.Map<Notas, NotasViewModel>(_notasService.GetById(id));
}
//public NotasViewModel GetByAluno(Guid id)
//{
// return Mapper.Map<Notas, NotasViewModel>(_notasService.GetByAluno(id));
//}
public IEnumerable<NotasViewModel> GetAll(int skip, int take)
{
return Mapper.Map<IEnumerable<Notas>, IEnumerable<NotasViewModel>>(_notasService.GetAll(skip, take));
}
public void Add(NotasViewModel notasViewModel)
{
var notas = Mapper.Map<NotasViewModel, Notas>(notasViewModel);
BeginTransaction();
_notasService.Add(notas);
Commit();
}
public void Update(NotasViewModel notasViewModel)
{
var notas = Mapper.Map<NotasViewModel, Notas>(notasViewModel);
BeginTransaction();
_notasService.Update(notas);
Commit();
}
public void Remove(NotasViewModel notasViewModel)
{
var notas = Mapper.Map<NotasViewModel, Notas>(notasViewModel);
BeginTransaction();
_notasService.Remove(notas);
Commit();
}
public void Dispose()
{
_notasService.Dispose();
}
}
} |
namespace Sample
{
public interface ICommand<TResult>
{
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using log4net;
using EasyDev.BL;
using SQMS.Services;
using SQMS.Services.Domain.Vehicle;
using System.Data;
using System.Web.Script.Serialization;
using EasyDev.Util;
namespace SQMS.Application.Views.AjaxServices.VehicleMission
{
public partial class VehicleMission : System.Web.UI.Page
{
private static readonly ILog log = LogManager.GetLogger("AjaxServicesVehicleMission");
public static readonly string URL_PARAM_TASKID = "taskid";
private NativeServiceManager svcManager = ServiceManagerFactory.CreateServiceManager<NativeServiceManager>();
private VehicleMissionService svcVehicleMission = null;
protected void Page_Init(object sender, EventArgs e)
{
this.svcVehicleMission = this.svcManager.CreateService<VehicleMissionService>();
}
protected void Page_Load(object sender, EventArgs e)
{
string taskId = ConvertUtil.ToStringOrDefault(this.Request.QueryString[URL_PARAM_TASKID]);
VehicleTask obj = this.svcVehicleMission.GetVehicleTaskObj(taskId);
string json = String.Empty;
try
{
JavaScriptSerializer s = new JavaScriptSerializer();
json = s.Serialize(obj);
}
catch (Exception exp)
{
log.Error(exp.ToString());
}
this.Response.Clear();
this.Response.Write(json);
}
}
}
|
using System;
using System.ComponentModel.DataAnnotations;
using FIMMonitoring.Domain.Enum;
namespace FIMMonitoring.Domain
{
public class ImportError : EntityBase
{
#region Properties
public ErrorSource ErrorSource { get; set; }
public ErrorLevel ErrorLevel { get; set; }
public ErrorType? ErrorType { get; set; }
public DateTime? ErrorDate { get; set; }
public DateTime? ErrorSendDate { get; set; }
public DateTime CreatedAt { get; set; }
public bool Cleared { get; set; }
public bool IsValidated { get; set; }
public bool IsParsed { get; set; }
public bool IsDownloaded { get; set; }
public bool IsChecked { get; set; }
public bool IsBusinessValidated { get; set; }
[MaxLength]
public string Description { get; set; }
public int SystemId { get; set; }
[MaxLength(200)]
public string Filename { get; set; }
//id of file in SoftLogs
public int? ImportId { get; set; }
#endregion Properties
#region ForeignKeys
public int? FimImportSourceId { get; set; }
public int? FimCustomerId { get; set; }
public int? FimCarrierId { get; set; }
#endregion ForeignKeys
#region Virtuals
public virtual FimSystem System { get; set; }
public virtual FimImportSource FimImportSource { get; set; }
public virtual FimCustomer FimCustomer { get; set; }
public virtual FimCarrier FimCarrier { get; set; }
#endregion Virtuals
}
}
|
using System.IO;
using Work.HTTP;
using Work.HTTP.Response;
using Work.MVC;
namespace SlusApp.Controllers
{
public class StaticFilesController : Controller
{
public HttpResponse Bootstrap()
{
return new FileResponse(File.ReadAllBytes("wwwroot/css/bootstrap.min.css"),"text/css");
}
public HttpResponse Reset()
{
return new FileResponse(File.ReadAllBytes("wwwroot/css/reset-css.css"), "text/css");
}
public HttpResponse Site()
{
return new FileResponse(File.ReadAllBytes("wwwroot/css/site.css"), "text/css");
}
public HttpResponse Text()
{
return new FileResponse(File.ReadAllBytes("wwwroot/css/text.css"), "text/css");
}
}
} |
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ObjectA : MonoBehaviour {
// Use this for initialization
public int poder;
private Transform tf;
private Renderer rend;
void Start()
{
GameController.Atacar +=
poder = 100;
tf = GetComponent<Transform> ();
rend = GetComponent<Renderer>();
}
// Update is called once per frame
void Update()
{
}
private void OnCollisionEnter(Collision other)
{
GameController.ReducirPoder();
transform.localScale += new Vector3(0, -0.25F, 0);
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using SharpDX;
using SharpDX.Toolkit;
namespace Project
{
//Abstract class inherited by any object with physics
abstract public class PhysicalObject : GameObject
{
public Vector3 velocity; //Speed relative to the map
public Vector2 direction; //Unit vector in the direction of velocity
public Vector3 acceleration; //Rate at which velocity is changing
public int hitpoints; //Health of the object, if it goes below 0, object dies
public float armour; //Value between 0 and 1 acting as a multiplier to reduce damage in
public float maxspeed; //A value that the magnitude of velocity cannot exceed
public float maxaccel; //A value that the magnitude of acceleration cannot exceed
public float heading; //Angle in radians from north
public float damagemodifier; //Damage modifier (multiplicative)
public LightingController.LightSource locallight; //A Point light that follows the object
/// <summary>
/// Get the magnitude of velocity.
/// </summary>
/// <returns>Magnitude of velocity.</returns>
public PhysicalObject()
{
this.velocity = new Vector3(0, 0, 0);
this.direction = new Vector2(1, 0);
this.acceleration = new Vector3(0, 0, 0);
this.hitpoints = 1;
this.armour = 1;
this.maxspeed = 1;
this.maxaccel = 1;
this.heading = 0;
this.damagemodifier = 1;
}
//Absolute velocity of an object
public float absVelocity()
{
return velocity.Length();
}
/// <summary>
/// Set the 2-D direction vector based on the 3-D velocity vector.
/// </summary>
public void setDirection()
{
direction.X = velocity.X;
direction.Y = velocity.Y;
direction.Normalize();
}
/// <summary>
/// Limit the magnitude of velocity to a maximum value.
/// </summary>
/// <param name="max"></param>
public void velocityLimiter(float max)
{
if (absVelocity() > max) {
this.velocity.Normalize();
this.velocity*=max;
}
}
/// <summary>
/// Gets the magnitude of acceleration, which is simply the magnitude of the vector.
/// </summary>
/// <returns>Magnitude of acceleration. </returns>
public float absAcceleration()
{
return acceleration.Length();
}
/// <summary>
/// Limit the magnitude of acceleration to a maximum value
/// </summary>
/// <param name="max">Maximum magnitude of acceleration.</param>
public void accelerationLimiter(float max)
{
if (absAcceleration() > max) {
this.acceleration.Normalize();
this.acceleration*=max;
}
}
///<summary>
/// Check if colliding with another object.
/// </summary>
public bool isColliding(PhysicalObject obj)
{
throw new NotImplementedException();
}
/// <summary>
/// Check if within X boundary.
/// </summary>
/// <returns>True if outside X boundary.</returns>
public bool edgeBoundingX()
{
return edgeBoundingGeneric(this.pos.X);
}
/// <summary>
/// Check if within Y boundary.
/// </summary>
/// <returns>True if outside Y boundary.</returns>
public bool edgeBoundingY()
{
return edgeBoundingGeneric(this.pos.Y);
}
/// <summary>
/// Check if somevalue within square boundary.
/// </summary>
/// <returns>True if outside boundary.</returns>
public bool edgeBoundingGeneric(float var)
{
if (var > game.edgemax)
{
return true;
}
if (var < -game.edgemax)
{
return true;
}
return false;
}
//Function to handle colliding between objects
public bool collisionHandling(float time)
{
for (int i = 0; i < game.gameObjects.Count; i++)
{
if (game.gameObjects[i].type != GameObjectType.Enemy && game.gameObjects[i].type != GameObjectType.Player)
{
continue;
}
if (game.gameObjects[i] == this)
{
continue;
}
if (Vector3.Distance(pos + (velocity * time), game.gameObjects[i].pos) <= (myModel.collisionRadius + game.gameObjects[i].myModel.collisionRadius))
{
if (game.gameObjects[i].GetType() != this.GetType())
{
float damage = (velocity - ((PhysicalObject)game.gameObjects[i]).velocity).Length() * 100;
hitpoints -= (int)damage;
((PhysicalObject)game.gameObjects[i]).hitpoints -= (int)damage;
}
pos = game.gameObjects[i].pos - Vector3.Normalize(velocity) * (myModel.collisionRadius + game.gameObjects[i].myModel.collisionRadius + 0.001f);
velocity = velocity / -2;
((PhysicalObject)game.gameObjects[i]).velocity = ((PhysicalObject)game.gameObjects[i]).velocity / -2;
return true;
}
}
// Land coliision handling
if (game.worldBase.isColidingTerrain(pos + (velocity * time), myModel.collisionRadius)){
// deal slight damage for hitting edge, just change the multiply factor to adjust
float damage = velocity.Length() * 50;
hitpoints -= (int)damage;
// adjust physics appropriately
pos = pos -Vector3.Normalize(velocity) * (myModel.collisionRadius + 0.001f);
velocity = velocity / -2;
}
// Land coliision handling
if (game.worldBase.isColidingEdge(pos + (velocity * time), myModel.collisionRadius)){
// deal slight damage for hitting edge, just change the multiply factor to adjust
float damage = velocity.Length() * 10;
hitpoints -= (int)damage;
// adjust physics appropriately
pos = pos -Vector3.Normalize(velocity) * (myModel.collisionRadius + 0.001f);
velocity = velocity / -2;
}
return false;
}
//Update the physics of the physical object (acceleration, velocity, position)
public void physicsUpdate(GameTime gameTime)
{
// limit acceleration
if (absAcceleration() > maxaccel)
{
accelerationLimiter(maxaccel);
}
// Multiplying by acceleration.Length() means that smaller movements are quadratically smaller
// This means there's no juddering with small input, and makes fine input control easier
acceleration *= maxspeed * acceleration.Length();
// Get elapsed time in milliseconds
float time = (float)(gameTime.ElapsedGameTime.Milliseconds);
// Arbitrary speed adjucstment
time /= 16;
/* Change the velocity with respect to acceleration and delta.
*/
velocity += (acceleration) * time / 1000;
// Limit velocity to some predefined value
if (absVelocity() > maxspeed)
{
velocityLimiter(maxspeed);
}
if (collisionHandling(time))
{
return;
}
// Calculate horizontal displacement and keep within the boundaries.
if (edgeBoundingGeneric(pos.X + velocity.X * time))
{
if (velocity.X < 0)
{
pos.X = -game.edgemax;
velocity.X = 0f;
}
if (velocity.X > 0)
{
pos.X = game.edgemax;
velocity.X = 0f;
}
}
else
{
pos.X += velocity.X * time;
}
// Calculate vertical displacement and keep within the boundaries.
if (edgeBoundingGeneric(pos.Y + velocity.Y * time))
{
if (velocity.Y < 0)
{
pos.Y = -game.edgemax;
velocity.Y = 0f;
}
if (velocity.Y > 0)
{
pos.Y = game.edgemax;
velocity.Y = 0f;
}
}
else
{
pos.Y += velocity.Y * time;
}
}
//Perform visual transformations on the object for drawing
public void transform()
{
this.setDirection();
Matrix Rotation = new Matrix(0, -1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1) * new Matrix(direction.X, direction.Y, 0, 0, -direction.Y, direction.X, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1);
Matrix Tilt = Matrix.RotationX(velocity.Length()/2);
Vector3 rollSize = acceleration -
Vector3.Dot(velocity, acceleration) / Vector3.Dot(velocity, velocity) * velocity;
int rollDir = 1;
if(Vector3.Cross(rollSize, velocity).Z > 0) { rollDir = -1; }
Matrix playerRoll = Matrix.RotationY(rollDir*rollSize.Length());
this.basicEffect.World = Tilt * playerRoll * Rotation * Matrix.Translation(pos);
}
/// <summary>
/// Remove the physical object from the world.
/// </summary>
public void die()
{
game.Remove(this);
}
/// <summary>
/// Method to create projectile texture to give to newly created projectiles.
/// </summary>
/// <returns></returns>
public MyModel CreateProjectileModel()
{
return game.assets.CreateTexturedCube("player projectile.png", new Vector3(0.3f, 0.2f, 0.25f));
}
/// <summary>
/// React to getting hit by an enemy bullet.
/// </summary>
public void Hit(int damage)
{
hitpoints -= damage;
}
//Update the lighting position details for the object
public void updateLight()
{
this.locallight.lightPos.X = this.pos.X;
this.locallight.lightPos.Y = this.pos.Y;
game.addLight(this.locallight);
}
}
}
|
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Profile;
using System.Web.UI;
using System.Web.UI.WebControls;
using DLib.DAL;
using BLL.DLib;
public partial class Controls_Admin_UserProfile : System.Web.UI.Page
{
private static DlibEntities Db
{
get
{
if (HttpContext.Current.Session["DB"] == null)
{
var entities = new DlibEntities();
HttpContext.Current.Session["DB"] = entities;
return entities;
}
else
return HttpContext.Current.Session["DB"] as DlibEntities;
}
}
public Guid UserID
{
get
{
if (Request.QueryString["UserID"] != null)
return new Guid(Request.QueryString["UserID"]);
else
return Guid.Empty;
}
}
protected void Page_Load(object sender, EventArgs e)
{
if (Access.IsAdminUser(Access.GetUserName(UserID)))
{
BTN_Save.Visible = false;
TBL_Libs.Visible = false;
LBL_Status.Text = "دسترسی کاربر کامل است";
}
else
{
initForm();
}
}
protected void initForm()
{
ProfileBase prof = ProfileCommon.Create(Access.GetUserName(UserID));
var q = Db.tblLibrary.Where(c => c.ID > 0);
foreach (var c in q)
{
int LibID = Convert.ToInt32(c.ID);
TableRow row = new TableRow();
AddTableCell(row, c.Title);
for (int i = 1; i <= 18; i++)
{
string var = LibID + "_u" + i.ToString();
AddTableCellControl(row, var, prof.GetPropertyValue("u" + i.ToString()).ToString(), LibID);
}
TBL_Libs.Rows.Add(row);
}
TBL_Libs.DataBind();
}
protected void AddTableCell(TableRow row, string Title)
{
TableCell c1 = new TableCell();
Label lbl = new Label { Text = Title };
c1.Controls.Add(lbl);
c1.HorizontalAlign = HorizontalAlign.Center;
row.Cells.Add(c1);
}
protected void AddTableCellControl(TableRow row, string controlID, string val, int LibID)
{
TableCell c1 = new TableCell();
CheckBox ch1 = new CheckBox { ID = controlID };
if (val.IndexOf("#" + LibID.ToString() + "#") > 0)
ch1.Checked = true;
c1.Controls.Add(ch1);
c1.HorizontalAlign = HorizontalAlign.Center;
row.Cells.Add(c1);
}
protected void BTN_Save_Click(object sender, EventArgs e)
{
ProfileBase prof = ProfileCommon.Create(Access.GetUserName(UserID));
for (int i = 1; i <= 18; i++)
{
prof.SetPropertyValue("u" + i.ToString(), "");
var q = Db.tblLibrary.Where(c => c.ID > 0);
foreach (var c in q)
{
int LibID = Convert.ToInt32(c.ID);
SaveToProfile(prof, "u" + i.ToString(), LibID);
}
}
prof.Save();
/*
foreach (var c in q)
{
int LibID = Convert.ToInt32(c.ID);
for (int i = 1; i <= 18; i++)
SaveToProfile(prof, "u" + i.ToString(), LibID);
prof.Save();
}*/
ScriptManager.RegisterStartupScript(this, this.GetType(), "mykey", "CloseAndRebind();", true);
}
protected void SaveToProfile(ProfileBase prof, string var, int LibID)
{
CheckBox ch1 = (Page.FindControl(LibID + "_" + var) as CheckBox);
string val = ch1.Checked ? " #" + LibID + "# " : "";
prof.SetPropertyValue(var, prof.GetPropertyValue(var).ToString() + val);
}
} |
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
using System.Collections.Generic;
public class RealAngusController : MonoBehaviour {
public GameObject realAngusElementButtonPrototype;
public GameObject parentScreen;
public RealAngusTextWidget realAngusTextWidget;
public RealAngusSelectedButtonParent realAngusSelectedButtonParent;
public Transform buttonContainer;
public GameObject tipDialogPrototype;
public int numColumns = 2;
public float buttonRotationDeg = 5f;
public float buttonWigglePixX = 10f;
public float buttonWigglePixY = 100f;
public float buttonPanelTopMargin;
public float buttonPanelBottomMargin;
public float buttonPanelSideMargin;
bool registeredForEvents;
int numRows;
RectTransform parentScreenRectTransform;
RealAngusElementButton selectedButton;
Vector2 selectedButtonLocation;
float selectedButtonScale;
public float selectedButtonTopMargin = 50f;
public float textWidgetOverlap = 10f;
float buttonPanelWidth;
float buttonPanelHeight;
List<RealAngusElementButton> buttons;
float columnWidth;
float rowHeight;
Vector2 textWidgetLocation;
Vector2 textWidgetOffscreenLocation;
public float textToButtonXRatio = 0.9f;
public float textToButtonYRatio = 1.1f;
float screenWidth;
float screenHeight;
void Awake() {
parentScreenRectTransform = parentScreen.GetComponent<RectTransform> ();
}
// Use this for initialization
void Start () {
RegisterForEvents ();
CalculateLayoutNumbers ();
LayoutDisplayElements ();
}
void OnDestroy() {
UnregisterForEvents ();
}
void RegisterForEvents() {
if (registeredForEvents) {
return;
}
registeredForEvents = true;
RealAngusData.instance.RealAngusDataChanged +=
new RealAngusData.RealAngusDataChangedEventHandler (OnRealAngusDataChanged);
GamePhaseState.instance.GamePhaseChanged +=
new GamePhaseState.GamePhaseChangedEventHandler (OnGamePhaseChanged);
}
void UnregisterForEvents() {
if (registeredForEvents) {
RealAngusData.instance.RealAngusDataChanged -=
new RealAngusData.RealAngusDataChangedEventHandler (OnRealAngusDataChanged);
GamePhaseState.instance.GamePhaseChanged -=
new GamePhaseState.GamePhaseChangedEventHandler (OnGamePhaseChanged);
}
}
void OnRealAngusDataChanged() {
LayoutDisplayElements ();
}
void OnGamePhaseChanged() {
if (GamePhaseState.instance.gamePhase != GamePhaseState.GamePhaseType.REAL_ANGUS) {
return;
}
if (buttons == null || buttons.Count == 0) {
return;
}
for (int i = 0; i < buttons.Count; i++) {
RealAngusElementButton button = buttons[i];
button.OnFirstDisplayed();
button.transform.SetParent (buttonContainer, false);
button.SetSelected(false, true);
}
selectedButton = null;
realAngusSelectedButtonParent.gameObject.SetActive (false);
realAngusTextWidget.transform.localPosition = new Vector2 (0, -2000);
}
void CalculateLayoutNumbers() {
screenWidth = parentScreenRectTransform.rect.width;
screenHeight = parentScreenRectTransform.rect.height;
buttonPanelWidth = screenWidth - 2 * buttonPanelSideMargin;
buttonPanelHeight = screenHeight - buttonPanelTopMargin - buttonPanelBottomMargin;
float selectedButtonWidth = buttonPanelWidth;
selectedButtonScale = selectedButtonWidth / TweakableParams.realAngusElementButtonWidth;
float scaledFrameSize = selectedButtonScale * TweakableParams.realAngusElementButtonFrameWidth;
float selectedImageWidth = selectedButtonWidth - 2 * scaledFrameSize;
float selectedImageHeight = selectedImageWidth / TweakableParams.realAngusImageAspectRatio;
float selectedButtonHeight = selectedImageHeight + 2 * scaledFrameSize;
float textWidgetWidth = selectedButtonWidth * textToButtonXRatio;
float textWidgetHeight = selectedButtonHeight * textToButtonYRatio;
float selectedButtonX = screenWidth / 2;
float selectedButtonY;
float textWidgetX = screenWidth / 2;
float textWidgetY;
if (selectedButtonHeight * 2 > screenHeight) {
selectedButtonY = screenHeight - selectedButtonHeight / 2 - selectedButtonTopMargin;
} else {
selectedButtonY = screenHeight / 2 + selectedButtonHeight/2;
}
textWidgetY = selectedButtonY - selectedButtonHeight / 2 - textWidgetHeight / 2 + textWidgetOverlap;
selectedButtonX -= screenWidth / 2;
selectedButtonY -= screenHeight / 2;
textWidgetX -= screenWidth / 2;
textWidgetY -= screenHeight / 2;
selectedButtonLocation = new Vector2 (selectedButtonX, selectedButtonY);
textWidgetLocation = new Vector2 (textWidgetX, textWidgetY);
textWidgetOffscreenLocation = new Vector2 (textWidgetX, -screenHeight/2 - textWidgetHeight);
realAngusTextWidget.ConfigureLayout (textWidgetWidth, textWidgetHeight,
textWidgetLocation, textWidgetOffscreenLocation);
}
void LayoutDisplayElements() {
if (buttons != null) {
return;
}
List<RealAngusItemDesc> realAngusItemDescs = RealAngusData.instance.GetRealAngusItemDescs ();
if (realAngusItemDescs == null || realAngusItemDescs.Count == 0) {
return;
}
numRows = 1 + (realAngusItemDescs.Count - 1)/ numColumns;
buttons = new List<RealAngusElementButton>();
columnWidth = buttonPanelWidth/ numColumns;
rowHeight = buttonPanelHeight / numRows;
Random.seed = 141234;
for (int i = 0; i < realAngusItemDescs.Count; i++) {
RealAngusItemDesc raid = realAngusItemDescs[i];
GameObject realAngusElementButtonGameObject =
Instantiate (realAngusElementButtonPrototype,
new Vector3(0, 0, 0),
Quaternion.identity) as GameObject;
RealAngusElementButton button = realAngusElementButtonGameObject.GetComponent<RealAngusElementButton>();
buttons.Add (button);
button.transform.SetParent (buttonContainer, false);
button.SetHomeTransform(GetNthPosition (i),
Random.Range (-buttonRotationDeg, buttonRotationDeg));
button.SetSelectedTransform(selectedButtonLocation, 0, selectedButtonScale);
button.Configure(raid);
button.SetClickHandler(OnButtonClicked);
button.SetTransitionCompleteHandler(OnSelectionTransitionCompleted);
}
}
void OnButtonClicked(RealAngusElementButton button) {
if (selectedButton) {
DeselectSelectedButton();
} else {
if (button.raid.unlocked) {
SelectButton (button);
} else {
CueToPlayMore ();
}
}
}
public void DeselectSelectedButton() {
if (selectedButton == null) {
return;
}
selectedButton.SetSelected (false);
selectedButton = null;
realAngusSelectedButtonParent.StartVisibilityTransition (false);
realAngusTextWidget.TransitionOut ();
}
void CueToPlayMore() {
int numUnlocked = RealAngusData.instance.CountUnlockedItemDescs ();
int levelForNextUnlock = LevelConfig.instance.LevelForRealAngusUnlocks (numUnlocked + 1);
string message = "Get to level " + levelForNextUnlock + " to unlock a new random tidbit about Angus!";
GameObject tipDialogGameObject = Instantiate (tipDialogPrototype,
new Vector3 (0, 0, 0),
Quaternion.identity) as GameObject;
TipDialog td = tipDialogGameObject.GetComponent<TipDialog> ();
td.ConfigureDialog (message);
DialogController.instance.ShowDialog (td);
}
void SelectButton (RealAngusElementButton button)
{
selectedButton = button;
selectedButton.SetSelected (true);
realAngusSelectedButtonParent.StartVisibilityTransition (true);
realAngusTextWidget.TransitionIn (selectedButton.raid);
selectedButton.transform.SetParent (realAngusSelectedButtonParent.transform,
false);
SFXPlayer.instance.Play (SFXPlayer.SFXType.CAMERA);
}
void OnSelectionTransitionCompleted(RealAngusElementButton button) {
if (!button.IsSelected()) {
button.transform.SetParent(buttonContainer, false);
}
}
Vector2 GetNthPosition(int n) {
int row = n / numColumns;
int column = n % numColumns;
float x = (column + 0.5f) * columnWidth;
float y = (row + 0.5f) * rowHeight;
y = buttonPanelHeight - y;
x += buttonPanelSideMargin;
y += buttonPanelBottomMargin;
x -= screenWidth / 2;
y -= screenHeight / 2;
float [] yOffsets = {
0.07f, -0.1f, 0.1f,
0.03f, 0, 0.12f,
0.06f, -0.12f, 0.07f,
0.1f, -0.1f, 0.05f,
};
y += rowHeight * yOffsets [n % yOffsets.Length];
x += Random.Range (-buttonWigglePixX, buttonWigglePixX);
return new Vector2 (x, y);
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class RotateHeal : MonoBehaviour
{
void FixedUpdate()
{
transform.Rotate(new Vector3(0, 100, 0) * Time.fixedDeltaTime);
}
}
|
using System.Collections.Generic;
using WebsiteManagerPanel.Data.Entities.Base;
namespace WebsiteManagerPanel.Data.Entities
{
//Her bir sayfaya, yani Controller’a karşılık gelen yetki tablosudur.
public partial class RoleGroup:Entity
{
public string GroupName { get; set; }
public bool IsActive { get; set; }
public virtual ICollection<Role> Roles { get; set; }
public virtual ICollection<UserRole> UserRoles { get; set; }
protected RoleGroup()
{
UserRoles = new List<UserRole>();
Roles = new List<Role>();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CheckAvability.Common
{
public class Configuration : IConfiguration
{
private string baseUrl { get; set; } = "https://reserve-hk.apple.com/HK/en_HK/";
//private string storesUrl { get; set; } = "https://reserve-hk.apple.com/HK/en_HK/reserve/iPhone/stores.json";
//private string availabilityUrl { get; set; } = "https://reserve-hk.apple.com/HK/en_HK/reserve/iPhone/availability.json";
private string storesUrl { get; set; } = "reserve/iPhone/stores.json";
private string availabilityUrl { get; set; } = "reserve/iPhone/availability.json";
private string LoginBaseUrl { get; set; } = "https://appleid.apple.com/";
private string LoginUrl { get; set; } = "#!&page=signin";
private string LoginPostBaseUrl { get; set; } = "https://idmsa.apple.com/";
private string LoginPostUrl { get; set; } = "appleauth/auth/signin";
public Configuration()
{
}
public string GetLoginPostBaseUrl()
{
return this.LoginPostBaseUrl;
}
public string GetLoginPostUrl()
{
return this.LoginPostUrl;
}
public string GetLoginBaseUrl()
{
return LoginBaseUrl;
}
public string GetLoginUrl()
{
return LoginUrl;
}
public string GetBaseUrl()
{
return baseUrl;
}
public string GetStoreUrl ()
{
//return string.Format("{0}{1}", baseUrl, storesUrl);
return storesUrl;
}
public string GetAvailabilityUrl()
{
//return string.Format("{0}{1}", baseUrl, availabilityUrl);
return availabilityUrl;
}
}
}
|
using UnityEngine;
using System.Collections;
[RequireComponent( typeof ( Rigidbody ) )]
public abstract class Ship : TNBehaviour {
//Madatory check for if a player is on this ship
//public abstract bool ContainsPlayer( TNet.Player check );
//A list of enemy ships this ship can see
protected TNet.List<GameObject> trackingList = new TNet.List<GameObject>();
#region Cache
private Transform _transform;
public new Transform transform{
get{
return _transform;
}
}
private Rigidbody _rigidBody;
public new Rigidbody rigidbody {
get {
return _rigidBody;
}
}
protected virtual void Awake() {
_transform = base.transform;
_rigidBody = GetComponent<Rigidbody>();
}
#endregion Cache
#region Ship Movement
[SerializeField, Group("Movement")]
protected float maxSpeed = 20f;
[SerializeField, Group("Movement")]
protected float maxBurstSpeed = 45f;
[SerializeField, Group("Movement")]
protected float forwardAcceleration, backwardAcceleration, sideAcceleration, verticalAcceration;
#endregion
}
|
namespace Docller.Core.Models
{
public abstract class FileBase : BlobBase
{
public string Title { get; set; }
public string DocNumber { get; set; }
public string Revision { get; set; }
public string Notes { get; set; }
public string Status { get; set; }
public long StatusId { get; set; }
}
} |
using System;
using System.Globalization;
namespace NStandard
{
public static class DateTimeEx
{
/// <summary>
/// Gets the DateTime(UTC) of UnixMinValue.
/// </summary>
/// <returns></returns>
public static readonly DateTime UnixMinValue = new(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
/// <summary>
/// Converts a Unix time expressed as the number of milliseconds that have elapsed
/// since 1970-01-01T00:00:00Z to a <see cref="DateTime"/> value.
/// </summary>
/// <param name="milliseconds"></param>
/// <returns></returns>
public static DateTime FromUnixTimeMilliseconds(long milliseconds) => new(DateTimeOffsetEx.FromUnixTimeMilliseconds(milliseconds).Ticks, DateTimeKind.Utc);
/// <summary>
/// Converts a Unix time expressed as the number of seconds that have elapsed since
/// 1970-01-01T00:00:00Z to a <see cref="DateTime"/> value.
/// </summary>
/// <param name="seconds"></param>
/// <returns></returns>
public static DateTime FromUnixTimeSeconds(long seconds) => new(DateTimeOffsetEx.FromUnixTimeSeconds(seconds).Ticks, DateTimeKind.Utc);
/// <summary>
/// The number of complete years in the period. [ Similar as DATEDIF(*, *, "Y") function in Excel. ]
/// </summary>
/// <param name="start"></param>
/// <param name="end"></param>
/// <returns></returns>
public static int Years(DateTime start, DateTime end)
{
if (start.Kind != DateTimeKind.Unspecified && end.Kind != DateTimeKind.Unspecified && start.Kind != end.Kind)
throw new ArgumentException($"The kind of {nameof(start)} and {nameof(end)} must be the same.");
var offset = end.Year - start.Year;
var target = DateTimeExtensions.AddYears(start, offset);
if (end >= start) return end >= target ? offset : offset - 1;
else return end <= target ? offset : offset + 1;
}
/// <summary>
/// The number of complete months in the period, similar as DATEDIF(*, *, "M") function in Excel, but more accurate.
/// </summary>
/// <param name="start"></param>
/// <param name="end"></param>
/// <returns></returns>
public static int Months(DateTime start, DateTime end)
{
if (start.Kind != DateTimeKind.Unspecified && end.Kind != DateTimeKind.Unspecified && start.Kind != end.Kind)
throw new ArgumentException($"The kind of {nameof(start)} and {nameof(end)} must be the same.");
var offset = (end.Year - start.Year) * 12 + end.Month - start.Month;
var target = DateTimeExtensions.AddMonths(start, offset);
if (end >= start) return end >= target ? offset : offset - 1;
else return end <= target ? offset : offset + 1;
}
/// <summary>
/// The number of complete years in the period, expressed in whole and fractional year. [ Similar as DATEDIF(*, *, "Y") function in Excel. ]
/// </summary>
/// <param name="start"></param>
/// <param name="end"></param>
/// <returns></returns>
public static double TotalYears(DateTime start, DateTime end)
{
var integer = Years(start, end);
var targetStart = DateTimeExtensions.AddYears(start, integer);
if (end >= start)
{
var targetEnd = DateTimeExtensions.AddYears(start, integer + 1);
var fractional = (end - targetStart).TotalDays / (targetEnd - targetStart).TotalDays;
return integer + fractional;
}
else
{
var targetEnd = DateTimeExtensions.AddYears(start, integer - 1);
var fractional = (targetStart - end).TotalDays / (targetStart - targetEnd).TotalDays;
return integer - fractional;
}
}
/// <summary>
/// The number of complete months in the period, expressed in whole and fractional month. [ similar as DATEDIF(*, *, "M") function in Excel. ]
/// </summary>
/// <param name="start"></param>
/// <param name="end"></param>
/// <returns></returns>
public static double TotalMonths(DateTime start, DateTime end)
{
var integer = Months(start, end);
var targetStart = DateTimeExtensions.AddMonths(start, integer);
if (end >= start)
{
var targetEnd = DateTimeExtensions.AddMonths(start, integer + 1);
var fractional = (end - targetStart).TotalDays / (targetEnd - targetStart).TotalDays;
return integer + fractional;
}
else
{
var targetEnd = DateTimeExtensions.AddMonths(start, integer - 1);
var fractional = (targetStart - end).TotalDays / (targetStart - targetEnd).TotalDays;
return integer - fractional;
}
}
/// <summary>
/// Gets a DateTime for the specified week of year.
/// </summary>
/// <param name="year"></param>
/// <param name="week"></param>
/// <param name="kind"></param>
/// <param name="weekStart"></param>
/// <returns></returns>
public static DateTime ParseFromWeek(int year, int week, DateTimeKind kind, DayOfWeek weekStart = DayOfWeek.Sunday)
{
var day1 = new DateTime(year, 1, 1, 0, 0, 0, kind);
var week0 = DateTimeExtensions.PastDay(day1, weekStart, true);
if (week0.Year == year) week0 = week0.AddDays(-7);
return week0.AddDays(week * 7);
}
/// <summary>
/// Converts the specified string representation of a date and time to its System.DateTime
/// equivalent using the specified format and culture-specific format information.
/// The format of the string representation must match the specified format exactly.
/// </summary>
/// <param name="s"></param>
/// <param name="format"></param>
/// <returns></returns>
public static DateTime ParseExact(string s, string format)
{
return DateTime.ParseExact(s, format, CultureInfo.CurrentCulture);
}
/// <summary>
/// Converts the specified string representation of a date and time to its System.DateTime
/// equivalent using the specified format, culture-specific format information, and
/// style. The format of the string representation must match the specified format
/// exactly. The method returns a value that indicates whether the conversion succeeded.
/// </summary>
/// <param name="s"></param>
/// <param name="format"></param>
/// <param name="result"></param>
/// <returns></returns>
public static bool TryParseExact(string s, string format, out DateTime result)
{
return DateTime.TryParseExact(s, format, CultureInfo.CurrentCulture, DateTimeStyles.None, out result);
}
/// <summary>
/// Returns the number of days in the specified month and year.
/// If the specified year is a leap year, return 366, else return 365.
/// </summary>
/// <param name="year"></param>
/// <returns></returns>
public static int DaysInYear(int year) => DateTime.IsLeapYear(year) ? 366 : 365;
}
}
|
using System.Collections.Generic;
using Breeze.AssetTypes.DataBoundTypes;
using Breeze.Helpers;
using Breeze.Screens;
using Breeze.Services.InputService;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
namespace Breeze.AssetTypes
{
public class SinglePixelLineAsset : KeyedAsset
{
public Color Color { get; set; }
public Vector2 StartPositon { get; set; }
public Vector2 EndPositon { get; set; }
public int BrushSize { get; set; } = 1;
public SinglePixelLineAsset()
{
}
public SinglePixelLineAsset(Color color, Vector2 start, Vector2 end, int brushSize = 1)
{
Color = color;
StartPositon = start;
EndPositon = end;
BrushSize = brushSize;
}
public override void Draw(BaseScreen.Resources screenResources, SmartSpriteBatch spriteBatch, ScreenAbstractor screen, float opacity, FloatRectangle? clip = null, Texture2D bgTexture = null, Vector2? scrollOffset = null)
{
if (Solids.Instance.InputService.IsPressed(InputService.ShiftKeys.LeftShift1))
{
// return;
}
Vector2 sp = new Vector2(StartPositon.X, StartPositon.Y).Move(scrollOffset);
Vector2 ep = new Vector2(EndPositon.X, EndPositon.Y).Move(scrollOffset);
if (clip != null && sp.X < clip.Value.X) sp.X = clip.Value.X;
if (clip != null && sp.X > clip.Value.BottomRight.X) sp.X = clip.Value.BottomRight.X;
if (clip != null && ep.X < clip.Value.X) ep.X = clip.Value.X;
if (clip != null && ep.X > clip.Value.BottomRight.X) ep.X = clip.Value.BottomRight.X;
if (clip != null && sp.Y < clip.Value.Y) sp.Y = clip.Value.Y;
if (clip != null && sp.Y > clip.Value.BottomRight.Y) sp.Y = clip.Value.BottomRight.Y;
if (clip != null && ep.Y < clip.Value.Y) ep.Y = clip.Value.Y;
if (clip != null && ep.Y > clip.Value.BottomRight.Y) ep.Y = clip.Value.BottomRight.Y;
Vector2 start = screen.Translate(sp);
Vector2 end = screen.Translate(ep);
FloatRectangle? tclip = screen.Translate(clip);
if (tclip.HasValue)
{
if ((start.X < tclip.Value.X && end.X < tclip.Value.X) || (start.X > tclip.Value.Right && end.X > tclip.Value.Right))
{
return;
}
}
spriteBatch.DrawLine(new Vector2(start.X, start.Y), new Vector2(end.X, end.Y), Color, null, BrushSize);
}
internal void Update(SinglePixelLineAsset singlePixelLineAsset)
{
this.StartPositon = singlePixelLineAsset.StartPositon;
this.EndPositon = singlePixelLineAsset.EndPositon;
}
}
public class LineListAsset : KeyedAsset
{
public List<SmartSpriteBatch.Line> Lines { get; set; }
public LineListAsset(List<SmartSpriteBatch.Line> lines)
{
Lines = lines;
}
public override void Draw(BaseScreen.Resources screenResources, SmartSpriteBatch spriteBatch, ScreenAbstractor screen, float opacity, FloatRectangle? clip = null, Texture2D bgTexture = null, Vector2? scrollOffset = null)
{
spriteBatch.DrawLines(TranslateLines(Lines, screen, opacity, scrollOffset), screen.Translate(clip));
}
internal void Update(LineListAsset singlePixelLineAsset)
{
this.Lines = singlePixelLineAsset.Lines;
}
List<SmartSpriteBatch.Line> TranslateLines(List<SmartSpriteBatch.Line> lines, ScreenAbstractor screen, float opacity, Vector2? scrollOffset = null)
{
List<SmartSpriteBatch.Line> result = new List<SmartSpriteBatch.Line>();
foreach (SmartSpriteBatch.Line line in lines)
{
result.Add(new SmartSpriteBatch.Line(screen.Translate(line.Start.Move(scrollOffset)), screen.Translate(line.End.Move(scrollOffset)), line.Color * opacity, line.BrushSize));
}
return result;
}
}
}
|
using gView.DataSources.VectorTileCache;
using gView.Framework.Data;
using gView.Framework.IO;
using gView.Framework.system.UI;
using gView.Framework.UI;
using gView.Win.DataSources.VectorTileCache.UI.Explorer.Dialogs;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace gView.Win.DataSources.VectorTileCache.UI.Explorer
{
[gView.Framework.system.RegisterPlugIn("9F64AC86-4FE0-4E34-85C5-23BFF2DB42D2")]
public class VectorTileCacheDatasetExplorerObject : ExplorerParentObject, IExplorerSimpleObject, IExplorerObjectDeletable, IExplorerObjectRenamable, ISerializableExplorerObject, IExplorerObjectContextMenu
{
private IExplorerIcon _icon = new Icons.VectorTileCacheDatasetIcon();
private string _name = String.Empty, _connectionString = String.Empty;
private ToolStripItem[] _contextItems = null;
private Dataset _dataset = null;
public VectorTileCacheDatasetExplorerObject()
: base(null, typeof(Dataset), 0) { }
public VectorTileCacheDatasetExplorerObject(IExplorerObject parent, string name, string connectionString)
: base(parent, typeof(Dataset), 0)
{
_name = name;
_connectionString = connectionString;
List<ToolStripMenuItem> items = new List<ToolStripMenuItem>();
ToolStripMenuItem item = new ToolStripMenuItem("Connection Properties...");
item.Click += new EventHandler(ConnectionProperties_Click);
items.Add(item);
_contextItems = items.ToArray();
}
void ConnectionProperties_Click(object sender, EventArgs e)
{
var dlg = new FormVectorTileCacheConnection();
dlg.ConnectionString = _connectionString;
if (dlg.ShowDialog() == DialogResult.OK)
{
ConfigConnections connStream = new ConfigConnections("VectorTileCache", "b9d6ae5b-9ca1-4a52-890f-caa4009784d4");
connStream.Add(_name, this.ConnectionString = dlg.ConnectionString);
}
}
internal string ConnectionString
{
get
{
return _connectionString;
}
set
{
_connectionString = value;
_dataset = null;
}
}
#region IExplorerObject Members
public string Name
{
get
{
return _name;
}
}
public string FullName
{
get
{
return @"TileCache\" + _name;
}
}
public string Type
{
get { return "Vector Tile Cache Dataset"; }
}
public IExplorerIcon Icon
{
get
{
return _icon;
}
}
new public void Dispose()
{
base.Dispose();
}
async public Task<object> GetInstanceAsync()
{
if (_dataset == null)
{
_dataset = new Dataset();
if (await _dataset.SetConnectionString(_connectionString) && await _dataset.Open())
{
return _dataset;
}
}
return _dataset;
}
#endregion
#region IExplorerParentObject Members
async public override Task<bool> Refresh()
{
await base.Refresh();
try
{
Dataset dataset = new Dataset();
await dataset.SetConnectionString(_connectionString);
await dataset.Open();
var elements = await dataset.Elements();
if (elements != null)
{
foreach (IDatasetElement element in elements)
{
if (element.Class is IFeatureClass)
{
base.AddChildObject(new VectorTileCacheLayerExplorerObject(this, element));
}
}
}
return true;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Exception", MessageBoxButtons.OK, MessageBoxIcon.Error);
return false;
}
}
#endregion
#region ISerializableExplorerObject Member
async public Task<IExplorerObject> CreateInstanceByFullName(string FullName, ISerializableExplorerObjectCache cache)
{
if (cache.Contains(FullName))
{
return cache[FullName];
}
VectorTileCacheGroupExplorerObject group = new VectorTileCacheGroupExplorerObject();
if (FullName.IndexOf(group.FullName) != 0 || FullName.Length < group.FullName.Length + 2)
{
return null;
}
group = (VectorTileCacheGroupExplorerObject)((cache.Contains(group.FullName)) ? cache[group.FullName] : group);
var childObjects = await group.ChildObjects();
if (childObjects != null)
{
foreach (IExplorerObject exObject in childObjects)
{
if (exObject.FullName == FullName)
{
cache.Append(exObject);
return exObject;
}
}
}
return null;
}
#endregion
#region IExplorerObjectDeletable Member
public event ExplorerObjectDeletedEvent ExplorerObjectDeleted = null;
public Task<bool> DeleteExplorerObject(ExplorerObjectEventArgs e)
{
ConfigConnections stream = new ConfigConnections("VectorTileCache", "b9d6ae5b-9ca1-4a52-890f-caa4009784d4");
stream.Remove(_name);
if (ExplorerObjectDeleted != null)
{
ExplorerObjectDeleted(this);
}
return Task.FromResult(true);
}
#endregion
#region IExplorerObjectRenamable Member
public event ExplorerObjectRenamedEvent ExplorerObjectRenamed = null;
public Task<bool> RenameExplorerObject(string newName)
{
bool ret = false;
ConfigConnections stream = new ConfigConnections("VectorTileCache", "b9d6ae5b-9ca1-4a52-890f-caa4009784d4");
ret = stream.Rename(_name, newName);
if (ret == true)
{
_name = newName;
if (ExplorerObjectRenamed != null)
{
ExplorerObjectRenamed(this);
}
}
return Task.FromResult(ret);
}
#endregion
#region IExplorerObjectContextMenu Member
public ToolStripItem[] ContextMenuItems
{
get { return _contextItems; }
}
#endregion
}
}
|
using System;
namespace CryptoLab.Infrastructure.Commands.Auth
{
public interface IAuthCommand : ICommand
{
Guid UserId { get; set; }
}
} |
using Microsoft.VisualStudio.TestTools.UnitTesting;
using EditGraph;
namespace GraphUnitTest
{
[TestClass]
public class EditCraphTest
{
[TestMethod]
public void TestAddVertex()
{
GraphWirth a = new GraphWirth();
bool expected = true;
bool actual = a.AddVertex(15);
Assert.AreEqual(expected, actual, "Error adding vertex.");
}
[TestMethod]
public void TestAddVertex_WithExistingID()
{
GraphWirth a = new GraphWirth();
bool expected = false;
a.AddVertex(15);
bool actual = a.AddVertex(15);
Assert.AreEqual(expected, actual, "Vertex with this key is already exists.");
}
[TestMethod]
public void TestDeleteVertex()
{
GraphWirth a = new GraphWirth();
bool expected = true;
a.AddVertex(15, 20);
a.AddVertex(20);
bool actual = a.DeleteVertex(15);
Assert.AreEqual(expected, actual, "Unable to delete vertex.");
}
[TestMethod]
public void TestDeleteVertex_NotExistant()
{
GraphWirth a = new GraphWirth();
bool expected = false;
bool actual = a.DeleteVertex(15);
Assert.AreEqual(expected, actual, "Non-existant vertex can not be deleated.");
}
[TestMethod]
public void TestDeleteVertex_LastVertex()
{
GraphWirth a = new GraphWirth();
bool expected = true;
a.AddVertex(10);
a.AddVertex(100);
a.AddVertex(15, 1000);
bool actual = a.DeleteVertex(15);
Assert.AreEqual(expected, actual, "Error deleting last vertex.");
}
[TestMethod]
public void TestDeleteVertex_LastOfTwo()
{
GraphWirth a = new GraphWirth();
bool expected = true;
a.AddVertex(15, 1000);
bool actual = a.DeleteVertex(15);
Assert.AreEqual(expected, actual, "Error deleting last of two vertexes.");
}
[TestMethod]
public void TestDeleteVertex_FirstOfMany()
{
GraphWirth a = new GraphWirth();
bool expected = true;
a.AddVertex(10);
a.AddVertex(100);
a.AddVertex(1000);
bool actual = a.DeleteVertex(1);
Assert.AreEqual(expected, actual, "Error deleting first vertex.");
}
[TestMethod]
public void TestAddDirectEdge()
{
GraphWirth a = new GraphWirth();
bool expected = true;
a.AddVertex(0);
bool actual = a.AddDirectEdge(1, 2, 0);
Assert.AreEqual(expected, actual, "Error adding direct edge.");
}
[TestMethod]
public void TestAddUndirectEdge()
{
GraphWirth a = new GraphWirth();
bool expected = true;
a.AddVertex(0);
bool actual = a.AddUndirectEdge(1, 2, 0);
Assert.AreEqual(expected, actual, "Error adding undirect edge.");
}
[TestMethod]
public void TestDeleteDirectEdge_FromTo()
{
GraphWirth a = new GraphWirth();
bool expected = true;
a.AddVertex(0);
a.AddDirectEdge(1, 2, 0);
bool actual = a.DeleteDirectEdge(1, 2);
Assert.AreEqual(expected, actual, "Error deleting direct edge.");
}
[TestMethod]
public void TestDeleteDirectEdge_ToFrom()
{
GraphWirth a = new GraphWirth();
bool expected = false;
a.AddVertex(0);
a.AddDirectEdge(1, 2, 0);
bool actual = a.DeleteDirectEdge(2, 1);
Assert.AreEqual(expected, actual, "Incorrect order of vertexes while deleting direct edge.");
}
[TestMethod]
public void TestDeleteUndirectEdge_FromTo()
{
GraphWirth a = new GraphWirth();
bool expected = true;
a.AddVertex(0);
a.AddUndirectEdge(1, 2, 0);
bool actual = a.DeleteUndirectEdge(1, 2);
Assert.AreEqual(expected, actual, "Error deleting undirect edge.");
}
[TestMethod]
public void TestDeleteUndirectEdge_ToFrom()
{
GraphWirth a = new GraphWirth();
bool expected = true;
a.AddVertex(0);
a.AddDirectEdge(1, 2, 0);
bool actual = a.DeleteDirectEdge(2, 1);
Assert.AreEqual(expected, actual, "Error deleting undirect edge.");
}
}
}
|
using System;
namespace CursoCsharp.ClassesEMetodos
{
class DesafioAcessarAtributo
{
int a = 10;
public static void Executar()
{
//Acessar a variavel "a" dentro do metodo executar!
//Console.WriteLine(a);
// vou acessar a instancia DesafioAcessarAtributo para ter acessi no meu static Executar
DesafioAcessarAtributo desafio = new DesafioAcessarAtributo();
Console.WriteLine(desafio.a);
// ou poderia mudar no DesafioAcessarAtributo ( static int a = 10 ) e teria o acesso via static
}
}
}
|
using UnityEngine;
using System.Collections;
public class CameraFollow : MonoBehaviour
{
private Entity target;
public Camera cameraComponent;
private int baseCullingMask;
private void Start()
{
cameraComponent = GetComponent<Camera>();
baseCullingMask = cameraComponent.cullingMask;
EventHub.PlayerChangeStory += PlayerChangeFloor;
}
void Update()
{
if (target)
{
transform.position = new Vector3(target.transform.position.x, target.transform.position.y, transform.position.z);
}
}
public void SetTarget(Entity target)
{
this.target = target;
UpdateCullingMask();
}
private void UpdateCullingMask()
{
cameraComponent.cullingMask = baseCullingMask + (1 << (int)Layering.StoryToPhysicsLayer(target.storyLocation));
}
private void PlayerChangeFloor(PlayerCharacter playerCharacter)
{
if (playerCharacter == target)
{
UpdateCullingMask();
}
}
} |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace tr
{
public partial class menu : Form
{
game1 game1 = new game1();
game2 game = new game2();
public menu()
{
InitializeComponent();
}
private void game2_Click(object sender, EventArgs e)
{
game.Show();
this.Hide();
}
private void game1_Click(object sender, EventArgs e)
{
game1.Show();
this.Hide();
game1.startTimer.Enabled = true;
}
private void button3_Click(object sender, EventArgs e)
{
Application.Exit();
}
}
}
|
using System;
using System.Collections;
using System.Linq;
using UnityEngine;
using VRUI;
using SongLoaderPlugin;
using NLog;
using SongLoaderPlugin.OverrideClasses;
namespace TwitchIntegrationPlugin.UI
{
public class LevelRequestFlowCoordinator : FlowCoordinator
{
private MenuSceneSetupData _menuSceneSetupData;
private MainGameSceneSetupData _mainGameSceneSetupData;
private ResultsFlowCoordinator _resultsFlowCoordinator;
private LevelRequestNavigationController _levelRequestNavigationController;
private RequestInfoViewController _requestInfoViewController;
private StandardLevelDifficultyViewController _levelDifficultyViewController;
private StandardLevelDetailViewController _levelDetailViewController;
private TwitchIntegrationUi _ui;
private QueuedSong _song;
private CustomLevel _customLevel;
private NLog.Logger _logger;
private bool _initialized;
public event Action DidFinishEvent;
public void Present(VRUIViewController parentViewController, bool fromDebug)
{
_ui = TwitchIntegrationUi.Instance;
_logger = LogManager.GetCurrentClassLogger();
try
{
_menuSceneSetupData = Resources.FindObjectsOfTypeAll<MenuSceneSetupData>().First();
_mainGameSceneSetupData = Resources.FindObjectsOfTypeAll<MainGameSceneSetupData>().First();
_resultsFlowCoordinator = Resources.FindObjectsOfTypeAll<ResultsFlowCoordinator>().First();
if (_levelRequestNavigationController == null)
{
_levelRequestNavigationController =
_ui.CreateViewController<LevelRequestNavigationController>("LevelRequestNavController");
}
if (_requestInfoViewController == null)
{
_requestInfoViewController = _ui.CreateViewController<RequestInfoViewController>("RequestInfo");
_requestInfoViewController.rectTransform.anchorMin = new Vector2(0.3f, 0f);
_requestInfoViewController.rectTransform.anchorMax = new Vector2(0.7f, 1f);
}
_levelDifficultyViewController =
Resources.FindObjectsOfTypeAll<StandardLevelDifficultyViewController>().First();
_levelDetailViewController =
Resources.FindObjectsOfTypeAll<StandardLevelDetailViewController>().First();
}
catch (Exception e)
{
_logger.Error("Unable to load UI components: " + e);
return;
}
if (!_initialized)
{
DidFinishEvent += Finish;
_levelRequestNavigationController.DidFinishEvent += HandleLevelRequestNavigationControllerDidfinish;
_levelDifficultyViewController.didSelectDifficultyEvent +=
HandleDifficultyViewControllerDidSelectDifficulty;
_levelDetailViewController.didPressPlayButtonEvent += HandleDetailViewControllerDidPressPlayButton;
_requestInfoViewController.DownloadButtonpressed += HandleDidPressDownloadButton;
_requestInfoViewController.SkipButtonPressed += HandleDidPressSkipButton;
_initialized = true;
}
//_levelRequestNavigationController.Init();
parentViewController.PresentModalViewController(_levelRequestNavigationController, null,
StaticData.DidStartFromQueue);
_requestInfoViewController.Init("Default Song Name", "Default User");
_levelRequestNavigationController.PushViewController(_requestInfoViewController, true);
if (!fromDebug) return; //Loading song preview arrests control from the results controller, causing it to display improperly.
CheckQueueAndUpdate();
}
private void Finish()
{
if (!_initialized) return;
DidFinishEvent -= Finish;
_levelRequestNavigationController.DidFinishEvent -= HandleLevelRequestNavigationControllerDidfinish;
_levelDifficultyViewController.didSelectDifficultyEvent -=
HandleDifficultyViewControllerDidSelectDifficulty;
_levelDetailViewController.didPressPlayButtonEvent -= HandleDetailViewControllerDidPressPlayButton;
_requestInfoViewController.DownloadButtonpressed -= HandleDidPressDownloadButton;
_requestInfoViewController.SkipButtonPressed -= HandleDidPressSkipButton;
_initialized = false;
}
private void HandleLevelRequestNavigationControllerDidfinish(LevelRequestNavigationController viewController)
{
viewController.DismissModalViewController(null);
DidFinishEvent?.Invoke();
}
private void HandleDifficultyViewControllerDidSelectDifficulty(
StandardLevelDifficultyViewController viewController,
IStandardLevelDifficultyBeatmap difficultyLevel)
{
if (!_levelDetailViewController.isInViewControllerHierarchy)
{
_levelDetailViewController.Init(
_customLevel.GetDifficultyLevel(_levelDifficultyViewController.selectedDifficultyLevel.difficulty),
GameplayMode.SoloStandard, StandardLevelDetailViewController.LeftPanelViewControllerType.HowToPlay);
_levelRequestNavigationController.PushViewController(_levelDetailViewController,
viewController.isRebuildingHierarchy);
}
else
_levelDetailViewController.SetContent(
_customLevel.GetDifficultyLevel(_levelDifficultyViewController.selectedDifficultyLevel.difficulty),
GameplayMode.SoloStandard);
}
private void HandleDetailViewControllerDidPressPlayButton(StandardLevelDetailViewController viewController)
{
StaticData.LastLevelCompletionResults = null;
StaticData.DidStartFromQueue = true;
StaticData.LastLevelPlayed = viewController.difficultyLevel;
StaticData.QueueList.RemoveAt(0);
Finish();
_mainGameSceneSetupData.Init(_levelDetailViewController.difficultyLevel, GameplayOptions.defaultOptions, GameplayMode.SoloStandard, 0f);
_mainGameSceneSetupData.didFinishEvent += HandleMainGameSceneDidFinish;
_mainGameSceneSetupData.TransitionToScene(0.7f);
}
private void HandleResultsFlowCoordinatorDidFinish()
{
_resultsFlowCoordinator.didFinishEvent -= HandleResultsFlowCoordinatorDidFinish;
CheckQueueAndUpdate();
_levelDetailViewController.RefreshContent();
}
private void HandleMainGameSceneDidFinish(MainGameSceneSetupData mainGameSceneSetupData, LevelCompletionResults levelCompletionResults)
{
StaticData.LastLevelCompletionResults = levelCompletionResults;
mainGameSceneSetupData.didFinishEvent -= HandleMainGameSceneDidFinish;
_menuSceneSetupData.TransitionToScene(0.7f);
}
private void HandleDidPressSkipButton()
{
_levelRequestNavigationController.ClearChildControllers();
_requestInfoViewController.Init("Default song", "Default Requestor");
_levelRequestNavigationController.PushViewController(_requestInfoViewController);
StaticData.QueueList.RemoveAt(0);
_song = (QueuedSong) StaticData.QueueList[0];
CheckQueueAndUpdate();
}
private void HandleDidPressDownloadButton()
{
StartCoroutine(_requestInfoViewController.DownloadSongCoroutine(_song));
}
public void CheckQueueAndUpdate()
{
if (StaticData.QueueList.Count <= 0) return;
_song = (QueuedSong) StaticData.QueueList[0];
_requestInfoViewController.SetQueuedSong(_song);
if (!_requestInfoViewController.DoesSongExist(_song))
{
_requestInfoViewController.SetDownloadButtonText("Download");
_requestInfoViewController.SetDownloadState(true);
return;
}
_requestInfoViewController.SetDownloadButtonText("Downloaded");
_requestInfoViewController.SetDownloadState(false);
_customLevel = SongLoader.CustomLevels.Find(x => x.levelID.Contains(_song.SongHash));
SongLoader.Instance.LoadAudioClipForLevel(_customLevel, (level) =>
{
try
{
var songPreviewPlayer = Resources.FindObjectsOfTypeAll<SongPreviewPlayer>().First();
songPreviewPlayer.CrossfadeTo(_customLevel.audioClip, _customLevel.previewStartTime,
_customLevel.previewDuration);
}
catch (Exception e)
{
_logger.Error("Unable to start song preview: " + e); // non critical
}
});
if (!_levelDifficultyViewController.isInViewControllerHierarchy)
{
_levelDifficultyViewController.Init(_customLevel.difficultyBeatmaps, false);
_levelRequestNavigationController.PushViewController(_levelDifficultyViewController);
}
else
_levelDifficultyViewController.SetDifficultyLevels(_customLevel.difficultyBeatmaps,
_levelDifficultyViewController.selectedDifficultyLevel);
}
public static void OnLoad(string levelName)
{
if (levelName != "Menu") return;
if (TwitchIntegrationUi.Instance.LevelRequestFlowCoordinator == null)
{
TwitchIntegrationUi.Instance.LevelRequestFlowCoordinator = new GameObject("Twitch Integration Coordinator").AddComponent<LevelRequestFlowCoordinator>();
}
FindObjectOfType<LevelRequestFlowCoordinator>().OnMenuLoaded();
}
private void OnMenuLoaded()
{
//_logger.Debug("Called");
if(_logger == null) _logger = LogManager.GetCurrentClassLogger();
StartCoroutine(StaticData.DidStartFromQueue ? WaitForMenu() : WaitForResults());
}
//This essentially rebuilds the UI Hiearchy without using a unity scene.
public IEnumerator WaitForMenu()
{
_logger.Debug("Starting wait");
yield return new WaitUntil(() => Resources.FindObjectsOfTypeAll<MainMenuViewController>().Any());
_logger.Debug("Wait over~");
VRUIViewController parent = FindObjectOfType<MainMenuViewController>();
try
{
if (FindObjectOfType<SoloModeSelectionViewController>() != null)
{
parent = FindObjectOfType<SoloModeSelectionViewController>();
_logger.Debug("Parent set");
}
}
catch (Exception e)
{
_logger.Error(e);
}
if (StaticData.QueueList.Count > 0 && StaticData.TwitchMode)
{
try
{
Present(parent, false);
// ReSharper disable once InvertIf
if (StaticData.LastLevelCompletionResults != null)
{
ShowResults(_levelRequestNavigationController);
}
}
catch (Exception ex)
{
_logger.Error("Failed to find MainMenuViewController: " + ex);
}
}
else
{
FindObjectOfType<StandardLevelSelectionFlowCoordinator>().Present(parent, FindObjectOfType<LevelCollectionsForGameplayModes>().GetLevels(GameplayMode.SoloStandard), GameplayMode.SoloStandard);
// ReSharper disable once InvertIf
if (StaticData.LastLevelCompletionResults != null)
{
_logger.Debug("Presenting Results");
ShowResults(FindObjectOfType<StandardLevelSelectionNavigationController>());
}
}
}
private void ShowResults(VRUIViewController parentViewController)
{
if (_resultsFlowCoordinator == null)
{
_resultsFlowCoordinator = Resources.FindObjectsOfTypeAll<ResultsFlowCoordinator>().First();
}
_resultsFlowCoordinator.didFinishEvent += HandleResultsFlowCoordinatorDidFinish;
_resultsFlowCoordinator.Present(parentViewController, StaticData.LastLevelCompletionResults, StaticData.LastLevelPlayed,
GameplayOptions.defaultOptions, GameplayMode.SoloStandard);
StaticData.LastLevelCompletionResults = null;
StartCoroutine(WaitForResults());
}
public IEnumerator WaitForResults()
{
if (!StaticData.TwitchMode || StaticData.QueueList.Count <= 0) yield break;
_logger.Debug("Waiting for contoller to init.");
yield return new WaitUntil(() => Resources.FindObjectsOfTypeAll<ResultsViewController>().Any());
var results = Resources.FindObjectsOfTypeAll<ResultsViewController>().First();
results.continueButtonPressedEvent += delegate(ResultsViewController viewController)
{
try
{
_logger.Debug("Results!");
viewController.DismissModalViewController(null, true);
StaticData.DidStartFromQueue = false;
FindObjectOfType<StandardLevelDetailViewController>().DismissModalViewController(null, true);
FindObjectOfType<StandardLevelDifficultyViewController>().DismissModalViewController(null, true);
FindObjectOfType<StandardLevelListViewController>().DismissModalViewController(null, true);
FindObjectOfType<StandardLevelSelectionNavigationController>().DismissModalViewController(null, true);
FindObjectOfType<SoloModeSelectionViewController>().DismissModalViewController(null, true);
FindObjectOfType<StandardLevelSelectionFlowCoordinator>().Finish();
Present(FindObjectOfType<MainMenuViewController>(), true);
StaticData.LastLevelCompletionResults = null;
StaticData.DidStartFromQueue = false;
}
catch (Exception e)
{
_logger.Error($"RESULTS EXCEPTION: {e}");
}
};
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.Windows;
namespace Arduino_Alarm.SetAlarm.GetSchedule
{
public class Settings
{
public int Subgroup { get; set; }
public string Minor { get; set; }
public string Address { get; set;}
public string TimeToReady { get; set; }
public string Transport { get; set; }
public Settings()
{
SubgroupAndMinor();
}
string[] GetSettings()
{
string[] settings;
var list = new List<string>();
try
{
Encoding enc = Encoding.GetEncoding(1251);
var file = new FileStream(@"..\\..\\Settings.txt", FileMode.Open, FileAccess.Read);
using (var streamReader = new StreamReader(file, enc))
{
string line;
while ((line = streamReader.ReadLine()) != null)
{
list.Add(line);
}
}
settings = list.ToArray();
}
catch
{
settings = null; MessageBox.Show("Programm cannot find a file with settings", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
}
return settings;
}
public void ChangeSettings(Settings set)
{
Encoding enc = Encoding.GetEncoding(1251);
try
{
string[] settings = new string[] { set.Subgroup.ToString(), set.Minor, set.Address, set.TimeToReady, set.Transport };
File.WriteAllLines(@"..\\..\\Settings.txt", settings, enc);
}
catch { MessageBox.Show("Programm cannot find a file with settings", "Error", MessageBoxButton.OK, MessageBoxImage.Error); }
}
void SubgroupAndMinor()
{
string[] settings = GetSettings();
try
{
if (settings.Any(c => c == null) || settings.Length < 5)
{
}
else
{
Subgroup = Convert.ToInt16(settings[0]);
Minor = settings[1];
Address = settings[2];
TimeToReady = settings[3];
Transport = settings[4];
}
}
catch
{
}
}
}
}
|
namespace JhinBot.Interface
{
public interface IValidator
{
(bool success, string errorMsg) Validate(string input);
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace _3._2_ProtectedData
{
static class Program
{
/// <summary>
/// ProtectedData é utilizada para proteger dados definidos pelo usuário. Essa classe não exige outras classes (algoritmos) de criptografia.
/// Essa classe fornece dois métodos principais chamados de Protect e Unprotect.
/// Ambos os métodos são estáticos e, o método Protect, além de outros parâmetros, recebe principalmente um array de bytes que representa o valor a ser protegido, retornando também um array de bytes contendo o valor criptografado;
/// já o método Unprotect recebe um array de bytes representando o dado protegido (criptografado) e retorna um array de bytes contendo o conteúdo em seu formato original.
///
/// Read more: http://www.linhadecodigo.com.br/artigo/2085/por-dentro-da-base-classe-library-capitulo-8-criptografia.aspx#ixzz5NSJZC5S9
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
}
}
|
using Cricetidae.Helper;
using Shouldly;
using Xunit;
namespace Cricetidae.Tests
{
public class BonusTextAnalyserText
{
[Fact]
public void AnalyseBonusText_bonusTextFromFor()
{
var fromPrice = 0;
var forPrice = 800;
var amountOfProducts = 1;
BonusTextAnalyser.AnalyseBonusText("2 VOOR 4.99", ref fromPrice, ref forPrice, ref amountOfProducts);
fromPrice.ShouldBe(800);
forPrice.ShouldBe(249);
amountOfProducts.ShouldBe(2);
}
[Fact]
public void AnalyseBonusText_bonusTextFromFor3()
{
var fromPrice = 0;
var forPrice = 800;
var amountOfProducts = 1;
BonusTextAnalyser.AnalyseBonusText("3 VOOR 9", ref fromPrice, ref forPrice, ref amountOfProducts);
fromPrice.ShouldBe(800);
forPrice.ShouldBe(300);
amountOfProducts.ShouldBe(3);
}
[Fact]
public void AnalyseBonusText_bonusTextFromForParts()
{
var fromPrice = 0;
var forPrice = 800;
var amountOfProducts = 1;
BonusTextAnalyser.AnalyseBonusText("3 STUKS 9.00", ref fromPrice, ref forPrice, ref amountOfProducts);
fromPrice.ShouldBe(800);
forPrice.ShouldBe(300);
amountOfProducts.ShouldBe(3);
}
[Fact]
public void AnalyseBonusText_bonusTextMoneyDeducted()
{
var fromPrice = 0;
var forPrice = 800;
var amountOfProducts = 1;
BonusTextAnalyser.AnalyseBonusText("3 EURO KORTING", ref fromPrice, ref forPrice, ref amountOfProducts);
fromPrice.ShouldBe(800);
forPrice.ShouldBe(500);
amountOfProducts.ShouldBe(1);
}
[Fact]
public void AnalyseBonusText_bonusTextSecondHalvePrice()
{
var fromPrice = 0;
var forPrice = 800;
var amountOfProducts = 1;
BonusTextAnalyser.AnalyseBonusText("2e halve prijs", ref fromPrice, ref forPrice, ref amountOfProducts);
fromPrice.ShouldBe(800);
forPrice.ShouldBe(600);
amountOfProducts.ShouldBe(2);
}
[Fact]
public void AnalyseBonusText_bonusTextPercentDeducted()
{
var fromPrice = 0;
var forPrice = 1000;
var amountOfProducts = 1;
BonusTextAnalyser.AnalyseBonusText("10% korting", ref fromPrice, ref forPrice, ref amountOfProducts);
fromPrice.ShouldBe(1000);
forPrice.ShouldBe(900);
amountOfProducts.ShouldBe(1);
}
[Fact]
public void AnalyseBonusText_bonusTextSecondGratis()
{
var fromPrice = 0;
var forPrice = 300;
var amountOfProducts = 1;
BonusTextAnalyser.AnalyseBonusText("1 + 1 GRATIS", ref fromPrice, ref forPrice, ref amountOfProducts);
fromPrice.ShouldBe(300);
forPrice.ShouldBe(150);
amountOfProducts.ShouldBe(2);
}
[Fact]
public void AnalyseBonusText_bonusTextSecondGratisAlt()
{
var fromPrice = 0;
var forPrice = 300;
var amountOfProducts = 1;
BonusTextAnalyser.AnalyseBonusText("2=1", ref fromPrice, ref forPrice, ref amountOfProducts);
fromPrice.ShouldBe(300);
forPrice.ShouldBe(150);
amountOfProducts.ShouldBe(2);
}
[Fact]
public void AnalyseBonusText_bonusText2Plus2Free()
{
var fromPrice = 0;
var forPrice = 400;
var amountOfProducts = 1;
BonusTextAnalyser.AnalyseBonusText("2 + 2 gratis", ref fromPrice, ref forPrice, ref amountOfProducts);
fromPrice.ShouldBe(400);
forPrice.ShouldBe(100);
amountOfProducts.ShouldBe(4);
}
}
}
|
using System;
namespace Iterator
{
class Program
{
static void Main(string[] args)
{
var concretAggregate = new ConcretAggregate();
concretAggregate[0] = "Item A";
concretAggregate[1] = "Item B";
concretAggregate[2] = "Item C";
concretAggregate[3] = "Item D";
var iterator = concretAggregate.CreateIterator();
Console.WriteLine("Interagindo com a coleção:");
object item = iterator.First();
while (item != null)
{
Console.WriteLine(item);
item = iterator.Next();
}
}
}
}
|
using Compent.Shared.DependencyInjection.Contract;
using Uintra.Core.Activity;
using Uintra.Core.Feed.Services;
using Uintra.Features.Notification.Services;
using Uintra.Features.Social;
using Uintra.Features.Social.Entities;
namespace Uintra.Infrastructure.Ioc
{
public class SocialInjectModule: IInjectModule
{
public IDependencyCollection Register(IDependencyCollection services)
{
services.AddScopedToCollection<INotifyableService, SocialService<Social>>();
services.AddScoped<ICacheableIntranetActivityService<Social>, SocialService<Social>>();
services.AddScoped<IFeedItemService, SocialService<Social>>();
services.AddScoped<ISocialService<Social>, SocialService<Social>>();
services.AddScoped<IIntranetActivityService, SocialService<Social>>();
return services;
}
}
} |
using System;
namespace Win_Lose
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Pick a number: 1-10");
string userValue = Console.ReadLine();
if (userValue == "8")
{
string message = "You Win!";
Console.WriteLine(message);
}
else
{
string message = "You Lose!";
Console.WriteLine(message);
}
Console.ReadLine();
}
}
}
|
namespace P01PermutationsWithoutRepetitions
{
using System;
public class EntryPoint
{
private static string[] sequence;
public static void Main()
{
sequence = Console.ReadLine().Split();
Gen(0);
}
private static void Gen(int index)
{
if (index == sequence.Length)
{
Console.WriteLine(string.Join(" ", sequence));
}
else
{
Gen(index + 1);
for (int i = index + 1; i < sequence.Length; i++)
{
Swap(index, i);
Gen(index + 1);
Swap(index, i);
}
}
}
private static void Swap(int i, int j)
{
var temp = sequence[i];
sequence[i] = sequence[j];
sequence[j] = temp;
}
}
} |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace ej_productos
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void dgv_productos_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
var senderGrid = (DataGridView)sender;
Frm_Prod_modal Frm_modDel = null;
if (senderGrid.Columns[e.ColumnIndex] is DataGridViewImageColumn && e.RowIndex >= 0)
{
if (e.ColumnIndex == dgv_productos.Columns["modificar"].Index)
{
String nombreProd = dgv_productos.Rows[e.RowIndex].Cells[dgv_productos.Columns["Nombre"].Index].Value.ToString();
if (MessageBox.Show("Seguro que deseas MODIFICAR el producto " + nombreProd.ToUpper() + " ?", "Modificar", MessageBoxButtons.YesNo) == DialogResult.Yes)
{
Frm_modDel = new Frm_Prod_modal();
Frm_modDel.cod = dgv_productos.Rows[e.RowIndex].Cells[dgv_productos.Columns["cod_prod"].Index].Value.ToString();
Frm_modDel.nombre = dgv_productos.Rows[e.RowIndex].Cells[dgv_productos.Columns["Nombre"].Index].Value.ToString();
Frm_modDel.Descripcion = dgv_productos.Rows[e.RowIndex].Cells[dgv_productos.Columns["Descripción"].Index].Value.ToString();
Frm_modDel.tipo = dgv_productos.Rows[e.RowIndex].Cells[dgv_productos.Columns["Tipo"].Index].Value.ToString();
Frm_modDel.cantidad = Convert.ToInt16(dgv_productos.Rows[e.RowIndex].Cells[dgv_productos.Columns["Cantidad"].Index].Value.ToString());
Frm_modDel.precio = Convert.ToSingle(dgv_productos.Rows[e.RowIndex].Cells[dgv_productos.Columns["Precio"].Index].Value.ToString());
if (Frm_modDel.ShowDialog() == DialogResult.OK)
{
dgv_productos.Rows[e.RowIndex].Cells[dgv_productos.Columns["cod_prod"].Index].Value = Frm_modDel.cod;
dgv_productos.Rows[e.RowIndex].Cells[dgv_productos.Columns["Nombre"].Index].Value = Frm_modDel.nombre;
dgv_productos.Rows[e.RowIndex].Cells[dgv_productos.Columns["Descripción"].Index].Value = Frm_modDel.Descripcion;
dgv_productos.Rows[e.RowIndex].Cells[dgv_productos.Columns["Tipo"].Index].Value = Frm_modDel.tipo;
dgv_productos.Rows[e.RowIndex].Cells[dgv_productos.Columns["Cantidad"].Index].Value = Frm_modDel.cantidad;
dgv_productos.Rows[e.RowIndex].Cells[dgv_productos.Columns["Precio"].Index].Value = Frm_modDel.precio;
}
}
}
if (e.ColumnIndex == dgv_productos.Columns["borrar"].Index)
{
String nombreProd = dgv_productos.Rows[e.RowIndex].Cells[dgv_productos.Columns["Nombre"].Index].Value.ToString();
if (MessageBox.Show("Seguro que deseas borrar el producto "+nombreProd.ToUpper()+" ?", "Borrar", MessageBoxButtons.YesNo) == DialogResult.Yes)
{
dgv_productos.Rows.RemoveAt(e.RowIndex);
if (dgv_productos.Rows.Count != 0)
{
btn_exportCSV.Enabled = true;
exportarCSVToolStripMenuItem.Enabled = true;
}
else
{
btn_exportCSV.Enabled = false;
exportarCSVToolStripMenuItem.Enabled = false;
modificarProductoToolStripMenuItem.Enabled = false;
borrarProductoToolStripMenuItem.Enabled = false;
}
}
}
}
}
private void Form1_Load(object sender, EventArgs e)
{
//string[] dato = { "1", "1", "1", "1", "1", "1" };
//dgv_productos.Rows.Add(dato);
}
private void btn_anyadir_Click(object sender, EventArgs e)
{
Frm_Prod_modal fpr = new Frm_Prod_modal();
if (fpr.ShowDialog() == DialogResult.OK)
{
string[] filaNueva = new string[6];
filaNueva[0] = fpr.cod;
filaNueva[1] = fpr.nombre;
filaNueva[2] = fpr.Descripcion;
filaNueva[3] = fpr.tipo;
filaNueva[4] = fpr.cantidad.ToString();
filaNueva[5] = fpr.precio.ToString();
dgv_productos.Rows.Add(filaNueva);
}
btn_exportCSV.Enabled = true;
exportarCSVToolStripMenuItem.Enabled = true;
modificarProductoToolStripMenuItem.Enabled = true;
borrarProductoToolStripMenuItem.Enabled = true;
}
private void btn_exportCSV_Click(object sender, EventArgs e)
{
// crear un streamWriter para poder escribir en el fichero
// StreamWriter miStrFile = new StreamWriter("C:\\Users\\alumno\\Documents\\ficheroCSV.csv");
StreamWriter miStrFile = null;
//crear fichero desde una ventana
SaveFileDialog sfd = new SaveFileDialog();
sfd.Title = "Elige un fichero";
sfd.InitialDirectory = @"C:\Users\alumno\Documents";
sfd.Filter = "Text and CSV Files(*.csv)|*.csv|CSV Files(*.csv)|*.csv|All Files(*.*)|*.*";
sfd.FilterIndex = 1;
sfd.RestoreDirectory = true;
if (sfd.ShowDialog() == DialogResult.OK)
{
miStrFile = new StreamWriter(sfd.FileName);
//Application.DoEvents();
// crear bucle para añadir cabeceras de tabla y utilizar el separador ","
for (int i = 0; i < (dgv_productos.Columns.Count) - 2; i++)
{
miStrFile.Write(dgv_productos.Columns[i].HeaderText);
if (i != (dgv_productos.Columns.Count)-3)
{
miStrFile.Write(";");
}
}
miStrFile.Write(miStrFile.NewLine);// añadir linea
// Con este bucle recorremos las filas
foreach (DataGridViewRow dr in dgv_productos.Rows)
{
// Recorremos las columnas de cada pasada de fila del bucle
for (int i = 0; i < (dgv_productos.Columns.Count) - 2; i++)
{
//Escribimos el contenido de cada celda de la fila
miStrFile.Write(dr.Cells[i].Value.ToString());
if (i != (dgv_productos.Columns.Count) - 3)
{
miStrFile.Write(";");//añadimos separador
}
}
miStrFile.Write(miStrFile.NewLine);//añadimos linea
}
//borra todos los búferes de esta secuencia y hace que todos los datos almacenados en el búfer se escriban en el dispositivo subyacente.
miStrFile.Flush();
//Cierra el streamWriter
miStrFile.Close();
MessageBox.Show("Fichero CSV creado con exito.");
}
}
private void btn_importCSV_Click(object sender, EventArgs e)
{
// crear un streamReader para poder escribir en el fichero
StreamReader miStrRead = null;
// Cargar fichero desde una ventana
OpenFileDialog ofd = new OpenFileDialog();
ofd.Title = "Elige un fichero";
ofd.InitialDirectory = @"C:\Users\alumno\Documents";
ofd.Filter = "Text and CSV Files(*.csv)|*.csv|CSV Files(*.csv)|*.csv|All Files(*.*)|*.*";
ofd.FilterIndex = 1;
ofd.RestoreDirectory = true;
if (ofd.ShowDialog() == DialogResult.OK)
{
miStrRead = new StreamReader(ofd.FileName);
//Creamos una lista para guardar los datos del CSV
List<string[]> datosCSV = new List<string[]>();
string linea;
string[] fila;
// Omitimos la 1ª linea que son las cabeceras
miStrRead.ReadLine();
//Cargamos la lista con el resto de datos
while ((linea = miStrRead.ReadLine()) != null)
{
fila = linea.Split(';');
// datosCSV.Add(fila);
dgv_productos.Rows.Add(fila);
}
miStrRead.Close();
}
if (dgv_productos.Rows.Count != 0)
{
btn_exportCSV.Enabled = true;
exportarCSVToolStripMenuItem.Enabled = true;
modificarProductoToolStripMenuItem.Enabled = true;
borrarProductoToolStripMenuItem.Enabled = true;
}
else
{
btn_exportCSV.Enabled = false;
exportarCSVToolStripMenuItem.Enabled = false;
modificarProductoToolStripMenuItem.Enabled = false;
borrarProductoToolStripMenuItem.Enabled = false;
}
}
private void modificarProductoToolStripMenuItem_Click(object sender, EventArgs e)
{
int posicion = dgv_productos.CurrentRow.Index;
Frm_Prod_modal Frm_modDel = null;
String nombreProd = dgv_productos.Rows[posicion].Cells[dgv_productos.Columns["Nombre"].Index].Value.ToString();
if (MessageBox.Show("Seguro que deseas MODIFICAR el producto "+nombreProd.ToUpper()+" ?", "Modificar", MessageBoxButtons.YesNo) == DialogResult.Yes)
{
Frm_modDel = new Frm_Prod_modal();
Frm_modDel.cod = dgv_productos.Rows[posicion].Cells[dgv_productos.Columns["cod_prod"].Index].Value.ToString();
Frm_modDel.nombre = dgv_productos.Rows[posicion].Cells[dgv_productos.Columns["Nombre"].Index].Value.ToString();
Frm_modDel.Descripcion = dgv_productos.Rows[posicion].Cells[dgv_productos.Columns["Descripción"].Index].Value.ToString();
Frm_modDel.tipo = dgv_productos.Rows[posicion].Cells[dgv_productos.Columns["Tipo"].Index].Value.ToString();
Frm_modDel.cantidad = Convert.ToInt16(dgv_productos.Rows[posicion].Cells[dgv_productos.Columns["Cantidad"].Index].Value.ToString());
Frm_modDel.precio = Convert.ToSingle(dgv_productos.Rows[posicion].Cells[dgv_productos.Columns["Precio"].Index].Value.ToString());
if (Frm_modDel.ShowDialog() == DialogResult.OK)
{
dgv_productos.Rows[posicion].Cells[dgv_productos.Columns["cod_prod"].Index].Value = Frm_modDel.cod;
dgv_productos.Rows[posicion].Cells[dgv_productos.Columns["Nombre"].Index].Value = Frm_modDel.nombre;
dgv_productos.Rows[posicion].Cells[dgv_productos.Columns["Descripción"].Index].Value = Frm_modDel.Descripcion;
dgv_productos.Rows[posicion].Cells[dgv_productos.Columns["Tipo"].Index].Value = Frm_modDel.tipo;
dgv_productos.Rows[posicion].Cells[dgv_productos.Columns["Cantidad"].Index].Value = Frm_modDel.cantidad;
dgv_productos.Rows[posicion].Cells[dgv_productos.Columns["Precio"].Index].Value = Frm_modDel.precio;
}
}
}
private void borrarProductoToolStripMenuItem_Click(object sender, EventArgs e)
{
int seleccion = dgv_productos.SelectedRows.Count;
if (seleccion == 0)
{
int posicion = dgv_productos.CurrentRow.Index;
String nombreProd = dgv_productos.Rows[posicion].Cells[dgv_productos.Columns["Nombre"].Index].Value.ToString();
if (MessageBox.Show("Seguro que deseas borrar el producto " + nombreProd.ToUpper() + " ?", "Borrar", MessageBoxButtons.YesNo) == DialogResult.Yes)
{
dgv_productos.Rows.RemoveAt(posicion);
}
}
else
{
if (MessageBox.Show("Seguro que deseas borrar " + seleccion + " productos ?", "Borrar", MessageBoxButtons.YesNo) == DialogResult.Yes)
{
foreach (DataGridViewRow fila in dgv_productos.SelectedRows)
{
dgv_productos.Rows.Remove(fila);
}
if (dgv_productos.Rows.Count != 0)
{
btn_exportCSV.Enabled = true;
exportarCSVToolStripMenuItem.Enabled = true;
}
else
{
btn_exportCSV.Enabled = false;
exportarCSVToolStripMenuItem.Enabled = false;
modificarProductoToolStripMenuItem.Enabled = false;
borrarProductoToolStripMenuItem.Enabled = false;
}
}
}
}
}
}
|
using System;
namespace DelftTools.Utils.UndoRedo
{
public class UndoRedoEventArgs : EventArgs
{
public IMemento Memento { get; set; }
}
} |
using EntityFrameworkCore.BootKit;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Text;
namespace Quickflow.Core.Entities
{
public class ActivityInWorkflow : DbRecord, IDbRecord
{
public override string ToString()
{
return $"{ActivityName} {Id}";
}
[Required]
[StringLength(36)]
public string WorkflowId { get; set; }
public Workflow Workflow { get; set; }
[Required]
[MaxLength(64)]
public String ActivityName { get; set; }
/// <summary>
/// Activity extra flag
/// </summary>
[NotMapped]
public int Flag { get; set; }
/// <summary>
/// NextWorkflowActivityId
/// </summary>
[StringLength(36)]
public String NextActivityId { get; set; }
/// <summary>
/// Originaal NextWorkflowActivityId
/// </summary>
[NotMapped]
public String OriginNextActivityId { get; set; }
[ForeignKey("WorkflowActivityId")]
public List<OptionsInActivity> Options { get; set; }
/// <summary>
/// Convert to options
/// </summary>
[NotMapped]
public JObject Configuration { get; set; }
[NotMapped]
public ActivityResult Input { get; set; }
[NotMapped]
public ActivityResult OriginInput { get; set; }
[NotMapped]
public ActivityResult Output { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
namespace Task2
{
class Program
{
public static bool Prime(int a) // булевая функция для проверки протое ли число
{
if (a <= 1) // число 1 или меньше сразу же исключается
{
return false;
}
for(int i = 2; i <= a / 2; i++) // если число разделяется без остатка на 2 и больше числа то оно составное
{
if (a % i == 0)
{
return false;
}
}
return true; // иначе простое
}
static void Main(string[] args)
{
StreamReader qw = new StreamReader(@"C:\Users\user1\Desktop\PP2\Week 2\Task2\Task2\Text.txt"); // "инструмент" для чтения текста
string arr = qw.ReadToEnd(); // переменная arr принимает значение текста Text
string[] arra = arr.Split(' '); // разделяем текст на элементы стрингового массива через пробел
StreamWriter s = new StreamWriter(@"C:\Users\user1\Desktop\PP2\Week 2\Task2\Task2\output.txt"); // "инструмент" для ввода текста
for (int i = 0; i < arra.Length; i++) // пробегаемся по количеству элементов массива
{
int we = int.Parse(arra[i]); // конвертируем каждый элемент массива со стринга в интеджер
if (Prime(we)) // проверяем простое ли число
{
s.Write(we); // если простое, то вводим его в текст output
s.Write(" ");
}
}
s.Close();
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Inventory : MonoBehaviour
{
public List<Item> inventoryItems = new List<Item>();
ItemDatabase itemDatabase;
[SerializeField] private UIInventory uiInventory;
private void Awake()
{
itemDatabase = FindObjectOfType<ItemDatabase>();
}
private void Start()
{
AddItem(1);
AddItem(2);
}
public void AddItem(int id)
{
Item itemToAdd = itemDatabase.GetItem(id);
uiInventory.AddItemToUI(itemToAdd);
inventoryItems.Add(itemToAdd);
}
public void AddItem(string itemName)
{
Item itemToAdd = itemDatabase.GetItem(itemName);
uiInventory.AddItemToUI(itemToAdd);
inventoryItems.Add(itemToAdd);
}
public Item CheckForItem(int id)
{
return inventoryItems.Find(item => item.ID == id);
}
public Item CheckForItem(string name)
{
return inventoryItems.Find(item => item.name == name);
}
public void RemoveItem(int id)
{
Item itemToRemove = CheckForItem(id);
if (itemToRemove != null)
{
inventoryItems.Remove(itemToRemove);
}
}
}
|
using System;
using System.Web.Mvc;
namespace Tomelt.Mvc.AntiForgery {
[AttributeUsage(AttributeTargets.Method)]
public class ValidateAntiForgeryTokenTomeltAttribute : FilterAttribute {
private readonly bool _enabled = true;
public ValidateAntiForgeryTokenTomeltAttribute() : this(true) {}
public ValidateAntiForgeryTokenTomeltAttribute(bool enabled) {
_enabled = enabled;
}
public bool Enabled { get { return _enabled; } }
}
} |
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
public partial class Administration_Reports_Rpt_SummaryReport : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string strRpt;
string qstr = Request.QueryString["rpt"];
if (qstr == "camps")
strRpt = "/CIPMS_Reports/StatusByCamps";
else
strRpt = "/CIPMS_Reports/rpt_StatusByFederation";
string strReportServerURL = ConfigurationManager.AppSettings["ReportServerURL"];
MyReportViewer.ProcessingMode = Microsoft.Reporting.WebForms.ProcessingMode.Remote;
MyReportViewer.ServerReport.ReportServerUrl = new Uri(strReportServerURL); // Report Server URL
MyReportViewer.ServerReport.ReportPath = strRpt; // Report Name
MyReportViewer.ShowParameterPrompts = true;
MyReportViewer.ShowDocumentMapButton = true;
MyReportViewer.ShowPrintButton = true;
//MyReportViewer.ServerReport.Refresh();
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using TMPro;
using System;
public class ScoreMonitor : MonoBehaviour {
TextMeshProUGUI scoreText;
GameStatus gameStatus;
// Use this for initialization
void Start () {
//Debug.Log("Execute start method");
scoreText = GetComponent<TextMeshProUGUI>();
gameStatus = FindObjectOfType<GameStatus>();
//Debug.Log("Game Score " + gameStatus.ReturnScore());
}
// Update is called once per frame
void Update () {
DisplayScore();
//Debug.Log("Execute Update method");
}
private void DisplayScore()
{
scoreText.text = gameStatus.ReturnScore().ToString();
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
using System.Data;
using System.Collections;
namespace CRL.Order.ProductOrder
{
/// <summary>
/// 产品订单维护
/// </summary>
public class ProductOrderBusiness<TType, TModel> : OrderBusiness<TType, TModel>
where TType : class
where TModel : ProductOrder, new()
{
public static ProductOrderBusiness<TType, TModel> Instance
{
get { return new ProductOrderBusiness<TType, TModel>(); }
}
protected override DBExtend dbHelper
{
get { return GetDbHelper<TType>(); }
}
/// <summary>
/// 是否启用库存
/// </summary>
public bool EnableStock
{
get{
bool a = false;
try
{
a =Convert.ToBoolean( CoreHelper.CustomSetting.GetConfigKey("CRL_EnableStock"));
}
catch { }
return a;
}
}
/// <summary>
/// 最否使用运费
/// </summary>
public bool UseFreight
{
get
{
bool a = false;
try
{
a = Convert.ToBoolean(CoreHelper.CustomSetting.GetConfigKey("CRL_UseFreight"));
}
catch { }
return a;
}
}
static int serialNumber = 0;
/// <summary>
/// 生成订单号
/// </summary>
/// <returns></returns>
public string MakeOrderId()
{
string no;
lock (lockObj)
{
serialNumber += 1;
if (serialNumber > 10000)
serialNumber = 1;
no = DateTime.Now.ToString("yyMMddhhmmssff") + serialNumber.ToString().PadLeft(5, '0');
}
return no;
}
/// <summary>
/// 查询订单明细
/// </summary>
/// <param name="orderId"></param>
/// <returns></returns>
public List<IOrderDetail> QueryOrderDetail(string orderId)
{
List<IOrderDetail> orderDetail = new List<IOrderDetail>();
DBExtend helper = dbHelper;
orderDetail = helper.QueryList<IOrderDetail>(b => b.OrderId == orderId);
return orderDetail;
}
/// <summary>
/// 查询订单第一个产品
/// </summary>
/// <param name="orderId"></param>
/// <returns></returns>
public IOrderDetail QueryFirstOrderDetail(string orderId)
{
var helper = dbHelper;
var orderDetail = helper.QueryItem<IOrderDetail>(b => b.OrderId == orderId);
return orderDetail;
}
/// <summary>
/// 提交订单
/// </summary>
/// <typeparam name="TMain"></typeparam>
/// <param name="order"></param>
/// <param name="orderDetail"></param>
/// <returns></returns>
public bool SubmitOrder(TModel order, List<IOrderDetail> orderDetail)
{
var helper = dbHelper;
order.OrderId = MakeOrderId();//生成订单号
decimal orderAmount = 0;
decimal orderIntegral = 0;
orderDetail.ForEach(b => {
b.OrderId = order.OrderId;
orderAmount += b.Price * b.Num;
orderIntegral += b.Integral * b.Num;
});
//if (UseFreight)
//{
// decimal freightAmount = 0;
// double freight1, freight2;
// Freight.FreightAction<TType>.CalculateFreight(orderDetail, order.AreaId, supplier, out freight1, out freight2);
// freightAmount = order.DeliverType == Freight.DeliverType.物流 ? (decimal)freight1 : (decimal)freight2;
// order.FreightAmount = freightAmount;
//}
order.OriginalAmount = orderAmount;
order.Integral = orderIntegral;
SubmitOrder(order);
//详细
helper.BatchInsert<IOrderDetail>( orderDetail);
return true;
}
/// <summary>
/// 更改订单状态
/// </summary>
/// <param name="order"></param>
/// <param name="status"></param>
/// <param name="remark"></param>
/// <returns></returns>
public bool UpdateOrderStatus(TModel order, ProductOrderStatus status, string remark)
{
UpdateOrderStatus(order, (int)status, remark);
order.Status = (int)status;
return true;
}
/// <summary>
/// 影响库存,在更改状态后使用
/// </summary>
/// <typeparam name="TProduct"></typeparam>
/// <typeparam name="TStock"></typeparam>
/// <typeparam name="TRecord"></typeparam>
/// <param name="orderId"></param>
/// <param name="status"></param>
public void AffectStock<TProduct, TStock, TRecord>(string orderId, ProductOrderStatus status)
where TProduct : Product.IProduct, new()
where TStock : CRL.Stock.Style, new()
where TRecord : CRL.Stock.IStockRecord, new()
{
#region 库存操作
var op = Stock.StockOperateType.出;
bool exc = false;
if (status == ProductOrderStatus.已付款)
{
exc = true;
}
if (status == ProductOrderStatus.已取消)
{
op = Stock.StockOperateType.入;
exc = true;
}
if (exc)
{
List<IOrderDetail> list = QueryOrderDetail(orderId);
List<TRecord> stockChanges = new List<TRecord>();
string batchNo = System.DateTime.Now.ToString("yyMMddhhmmssff");
foreach (var item in list)
{
TRecord s = new TRecord() { Num = item.Num, StyleId = item.StyleId };
stockChanges.Add(s);
if (op == Stock.StockOperateType.出)
{
Product.ProductBusiness<TType,TProduct>.Instance.SoldAdd(item.ProductId, item.Num);
}
}
if (EnableStock)
{
Stock.StockRecordBusiness<TType, TRecord>.Instance.SubmitRecord(stockChanges, batchNo, Stock.FromType.订单);
Stock.StockRecordBusiness<TType, TRecord>.Instance.ConfirmSubmit<TStock>(batchNo, op);
}
}
#endregion
}
/// <summary>
/// 取消订单
/// </summary>
/// <param name="order"></param>
/// <param name="remark"></param>
/// <returns></returns>
public bool CancelOrder<TMain>(TModel order, string remark)
{
UpdateOrderStatus(order, ProductOrderStatus.已取消, remark);
return true;
}
/// <summary>
/// 确认订单
/// </summary>
/// <param name="order"></param>
/// <param name="remark"></param>
/// <returns></returns>
public bool ConfirmOrder(TModel order, string remark)
{
UpdateOrderStatus(order, ProductOrderStatus.已付款, remark);
return true;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TP.BusinessLayer.Abstract;
using TP.Entities;
namespace TP.BusinessLayer.JobManagers
{
public class JobAnsManager:ManagerBase<Job_Ans>
{
}
}
|
using ChatBot.Domain.Core;
using ChatBot.Domain.Services.OpenData.Conf;
using ChatBot.Entities;
using Microsoft.Extensions.Options;
using Newtonsoft.Json.Linq;
using System.Collections.Generic;
using System.Linq;
namespace ChatBot.Domain.Services.OpenData
{
public class OpenDataService : IOpenDataService
{
//COMUN
private const string TAG_VALUE = "value";
private const string TAG_RESULTS = "results";
private const string TAG_BINDINGS = "bindings";
//CENTERS
private const string TAG_CENTER_CODE = "ou_codCentro";
private const string TAG_CENTER_NAME = "foaf_name";
private const string TAG_CENTER_EMAIL = "schema_email";
private const string TAG_CENTER_TELEPHONE = "schema_telephone";
//DEGREES
private const string TAG_DEGREE_NAME = "foaf_name";
private const string TAG_DEGREE_CODE = "ou_codTitulacion";
private const string TAG_DEGREE_CENTER = "foaf_name_centro";
//SUBJECTS
private const string TAG_SUBJECT_CODE = "aiiso_code";
private const string TAG_SUBJECT_NAME = "teach_courseTitle";
private const string TAG_SUBJECT_DEGREE = "titulacion";
private const string TAG_SUBJECT_ECTS = "teach_ects";
private const string TAG_SUBJECT_CHARACTER = "ou_caracterAsignatura";
private const string TAG_SUBJECT_TIME = "ou_temporalidadAsignatura";
protected readonly DegreeConfigModel _degreeConfigModel;
public OpenDataService(IOptions<DegreeConfigModel> degreeConfigModel)
{
_degreeConfigModel = degreeConfigModel.Value;
}
public List<StudyCenterModel> GetStudyCenters()
{
var result = string.Empty;
using (var client = new System.Net.Http.HttpClient())
{
result = client.GetStringAsync(_degreeConfigModel.CentersQuery)?.Result ?? string.Empty;
}
if (string.IsNullOrEmpty(result))
return new List<StudyCenterModel>();
List<StudyCenterModel> centers = GetCenters(result);
var subjects = GetSubjects();
foreach (var degree in GetDegrees())
{
var center = centers.FirstOrDefault(x => x.Name.Equals(degree.Center));
if(center != null) {
degree.Url = string.Format(_degreeConfigModel.PathAbsoluteDegree, center.UnexCode, degree.Code.ToString("D4"));
degree.Subjects.AddRange(subjects
.Where(x => x.Degree.Equals(degree.Name))
.Select(c => { c.InfoUrl = string.Format(_degreeConfigModel.PathAbsoluteFrom12A, center.UnexCode, degree.Code.ToString("D4"), c.Code); return c; }));
center.Degrees.Add(degree);
}
}
return centers;
}
private List<StudyCenterModel> GetCenters(string result)
{
var jsonCenters = (JArray)JObject.Parse(result)[TAG_RESULTS][TAG_BINDINGS];
var centers = new List<StudyCenterModel>();
foreach (var center in jsonCenters)
{
var unexCode = _degreeConfigModel.StudyCentres.FirstOrDefault(x => x.OpenDataCode == (int)center[TAG_CENTER_CODE][TAG_VALUE])?.UnexPageCode ?? string.Empty;
if (string.IsNullOrEmpty(unexCode)) continue;
centers.Add(new StudyCenterModel
{
Code = (int)center[TAG_CENTER_CODE][TAG_VALUE],
Name = (string)center[TAG_CENTER_NAME][TAG_VALUE],
UnexCode = unexCode,
Url = string.Format(_degreeConfigModel.PathAbsoluteCenter, unexCode),
Telephone = (string)center[TAG_CENTER_TELEPHONE][TAG_VALUE],
Email = (string)center[TAG_CENTER_EMAIL][TAG_VALUE],
Degrees = new List<DegreeModel>()
});
}
return centers;
}
private List<DegreeModel> GetDegrees()
{
var result = string.Empty;
using (var client = new System.Net.Http.HttpClient())
{
result = client.GetStringAsync(_degreeConfigModel.DegreesQuery)?.Result ?? string.Empty;
}
if (string.IsNullOrEmpty(result))
return new List<DegreeModel>();
return GetDegreesFromJson(result);
}
private List<SubjectModel> GetSubjects()
{
var result = string.Empty;
using (var client = new System.Net.Http.HttpClient())
{
result = client.GetStringAsync(_degreeConfigModel.SubjectsQuery)?.Result ?? string.Empty;
}
if (string.IsNullOrEmpty(result))
return new List<SubjectModel>();
return GetSubjectsFromJson(result);
}
private List<DegreeModel> GetDegreesFromJson(string result)
{
var jsonDegrees = (JArray)JObject.Parse(result)[TAG_RESULTS][TAG_BINDINGS];
var degrees = new List<DegreeModel>();
foreach (var degree in jsonDegrees)
{
var centro = degree[TAG_DEGREE_CENTER]?[TAG_VALUE] ?? string.Empty;
degrees.Add(new DegreeModel
{
Code = (int)degree[TAG_DEGREE_CODE][TAG_VALUE],
Name = (string)degree[TAG_DEGREE_NAME][TAG_VALUE],
Center = (string)centro,
Subjects = new List<SubjectModel>()
});
}
return degrees;
}
private List<SubjectModel> GetSubjectsFromJson(string result)
{
var jsonSubjects = (JArray)JObject.Parse(result)[TAG_RESULTS][TAG_BINDINGS];
var subjects = new List<SubjectModel>();
foreach (var subject in jsonSubjects)
{
subjects.Add(new SubjectModel
{
Code = (int)subject[TAG_SUBJECT_CODE][TAG_VALUE],
Name = (string)subject[TAG_SUBJECT_NAME][TAG_VALUE],
Degree = (string)subject[TAG_SUBJECT_DEGREE][TAG_VALUE],
Ects = (int)subject[TAG_SUBJECT_ECTS][TAG_VALUE],
//Semester = (string)subject[TAG_SUBJECT_TIME][TAG_VALUE],
Caracter = (string)subject[TAG_SUBJECT_CHARACTER][TAG_VALUE],
//Students = (int)subject[TAG_SUBJECT_STUDENTS][TAG_VALUE]
});
}
return subjects;
}
}
}
|
using System;
using System.Xml.Serialization;
using System.Collections.Generic;
using Top.Api;
namespace DingTalk.Api.Response
{
/// <summary>
/// OapiChatGetResponse.
/// </summary>
public class OapiChatGetResponse : DingTalkResponse
{
/// <summary>
/// chat_info
/// </summary>
[XmlElement("chat_info")]
public ChatInfoDomain ChatInfo { get; set; }
/// <summary>
/// errcode
/// </summary>
[XmlElement("errcode")]
public long Errcode { get; set; }
/// <summary>
/// errmsg
/// </summary>
[XmlElement("errmsg")]
public string Errmsg { get; set; }
/// <summary>
/// ChatInfoDomain Data Structure.
/// </summary>
[Serializable]
public class ChatInfoDomain : TopObject
{
/// <summary>
/// agentidlist
/// </summary>
[XmlArray("agentidlist")]
[XmlArrayItem("string")]
public List<string> Agentidlist { get; set; }
/// <summary>
/// conversationTag
/// </summary>
[XmlElement("conversationTag")]
public long ConversationTag { get; set; }
/// <summary>
/// extidlist
/// </summary>
[XmlArray("extidlist")]
[XmlArrayItem("string")]
public List<string> Extidlist { get; set; }
/// <summary>
/// name
/// </summary>
[XmlElement("name")]
public string Name { get; set; }
/// <summary>
/// owner
/// </summary>
[XmlElement("owner")]
public string Owner { get; set; }
/// <summary>
/// useridlist
/// </summary>
[XmlArray("useridlist")]
[XmlArrayItem("string")]
public List<string> Useridlist { get; set; }
}
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Runtime.CompilerServices;
namespace WpfApp4
{
public class FolderViewModel : INotifyPropertyChanged, IExpandable
{
private List<FolderViewModel> _subItems;
public FolderViewModel(string path)
{
ShortPath = System.IO.Path.GetFileName(path);
if (string.IsNullOrEmpty(ShortPath))
ShortPath = path;
Path = path;
SubItems = new List<FolderViewModel>();
}
public string Path { get; }
public string ShortPath { get; }
public List<FolderViewModel> SubItems
{
get => _subItems;
set
{
_subItems = value;
OnPropertyChanged();
}
}
public event PropertyChangedEventHandler PropertyChanged;
public void LoadChildren()
{
SubItems = Directory.GetDirectories(Path).Select(CreateDirectory).ToList();
}
public static FolderViewModel CreateDirectory(string path)
{
bool hasChildren;
try
{
hasChildren = Directory.GetDirectories(path).Any();
}
catch (UnauthorizedAccessException)
{
hasChildren = false;
}
catch (IOException)
{
hasChildren = false;
}
var dir = new FolderViewModel(path);
if (hasChildren)
{
dir.SubItems = new List<FolderViewModel> {new FolderViewModel("dummy")};
}
return dir;
}
protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ReSharper.Console
{
class Program
{
static void Main(string[] args)
{
new TestGenericOuter<int>();
}
}
public class TestGeneric<T>
{
}
public class TestGenericOuter<T> : TestGeneric<TestGenericOuter<TestGenericOuter<T>>>
{
}
}
|
using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Internal;
using Microsoft.Extensions.Configuration;
using Pobs.Domain;
using Pobs.Web.Helpers;
using Pomelo.EntityFrameworkCore.MySql.Infrastructure;
namespace Pobs.Tests.Integration.Helpers
{
internal static class TestSetup
{
internal static IConfiguration Configuration = new ConfigurationBuilder().AddJsonFile("appsettings.json").Build();
internal static AppSettings AppSettings = Configuration.GetSection("AppSettings").Get<AppSettings>();
private static readonly Lazy<DbContextPool<HonestQDbContext>> s_honestQDbContextPool = new Lazy<DbContextPool<HonestQDbContext>>(() =>
{
var connectionString = TestSetup.Configuration.GetConnectionString("DefaultConnection");
var options = new DbContextOptionsBuilder<HonestQDbContext>().UseMySql(
connectionString,
b =>
{
b.ServerVersion(new Version(5, 7, 21), ServerType.MySql);
}).Options;
return new DbContextPool<HonestQDbContext>(options);
});
internal static HonestQDbContext CreateDbContext()
{
return s_honestQDbContextPool.Value.Rent();
}
}
}
|
using PopulationFitness.Models.Genes;
using PopulationFitness.Models.Genes.Cache;
using PopulationFitness.Models.Genes.Fitness;
using PopulationFitness.Models.Genes.Performance;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
namespace PopulationFitness.Models
{
/**
* The generations recorded for a population
*
* Created by pete.callaghan on 04/07/2017.
*/
public class Generations
{
private static readonly int UNDEFINED_YEAR = -1;
public readonly List<GenerationStatistics> History;
public readonly Config Config;
private Population _population;
private int _firstYear;
private readonly int _seriesRun;
private readonly int _parallelRun;
public Generations(Population population) : this(population, 1, 1)
{
}
public Generations(Population population, int parallel_run, int series_run)
{
this._population = population;
this.Config = population.Config;
this._seriesRun = series_run;
this._parallelRun = parallel_run;
History = new List<GenerationStatistics>();
_firstYear = UNDEFINED_YEAR;
}
public void CreateForAllEpochs(Epochs epochs)
{
AddInitialPopulation(epochs);
foreach (Epoch epoch in epochs.All)
{
for (int year = epoch.StartYear; year <= epoch.EndYear; year++)
{
GenerateForYear(year, epoch);
}
}
}
private void AddInitialPopulation(Epochs epochs)
{
Epoch epoch = epochs.First;
_firstYear = epoch.StartYear;
_population.AddNewIndividuals(epoch, _firstYear);
}
public PopulationComparison TuneFitnessFactorsForAllEpochs(Epochs epochs, double minFactor, double maxFactor, double increment, int percentage)
{
AddInitialPopulation(epochs);
PopulationComparison divergence = PopulationComparison.TooLow;
Epoch previousEpoch = null;
foreach (Epoch epoch in epochs.All)
{
Population previousPopulation = new Population(_population);
Search search = new Search();
search.Increment(increment).Min(minFactor).Max(maxFactor);
if (previousEpoch != null)
{
search.Current = previousEpoch.Fitness();
}
previousEpoch = epoch;
divergence = GenerateAndCompareEpochPopulation(search, percentage, epoch, previousPopulation);
if (divergence != PopulationComparison.WithinRange)
{
FlushBodiesFromTheCache();
return divergence;
}
FlushBodiesFromTheCache();
}
return divergence;
}
private void FlushBodiesFromTheCache()
{
if (SharedCache.Cache.IsFlushable)
{
ICollection<IGenesIdentifier> survivors = _population.Individuals.Select(i => i.Genes.Identifier).ToList<IGenesIdentifier>();
SharedCache.Cache.RetainOnly(survivors);
}
}
private PopulationComparison GenerateAndCompareEpochPopulation(
Search search,
int percentage,
Epoch epoch,
Population previousPopulation)
{
_population = new Population(previousPopulation);
epoch.Fitness(search.Current);
PopulationComparison divergence = CompareToExpectedForEpoch(epoch, percentage);
Console.WriteLine("Year " + epoch.EndYear + " Pop " + _population.Individuals.Count + " Expected " + epoch.ExpectedMaxPopulation + " F=" + epoch.Fitness() + " F'=" + epoch.AverageCapacityFactor() * epoch.Fitness());
if (divergence != PopulationComparison.WithinRange)
{
Search nextSearch = search.FindNext(divergence);
if (nextSearch == null) return divergence;
return GenerateAndCompareEpochPopulation(nextSearch, percentage, epoch, previousPopulation);
}
return divergence;
}
private PopulationComparison CompareToExpectedForEpoch(Epoch epoch, int percentage)
{
for (int year = epoch.StartYear; year <= epoch.EndYear; year++)
{
_population.KillThoseUnfitOrReadyToDie(year, epoch);
_population.AddNewGeneration(epoch, year);
PopulationComparison divergence = CompareToExpected(epoch, year, _population.Individuals.Count, percentage);
if (divergence != PopulationComparison.WithinRange)
{
return divergence;
}
}
return PopulationComparison.WithinRange;
}
private static PopulationComparison CompareToExpected(Epoch epoch, int year, int population, int percentage)
{
if (population == 0) return PopulationComparison.TooLow;
int expected = epoch.CapacityForYear(year);
if (population >= expected * 2) return PopulationComparison.TooHigh;
int divergence = (population - expected) * 100;
int max_divergence = expected * percentage;
if (year >= epoch.EndYear)
{
if (divergence >= max_divergence) return PopulationComparison.TooHigh;
if (divergence < 0 - max_divergence) return PopulationComparison.TooLow;
}
return PopulationComparison.WithinRange;
}
private void GenerateForYear(int year, Epoch epoch)
{
Stopwatch stopWatch = Stopwatch.StartNew();
int fatalities = _population.KillThoseUnfitOrReadyToDie(year, epoch);
FlushBodiesFromTheCache();
long kill_elapsed = GenesTimer.GetElapsed(stopWatch);
stopWatch = Stopwatch.StartNew();
List<Individual> babies = _population.AddNewGeneration(epoch, year);
long born_elapsed = GenesTimer.GetElapsed(stopWatch);
AddHistory(epoch, year, babies.Count, fatalities, born_elapsed, kill_elapsed);
}
private void AddHistory(Epoch epoch, int year, int number_born, int number_killed, long born_elapsed, long kill_elapsed)
{
GenerationStatistics generation = new GenerationStatistics(epoch,
year,
_population.Individuals.Count,
number_born,
number_killed,
born_elapsed,
kill_elapsed,
_population.CapacityFactor(),
_population.AverageMutations);
generation.AverageFitness = _population.AverageFitness();
generation.AverageFactoredFitness = _population.AverageFactoredFitness();
generation.FitnessDeviation = _population.StandardDeviationFitness();
generation.AverageAge = _population.AverageAge;
generation.AverageLifeExpectancy = _population.AverageLifeExpectancy;
History.Add(generation);
Console.WriteLine("Run " + _parallelRun + "x" + _seriesRun + " Year " + generation.Year + " Pop " + generation.Population + " Expected " + epoch.ExpectedMaxPopulation + " Born " + generation.NumberBorn + " in " + generation.BornElapsedInHundredths() + "s Killed " + generation.NumberKilled + " in " + generation.KillElapsedInHundredths() + "s");
}
public static Generations Add(Generations first, Generations second)
{
Generations result = new Generations(first._population);
result._firstYear = first._firstYear;
result.History.AddRange(GenerationStatistics.Add(first.History, second.History));
return result;
}
}
}
|
using System.Windows.Controls;
using System.Windows.Input;
namespace ServiceCenter.View.Repair
{
public partial class PageOrderWorkAdd : Page
{
public PageOrderWorkAdd()
{
InitializeComponent();
}
private void TextBox_PreviewTextInput(object sender, TextCompositionEventArgs e)
{
e.Handled = "0123456789,".IndexOf(e.Text) < 0;
}
private void tbPercent_PreviewTextInput(object sender, TextCompositionEventArgs e)
{
e.Handled = "0123456789".IndexOf(e.Text) < 0;
}
}
}
|
using Core;
using DBCore;
using MaterialDesignThemes.Wpf;
using ServiceCenter.Helpers;
using ServiceCenter.View.Repair;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Windows;
using System.Windows.Input;
namespace ServiceCenter.ViewModel.Repair
{
class PageEquipmentAddViewModel : BaseViewModel
{
//наша форма
private FormOrderInfo window = Application.Current.Windows.OfType<FormOrderInfo>().FirstOrDefault();
ICallbackUpdate callback;
//индикатор ожидания
private bool _isAwait = false;
public bool IsAwait { get => _isAwait; set => Set(ref _isAwait, value); }
//список категорий
private ObservableCollection<Category> _categoryList = new ObservableCollection<Category>();
public ObservableCollection<Category> CategoryList { get => _categoryList; }
private Category _selectedCategory = null;
public Category SelectedCategory { get => _selectedCategory; set => Set(ref _selectedCategory, value); }
//список производителей
private ObservableCollection<Manufacturer> _manufacturerList = new ObservableCollection<Manufacturer>();
public ObservableCollection<Manufacturer> ManufacturerList { get => _manufacturerList; }
private Manufacturer _selectedManufacturer = null;
public Manufacturer SelectedManufacturer { get => _selectedManufacturer; set => Set(ref _selectedManufacturer, value); }
//название модели для добавления
private string _newModel = string.Empty;
public string NewModel { get => _newModel; set => Set(ref _newModel, value); }
public ICommand AddCategoryCommand { get; }
public ICommand AddManufacturerCommand { get; }
public ICommand AddModelCommand { get; }
//конструктор
public PageEquipmentAddViewModel(ICallbackUpdate callback)
{
this.callback = callback;
AddCategoryCommand = new Command(AddCategoryExecute);
AddManufacturerCommand = new Command(AddManufacturerExecute);
AddModelCommand = new Command(AddModelExecute, AddModelCanExecute);
GetCategory();
GetManufacturer();
}
#region обработка комманд
private bool AddModelCanExecute(object arg)
{
if (SelectedCategory != null && SelectedManufacturer != null && !String.IsNullOrEmpty(NewModel)) return true;
return false;
}
private async void AddModelExecute(object obj)
{
Model model = new Model(0, NewModel, SelectedCategory, SelectedManufacturer);
IsAwait = true;
bool result = await EquipmentDB.IsExistsModelAsync(model);
IsAwait = false;
if (!result)
{
IsAwait = true;
int id = await EquipmentDB.AddModelAsync(model);
IsAwait = false;
Model newModel = new Model(id, NewModel, SelectedCategory, SelectedManufacturer);
callback.AddToList(newModel);
window.frame_OrderInfo.GoBack();
}
else
{
callback.Select(model);
window.frame_OrderInfo.GoBack();
}
}
private async void AddManufacturerExecute(object obj)
{
View.Dialog.InputTextDialog inputDialog = new View.Dialog.InputTextDialog();
Dialog.InputDialogViewModel viewModel = new Dialog.InputDialogViewModel("Введите название нового производителя", "производитель оборудования");
inputDialog.DataContext = viewModel;
IsAwait = true;
var result = await DialogHost.Show(inputDialog, "OrderDialog");
IsAwait = false;
if ((bool)result == true)
{
//проверка на существование производителя
if (await EquipmentDB.IsExistManufacturerAsync(viewModel.Name))
{
View.Dialog.InfoDialog infoDialog = new View.Dialog.InfoDialog();
Dialog.InfoDialogViewModel context = new Dialog.InfoDialogViewModel("Производитель уже существует");
infoDialog.DataContext = context;
await DialogHost.Show(infoDialog, "OrderDialog");
//выбираем, если существует
foreach (var item in _manufacturerList)
{
if (item.ManufacturerName.ToLower().Equals(viewModel.Name.ToLower()))
{
SelectedManufacturer = item;
}
}
}
else
{
//добавление производителя
IsAwait = true;
int id = await EquipmentDB.AddManufacturerAsync(viewModel.Name);
IsAwait = false;
if (id != 0)
{
Manufacturer manufacturer = new Manufacturer(id, viewModel.Name);
_manufacturerList.Add(manufacturer);
SelectedManufacturer = manufacturer;
}
else
{
View.Dialog.InfoDialog infoDialog = new View.Dialog.InfoDialog();
Dialog.InfoDialogViewModel context = new Dialog.InfoDialogViewModel("ошибка добавления производителя");
infoDialog.DataContext = context;
await DialogHost.Show(infoDialog, "OrderDialog");
}
}
}
}
private async void AddCategoryExecute(object obj)
{
View.Dialog.InputTextDialog inputDialog = new View.Dialog.InputTextDialog();
Dialog.InputDialogViewModel viewModel = new Dialog.InputDialogViewModel("Введите название новой категории", "категория оборудования");
inputDialog.DataContext = viewModel;
IsAwait = true;
var result = await DialogHost.Show(inputDialog, "OrderDialog");
IsAwait = false;
if ((bool)result == true)
{
//проверка на существование категории
if (await EquipmentDB.IsExistCategoryAsync(viewModel.Name))
{
View.Dialog.InfoDialog infoDialog = new View.Dialog.InfoDialog();
Dialog.InfoDialogViewModel context = new Dialog.InfoDialogViewModel("Группа уже существует");
infoDialog.DataContext = context;
await DialogHost.Show(infoDialog, "OrderDialog");
//выбираем, если существует
foreach (var item in _categoryList)
{
if (item.CategoryName.ToLower().Equals(viewModel.Name.ToLower()))
{
SelectedCategory = item;
}
}
}
else
{
//добавление категории
IsAwait = true;
int id = await EquipmentDB.AddCategoryAsync(viewModel.Name);
IsAwait = false;
if (id != 0)
{
Category category = new Category(id, viewModel.Name);
_categoryList.Add(category);
SelectedCategory = category;
}
else
{
View.Dialog.InfoDialog infoDialog = new View.Dialog.InfoDialog();
Dialog.InfoDialogViewModel context = new Dialog.InfoDialogViewModel("ошибка добавления категории");
infoDialog.DataContext = context;
await DialogHost.Show(infoDialog, "OrderDialog");
}
}
}
}
#endregion
private async void GetManufacturer()
{
IsAwait = true;
var list = await EquipmentDB.GetManufacturerAsync();
IsAwait = false;
if (list == null)
Message("Ошибка чтения информации из базы данных!");
else
foreach (var item in list) { _manufacturerList.Add(item); }
}
private async void GetCategory()
{
IsAwait = true;
var list = await EquipmentDB.GetCategoryAsync();
IsAwait = false;
if (list == null)
Message("Ошибка чтения информации из базы данных!");
else
foreach (var item in list) { _categoryList.Add(item); }
}
//Wpf.DialogHost
private async void Message(string msg)
{
View.Dialog.InfoDialog infoDialog = new View.Dialog.InfoDialog();
Dialog.InfoDialogViewModel context = new Dialog.InfoDialogViewModel(msg);
infoDialog.DataContext = context;
await DialogHost.Show(infoDialog, "OrderDialog");
}
}
}
|
using UnityEngine;
using System.Collections;
public class ActionTreasureSet : MonoBehaviour {
//ボタンの宝番号
public int treasureNum = 0;
//スプライトリスト
public Sprite[] buttonSprite;
//プレイヤーアクション4のチェックボタン
public CheckFrameYesButton cfyb;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
}
public void OnBottonClick() {
for (int i=1; i<=3; i++) {
//GameObject.Find("PlayerButton_" + i).GetComponent<SpriteRenderer>().color = Color.white;
GameObject.Find("TreasureButton_" + i).GetComponent<SpriteRenderer>().sprite = buttonSprite[0];
}
//this.GetComponent<SpriteRenderer>().color = Color.red;
this.GetComponent<SpriteRenderer>().sprite = buttonSprite[1];
cfyb.treasureSelect = treasureNum;
}
public void InitSprite() {
this.GetComponent<SpriteRenderer>().sprite = buttonSprite[0];
}
}
|
namespace DemoSite.Services
{
#region namespaces
using System;
using System.Management.Automation;
using System.Management.Automation.Runspaces;
using System.Collections.ObjectModel;
using System.IO;
using System.Collections;
using DemoSite.Models;
#endregion
public class ConfigLoader
{
public DemoConfig DemoConfig { get; private set; }
public ConfigLoader(string env, string location)
{
var scriptFilePath = Path.Combine(location, @"..\Scripts\Get-Config.ps1");
DemoConfig = CreateDemoConfig(GetConfigRaw(env, scriptFilePath));
}
public ConfigLoader(Tuple<string, string> args /* to work-around powershell bug in method resolve*/)
{
var env = args.Item1;
var xmlDefn = args.Item2;
var sfd = GetScriptFileFromEmbeddedResource();
var scriptFilePath = sfd.Item1;
using (sfd.Item2)
{
DemoConfig = CreateDemoConfig(GetConfigRaw(env, scriptFilePath, xmlDefn));
}
}
private DemoConfig CreateDemoConfig(Hashtable ht)
{
return new DemoConfig(ht);
}
private Hashtable GetConfigRaw(string env, string scriptFilePath, string xmlDefn = null)
{
using (var runspace = RunspaceFactory.CreateRunspace())
{
using (var pipeline = runspace.CreatePipeline())
{
var getConfigCmd = new Command(scriptFilePath);
var envParam = new CommandParameter("Env", env);
getConfigCmd.Parameters.Add(envParam);
if (xmlDefn != null)
{
var envFileContentParam = new CommandParameter("EnvFileContent", xmlDefn);
getConfigCmd.Parameters.Add(envFileContentParam);
}
pipeline.Commands.Add(getConfigCmd);
runspace.Open();
Collection<PSObject> results = pipeline.Invoke();
var res = results[0].BaseObject as Hashtable;
if (res == null)
{
throw new Exception("Missing Config");
}
return res;
}
}
}
private Tuple<string, IDisposable> GetScriptFileFromEmbeddedResource()
{
var path = Path.GetTempPath();
var scriptFile = Path.Combine(path, "Get-Config.ps1");
var modFile = Path.Combine(path, "DPAPI.psm1");
File.WriteAllBytes(scriptFile, Properties.Resources.Get_Config);
File.WriteAllBytes(modFile, Properties.Resources.DPAPI);
return new Tuple<string, IDisposable>(scriptFile, System.Disposables.Disposable.Create(() =>
{
File.Delete(scriptFile);
File.Delete(modFile);
}));
}
}
} |
using System;
using System.Collections.Generic;
using System.Reflection;
using Atc.CodeAnalysis.CSharp.SyntaxFactories;
using Atc.XUnit;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Xunit;
using Xunit.Abstractions;
namespace Atc.CodeAnalysis.CSharp.Tests
{
public class CodeComplianceTests
{
// ReSharper disable once NotAccessedField.Local
private readonly ITestOutputHelper testOutputHelper;
private readonly Assembly sourceAssembly = typeof(AtcCodeAnalysisCSharpTypeInitializer).Assembly;
private readonly Assembly testAssembly = typeof(CodeComplianceTests).Assembly;
private readonly List<Type> excludeTypes = new List<Type>
{
// TODO: Add UnitTest and remove from this list!!
typeof(ClassDeclarationSyntaxExtensions),
typeof(EnumDeclarationSyntaxExtensions),
typeof(MethodDeclarationSyntaxExtensions),
typeof(SyntaxNodeExtensions),
typeof(InterfaceDeclarationSyntaxExtensions),
typeof(CompilationUnitSyntaxExtensions),
typeof(Factories.SuppressMessageAttributeFactory),
typeof(SyntaxAccessorDeclarationFactory),
typeof(SyntaxArgumentListFactory),
typeof(SyntaxAssignmentExpressionFactory),
typeof(SyntaxAttributeArgumentFactory),
typeof(SyntaxAttributeArgumentListFactory),
typeof(SyntaxAttributeFactory),
typeof(SyntaxAttributeListFactory),
typeof(SyntaxClassDeclarationFactory),
typeof(SyntaxIfStatementFactory),
typeof(SyntaxInterfaceDeclarationFactory),
typeof(SyntaxInterpolatedFactory),
typeof(SyntaxMemberAccessExpressionFactory),
typeof(SyntaxNameEqualsFactory),
typeof(SyntaxObjectCreationExpressionFactory),
typeof(SyntaxParameterFactory),
typeof(SyntaxParameterListFactory),
typeof(SyntaxThrowStatementFactory),
typeof(SyntaxTokenFactory),
typeof(SyntaxTokenListFactory),
typeof(SyntaxTypeArgumentListFactory),
typeof(SyntaxVariableDeclarationFactory),
};
public CodeComplianceTests(ITestOutputHelper testOutputHelper)
{
this.testOutputHelper = testOutputHelper;
}
[Fact]
public void AssertExportedMethodsWithMissingTests_AbstractSyntaxTree()
{
// Act & Assert
CodeComplianceTestHelper.AssertExportedMethodsWithMissingTests(
DecompilerType.AbstractSyntaxTree,
sourceAssembly,
testAssembly,
excludeTypes);
}
[Fact]
public void AssertExportedMethodsWithMissingTests_MonoReflection()
{
// Act & Assert
CodeComplianceTestHelper.AssertExportedMethodsWithMissingTests(
DecompilerType.MonoReflection,
sourceAssembly,
testAssembly,
excludeTypes);
}
[Fact]
public void AssertExportedTypesWithMissingComments()
{
// Act & Assert
CodeComplianceDocumentationHelper.AssertExportedTypesWithMissingComments(
sourceAssembly);
}
[Fact]
public void AssertExportedTypesWithWrongNaming()
{
// Act & Assert
CodeComplianceHelper.AssertExportedTypesWithWrongDefinitions(
sourceAssembly);
}
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[ExecuteInEditMode]
public class T : MonoBehaviour {
LightmapData[] m_savedSceneLightmapData;
[System.Serializable]
public struct CustomLightmaps {
public Texture2D lightmapColor;
public Texture2D lightmapDir;
//public Texture2D lightmapLight;
public Texture2D shadowMask;
}
[System.Serializable]
public struct MeshRendererLightmapData {
public string friendlyName;
public MeshRenderer actualMeshRenderer;
public int objectHash;
public int RendererLightmapIndex;
public Vector4 RendererLightmapScaleOffset;
public MeshRendererLightmapData(MeshRenderer actualMeshRenderer, string friendlyName, int objectHash, int RendererLightmapIndex, Vector4 RendererLightmapScaleOffset) {
this.actualMeshRenderer = actualMeshRenderer;
this.friendlyName = friendlyName;
this.objectHash = objectHash;
this.RendererLightmapIndex = RendererLightmapIndex;
this.RendererLightmapScaleOffset = RendererLightmapScaleOffset;
}
}
[Space(15)]
[SerializeField]
List<CustomLightmapsArray> m_savedSceneLightmaps;
[Space(30)]
[TextArea(3, 3)]
public string info0 = "Press this bool after you finished a full bake \nto record all generated lightmap references.";
[Space(5)]
[SerializeField]
bool m_SaveNewLightmapData;
[Space(15)]
[TextArea(3, 3)]
public string info1 = "Press this bool after you Render Selected Groups \nand you see the other non-re-rendered groups \nsuddenly got broken lightmaps/UVs. Or if \nyou just want to swap between different lightmap variants (e.g. day/night).";
[Space(15)]
[SerializeField]
int m_LightmapSelectionToRestoreFrom = 0;
[Space(5)]
[SerializeField]
bool m_LoadLightmapFromSelection;
[Space(20)]
[Header("________________________________________________________________________________ Nice custom GUI skills amirite?")]
[Space(45)]
[SerializeField]
bool m_AlsoSaveLightmapDataFromAllMeshRenderers = false;
[TextArea(3, 3)]
public string info2 = "Be patient when you click Save or Load. It may take a while (e.g. up to 10 seconds) if you have many thousands of mesh renderers in your scene.";
[System.Serializable]
public class CustomLightmapsArray {//we need a struct/class to hold arrays because unity inspector does not support arrays of arrays, but supports arrays of structs/classes that hold arrays........!
public string friendlyName;
public CustomLightmaps[] customLightmaps;
public Dictionary<int, MeshRendererLightmapData> meshRendererLightmapDataFromScene;
[TextArea(4, 4)]
public string info;// "The following array is just for show in the inspector. Internally I use a dictionary of instance ids, so it can be ported between similar scenes without needing mesh renderer references.";
public List<MeshRendererLightmapData> meshRendererLightmapDataFromScene_inspector;
public CustomLightmapsArray(int length) {
friendlyName = "";
customLightmaps = new CustomLightmaps[length];
meshRendererLightmapDataFromScene = new Dictionary<int, MeshRendererLightmapData>();
info = "The following array is for show in the inspector. BUT also to save the non-serializable internal dictionary of instance ids";
meshRendererLightmapDataFromScene_inspector = new List<MeshRendererLightmapData>();
}
public CustomLightmapsArray(int length, string friendlyName) {
this.friendlyName = friendlyName;
customLightmaps = new CustomLightmaps[length];
meshRendererLightmapDataFromScene = new Dictionary<int, MeshRendererLightmapData>();
info = "The following array is for show in the inspector. BUT also to save the non-serializable internal dictionary of instance ids";
meshRendererLightmapDataFromScene_inspector = new List<MeshRendererLightmapData>();
}
public void CloneToInspectorArray() {
meshRendererLightmapDataFromScene_inspector.Clear();
meshRendererLightmapDataFromScene_inspector.AddRange(meshRendererLightmapDataFromScene.Values);
}
public void LoadDictionaryFromInspectorArray() {
meshRendererLightmapDataFromScene = new Dictionary<int, MeshRendererLightmapData>();
foreach(MeshRendererLightmapData lmd in meshRendererLightmapDataFromScene_inspector) {
meshRendererLightmapDataFromScene.Add(lmd.objectHash, lmd);
}
}
}
public void SaveLightmapData() {
m_savedSceneLightmapData = new LightmapData[LightmapSettings.lightmaps.Length];
for(int i = 0; i < LightmapSettings.lightmaps.Length; i++) {
m_savedSceneLightmapData[i] = LightmapSettings.lightmaps[i];
}
int index;
if(m_AlsoSaveLightmapDataFromAllMeshRenderers) {
MeshRenderer[] allMeshRenderers = (MeshRenderer[])FindObjectsOfType(typeof(MeshRenderer));
m_savedSceneLightmaps.Add(new CustomLightmapsArray(m_savedSceneLightmapData.Length, m_savedSceneLightmaps.Count + " "));
index = m_savedSceneLightmaps.Count - 1;
m_LightmapSelectionToRestoreFrom = index;
for(int i = 0; i < allMeshRenderers.Length; i++) {
if(allMeshRenderers[i].lightmapIndex == -1) {
continue;
}
MeshRendererLightmapData newLMD = new MeshRendererLightmapData(allMeshRenderers[i], allMeshRenderers[i].name, allMeshRenderers[i].GetHashCode(), allMeshRenderers[i].lightmapIndex, allMeshRenderers[i].lightmapScaleOffset);
m_savedSceneLightmaps[index].meshRendererLightmapDataFromScene.Add(newLMD.objectHash, newLMD);
}
m_savedSceneLightmaps[m_LightmapSelectionToRestoreFrom].CloneToInspectorArray();
} else {
index = m_savedSceneLightmaps.Count - 1;
m_LightmapSelectionToRestoreFrom = index;
}
for(int i = 0; i < LightmapSettings.lightmaps.Length; i++) {
m_savedSceneLightmaps[index].customLightmaps[i].lightmapColor = m_savedSceneLightmapData[i].lightmapColor;
m_savedSceneLightmaps[index].customLightmaps[i].lightmapDir = m_savedSceneLightmapData[i].lightmapDir;
//m_savedSceneLightmaps[i].lightmapLight = m_savedSceneLightmapData[i].lightmapLight;
m_savedSceneLightmaps[index].customLightmaps[i].shadowMask = m_savedSceneLightmapData[i].shadowMask;
}
Debug.Log("[BakeryLightmapManager][SAVED] Current LightmapSettings.lightmaps (lightmap texture references) saved to m_savedSceneLightmaps!");
}
public void LoadLightmapData(int lightmapSelectionToRestoreFrom) {
m_LightmapSelectionToRestoreFrom = lightmapSelectionToRestoreFrom;
//LightmapSettings.lightmaps = new LightmapData[m_savedSceneLightmapData.Length];
LightmapData[] customLightmapDataArr = new LightmapData[m_savedSceneLightmaps[m_LightmapSelectionToRestoreFrom].customLightmaps.Length];
/*
if(m_savedSceneLightmapData!=null)
for(int i = 0; i< m_savedSceneLightmaps.Length; i++){
if(i<m_savedSceneLightmapData.Length)
customLightmapDataArr[i] = m_savedSceneLightmapData[i];
else{
customLightmapDataArr[i] = new LightmapData();
Debug.Log("[BakeryLightmapManager] The internal m_savedSceneLightmapData number of textures does not match the m_savedSceneLightmaps number of textures that you have in the inspector. Did you forget to Save New Lightmap Data after the previous bake completed?");
}
}
else*/
for(int i = 0; i < m_savedSceneLightmaps[m_LightmapSelectionToRestoreFrom].customLightmaps.Length; i++) {
customLightmapDataArr[i] = new LightmapData();
}
if(m_AlsoSaveLightmapDataFromAllMeshRenderers) {
//Unity can't serialize dictionaries, and this editor script will have its internal dictionary flushed/reset for instance every time you recompile any scripts in your project.
if(m_savedSceneLightmaps[m_LightmapSelectionToRestoreFrom].meshRendererLightmapDataFromScene == null) {
m_savedSceneLightmaps[m_LightmapSelectionToRestoreFrom].LoadDictionaryFromInspectorArray();
}
MeshRenderer[] allMeshRenderers = (MeshRenderer[])FindObjectsOfType(typeof(MeshRenderer));
//foreach(KeyValuePair<int,MeshRendererLightmapData> mrld in m_savedSceneLightmaps[m_LightmapSelectionToRestoreFrom].meshRendererLightmapDataForLoadedScenes){
//foreach(MeshRendererLightmapData mrld in m_savedSceneLightmaps[m_LightmapSelectionToRestoreFrom].meshRendererLightmapDataForLoadedScenes){
//mrld.actualMeshRenderer.lightmapIndex = mrld.RendererLightmapIndex;
//mrld.actualMeshRenderer.lightmapScaleOffset = mrld.RendererLightmapScaleOffset;
//}
for(int i = 0; i < allMeshRenderers.Length; i++) {
MeshRendererLightmapData mrld;
bool success = m_savedSceneLightmaps[m_LightmapSelectionToRestoreFrom].meshRendererLightmapDataFromScene.TryGetValue(allMeshRenderers[i].GetInstanceID(), out mrld);
if(success) {
allMeshRenderers[i].lightmapIndex = mrld.RendererLightmapIndex;
allMeshRenderers[i].lightmapScaleOffset = mrld.RendererLightmapScaleOffset;
//this is so you can see it in the inspector. I wish Dictionaries worked witht he inspector without having to install 3rd party assets...
mrld.actualMeshRenderer = allMeshRenderers[i];
}
}
m_savedSceneLightmaps[m_LightmapSelectionToRestoreFrom].CloneToInspectorArray();
}
for(int i = 0; i < m_savedSceneLightmaps[m_LightmapSelectionToRestoreFrom].customLightmaps.Length; i++) {
customLightmapDataArr[i].lightmapColor = m_savedSceneLightmaps[m_LightmapSelectionToRestoreFrom].customLightmaps[i].lightmapColor;
customLightmapDataArr[i].lightmapDir = m_savedSceneLightmaps[m_LightmapSelectionToRestoreFrom].customLightmaps[i].lightmapDir;
customLightmapDataArr[i].shadowMask = m_savedSceneLightmaps[m_LightmapSelectionToRestoreFrom].customLightmaps[i].shadowMask;
}
LightmapSettings.lightmaps = customLightmapDataArr;
Debug.Log("[BakeryLightmapManager][RESTORED] Current LightmapSettings.lightmaps (lightmap texture references) restored from m_savedSceneLightmaps!");
}
// Update is called once per frame
void Update() {
#if UNITY_EDITOR
if(m_SaveNewLightmapData) {
m_SaveNewLightmapData = false;
SaveLightmapData();
}
if(m_LoadLightmapFromSelection) {
m_LoadLightmapFromSelection = false;
LoadLightmapData(m_LightmapSelectionToRestoreFrom);
}
#endif
}
} |
using System;
using System.Collections.Generic;
using System.IO;
using System.Xml;
using System.Xml.Serialization;
using Microsoft.SqlServer.TransactSql.ScriptDom;
namespace SSDTDevPack.Common.Settings
{
public class Settings
{
public Settings()
{
GeneratorOptions = new SqlScriptGeneratorOptions();
}
public SqlScriptGeneratorOptions GeneratorOptions { get; set; }
public string PrimaryKeyName { get; set; }
}
public class SavedSettings
{
private const string primaryKeyNameTemplate = "PK_%TABLENAME%";
public static Settings Get()
{
XmlSerializer serializer = new XmlSerializer(typeof(Settings));
var settings = GetSettings(serializer);
if (String.IsNullOrEmpty(settings.PrimaryKeyName))
settings.PrimaryKeyName = primaryKeyNameTemplate;
return settings;
}
private static Settings GetSettings(XmlSerializer serializer)
{
if (File.Exists(GetPath("config.xml")))
{
StreamReader reader = new StreamReader(GetPath("config.xml"));
var settings = (Settings) serializer.Deserialize(reader);
reader.Close();
return settings;
}
return new Settings();
}
private static string GetPath(string file)
{
return Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), Path.Combine("SSDTDevPack", file));
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class RoomTemplates : MonoBehaviour
{
public GameObject[] startRooms;
public GameObject[] topRooms;
public GameObject[] bottomRooms;
public GameObject[] leftRooms;
public GameObject[] rightRooms;
public GameObject[] endTopRooms;
public GameObject[] endBottomRooms;
public GameObject[] endLeftRooms;
public GameObject[] endRightRooms;
[Space(16)]
public GameObject closedRoom;
[Space(16)]
public GameObject miniBoss;
public bool spawnedMiniBoss;
[Space(16)]
public float maxRooms;
public List<GameObject> rooms;
[Space(16)]
public float waitTime;
} |
namespace Witsml.Extensions
{
public static class StringExtensions
{
public static bool IsNumeric(this string input)
{
return double.TryParse(input, out _);
}
public static string NullIfEmpty(this string value)
{
return string.IsNullOrEmpty(value) ? null : value;
}
}
}
|
using System;
using System.Linq;
using System.Threading.Tasks;
using System.Linq.Expressions;
using System.Collections.Generic;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Http;
using Microsoft.EntityFrameworkCore;
using VipcoSageX3.Services;
using VipcoSageX3.ViewModels;
using VipcoSageX3.Models.SageX3;
using AutoMapper;
using VipcoSageX3.Helper;
using RtfPipe;
using System.Data;
using Microsoft.AspNetCore.Hosting;
using ClosedXML.Excel;
using System.IO;
using System.Text;
using HtmlAgilityPack;
namespace VipcoSageX3.Controllers.SageX3
{
// : api/PurchaseRequest
[Route("api/[controller]")]
[ApiController]
public class PurchaseRequestController : GenericSageX3Controller<Prequisd>
{
private readonly IRepositorySageX3<Cacce> repositoryDim;
private readonly IRepositorySageX3<Prequiso> repositoryPRLink;
private readonly IRepositorySageX3<Porderq> repositoryPOLine;
private readonly IRepositorySageX3<Porder> repositoryPoHeader;
private readonly IRepositorySageX3<Preceiptd> repositoryRCLine;
private readonly IRepositorySageX3<Cptanalin> repositoryDimLink;
private readonly IRepositoryDapperSageX3<PurchaseRequestAndOrderViewModel> repositoryPrAndPo;
private readonly IRepositoryDapperSageX3<PurchaseReceiptViewModel> repositoryPrq;
private readonly IHelperService helperService;
private readonly IHostingEnvironment hosting;
//Context
private readonly SageX3Context sageContext;
// GET: api/PurchaseRequest
public PurchaseRequestController(
IRepositorySageX3<Prequisd> repo,
IRepositorySageX3<Prequiso> repoPrLink,
IRepositorySageX3<Porderq> repoPoLine,
IRepositorySageX3<Preceiptd> repoRcLine,
IRepositorySageX3<Cptanalin> repoDimLink,
IRepositorySageX3<Porder> repoPoHeader,
IRepositorySageX3<Cacce> repoDim,
IRepositoryDapperSageX3<PurchaseRequestAndOrderViewModel> repoPrAndPo,
IRepositoryDapperSageX3<PurchaseReceiptViewModel> repoPrq,
IHelperService helper,
SageX3Context x3Context,
IHostingEnvironment hosting,
IMapper mapper) : base(repo, mapper)
{
// Repository SageX3
this.repositoryDim = repoDim;
this.repositoryDimLink = repoDimLink;
this.repositoryPoHeader = repoPoHeader;
this.repositoryPOLine = repoPoLine;
this.repositoryPRLink = repoPrLink;
this.repositoryRCLine = repoRcLine;
this.repositoryPrAndPo = repoPrAndPo;
this.repositoryPrq = repoPrq;
//DI
this.helperService = helper;
// Context
this.sageContext = x3Context;
// Hosting
this.hosting = hosting;
}
private string ConvertHtmlToText(string Html)
{
var htmlDoc = new HtmlDocument();
htmlDoc.LoadHtml(Html);
var htmlBody = htmlDoc.DocumentNode;
// return htmlBody.OuterHtml;
var sb = new StringBuilder();
foreach (var node in htmlBody.DescendantsAndSelf())
{
if (!node.HasChildNodes)
{
string text = node.InnerText;
text = text.Replace(" ", "");
if (!string.IsNullOrEmpty(text))
sb.AppendLine(text.Trim());
}
}
return sb.ToString();
}
private async Task<List<PurchaseRequestAndOrderViewModel>> GetData(ScrollViewModel Scroll,bool option = false)
{
#region Query
var QueryData = (from prh in this.sageContext.Prequis
join prd in this.sageContext.Prequisd on prh.Pshnum0 equals prd.Pshnum0 into new_pr
from all1 in new_pr.DefaultIfEmpty()
join itm in this.sageContext.Itmmaster on all1.Itmref0 equals itm.Itmref0 into new_pr_itm
from all2 in new_pr_itm.DefaultIfEmpty()
join dim in this.sageContext.Cptanalin on new { key1 = all1.Pshnum0, key2 = all1.Psdlin0 } equals new { key1 = dim.Vcrnum0, key2 = dim.Vcrlin0 } into new_pr_dim
from all3 in new_pr_dim.DefaultIfEmpty()
join pro in this.sageContext.Prequiso on new { all1.Pshnum0, all1.Psdlin0 } equals new { pro.Pshnum0, pro.Psdlin0 } into new_pr_lik
from all4 in new_pr_lik.DefaultIfEmpty()
join pod in this.sageContext.Porderq on new { all4.Pohnum0, all4.Poplin0 } equals new { pod.Pohnum0, pod.Poplin0 } into new_pr_po
from all5 in new_pr_po.DefaultIfEmpty()
join dim in this.sageContext.Cptanalin on
new { key1 = all5.Pohnum0, key2 = all5.Poplin0 } equals
new { key1 = dim.Vcrnum0, key2 = dim.Vcrlin0 } into new_po_dim
from all6 in new_po_dim.DefaultIfEmpty()
where all2.Tclcod0.StartsWith('1') //&& (all4.Pohnum0 == "PO1808-0006" || all4.Pohnum0 == "PO1808-0008" || all4.Pohnum0 == "PO1808-0072")
select new
{
item = all2,
pod = all5,
prd = all1,
prh,
pro = all4,
dim = all3,
dimPo = all6
}).AsQueryable();
#endregion
#region Filter&Scroll
// Filter
var filters = string.IsNullOrEmpty(Scroll.Filter) ? new string[] { "" }
: Scroll.Filter.Split(null);
foreach (string temp in filters)
{
string keyword = temp.ToLower();
QueryData = QueryData.Where(x => x.prd.Pjt0.ToLower().Contains(keyword) ||
x.prd.Itmref0.ToLower().Contains(keyword) ||
x.prd.Itmdes0.ToLower().Contains(keyword) ||
x.prh.Creusr0.ToLower().Contains(keyword) ||
x.prd.Pshnum0.ToLower().Contains(keyword) ||
x.pod.Pohnum0.ToLower().Contains(keyword) ||
x.pod.Itmref0.ToLower().Contains(keyword));
}
if (!string.IsNullOrEmpty(Scroll.WhereBranch))
QueryData = QueryData.Where(x => x.dim.Cce0 == Scroll.WhereBranch);
if (!string.IsNullOrEmpty(Scroll.WhereWorkGroup))
QueryData = QueryData.Where(x => x.dim.Cce3 == Scroll.WhereWorkGroup);
if (!string.IsNullOrEmpty(Scroll.WhereWorkItem))
QueryData = QueryData.Where(x => x.dim.Cce1 == Scroll.WhereWorkItem);
if (!string.IsNullOrEmpty(Scroll.WhereProject))
QueryData = QueryData.Where(x => x.dim.Cce2 == Scroll.WhereProject);
if (Scroll.SDate.HasValue && Scroll.EDate.HasValue)
{
QueryData = QueryData.Where(x =>
x.prh.Prqdat0.Date >= Scroll.SDate.Value.Date &&
x.prh.Prqdat0.Date <= Scroll.EDate.Value.Date);
}
//MapData.Branch = PrDim.Cce0;
//MapData.WorkItem = PrDim.Cce1;
//MapData.Project = PrDim.Cce2;
//MapData.WorkGroup = PrDim.Cce3;
switch (Scroll.SortField)
{
case "PrNumber":
if (Scroll.SortOrder == -1)
QueryData = QueryData.OrderByDescending(x => x.prh.Pshnum0);
else
QueryData = QueryData.OrderBy(x => x.prh.Pshnum0);
break;
case "Project":
if (Scroll.SortOrder == -1)
QueryData = QueryData.OrderByDescending(x => x.prh.Pjth0);
else
QueryData = QueryData.OrderBy(x => x.prh.Pjth0);
break;
case "PRDateString":
if (Scroll.SortOrder == -1)
QueryData = QueryData.OrderByDescending(x => x.prh.Prqdat0);
else
QueryData = QueryData.OrderBy(x => x.prh.Prqdat0);
break;
case "ItemName":
if (Scroll.SortOrder == -1)
QueryData = QueryData.OrderByDescending(x => x.prd.Itmdes0);
else
QueryData = QueryData.OrderBy(x => x.prd.Itmdes0);
break;
case "Branch":
if (Scroll.SortOrder == -1)
QueryData = QueryData.OrderByDescending(x => x.dim.Cce0);
else
QueryData = QueryData.OrderBy(x => x.dim.Cce0);
break;
case "WorkItemName":
if (Scroll.SortOrder == -1)
QueryData = QueryData.OrderByDescending(x => x.dim.Cce1);
else
QueryData = QueryData.OrderBy(x => x.dim.Cce1);
break;
case "WorkGroupName":
if (Scroll.SortOrder == -1)
QueryData = QueryData.OrderByDescending(x => x.dim.Cce3);
else
QueryData = QueryData.OrderBy(x => x.dim.Cce3);
break;
case "PoNumber":
if (Scroll.SortOrder == -1)
QueryData = QueryData.OrderByDescending(x => x.pod.Pohnum0);
else
QueryData = QueryData.OrderBy(x => x.pod.Pohnum0);
break;
case "PoDateString":
if (Scroll.SortOrder == -1)
QueryData = QueryData.OrderByDescending(x => x.pod.Orddat0);
else
QueryData = QueryData.OrderBy(x => x.pod.Orddat0);
break;
case "DueDateString":
if (Scroll.SortOrder == -1)
QueryData = QueryData.OrderByDescending(x => x.pod.Extrcpdat0);
else
QueryData = QueryData.OrderBy(x => x.pod.Extrcpdat0);
break;
case "CreateBy":
if (Scroll.SortOrder == -1)
QueryData = QueryData.OrderByDescending(x => x.prh.Creusr0);
else
QueryData = QueryData.OrderBy(x => x.prh.Creusr0);
break;
default:
QueryData = QueryData.OrderByDescending(x => x.prh.Prqdat0);
break;
}
Scroll.TotalRow = await QueryData.CountAsync();
#endregion
#region MyRegion
var DataSource = await QueryData.Skip(Scroll.Skip ?? 0).Take(Scroll.Take ?? 15).AsNoTracking().ToListAsync();
var MapDatas = new List<PurchaseRequestAndOrderViewModel>();
var ListCCE = new List<string>();
foreach (var item in DataSource)
{
var MapData = this.mapper.Map<Prequis, PurchaseRequestAndOrderViewModel>(item.prh);
MapData.ToDate = DateTime.Today.AddDays(-2);
this.mapper.Map<Prequisd, PurchaseRequestAndOrderViewModel>(item.prd, MapData);
// PrWeight
if (item?.item?.Itmwei0 > 0)
MapData.PrWeight = (double)item.item.Itmwei0 * MapData.QuantityPur;
//ItemName
if (!string.IsNullOrEmpty(item?.item?.Purtex0))
{
var fulltext = await this.sageContext.Texclob.Where(x => x.Code0 == item.item.Purtex0)
.Select(x => x.Texte0)
.FirstOrDefaultAsync();
if (!string.IsNullOrEmpty(fulltext))
{
if (fulltext.StartsWith("{\\rtf1") && !option)
MapData.ItemName = Rtf.ToHtml(fulltext);
else
MapData.ItemName = fulltext;
}
else
MapData.ItemName = MapData.ItemName;
}
else
MapData.ItemName = MapData.ItemName;
// Get Dimension for PurchaseRequest1
if (item.dim != null)
{
MapData.Branch = item.dim.Cce0;
MapData.WorkItem = item.dim.Cce1;
MapData.Project = item.dim.Cce2;
MapData.WorkGroup = item.dim.Cce3;
// Add CCE
ListCCE.Add(item.dim.Cce0);
ListCCE.Add(item.dim.Cce1);
ListCCE.Add(item.dim.Cce2);
ListCCE.Add(item.dim.Cce3);
}
// Get Purchase Request Link
if (item.pro != null)
{
this.mapper.Map<Prequiso, PurchaseRequestAndOrderViewModel>(item.pro, MapData);
// Get Purchase Order
if (item.pod != null)
{
// Get Status PurchaseOrder
var PoHeader = await this.repositoryPoHeader.GetFirstOrDefaultAsync(x => new Porder()
{
Pohnum0 = x.Pohnum0,
Zpo210 = x.Zpo210,
Cleflg0 = x.Cleflg0,
Rowid = x.Rowid
}, x => x.Pohnum0 == item.pod.Pohnum0);
if (PoHeader != null)
this.mapper.Map<Porder, PurchaseRequestAndOrderViewModel>(PoHeader, MapData);
this.mapper.Map<Porderq, PurchaseRequestAndOrderViewModel>(item.pod, MapData);
if (item.dimPo != null)
{
MapData.PoBranch = item.dimPo.Cce0;
MapData.PoWorkItem = item.dimPo.Cce1;
MapData.PoProject = item.dimPo.Cce2;
MapData.PoWorkGroup = item.dimPo.Cce3;
// Add CCE
ListCCE.Add(item.dimPo.Cce0);
ListCCE.Add(item.dimPo.Cce1);
ListCCE.Add(item.dimPo.Cce2);
ListCCE.Add(item.dimPo.Cce3);
}
//var ListRcs = await this.repositoryRCLine.GetToListAsync(
// x => x,
// x => x.Pohnum0 == item.pod.Pohnum0 && x.Poplin0 == item.pod.Poplin0 && x.Poqseq0 == item.pod.Poqseq0);
var ReciptionLine = await (from prc in this.sageContext.Preceiptd
join sto in this.sageContext.Stojou on
new { key1 = prc.Pthnum0, key2 = prc.Ptdlin0 } equals
new { key1 = sto.Vcrnum0, key2 = sto.Vcrlin0 } into new_sto
from all1 in new_sto.DefaultIfEmpty()
where prc.Pohnum0 == item.pod.Pohnum0 &&
prc.Poplin0 == item.pod.Poplin0 &&
prc.Poqseq0 == item.pod.Poqseq0 &&
((all1.Vcrtypreg0 == 0 && all1.Regflg0 == 1) ||
(all1.Vcrtypreg0 == 17 && all1.Regflg0 == 1))
select new
{
preciptD = prc,
stock = all1,
}).ToListAsync();
if (ReciptionLine.Any())
{
foreach (var itemRc in ReciptionLine)
{
var RcMapData = this.mapper.Map<Preceiptd, PurchaseReceiptViewModel>(itemRc.preciptD);
RcMapData.HeatNumber = itemRc?.stock?.Lot0 ?? "";
RcMapData.HeatNumber += itemRc?.stock?.Slo0 ?? "";
var RcDim = await this.repositoryDimLink.GetFirstOrDefaultAsync(x => x, x => x.Vcrnum0 == itemRc.preciptD.Pthnum0 && x.Vcrlin0 == itemRc.preciptD.Ptdlin0);
if (RcDim != null)
{
RcMapData.RcBranch = RcDim.Cce0;
RcMapData.RcWorkItem = RcDim.Cce1;
RcMapData.RcProject = RcDim.Cce2;
RcMapData.RcWorkGroup = RcDim.Cce3;
// Add CCE
ListCCE.Add(RcDim.Cce0);
ListCCE.Add(RcDim.Cce1);
ListCCE.Add(RcDim.Cce2);
ListCCE.Add(RcDim.Cce3);
}
// Add Rc to mapData
MapData.PurchaseReceipts.Add(RcMapData);
}
}
else
MapData.DeadLine = MapData.DueDate != null ? MapData.ToDate.Date > MapData.DueDate.Value.Date : false;
}
}
MapDatas.Add(MapData);
}
var allDim = await this.repositoryDim.GetToListAsync(x => new { Code = x.Cce0, Desc = x.Des0 }, x => ListCCE.Contains(x.Cce0));
if (allDim.Any())
{
foreach (var item in MapDatas)
{
//CCE name purchase request
item.BranchName = allDim.FirstOrDefault(x => x.Code == item.Branch)?.Desc ?? "-";
item.WorkGroupName = allDim.FirstOrDefault(x => x.Code == item.WorkGroup)?.Desc ?? "-";
item.WorkItemName = allDim.FirstOrDefault(x => x.Code == item.WorkItem)?.Desc ?? "-";
item.ProjectName = allDim.FirstOrDefault(x => x.Code == item.Project)?.Desc ?? "-";
//CCE name purchase order
item.PoBranchName = allDim.FirstOrDefault(x => x.Code == item.PoBranch)?.Desc ?? "-";
item.PoWorkGroupName = allDim.FirstOrDefault(x => x.Code == item.PoWorkGroup)?.Desc ?? "-";
item.PoWorkItemName = allDim.FirstOrDefault(x => x.Code == item.PoWorkItem)?.Desc ?? "-";
item.PoProjectName = allDim.FirstOrDefault(x => x.Code == item.PoProject)?.Desc ?? "-";
foreach (var item2 in item.PurchaseReceipts)
{
//CCE name purchase order
item2.RcBranchName = allDim.FirstOrDefault(x => x.Code == item2.RcBranch)?.Desc ?? "-";
item2.RcWorkGroupName = allDim.FirstOrDefault(x => x.Code == item2.RcWorkGroup)?.Desc ?? "-";
item2.RcWorkItemName = allDim.FirstOrDefault(x => x.Code == item2.RcWorkItem)?.Desc ?? "-";
item2.RcProjectName = allDim.FirstOrDefault(x => x.Code == item2.RcProject)?.Desc ?? "-";
}
}
}
#endregion
return MapDatas;
}
private async Task<List<PurchaseRequestAndOrderViewModel>> GetData2(ScrollViewModel scroll,bool option = false)
{
if (scroll != null)
{
var dbData = await this.repositoryPrAndPo.GetPurchaseRequestAndOrders(scroll);
scroll.TotalRow = 999;
foreach (var item in dbData)
{
item.ToDate = DateTime.Today.AddDays(-2);
if (item.ItemName.StartsWith("{\\rtf1") && !option)
item.ItemName = Rtf.ToHtml(item.ItemName);
// var ReciptionLine = await (from prc in this.sageContext.Preceiptd
// join sto in this.sageContext.Stojou on
// new { key1 = prc.Pthnum0, key2 = prc.Ptdlin0 } equals
// new { key1 = sto.Vcrnum0, key2 = sto.Vcrlin0 } into new_sto
// from all1 in new_sto.DefaultIfEmpty()
// where prc.Pohnum0 == item.PoNumber &&
// prc.Poplin0 == item.PoLine &&
// prc.Poqseq0 == item.PoSequence &&
// ((all1.Vcrtypreg0 == 0 && all1.Regflg0 == 1) ||
// (all1.Vcrtypreg0 == 17 && all1.Regflg0 == 1))
// select new
// {
// preciptD = prc,
// stock = all1,
// }).ToListAsync();
// if (ReciptionLine.Any())
// {
// foreach (var itemRc in ReciptionLine)
// {
// var RcMapData = this.mapper.Map<Preceiptd, PurchaseReceiptViewModel>(itemRc.preciptD);
// RcMapData.HeatNumber = itemRc?.stock?.Lot0 ?? "";
// RcMapData.HeatNumber += itemRc?.stock?.Slo0 ?? "";
// var RcDim = await this.repositoryDimLink.GetFirstOrDefaultAsync(x => x, x => x.Vcrnum0 == itemRc.preciptD.Pthnum0 && x.Vcrlin0 == itemRc.preciptD.Ptdlin0);
// if (RcDim != null)
// {
// RcMapData.RcBranch = RcDim.Cce0;
// RcMapData.RcWorkItem = RcDim.Cce1;
// RcMapData.RcProject = RcDim.Cce2;
// RcMapData.RcWorkGroup = RcDim.Cce3;
// }
// // Add Rc to mapData
// item.PurchaseReceipts.Add(RcMapData);
// }
// }
// else
// item.DeadLine = item.DueDate != null ? item.ToDate.Date > item.DueDate.Value.Date : false;
}
return dbData;
}
return null;
}
private async Task<List<PurchaseRequestAndOrderViewModel>> GetData3(ScrollViewModel scroll)
{
if (scroll != null)
{
string sWhere = "WHERE [ITM].[TCLCOD_0] LIKE '1%'";
string sSort = "";
string sQuery = "";
#region Where
var filters = string.IsNullOrEmpty(scroll.Filter) ? new string[] { "" }
: scroll.Filter.Split(null);
foreach (string temp in filters)
{
if (string.IsNullOrEmpty(temp))
continue;
string keyword = temp.ToLower();
sWhere += (string.IsNullOrEmpty(sWhere) ? "WHERE " : " AND ") +
$@"(LOWER(PRD.PJT_0) LIKE '%{keyword}%'
OR LOWER([PRD].[ITMREF_0]) LIKE '%{keyword}%'
OR LOWER([PRD].[ITMDES_0]) LIKE '%{keyword}%'
OR LOWER([PRH].[CREUSR_0]) LIKE '%{keyword}%'
OR LOWER([PRD].[PSHNUM_0]) LIKE '%{keyword}%'
OR LOWER([POD].[POHNUM_0]) LIKE '%{keyword}%'
OR LOWER([POD].[ITMREF_0]) LIKE '%{keyword}%')";
}
if (!string.IsNullOrEmpty(scroll.WhereBranch))
sWhere += (string.IsNullOrEmpty(sWhere) ? "WHERE " : " AND ") + $"DIM.CCE_0 = '{scroll.WhereProject}'";
if (!string.IsNullOrEmpty(scroll.WhereWorkGroup))
sWhere += (string.IsNullOrEmpty(sWhere) ? "WHERE " : " AND ") + $"DIM.CCE_3 = '{scroll.WhereProject}'";
if (!string.IsNullOrEmpty(scroll.WhereWorkItem))
sWhere += (string.IsNullOrEmpty(sWhere) ? "WHERE " : " AND ") + $"DIM.CCE_1 = '{scroll.WhereProject}'";
if (!string.IsNullOrEmpty(scroll.WhereProject))
sWhere += (string.IsNullOrEmpty(sWhere) ? "WHERE " : " AND ") + $"DIM.CCE_2 = '{scroll.WhereProject}'";
if (scroll.SDate.HasValue)
sWhere +=
(string.IsNullOrEmpty(sWhere) ? "WHERE " : " AND ") + $"PRH.PRQDAT_0 >= '{scroll.SDate.Value.AddHours(7).ToString("yyyy-MM-dd")}'";
if (scroll.EDate.HasValue)
sWhere +=
(string.IsNullOrEmpty(sWhere) ? "WHERE " : " AND ") + $"PRH.PRQDAT_0 <= '{scroll.EDate.Value.AddHours(7).ToString("yyyy-MM-dd")}'";
#endregion Where
#region Sort
switch (scroll.SortField)
{
case "PrNumber":
if (scroll.SortOrder == -1)
sSort = $"PRH.PSHNUM_0 DESC";//QueryData = QueryData.OrderByDescending(x => x.prh.Pshnum0);
else
sSort = $"PRH.PSHNUM_0 ASC";//QueryData = QueryData.OrderBy(x => x.prh.Pshnum0);
break;
case "Project":
if (scroll.SortOrder == -1)
sSort = $"DIM.CCE_2 DESC";//QueryData = QueryData.OrderByDescending(x => x.prh.Pjth0);
else
sSort = $"DIM.CCE_2 ASC";//QueryData = QueryData.OrderBy(x => x.prh.Pjth0);
break;
case "PRDateString":
if (scroll.SortOrder == -1)
sSort = $"PRH.PRQDAT_0 DESC";//QueryData = QueryData.OrderByDescending(x => x.prh.Prqdat0);
else
sSort = $"PRH.PRQDAT_0 ASC";//QueryData = QueryData.OrderBy(x => x.prh.Prqdat0);
break;
case "ItemName":
if (scroll.SortOrder == -1)
sSort = $"PRD.ITMDES_0 DESC";//QueryData = QueryData.OrderByDescending(x => x.prd.Itmdes0);
else
sSort = $"PRD.ITMDES_0 ASC";//QueryData = QueryData.OrderBy(x => x.prd.Itmdes0);
break;
case "Branch":
if (scroll.SortOrder == -1)
sSort = $"DIM.CCE_0 DESC";//QueryData = QueryData.OrderByDescending(x => x.dim.Cce0);
else
sSort = $"DIM.CCE_0 ASC";//QueryData = QueryData.OrderBy(x => x.dim.Cce0);
break;
case "WorkItemName":
if (scroll.SortOrder == -1)
sSort = $"DIM.CCE_1 DESC";//QueryData = QueryData.OrderByDescending(x => x.dim.Cce1);
else
sSort = $"DIM.CCE_1 ASC";//QueryData = QueryData.OrderBy(x => x.dim.Cce1);
break;
case "WorkGroupName":
if (scroll.SortOrder == -1)
sSort = $"DIM.CCE_3 DESC";//QueryData = QueryData.OrderByDescending(x => x.dim.Cce3);
else
sSort = $"DIM.CCE_3 ASC";//QueryData = QueryData.OrderBy(x => x.dim.Cce3);
break;
case "PoNumber":
if (scroll.SortOrder == -1)
sSort = $"POD.POHNUM_0 DESC";//QueryData = QueryData.OrderByDescending(x => x.pod.Pohnum0);
else
sSort = $"POD.POHNUM_0 ASC";//QueryData = QueryData.OrderBy(x => x.pod.Pohnum0);
break;
case "PoDateString":
if (scroll.SortOrder == -1)
sSort = $"POD.ORDDAT_0 DESC";//QueryData = QueryData.OrderByDescending(x => x.pod.Orddat0);
else
sSort = $"POD.ORDDAT_0 ASC";//QueryData = QueryData.OrderBy(x => x.pod.Orddat0);
break;
case "DueDateString":
if (scroll.SortOrder == -1)
sSort = $"POD.EXTRCPDAT_0 DESC";//QueryData = QueryData.OrderByDescending(x => x.pod.Extrcpdat0);
else
sSort = $"POD.EXTRCPDAT_0 ASC";//QueryData = QueryData.OrderBy(x => x.pod.Extrcpdat0);
break;
case "CreateBy":
if (scroll.SortOrder == -1)
sSort = $"PRH.CREUSR_0 DESC";//QueryData = QueryData.OrderByDescending(x => x.prh.Creusr0);
else
sSort = $"PRH.CREUSR_0 ASC";//QueryData = QueryData.OrderBy(x => x.prh.Creusr0);
break;
default:
sSort = $"PRH.PRQDAT_0 DESC";//QueryData = QueryData.OrderByDescending(x => x.prh.Prqdat0);
break;
}
#endregion Sort
#region Query
// Query mulitple command
sQuery = $@"SELECT --PRH
PRH.CLEFLG_0 AS [PrCloseStatusInt],
PRH.CREUSR_0 AS [CreateBy],
PRH.PRQDAT_0 AS [PRDate],
--PRD
PRD.EXTRCPDAT_0 AS [RequestDate],
PRD.PSHNUM_0 AS [PrNumber],
PRD.PSDLIN_0 AS [PrLine],
PRD.ITMREF_0 AS [ItemCode],
PRD.PUU_0 AS [PurUom],
PRD.STU_0 AS [StkUom],
PRD.QTYPUU_0 AS [QuantityPur],
PRD.QTYSTU_0 AS [QuantityStk],
--ITM
ITM.ITMWEI_0 AS [ItemWeight],
TXT.TEXTE_0 AS [ItemName],
--PRO
PRO.POHNUM_0 AS [LinkPoNumber],
PRO.POPLIN_0 AS [LinkPoLine],
PRO.POQSEQ_0 AS [LinkPoSEQ],
--POH
POH.CLEFLG_0 AS [CloseStatusInt],
POH.ZPO21_0 AS [PoStatusInt],
--POD
POD.POHNUM_0 AS [PoNumber],
POD.POPLIN_0 AS [PoLine],
POD.POQSEQ_0 AS [PoSequence],
POD.ORDDAT_0 AS [PoDate],
POD.EXTRCPDAT_0 AS [DueDate],
POD.PUU_0 AS [PoPurUom],
POD.STU_0 AS [PoStkUom],
POD.QTYPUU_0 AS [PoQuantityPur],
POD.QTYSTU_0 AS [PoQuantityStk],
POD.QTYWEU_0 AS [PoQuantityWeight],
--DIM
DIM.CCE_0 AS [Branch],
DIM.CCE_1 AS [WorkItem],
DIM.CCE_2 AS [Project],
DIM.CCE_3 AS [WorkGroup],
(SELECT CAC.DES_0 FROM VIPCO.CACCE CAC WHERE CAC.CCE_0 = DIM.CCE_0) AS [BranchName],
(SELECT CAC.DES_0 FROM VIPCO.CACCE CAC WHERE CAC.CCE_0 = DIM.CCE_1) AS [WorkItemName],
(SELECT CAC.DES_0 FROM VIPCO.CACCE CAC WHERE CAC.CCE_0 = DIM.CCE_2) AS [ProjectName],
(SELECT CAC.DES_0 FROM VIPCO.CACCE CAC WHERE CAC.CCE_0 = DIM.CCE_3) AS [WorkGroupName],
--DIMPO
DIMPO.CCE_0 AS [PoBranch],
DIMPO.CCE_1 AS [PoWorkItem],
DIMPO.CCE_2 AS [PoProject],
DIMPO.CCE_3 AS [PoWorkGroup],
(SELECT CAC.DES_0 FROM VIPCO.CACCE CAC WHERE CAC.CCE_0 = DIMPO.CCE_0) AS [PoBranchName],
(SELECT CAC.DES_0 FROM VIPCO.CACCE CAC WHERE CAC.CCE_0 = DIMPO.CCE_1) AS [PoWorkItemName],
(SELECT CAC.DES_0 FROM VIPCO.CACCE CAC WHERE CAC.CCE_0 = DIMPO.CCE_2) AS [PoProjectName],
(SELECT CAC.DES_0 FROM VIPCO.CACCE CAC WHERE CAC.CCE_0 = DIMPO.CCE_3) AS [PoWorkGroupName]
FROM VIPCO.PREQUIS PRH
INNER JOIN VIPCO.PREQUISD PRD
ON PRH.PSHNUM_0 = PRD.PSHNUM_0
LEFT OUTER JOIN VIPCO.PREQUISO PRO
ON PRD.PSHNUM_0 = PRO.PSHNUM_0
AND PRD.PSDLIN_0 = PRO.PSDLIN_0
LEFT OUTER JOIN VIPCO.PORDER POH
ON PRO.POHNUM_0 = POH.POHNUM_0
LEFT OUTER JOIN VIPCO.PORDERQ POD
ON PRO.POHNUM_0 = POD.POHNUM_0
AND PRO.POPLIN_0 = POD.POPLIN_0
LEFT OUTER JOIN VIPCO.CPTANALIN DIM
ON DIM.ABRFIC_0 = 'PSD'
AND DIM.VCRTYP_0 = 0
AND DIM.VCRSEQ_0 = 0
AND DIM.CPLCLE_0 = ''
AND DIM.ANALIG_0 = 1
AND PRD.PSHNUM_0 = DIM.VCRNUM_0
AND PRD.PSDLIN_0 = DIM.VCRLIN_0
LEFT OUTER JOIN VIPCO.CPTANALIN DIMPO
ON DIMPO.ABRFIC_0 = 'POP'
AND DIMPO.VCRTYP_0 = 0
AND POD.POQSEQ_0 = DIMPO.VCRSEQ_0
AND POD.POHNUM_0 = DIMPO.VCRNUM_0
AND POD.POPLIN_0 = DIMPO.VCRLIN_0
AND DIMPO.CPLCLE_0 = ''
AND DIMPO.ANALIG_0 = 1
LEFT OUTER JOIN VIPCO.ITMMASTER ITM
ON PRD.ITMREF_0 = ITM.ITMREF_0
LEFT OUTER JOIN VIPCO.TEXCLOB TXT
ON TXT.CODE_0 = ITM.PURTEX_0
{sWhere}
ORDER BY {sSort}
OFFSET @Skip ROWS -- skip 10 rows
FETCH NEXT @Take ROWS ONLY; -- take 10 rows;
SELECT COUNT(*)
FROM VIPCO.PREQUIS PRH
INNER JOIN VIPCO.PREQUISD PRD
ON PRH.PSHNUM_0 = PRD.PSHNUM_0
LEFT OUTER JOIN VIPCO.PREQUISO PRO
ON PRD.PSHNUM_0 = PRO.PSHNUM_0
AND PRD.PSDLIN_0 = PRO.PSDLIN_0
LEFT OUTER JOIN VIPCO.PORDER POH
ON PRO.POHNUM_0 = POH.POHNUM_0
LEFT OUTER JOIN VIPCO.PORDERQ POD
ON PRO.POHNUM_0 = POD.POHNUM_0
AND PRO.POPLIN_0 = POD.POPLIN_0
LEFT OUTER JOIN VIPCO.CPTANALIN DIM
ON DIM.ABRFIC_0 = 'PSD'
AND DIM.VCRTYP_0 = 0
AND DIM.VCRSEQ_0 = 0
AND DIM.CPLCLE_0 = ''
AND DIM.ANALIG_0 = 1
AND PRD.PSHNUM_0 = DIM.VCRNUM_0
AND PRD.PSDLIN_0 = DIM.VCRLIN_0
LEFT OUTER JOIN VIPCO.CPTANALIN DIMPO
ON DIMPO.ABRFIC_0 = 'POP'
AND DIMPO.VCRTYP_0 = 0
AND POD.POQSEQ_0 = DIMPO.VCRSEQ_0
AND POD.POHNUM_0 = DIMPO.VCRNUM_0
AND POD.POPLIN_0 = DIMPO.VCRLIN_0
AND DIMPO.CPLCLE_0 = ''
AND DIMPO.ANALIG_0 = 1
LEFT OUTER JOIN VIPCO.ITMMASTER ITM
ON PRD.ITMREF_0 = ITM.ITMREF_0
LEFT OUTER JOIN VIPCO.TEXCLOB TXT
ON TXT.CODE_0 = ITM.PURTEX_0
{sWhere};";
#endregion Query
var result = await this.repositoryPrAndPo.GetListEntitesAndTotalRow(sQuery, new { Skip = scroll.Skip ?? 0, Take = scroll.Take ?? 15 });
var dbData = result.Entities;
scroll.TotalRow = result.TotalRow;
string sReceipt = "";
foreach (var item in dbData)
{
item.ToDate = DateTime.Today.AddDays(-2);
if (item.ItemName.StartsWith("{\\rtf1"))
item.ItemName = Rtf.ToHtml(item.ItemName);
if (item?.ItemWeight > 0)
item.PrWeight = (double)item.ItemWeight * item.QuantityPur;
#region Receipt
sReceipt = $@"SELECT --STOJOU
STO.LOT_0 AS [HeatNumber],
STO.SLO_0 AS [HeatNumber2],
--PRECEIPTD
PRC.PTHNUM_0 AS [RcNumber],
PRC.PTDLIN_0 AS [RcLine],
PRC.RCPDAT_0 AS [RcDate],
PRC.PUU_0 AS [RcPurUom],
PRC.STU_0 AS [RcStkUom],
PRC.UOM_0 AS [RcUom],
PRC.QTYPUU_0 AS [RcQuantityPur],
PRC.QTYSTU_0 AS [RcQuantityStk],
PRC.QTYUOM_0 AS [RcQuantityUom],
PRC.QTYWEU_0 AS [RcQuantityWeight],
PRC.INVQTYPUU_0 AS [RcQuantityInvPur],
PRC.INVQTYSTU_0 AS [RcQuantityInvStk],
--DIM
DIM.CCE_0 AS [RcBranch],
DIM.CCE_1 AS [RcWorkItem],
DIM.CCE_2 AS [RcProject],
DIM.CCE_3 AS [RcWorkGroup],
(SELECT CAC.DES_0 FROM VIPCO.CACCE CAC WHERE CAC.CCE_0 = DIM.CCE_0) AS [RcBranchName],
(SELECT CAC.DES_0 FROM VIPCO.CACCE CAC WHERE CAC.CCE_0 = DIM.CCE_1) AS [RcWorkItemName],
(SELECT CAC.DES_0 FROM VIPCO.CACCE CAC WHERE CAC.CCE_0 = DIM.CCE_2) AS [RcProjectName],
(SELECT CAC.DES_0 FROM VIPCO.CACCE CAC WHERE CAC.CCE_0 = DIM.CCE_3) AS [RcWorkGroupName]
FROM [VIPCO].[STOJOU] STO WITH(INDEX(STOJOU_STJ0))
LEFT OUTER JOIN [VIPCO].[PRECEIPTD] PRC
ON STO.VCRNUM_0 = PRC.PTHNUM_0
AND STO.VCRLIN_0 = PRC.PTDLIN_0
LEFT OUTER JOIN VIPCO.CPTANALIN DIM
ON DIM.ABRFIC_0 = 'PTD'
AND DIM.VCRTYP_0 = 0
AND DIM.VCRSEQ_0 = 0
AND DIM.CPLCLE_0 = ''
AND DIM.ANALIG_0 = 1
AND PRC.PTHNUM_0 = DIM.VCRNUM_0
AND PRC.PTDLIN_0 = DIM.VCRLIN_0
WHERE PRC.POHNUM_0 = @PoNumber
AND PRC.POPLIN_0 = @PoLine
AND PRC.POQSEQ_0 = @PoSequence
AND ((STO.VCRTYPREG_0 = 0 AND STO.REGFLG_0 = 1) OR (STO.VCRTYPREG_0 = 17 AND STO.REGFLG_0 = 1))
ORDER BY PRC.POPLIN_0 ASC";
var receipts = await this.repositoryPrq.GetListEntites(sReceipt, new { item.PoNumber,item.PoLine,item.PoSequence });
if (receipts.Any())
{
receipts.ForEach(receipt =>
{
if (string.IsNullOrEmpty(receipt.HeatNumber2))
receipt.HeatNumber += receipt.HeatNumber2;
item.PurchaseReceipts.Add(receipt);
});
}
else
item.DeadLine = item.DueDate != null ? item.ToDate.Date > item.DueDate.Value.Date : false;
#endregion Receipt
}
return dbData;
}
return null;
}
// POST: api/PurchaseRequest/GetScroll
[HttpPost("GetScroll")]
public async Task<IActionResult> GetScroll([FromBody] ScrollViewModel Scroll)
{
if (Scroll == null)
return BadRequest();
var Message = "";
try
{
var MapDatas = await this.GetData3(Scroll);
return new JsonResult(new ScrollDataViewModel<PurchaseRequestAndOrderViewModel>(Scroll, MapDatas), this.DefaultJsonSettings);
}
catch (Exception ex)
{
Message = $"{ex.ToString()}";
}
return BadRequest(new { Message });
}
[HttpPost("GetReport")]
public async Task<IActionResult> GetReport([FromBody] ScrollViewModel Scroll)
{
if (Scroll == null)
return BadRequest();
var Message = "Data not been found.";
try
{
// Set skip and take
// Scroll.Skip = 0;
// Scroll.Take = 999;
var MapDatas = await this.GetData3(Scroll);
if (MapDatas.Any())
{
var table = new DataTable();
//Adding the Columns
table.Columns.AddRange(new DataColumn[]
{
new DataColumn("PrNo", typeof(string)),
new DataColumn("JobNo", typeof(string)),
new DataColumn("PrDate",typeof(string)),
new DataColumn("RequestDate",typeof(string)),
new DataColumn("Item-Code",typeof(string)),
new DataColumn("Item-Name",typeof(string)),
new DataColumn("Uom",typeof(string)),
new DataColumn("Branch",typeof(string)),
new DataColumn("BomLv",typeof(string)),
new DataColumn("WorkGroup",typeof(string)),
new DataColumn("Qty",typeof(int)),
new DataColumn("PrWeight",typeof(string)),
new DataColumn("PrClose",typeof(string)),
new DataColumn("Create",typeof(string)),
new DataColumn("PoNo",typeof(string)),
new DataColumn("JobNo-2",typeof(string)),
new DataColumn("PoDate",typeof(string)),
new DataColumn("DueDate",typeof(string)),
new DataColumn("QtyPo",typeof(int)),
new DataColumn("Weight",typeof(int)),
new DataColumn("Uom-2",typeof(string)),
new DataColumn("Branch-2",typeof(string)),
new DataColumn("BomLv-2",typeof(string)),
new DataColumn("WorkGroup-2",typeof(string)),
new DataColumn("TypePo",typeof(string)),
new DataColumn("PoStatus",typeof(string)),
new DataColumn("Receipt",typeof(string))
});
//Adding the Rows
foreach (var item in MapDatas)
{
item.ItemName = this.helperService.ConvertHtmlToText(item.ItemName);
item.ItemName = item.ItemName.Replace("\r\n", "");
item.ItemName = item.ItemName.Replace("\n", "");
var Receipt = "";
foreach(var item2 in item.PurchaseReceipts)
{
if (!string.IsNullOrEmpty(Receipt))
Receipt += "\r\n";
Receipt += item2.RcNumber + " ";
Receipt += item2.HeatNumber + " ";
Receipt += item2.RcProject + " ";
Receipt += item2.RcDateString + " ";
Receipt += item2.RcQuantityPur + " ";
Receipt += item2.RcQuantityWeight + " ";
Receipt += item2.RcPurUom + " ";
Receipt += item2.RcBranch + " ";
Receipt += item2.RcWorkItemName + " ";
Receipt += item2.RcWorkGroupName + " ";
}
table.Rows.Add(
item.PrNumber,
item.Project,
item.PRDateString,
item.RequestDateString,
item.ItemCode,
item.ItemName,
item.PurUom,
item.Branch,
item.WorkItemName,
item.WorkGroupName,
item.QuantityPur,
item.PrWeightString,
item.PrCloseStatus,
item.CreateBy,
item.PoNumber,
item.PoProject,
item.PoDateString,
item.DueDateString,
item.PoQuantityPur,
item.PoQuantityWeight,
item.PoPurUom,
item.PoBranch,
item.PoWorkItemName,
item.PoWorkGroupName,
item.PoStatus,
item.CloseStatus,
Receipt
);
}
//var templateFolder = this.hosting.WebRootPath + "/reports/";
//var fileExcel = templateFolder + $"PurchaseStatus_Report.xlsx";
//var memory = new MemoryStream();
//using (XLWorkbook wb = new XLWorkbook())
//{
// var wsFreeze = wb.Worksheets.Add(table, "PurchaseStatus");
// wsFreeze.Columns().AdjustToContents();
// wsFreeze.SheetView.FreezeRows(1);
// wb.SaveAs(memory);
//}
//using (var stream = new FileStream(fileExcel, FileMode.Open))
//{
// await stream.CopyToAsync(memory);
//}
//memory.Position = 0;
return File(this.helperService.CreateExcelFile(table, "PurchaseStatus"),
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "Payment_Report.xlsx");
}
}
catch(Exception ex)
{
Message = $"Has error{ex.ToString()}";
}
return BadRequest(new { Error = Message });
}
}
}
|
// <copyright file="SharedSettingsTests.cs" company="Morten Larsen">
// Copyright (c) Morten Larsen. All rights reserved.
// Licensed under the MIT license. See LICENSE.txt file in the project root for full license information.
// </copyright>
using System;
using AspNetWebpack.AssetHelpers.Testing;
using FluentAssertions;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Options;
using Moq;
using Xunit;
namespace AspNetWebpack.AssetHelpers.Tests
{
public class SharedSettingsTests
{
private const string PublicDevServer = "https://public.dev";
private const string InternalDevServer = "https://internal.dev";
private const string PublicPath = "/public";
private const string ManifestFile = "manifest.json";
private readonly Mock<IOptions<WebpackOptions>> _optionsMock;
public SharedSettingsTests()
{
_optionsMock = new Mock<IOptions<WebpackOptions>>();
_optionsMock
.SetupGet(x => x.Value)
.Returns(new WebpackOptions
{
PublicDevServer = PublicDevServer,
InternalDevServer = InternalDevServer,
PublicPath = PublicPath,
ManifestFile = ManifestFile,
});
}
private static string DevAssetsDirectoryPathResult => $"{InternalDevServer}{PublicPath}";
private static string DevAssetsWebPathResult => $"{PublicDevServer}{PublicPath}";
private static string DevManifestPathResult => $"{DevAssetsDirectoryPathResult}{ManifestFile}";
private static string ProdAssetsDirectoryPathResult => $"{TestValues.WebRootPath}{PublicPath}";
private static string ProdAssetsWebPathResult => PublicPath;
private static string ProdManifestPathResult => $"{ProdAssetsDirectoryPathResult}{ManifestFile}";
[Fact]
public void Constructor_OptionsNull_ShouldThrowArgumentNullException()
{
// Arrange
var webHostEnvironment = new Mock<IWebHostEnvironment>();
// Act
Action act = () => _ = new SharedSettings(null!, webHostEnvironment.Object);
// Assert
act.Should().ThrowExactly<ArgumentNullException>();
webHostEnvironment.VerifyNoOtherCalls();
}
[Fact]
public void Constructor_WebHostEnvironmentNull_ShouldThrowArgumentNullException()
{
// Act
Action act = () => _ = new SharedSettings(_optionsMock.Object, null!);
// Assert
act.Should().ThrowExactly<ArgumentNullException>();
_optionsMock.VerifyNoOtherCalls();
}
[Fact]
public void Constructor_Development_ShouldSetAllVariables()
{
// Arrange
var webHostEnvironmentMock = DependencyMocker.GetWebHostEnvironment(TestValues.Development);
// Act
var sharedSettings = new SharedSettings(_optionsMock.Object, webHostEnvironmentMock.Object);
// Assert
sharedSettings.DevelopmentMode.Should().BeTrue();
sharedSettings.AssetsDirectoryPath.Should().Be(DevAssetsDirectoryPathResult);
sharedSettings.AssetsWebPath.Should().Be(DevAssetsWebPathResult);
sharedSettings.ManifestPath.Should().Be(DevManifestPathResult);
_optionsMock.VerifyGet(x => x.Value, Times.Exactly(5));
_optionsMock.VerifyNoOtherCalls();
webHostEnvironmentMock.VerifyGet(x => x.EnvironmentName, Times.Once);
webHostEnvironmentMock.VerifyNoOtherCalls();
}
[Fact]
public void Constructor_Production_ShouldSetAllVariables()
{
// Arrange
var webHostEnvironmentMock = DependencyMocker.GetWebHostEnvironment(TestValues.Production);
// Act
var sharedSettings = new SharedSettings(_optionsMock.Object, webHostEnvironmentMock.Object);
// Assert
sharedSettings.DevelopmentMode.Should().BeFalse();
sharedSettings.AssetsDirectoryPath.Should().Be(ProdAssetsDirectoryPathResult);
sharedSettings.AssetsWebPath.Should().Be(ProdAssetsWebPathResult);
sharedSettings.ManifestPath.Should().Be(ProdManifestPathResult);
_optionsMock.VerifyGet(x => x.Value, Times.Exactly(3));
_optionsMock.VerifyNoOtherCalls();
webHostEnvironmentMock.VerifyGet(x => x.EnvironmentName, Times.Once);
webHostEnvironmentMock.VerifyGet(x => x.WebRootPath, Times.Once);
webHostEnvironmentMock.VerifyNoOtherCalls();
}
}
}
|
using System;
namespace ConsoleApplication1
{
class SexException : Exception
{
public SexException() : base() { }
public SexException(string mes) : base(mes) { }
}
} |
using SQLite;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Client.Features.Jobs.Models
{
public class JobConfigurationDuplicates
{
[PrimaryKey]
public Guid Id { get; set; }
public Guid JobId { get; set; }
public int CompareValueTypes { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using Kattis.IO;
public class PlantingTrees
{
static public void Main ()
{
Scanner scanner = new Scanner();
BufferedStdoutWriter writer = new BufferedStdoutWriter();
string a = scanner.Next();
string b = scanner.Next();
int start = 0;
int end = 0;
for (int i = 0; i < a.Length && i < b.Length; i++){
if(a[i] != b[i]){
start = i;
break;
}
}
for (int i = 0; i < a.Length && i < b.Length; i++){
if(a[a.Length-i-1] != b[b.Length-i-1]){
end = b.Length - i;
break;
}
}
int changes = Math.Max(Math.Max(end - start, 0), b.Length - a.Length);
string s = changes.ToString() + "\n";
writer.Write(s, 0, s.Length);
writer.Flush();
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ParticleEffect_Timer : MonoBehaviour {
ParticleSystem _particlesystem; //Storing the attached Particle system
public bool BInfinite = false;//Is this Endless
void Start(){
_particlesystem = GetComponent<ParticleSystem> ();
var loopMain = _particlesystem.main;
loopMain.loop = BInfinite;
}
void Update(){
if (_particlesystem.isStopped)
gameObject.SetActive (false);
}
}
|
using Barebone.Common.Services.Interfaces;
using Barebone.Common.ViewModels.Base;
using MvvmCross.Core.Navigation;
using MvvmCross.Core.ViewModels;
namespace Barebone.Common.ViewModels
{
public class HomeViewModel : BaseViewModel<HomeViewModel.Parameters>
{
bool _hasInternet = true;
public class Parameters
{
}
public IMvxCommand OpenLeftDrawerCommand => new MvxCommand(OpenLeftDrawer);
public IMvxCommand FakeToggleInternetConnectionCommand => new MvxCommand(() =>
{
_hasInternet = !_hasInternet;
ConnectivityService.FakeToggleInternetConnection(_hasInternet);
});
public HomeViewModel(IMvxNavigationService navigationService, IUserInteractionService userInteractionService, IConnectivityService connectivityService)
: base(navigationService, userInteractionService, connectivityService)
{
}
public override void ViewAppeared()
{
base.ViewAppeared();
RaisePropertyChanged(() => Title);
}
void OpenLeftDrawer()
{
NavigationService.Navigate<LeftDrawerViewModel>();
}
}
}
|
using System;
using System.Windows.Controls;
namespace MinecraftToolsBox.Commands
{
/// <summary>
/// EntityHostile.xaml 的交互逻辑
/// </summary>
public partial class EntityHostile : Grid
{
public EntityHostile()
{
InitializeComponent();
}
public void Enable(string id)
{
E1.IsEnabled = false;
E2.IsEnabled = false;
E3.IsEnabled = false;
E4.IsEnabled = false;
switch (id)
{
default: break;
case "Slime": E1.IsEnabled = true; break;
case "LavaSlime": E1.IsEnabled = true; break;
case "Ghast": E2.IsEnabled = true; break;
case "Creeper": E3.IsEnabled = true; break;
case "Endermite": E4.IsEnabled = true; break;
}
}
public string getNBT()
{
string tag = "";
if (E1.IsEnabled)
{
if (size.Value != null) tag += "Size:" + size.Value + ",";
if (ground.IsChecked == true) tag += "wasOnGround:true,";
}
else if (E2.IsEnabled)
{
if (power.Value != 1) tag += "ExplosionPower:" + power.Value + ",";
}
else if (E3.IsEnabled)
{
if (powered.IsChecked == true) tag += "powered:true,";
if (r.Value != 3) tag += "ExplosionRadius:" + r.Value + ",";
if (p.IsChecked == true) tag += "ignited:true,";
if (t.Value != 1.5) tag += "Fuse:" + Convert.ToInt32(t.Value * 20) + ",";
}
else if (E4.IsEnabled)
{
if (life.Value != 240) tag += "Lifetime:" + Convert.ToInt32((120 - life.Value) * 20) + ",";
if (player.IsChecked == true) tag += "PlayerSpawned:true,";
}
return tag;
}
}
}
|
using UnityEngine;
using System.Collections;
public class Obstacle : MonoBehaviour {
public string obstacleName;
public string deathMessage;
public enum Direction {
Up,
Down
}
public Direction dir;
void Awake()
{
Destroy (gameObject, 10);
tag = "Enemy";
}
void Update()
{
if (dir == Direction.Down)
{
transform.Translate (Vector3.down * 0.1f);
}
else
{
transform.Translate (Vector3.up * 0.1f);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using ppedv.Planner.Logic;
using ppedv.Planner.Model;
namespace ppedv.Planner.UI.Web.Controllers
{
public class MitarbeiterController : Controller
{
Core core = new Core();
// GET: Mitarbeiter
public ActionResult Index()
{
return View(core.Repository.GetAll<Mitarbeiter>());
}
// GET: Mitarbeiter/Details/5
public ActionResult Details(int id)
{
return View(core.Repository.Query<Mitarbeiter>().FirstOrDefault(x => x.Id == id));
}
// GET: Mitarbeiter/Create
public ActionResult Create()
{
return View(new Mitarbeiter() { Name = "Fred" });
}
// POST: Mitarbeiter/Create
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(Mitarbeiter m)
{
try
{
core.Repository.Add(m);
core.Repository.SaveChanges();
return RedirectToAction(nameof(Index));
}
catch
{
return View();
}
}
// GET: Mitarbeiter/Edit/5
public ActionResult Edit(int id)
{
return View(core.Repository.Query<Mitarbeiter>().FirstOrDefault(x => x.Id == id));
}
// POST: Mitarbeiter/Edit/5
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(int id, Mitarbeiter m)
{
try
{
core.Repository.Update(m);
core.Repository.SaveChanges();
return RedirectToAction(nameof(Index));
}
catch
{
return View();
}
}
// GET: Mitarbeiter/Delete/5
public ActionResult Delete(int id)
{
return View(core.Repository.Query<Mitarbeiter>().FirstOrDefault(x => x.Id == id));
}
// POST: Mitarbeiter/Delete/5
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Delete(int id, Mitarbeiter m)
{
try
{
var loaded = core.Repository.Query<Mitarbeiter>().FirstOrDefault(x => x.Id == id);
if (loaded != null)
{
foreach (var u in loaded.Urlaube.ToList())
{
core.Repository.Delete(u);
}
core.Repository.Delete(loaded);
core.Repository.SaveChanges();
}
return RedirectToAction(nameof(Index));
}
catch
{
return View();
}
}
}
} |
using gView.Framework.UI;
using System.Windows.Forms;
namespace gView.Framework.Symbology.UI
{
internal partial class PropertyForm_SimpleTextSymbol : Form, IPropertyPageUI, gView.Framework.Symbology.UI.IPropertyPanel
{
private ITextSymbol _symbol = null;
public PropertyForm_SimpleTextSymbol()
{
InitializeComponent();
}
#region IPropertyPageUI Members
public event PropertyChangedEvent PropertyChanged;
#endregion
private void propertyGrid_PropertyValueChanged(object s, PropertyValueChangedEventArgs e)
{
if (PropertyChanged != null)
{
PropertyChanged(_symbol);
}
}
#region IPropertyPanel Member
public object PropertyPanel(ISymbol symbol)
{
if (!(symbol is ITextSymbol))
{
return null;
}
_symbol = (ITextSymbol)symbol;
propertyGrid.SelectedObject = new CustomClass(_symbol);
return panelTextSymbol;
}
#endregion
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class UIOff : MonoBehaviour {
public GameObject UI;
public GameObject UILESSON;
public GameObject PlayButton;
public GameObject PauseButton;
public GameObject MenuPlane;
//public GameObject Model;
//public Component Translate;
//public Component Rotate;
//public Component Scale;
public GameObject Paragraph1;
public GameObject Paragraph2;
public GameObject Plane;
//public float counter;
public Animator Fizzzra;
public Animator Kavend;
//public Animation Anim;
//public GameObject LightSource;
public GameObject Light;
public float ButtonsCounter;
public float NeedStart;
public GameObject PausedParag;
void Start (){
// Translate = Model.GetComponent<LeanTranslate> ();
// Rotate = Model.GetComponent<LeanRotate> ();
// Scale = Model.GetComponent<LeanScale>();
UI.SetActive (true);
UILESSON.SetActive (false);
PauseButton.SetActive (false);
ButtonsCounter = 1f;
NeedStart = 0f;
PausedParag = Paragraph1;
//Light = LightSource.GetComponent<Light> ();
//Next = null;
//Prev = null;
}
public void STARTFUCKINGLESSON(){
UI.SetActive (false);
// Translate.enabled = false;
// Rotate.enabled = false;
// Scale.enabled = false;
UILESSON.SetActive (true);
}
public void PlaytoPause (){
if (NeedStart == 0) {
NeedStart++;
}
Light.SetActive (true);
Plane.SetActive (true);
PausedParag.SetActive (true);
PlayButton.SetActive (false);
PauseButton.SetActive (true);
}
public void PausetoPlay (){
if (NeedStart == 1) {
NeedStart--;
}
if (Paragraph1.activeInHierarchy == true) {
PausedParag = Paragraph1;
}
if (Paragraph2.activeInHierarchy == true) {
PausedParag = Paragraph2;
}
Paragraph2.SetActive (false);
Paragraph1.SetActive (false);
Plane.SetActive (false);
PauseButton.SetActive (false);
PlayButton.SetActive (true);
}
public void PauseMenuu (){
UILESSON.SetActive (false);
MenuPlane.SetActive (true);
}
public void PauseMenuuBack (){
MenuPlane.SetActive (false);
UILESSON.SetActive (true);
}
public void PauseMenuuBacktoStart (){
SceneManager.LoadScene (0);
}
public void Next (){
if (NeedStart>0f){
ButtonsCounter++;
}
if (ButtonsCounter == 3) {
ButtonsCounter--;
}
if ((ButtonsCounter == 2)&&(NeedStart>0)) {
Light.SetActive (true);
Plane.SetActive (true);
Paragraph1.SetActive (false);
Paragraph2.SetActive (true);
}
}
public void Prev(){
if (NeedStart > 0f) {
ButtonsCounter--;
}
if (ButtonsCounter == 0) {
ButtonsCounter++;
}
if ((ButtonsCounter == 1)&&(NeedStart>0)) {
Light.SetActive (true);
Plane.SetActive (true);
Paragraph2.SetActive (false);
Paragraph1.SetActive (true);
}
}
/*public void Playyy (){
counter = 0f;
while (counter == 0f) {
ParagraphAct1 ();
new WaitForSeconds (5);
ParagraphAct2 ();
}
}
public void Pauuuuse(){
counter++;
}*/
/*public void Inlight (){
}
public void OutLight(){
}*/
/*public void StartAnim(){
Anim.Play ();
}*/
public void Kavendish(){
Kavend.SetBool ("StartAn", true);
Kavend.SetBool ("StopAn", true);
}
public void FizraStart(){
Fizzzra.SetBool ("Stop", false);
Fizzzra.SetBool ("Start", true);
}
public void FizraStop ()
{
Fizzzra.SetBool ("Start", false);
Fizzzra.SetBool ("Stop", true);
}
}
|
using Content.Shared.Sound;
using Robust.Shared.Prototypes;
using Robust.Shared.Serialization;
using Robust.Shared.Serialization.TypeSerializers.Implementations.Custom.Prototype;
using Robust.Shared.Utility;
namespace Content.Server.Weapon.Ranged.Ammunition.Components
{
/// <summary>
/// Allows this entity to be loaded into a ranged weapon (if the caliber matches)
/// Generally used for bullets but can be used for other things like bananas
/// </summary>
[RegisterComponent]
[Friend(typeof(GunSystem))]
public sealed class AmmoComponent : Component, ISerializationHooks
{
[DataField("caliber")]
public BallisticCaliber Caliber { get; } = BallisticCaliber.Unspecified;
public bool Spent
{
get
{
if (AmmoIsProjectile)
{
return false;
}
return _spent;
}
set => _spent = value;
}
private bool _spent;
// TODO: Make it so null projectile = dis
/// <summary>
/// Used for anything without a case that fires itself
/// </summary>
[DataField("isProjectile")] public bool AmmoIsProjectile;
/// <summary>
/// Used for something that is deleted when the projectile is retrieved
/// </summary>
[DataField("caseless")]
public bool Caseless { get; }
// Rather than managing bullet / case state seemed easier to just have 2 toggles
// ammoIsProjectile being for a beanbag for example and caseless being for ClRifle rounds
/// <summary>
/// For shotguns where they might shoot multiple entities
/// </summary>
[DataField("projectilesFired")]
public int ProjectilesFired { get; } = 1;
[DataField("projectile", customTypeSerializer: typeof(PrototypeIdSerializer<EntityPrototype>))]
public string? ProjectileId;
// How far apart each entity is if multiple are shot
[DataField("ammoSpread")]
public float EvenSpreadAngle { get; } = default;
/// <summary>
/// How fast the shot entities travel
/// </summary>
[DataField("ammoVelocity")]
public float Velocity { get; } = 20f;
[DataField("muzzleFlash")]
public ResourcePath? MuzzleFlashSprite = new("Objects/Weapons/Guns/Projectiles/bullet_muzzle.png");
[DataField("soundCollectionEject")]
public SoundSpecifier SoundCollectionEject { get; } = new SoundCollectionSpecifier("CasingEject");
void ISerializationHooks.AfterDeserialization()
{
// Being both caseless and shooting yourself doesn't make sense
DebugTools.Assert(!(AmmoIsProjectile && Caseless));
if (ProjectilesFired < 1)
{
Logger.Error("Ammo can't have less than 1 projectile");
}
if (EvenSpreadAngle > 0 && ProjectilesFired == 1)
{
Logger.Error("Can't have an even spread if only 1 projectile is fired");
throw new InvalidOperationException();
}
}
}
public enum BallisticCaliber
{
Unspecified = 0,
A357, // Placeholder?
ClRifle,
SRifle,
Pistol,
A35, // Placeholder?
LRifle,
HRifle,
Magnum,
AntiMaterial,
Shotgun,
Cap,
Rocket,
Dart, // Placeholder
Grenade,
Energy,
}
}
|
using System;
namespace Puppeteer.Core.Planning
{
public interface IAStarNode : External.IFastPriorityQueueNode, IEquatable<IAStarNode>
{
/// <summary>
/// In A* referred to as F. G (path cost) and H (heuristic cost) combined. (f = g + h)
/// </summary>
float GetCost();
/// <summary>
/// In A* referred to as H. The heuristic cost of the current node.
/// </summary>
float GetHeuristicCost();
/// <summary>
/// In A* referred to as G. The cost to get to this node.
/// </summary>
float GetPathCost();
/// <summary>
/// Returns the parent node of this node. Null if it's the first node in the queue.
/// </summary>
IAStarNode GetParent();
/// <summary>
/// Overrides the parent node. <see cref="CalculateCosts"/> should be called afterwards.
/// </summary>
void SetParent(IAStarNode _parentNode);
/// <summary>
/// Calculates the cost of this node based on parent and heuristic.
/// </summary>
void CalculateCosts();
bool ReachesEnd(IAStarNode _end);
}
} |
using AutoTests.Framework.Web.Attributes;
using AutoTests.Framework.Web.Common.Handlers;
namespace AutoTests.Framework.Web.Common.Elements
{
public class Input : CommonElement
{
[FromLocator]
private string Locator { get; set; }
public Input(WebDependencies dependencies) : base(dependencies)
{
}
[Displayed]
public bool IsDisplayed()
{
return Context.IsDisplayed(Locator);
}
[Enabled]
public bool IsEnabled()
{
return Context.IsEnabled(Locator);
}
[Selected]
public bool IsSelected()
{
return Context.IsSelected(Locator);
}
[GetValue]
public string GetValue()
{
return CommonScriptLibrary.GetValue(Locator);
}
[SetValue]
public void SetValue(string value)
{
Context.Clear(Locator);
Context.SetValue(Locator, value);
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class TelaInicial : System.Web.UI.Page
{
public static void VerificaLogin()
{
if (HttpContext.Current.Session["autenticado"] == null ||
HttpContext.Current.Session["autenticado"].ToString() != "OK")
{
HttpContext.Current.Session.Abandon();
HttpContext.Current.Response.Redirect("Default.aspx?msg=Por favor, autentique-se");
}
}
protected void Page_Load(object sender, EventArgs e)
{
VerificaLogin();
}
protected void Button1_Click(object sender, EventArgs e)
{
switch (radRelatorios.Text)
{
case "Logins":
//Server.Transfer("ReportLogin.aspx");
Response.Redirect("ReportLogin.aspx");
break;
case "Exames":
//Server.Transfer("ReportExame.aspx");
Response.Redirect("ReportExame.aspx");
break;
case "Moradores":
//Server.Transfer("ReportMorador.aspx");
Response.Redirect("ReportMorador.aspx");
break;
case "Visitantes":
//Server.Transfer("ReportVisitantes.aspx");
Response.Redirect("ReportVisitantes.aspx");
break;
default:
string msg = "Selecione o Relatório";
ClientScript.RegisterStartupScript(typeof(string), string.Empty,
string.Format("window.alert(\"{0}\");", msg), true);
break;
}
}
protected void btnSair_Click(object sender, EventArgs e)
{
Response.Redirect("Logout.aspx");
}
} |
using UnityEngine;
public class ChangeBackground : MonoBehaviour
{
public Sprite[] background;
// Start is called before the first frame update
void Start()
{
this.gameObject.transform.GetChild(0).GetChild(0).GetComponentInChildren<SpriteRenderer>().sprite = background[Levels.backgroundScene];
this.gameObject.transform.GetChild(1).GetChild(0).GetComponentInChildren<SpriteRenderer>().sprite = background[Levels.backgroundScene];
}
}
|
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using SuperMario.ScoreSystem;
using SuperMario.Sound;
namespace SuperMario
{
public sealed class HUDController
{
SpriteFont currentFont;
long timeCounter;
long limitInTicks = 4000000000;
readonly int hurryTimeInTicks = 1000000000;
bool hurryTime = false;
GameTime gameTime;
public long TimeInTicks { get; private set; } = 4000000000;
private static readonly HUDController instance = new HUDController();
private HUDController()
{
}
public static HUDController Instance
{
get
{
return instance;
}
}
public void Initialize(SpriteFont font)
{
currentFont = font;
}
public void SetGameTime(GameTime currentGameTime)
{
gameTime = currentGameTime;
}
public void ResetTimer()
{
TimeInTicks = 4000000000;
limitInTicks = 4000000000;
timeCounter = 0;
}
public void KeepTime()
{
timeCounter += gameTime.ElapsedGameTime.Ticks;
TimeInTicks = limitInTicks - timeCounter;
if (!hurryTime && TimeInTicks <= hurryTimeInTicks)
{
hurryTime = true;
Music.Event();
}
}
public void Draw(SpriteBatch spriteBatch)
{
int tickToSecondConversion = 10000000;
int worldLocationYOffset = 30;
int coinLocationXOffset = 700;
int lifeLocationXOffset = 350;
int timeLocationXOffset = 700;
int timeLocationYOffset = 30;
Vector2 scoreLocation = Vector2.Zero;
Vector2 worldLocation = new Vector2(0, worldLocationYOffset);
Vector2 coinLocation = new Vector2(coinLocationXOffset, 0);
Vector2 timeLocation = new Vector2(timeLocationXOffset, timeLocationYOffset);
Vector2 lifeLocation = new Vector2(lifeLocationXOffset, 0);
spriteBatch.DrawString(currentFont, "Score : " + ScoreKeeper.Instance.Score, scoreLocation, Color.NavajoWhite);
spriteBatch.DrawString(currentFont, "World 1-1", worldLocation, Color.NavajoWhite);
spriteBatch.DrawString(currentFont, "Lives: " + ScoreKeeper.LifeCount, lifeLocation, Color.NavajoWhite);
spriteBatch.DrawString(currentFont, "Coin : " + ScoreKeeper.CoinCount, coinLocation, Color.NavajoWhite);
spriteBatch.DrawString(currentFont, "Time : " + TimeInTicks / tickToSecondConversion, timeLocation, Color.NavajoWhite);
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.Mvc;
namespace Gibe.CacheBusting
{
public static class UrlExtensions
{
public static string Asset(this UrlHelper url, string filename)
{
var manifest = DependencyResolver.Current.GetService<IRevisionManifest>();
return manifest.ContainsPath(filename) ? manifest.GetHashedPath(filename) : filename;
}
}
}
|
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace WebShop.API.Models
{
public class CATEGORIES
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.None)]
public int ID { get; set; }
public string TITLE { get; set; }
public string DESCRIPTION { get; set; }
public int SORT_ORDER { get; set; }
[ForeignKey("CATEGORIES")]
public int? PARENT_ID { get; set; }
public int? REDIRECT_TO_ID { get; set; }
public bool ACTIVE { get; set; }
[ForeignKey("PARENT_ID")]
public List<CATEGORIES> SUBCATEGORIES { get; set; }
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.