text stringlengths 13 6.01M |
|---|
using ShoppingCartLib.Interface;
using ShoppingCartLib.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ShoppingCartLib
{
public class ReceiptGenerator : IReceiptGenerator
{
private IProductRepository _productRepository;
public ReceiptGenerator(IProductRepository productRepository)
{
_productRepository = productRepository;
}
public ShoppingCartReceipt GetReceipt(int shoppingCartId)
{
ShoppingCartReceipt shoppingCartReceipt = new ShoppingCartReceipt();
shoppingCartReceipt.CartItems = new List<ShoppingCartItemWithTax>();
var cartProducts = _productRepository.GetShoppingCartProducts(shoppingCartId);
if(cartProducts != null)
{
if (cartProducts.Count > 0)
{
double totalCost = 0, totalBasicSalesTax = 0, totalImportDutyTax = 0, grandTotal = 0;
foreach (var cartProduct in cartProducts)
{
var productDetail = _productRepository.GetProduct(cartProduct.ProductId);
if (productDetail != null)
{
double totalCostPrice = productDetail.Cost * cartProduct.Quantity;
double basicSalesTax = 0;
if (!productDetail.IsExemptFromSalesTax)
basicSalesTax = Utills.RoundNearest((10 * totalCostPrice) / 100); // 10% sales tax
double imprtDutyTax = 0;
if (productDetail.IsImported)
imprtDutyTax = Utills.RoundNearest((5 * totalCostPrice) / 100); // 5% import duty tax
ShoppingCartItemWithTax shoppingCartProductWithTax = new ShoppingCartItemWithTax(cartProduct)
{
TotalCostPrice = totalCostPrice,
BasicSalesTax = basicSalesTax,
ImportDutyTax = imprtDutyTax,
TotalSalesTax = basicSalesTax + imprtDutyTax
};
shoppingCartReceipt.CartItems.Add(shoppingCartProductWithTax);
totalCost += totalCostPrice;
totalBasicSalesTax += basicSalesTax;
totalImportDutyTax += imprtDutyTax;
grandTotal += totalCostPrice + basicSalesTax + imprtDutyTax;
}
}
shoppingCartReceipt.TotalCostPrice = Utills.RoundNearest(totalCost);
shoppingCartReceipt.BasicSalesTax = Utills.RoundNearest(totalBasicSalesTax);
shoppingCartReceipt.ImportDutyTax = Utills.RoundNearest(totalImportDutyTax);
shoppingCartReceipt.GrandTotal = Utills.RoundNearest(grandTotal);
}
}
return shoppingCartReceipt;
}
}
}
|
//using System;
//using System.Collections.Generic;
//using System.Linq;
//using System.Threading.Tasks;
//using Microsoft.AspNetCore.Mvc.Razor;
//namespace WebApplication
//{
// /// <summary>
// ///
// /// </summary>
// /// <example>
// /// services.AddMvc().Configure<MvcOptions>(options =>
// /// {
// /// options.ViewEngines.Clear();
// /// options.ViewEngines.Add(typeof(ThemeViewEngine));
// /// });
// /// </example>
// public class ThemeViewEngine : RazorViewEngine
// {
// public ThemeViewEngine(IRazorPageFactory pageFactory,
// IRazorViewFactory viewFactory,
// IViewLocationExpanderProvider viewLocationExpanderProvider,
// IViewLocationCache viewLocationCache)
// : base(pageFactory,
// viewFactory,
// viewLocationExpanderProvider,
// viewLocationCache)
// {
// }
// public override IEnumerable<string> AreaViewLocationFormats
// {
// get
// {
// var value = new Random().Next(0, 1);
// var theme = value == 0 ? "Theme1" : "Theme2"; // 可通过其它条件,设置皮肤的种类
// return base.AreaViewLocationFormats.Select(f => f.Replace("/Views/", "/Views/" + theme + "/"));
// }
// }
// public override IEnumerable<string> ViewLocationFormats
// {
// get
// {
// var value = new Random().Next(0, 1);
// var theme = value == 0 ? "Theme1" : "Theme2"; // 可通过其它条件,设置皮肤的种类
// return base.ViewLocationFormats.Select(f => f.Replace("/Views/", "/Views/" + theme + "/"));
// }
// }
// }
//}
|
#region Copyright
//=======================================================================================
// Author: Paolo Salvatori
// GitHub: https://github.com/paolosalvatori
//=======================================================================================
// Copyright © 2021 Microsoft Corporation. All rights reserved.
//
// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER
// EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED WARRANTIES OF
// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. YOU BEAR THE RISK OF USING IT.
//=======================================================================================
#endregion
#region Using Directives
using Microsoft.EntityFrameworkCore;
using System;
#endregion
namespace Products.Models
{
/// <summary>
/// ProductsDbContext class
/// </summary>
public class ProductsContext : DbContext
{
#region Public Constructor
/// <summary>
/// Public Constructor
/// </summary>
/// <param name="options">DbContextOptions object</param>
public ProductsContext(DbContextOptions<ProductsContext> options)
: base(options)
{
}
#endregion
#region Public Properties
/// <summary>
/// Gets or sets the Products property
/// </summary>
public DbSet<Product> Products { get; set; }
#endregion
#region Protected Methods
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
=> optionsBuilder
.EnableSensitiveDataLogging()
.EnableDetailedErrors()
.LogTo(Console.WriteLine);
#endregion
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Diagnostics;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;
namespace GP3_Coursework
{
/// <summary>
/// This is the main type for your game
/// </summary>
public class Game1 : Microsoft.Xna.Framework.Game
{
// graphics variables
GraphicsDeviceManager graphics;
SpriteBatch spriteBatch;
// Image used to display the static background
Texture2D mainBackground;
// Font
SpriteFont scoreFont;
//player score
public int score;
// space Station health
public int spaceStationHealth;
//player
playerShip player;
// Parallaxing Layers
Background bgLayer1;
Background bgLayer2;
// The aspect ratio determines how to scale 3d to 2d projection.
float aspectRatio;
//Camera 1 position
Vector3 cameraPosition = new Vector3(0.0f, 50.0f, 5000.0f);
// View 1 Matrix
Matrix viewMatrix;
// Projection 1 Matrix
Matrix projectionMatrix;
// camera 2 position
Vector3 camera2Position = new Vector3(0.0f, 50.0f, 5000.0f);
// View 2 Matrix
Matrix view2Matrix;
// Projection 2 Matrix
Matrix projection2Matrix;
// random number generator
Random random;
// basic Weapon Bullet
private PlayerBasicWeapon[] basicWeaponBulletList = new PlayerBasicWeapon[GameConstants.NumBasicBullets];
// model for basic weapons (player)
public Model basicWeaponBulletModel;
// Matrix for storing basicweapon bullet transforms
public Matrix[] basicWeaponbulletTransforms;
// basic enemy model
private Model basicEnemyModel;
// matrix for basicEnemy transforms
private Matrix[] basicEnemyModelTransforms;
// basicEnemyList
private BasicEnemy[] basicEnemyList = new BasicEnemy[GameConstants.basicEnemyNumbers];
// fast enemy model
private Model fastEnemyModel;
// matrix for basicEnemy transforms
private Matrix[] fastEnemyModelTransforms;
// basicEnemyList
private fastEnemy[] fastEnemyList = new fastEnemy[GameConstants.fastEnemyNumbers];
// strong enemy model
private Model strongEnemyModel;
// matrix for strongEnemy transforms
private Matrix[] strongEnemyModelTransforms;
// strongEnemyList
private strongEnemy[] strongEnemyList = new strongEnemy[GameConstants.strongEnemyNumbers];
// basic enemy bullet model
private Model basicEnemyWeaponBulletmodel;
// matrix for basic enemy bullet transforms
private Matrix[] basicEnemyWeaponbulletTransforms;
// list for basic enemy bullets
private BasicEnemyWeapon[] basicEnemyWeaponBulletList = new BasicEnemyWeapon[GameConstants.NumBasicEnemyBullets];
// strong enemy bullet model
private Model strongEnemyWeaponBulletmodel;
// matrix for strong enemy bullet transforms
private Matrix[] strongEnemyWeaponbulletTransforms;
// list for basic enemy bullets
private BasicEnemyWeapon[] strongEnemyWeaponBulletList = new BasicEnemyWeapon[GameConstants.NumBasicEnemyBullets];
// last state for keyboard
private KeyboardState lastState;
// old keyboard state
KeyboardState oldState;
// hit count
private int hitCount;
// reload timer
public Timer playerReloadTime;
// basic Enemy Timer
public Timer enemySpawnTime;
// fast enemy Timer
public Timer fastEnemySpawnTime;
// strong enemy timer
public Timer strongEnemySpawnTime;
// enemy bullet timer
public Timer basicEnemyBulletTimer;
// strong enemy bullet timer
public Timer strongEnemyBulletTimer;
// Sprite explosion variables
Texture2D explosionTexture;
List<Animation> explosions;
// background song
private Song backgroundSong;
// toggle sound effects boolean
public Boolean musicToggle;
// list for crash sound effects
static int iMaxCrashSounds = 5;
private static SoundEffect[] CrashSounds = new SoundEffect[iMaxCrashSounds];
// sound effects for lasers
static int iMaxLaserSounds = 3;
private static SoundEffect[] LaserSounds = new SoundEffect[iMaxLaserSounds];
//Initialize view and projection
private void InitializeTransform()
{
aspectRatio = graphics.GraphicsDevice.Viewport.AspectRatio;
viewMatrix = Matrix.CreateLookAt(cameraPosition, Vector3.Zero, Vector3.Up);
projectionMatrix = Matrix.CreatePerspectiveFieldOfView(MathHelper.ToRadians(45.0f), aspectRatio, 1.0f, 10000.0f);
}
// Initialize second View and Projection
private void InitilizeSecondTransform()
{
aspectRatio = graphics.GraphicsDevice.Viewport.AspectRatio;
viewMatrix = Matrix.CreateLookAt(cameraPosition, Vector3.Zero, Vector3.Up);
projectionMatrix = Matrix.CreatePerspectiveFieldOfView(MathHelper.ToRadians(45.0f), aspectRatio, 1.0f, 10000.0f);
}
// shoot bullets
public void shootbullets()
{
// get keyboard state
KeyboardState keyboardState = Keyboard.GetState();
// if space bar is pressed
if (keyboardState.IsKeyDown(Keys.Space) || lastState.IsKeyDown(Keys.Space))
{
// for each bullet defined in gameConstants
for (int i = 0; i < GameConstants.NumBasicBullets; i++)
{
// if the bullet isnt active and reload time is 0
if (!basicWeaponBulletList[i].isActive && playerReloadTime.time == 0)
{
// set bullet direction
basicWeaponBulletList[i].direction = new Vector3(5.0f, 0.0f, 0.0f);
// set bullet speed
basicWeaponBulletList[i].basicBulletspeed = GameConstants.basicWeaponSpeedAdjustment;
// bullet position
basicWeaponBulletList[i].basicWeaponBulletposition = player.playerPosition;
// set bullet to active
basicWeaponBulletList[i].isActive = true;
// play laser sound at [0]
LaserSounds[0].Play();
// set reload time to 2
playerReloadTime.time = 2;
break;
}
}
}
lastState = keyboardState;
}
// allow bullets to be shot by gamePad
public void gamePadShootBullets()
{
// input for controller
GamePadState gamePadState = GamePad.GetState(PlayerIndex.One);
// right trigger variable
float rightTriggerValue = gamePadState.Triggers.Right;
// if gamepad is connected
if (gamePadState.IsConnected)
{
// if right trigger is pressed
if (rightTriggerValue == 1)
{
// for each bullet defined in game constants
for (int i = 0; i < GameConstants.NumBasicBullets; i++)
{
// is the bullet isnt active and reload time = 0
if (!basicWeaponBulletList[i].isActive && playerReloadTime.time == 0)
{
// set bullet direction
basicWeaponBulletList[i].direction = new Vector3(5.0f, 0.0f, 0.0f);
// set bullet speed
basicWeaponBulletList[i].basicBulletspeed = GameConstants.basicWeaponSpeedAdjustment;
// set bullet position
basicWeaponBulletList[i].basicWeaponBulletposition = player.playerPosition;
// set bullet to active
basicWeaponBulletList[i].isActive = true;
// play laser sound 0
LaserSounds[0].Play();
// set reload time till 2
playerReloadTime.time = 2;
break;
}
}
}
}
}
// spawning methods
public void spawnBasicEnemies()
{
// for each number defined in game constants
for (int i = 0; i < GameConstants.basicEnemyNumbers; i++)
// if enemy isnt active and spawn time = 0
if (!basicEnemyList[i].isActive && enemySpawnTime.time == 0)
{
// position
basicEnemyList[i].basicEnemyposition = new Vector3(4000, random.Next(-1850, 1850), 0.0f);
// direction
basicEnemyList[i].basicEnemydirection = new Vector3(-10.0f,0.0f,0.0f);
// speed
basicEnemyList[i].basicEnemyspeed = GameConstants.basicEnemySpeedAdjustment;
// health
basicEnemyList[i].health = 3;
// is active = true
basicEnemyList[i].isActive = true;
// spawn time
enemySpawnTime.time = 7;
break;
}
}
public void spawnFastEnemies()
{
// for each number defined in game constants
for (int i = 0; i < GameConstants.fastEnemyNumbers; i++)
// is enemy isnt active and spawn time = 0
if (!fastEnemyList[i].isActive && fastEnemySpawnTime.time == 0)
{
// position
fastEnemyList[i].fastEnemyposition = new Vector3(4000, random.Next(-1850, 1850), 0.0f);
// direction
fastEnemyList[i].fastEnemydirection = new Vector3(-10.0f, 0.0f, 0.0f);
// speed
fastEnemyList[i].fastEnemyspeed = GameConstants.fastEnemySpeedAdjustment;
// health
fastEnemyList[i].health = 1;
// set to active
fastEnemyList[i].isActive = true;
// respawn time
fastEnemySpawnTime.time = 15;
break;
}
}
public void spawnStrongEnemies()
{
// number of strong enemys defined in game constants
for (int i = 0; i < GameConstants.strongEnemyNumbers; i++)
// if enemy isnt active and spawn time is 0
if (!strongEnemyList[i].isActive && strongEnemySpawnTime.time == 0)
{
// position
strongEnemyList[i].strongEnemyposition = new Vector3(4000, random.Next(-1850, 1850), 0.0f);
// direction
strongEnemyList[i].strongEnemydirection = new Vector3(-10.0f, 0.0f, 0.0f);
// speed
strongEnemyList[i].strongEnemyspeed = GameConstants.strongEnemySpeedAdjustment;
// health
strongEnemyList[i].health = 10;
// set to active
strongEnemyList[i].isActive = true;
// spawn time set to 60 seconds
strongEnemySpawnTime.time = 60;
break;
}
}
public void spawnBasicEnemybullets()
{
// number of basic bullets
for (int i = 0; i < GameConstants.NumBasicEnemyBullets; i++)
// if bullet isnt active and spawn time is 0
if (!basicEnemyWeaponBulletList[i].isActive && basicEnemyBulletTimer.time == 0)
{
// for each basic enemy
for (int K = 0; K < GameConstants.basicEnemyNumbers; K++)
{
// direction
basicEnemyWeaponBulletList[i].basicEnemyWeaponBulletdirection = new Vector3(-10.0f, 0.0f, 0.0f);
// speed
basicEnemyWeaponBulletList[i].basicEnemyWeaponBulletspeed = GameConstants.basicEnemyWeaponSpeedAdjustment;
// if basic enemy at K is active
if (basicEnemyList[K].isActive)
{
basicEnemyWeaponBulletList[i].basicEnemyWeaponBulletposition = basicEnemyList[K].basicEnemyposition;
}
// bullet is set to true
basicEnemyWeaponBulletList[i].isActive = true;
// play laser sounds
LaserSounds[0].Play();
// set spawn time
basicEnemyBulletTimer.time = 3;
}
}
}
public void spawnStrongEnemybullets()
{
// number of bullets
for (int i = 0; i < GameConstants.NumBasicEnemyBullets; i++)
// is bullet isnt active and spawn time = 0
if (!strongEnemyWeaponBulletList[i].isActive && strongEnemyBulletTimer.time == 0)
{
// for each strong enemy
for (int K = 0; K < GameConstants.strongEnemyNumbers; K++)
{
// bullet direction
strongEnemyWeaponBulletList[i].basicEnemyWeaponBulletdirection = new Vector3(-10.0f, 0.0f, 0.0f);
// bullet speed
strongEnemyWeaponBulletList[i].basicEnemyWeaponBulletspeed = GameConstants.basicEnemyWeaponSpeedAdjustment;
// if strong enemy is active
if (strongEnemyList[K].isActive)
{
// bullet position set to enemy position
strongEnemyWeaponBulletList[i].basicEnemyWeaponBulletposition = strongEnemyList[K].strongEnemyposition;
}
// bullet set to active
strongEnemyWeaponBulletList[i].isActive = true;
// play laser sounds
LaserSounds[0].Play();
// timer set to 3 seconds
strongEnemyBulletTimer.time = 3;
}
}
}
// explosion method
/*private void AddExplosion(Vector2 position)
{
Animation explosion = new Animation();
explosion.Initialize(explosionTexture, position, 1340, 1340, 12, 45, Color.White, 1f, false);
explosions.Add(explosion);
}*/
// method for writing text
private void writeText(string msg,Vector2 msgPos, Color msgCol)
{
// start sprite batch
spriteBatch.Begin();
// message to output
string output = msg;
Vector2 FontOrigin = scoreFont.MeasureString(output) / 2;
// position
Vector2 FontPos = msgPos;
// draw message
spriteBatch.DrawString(scoreFont, output, FontPos,Color.Yellow);
// end sprite batch
spriteBatch.End();
}
// set up model for drawing
private Matrix[] SetupEffectTransformDefaults(Model myModel)
{
// matrix for each mesh count
Matrix[] absoluteTransforms = new Matrix[myModel.Bones.Count];
myModel.CopyAbsoluteBoneTransformsTo(absoluteTransforms);
// foreach mesh in the model
foreach (ModelMesh mesh in myModel.Meshes)
{
foreach (BasicEffect effect in mesh.Effects)
{
effect.EnableDefaultLighting();
effect.Projection = projectionMatrix;
effect.View = viewMatrix;
}
}
return absoluteTransforms;
}
// draw model method
public void DrawModel(Model model, Matrix modelTransform, Matrix[] absoluteBoneTransforms)
{
//Draw the model, a model can have multiple meshes, so loop
foreach (ModelMesh mesh in model.Meshes)
{
//This is where the mesh orientation is set
foreach (BasicEffect effect in mesh.Effects)
{
effect.World = absoluteBoneTransforms[mesh.ParentBone.Index] * modelTransform;
}
//Draw the mesh, will use the effects set above.
mesh.Draw();
}
}
// ability to toggle audio
public void toggleAudio()
{
// get keyboard state
KeyboardState keyboardState = Keyboard.GetState();
// keyboard state setup
if (keyboardState.GetPressedKeys() == oldState.GetPressedKeys())
{
return;
}
// if music toggle is true
if (musicToggle == true)
{
// if Q is pressed
if (oldState.IsKeyUp(Keys.Q) && keyboardState.IsKeyDown(Keys.Q))
{
// music toggle is false
musicToggle = false;
// music is muted
MediaPlayer.IsMuted = true;
}
}
// if music toggle is false
else if (musicToggle == false)
{
// if Q is pressed
if (oldState.IsKeyUp(Keys.Q) && keyboardState.IsKeyDown(Keys.Q))
{
// music toggle = true
musicToggle = true;
// music is not muted
MediaPlayer.IsMuted = false;
}
}
// old state = keyboard state
oldState = keyboardState;
}
// game1 code
public Game1()
{
graphics = new GraphicsDeviceManager(this);
Content.RootDirectory = "Content";
}
/// <summary>
/// Allows the game to perform any initialization it needs to before starting to run.
/// This is where it can query for any required services and load any non-graphic
/// related content. Calling base.Initialize will enumerate through any components
/// and initialize them as well.
/// </summary>
protected override void Initialize()
{
// Initialize background layer 1 & 2
bgLayer1 = new Background();
bgLayer2 = new Background();
// initialize transform
InitializeTransform();
// Initialize our random number generator
random = new Random();
// set music to on
musicToggle = true;
// Initialize hit counter
hitCount = 0;
// explosion animation
explosions = new List<Animation>();
// Initialize Score
score = 0;
// space Station
spaceStationHealth = 100;
// Initialize Player
player = new playerShip();
// Initialize reload timer
playerReloadTime = new Timer();
// Initialize enemy spawn timer
enemySpawnTime = new Timer();
// initialize fast spawn timer
fastEnemySpawnTime = new Timer();
// initialize strong enemy timer
strongEnemySpawnTime = new Timer();
// initialize basic enemy bullet
basicEnemyBulletTimer = new Timer();
// initialize strong enemy bullet
strongEnemyBulletTimer = new Timer();
// Initialize
base.Initialize();
}
/// <summary>
/// LoadContent will be called once per game and is the place to load
/// all of your content.
/// </summary>
protected override void LoadContent()
{
// Create a new SpriteBatch, which can be used to draw textures.
spriteBatch = new SpriteBatch(GraphicsDevice);
aspectRatio = graphics.GraphicsDevice.Viewport.AspectRatio;
// Load player model
player.playerModel = Content.Load<Model>("Models\\Feisar_Ship");
player.playerTransforms = SetupEffectTransformDefaults(player.playerModel);
// Load basicweapon bullets
basicWeaponBulletModel = Content.Load<Model>("Models\\massiveorb");
basicWeaponbulletTransforms = SetupEffectTransformDefaults(basicWeaponBulletModel);
// load basic enemy
basicEnemyModel = Content.Load<Model>("Models\\cottus_elec");
basicEnemyModelTransforms = SetupEffectTransformDefaults(basicEnemyModel);
// load fast enemy
fastEnemyModel = Content.Load<Model>("Models\\Feisar_Ship");
fastEnemyModelTransforms = SetupEffectTransformDefaults(fastEnemyModel);
// load strong enemy
strongEnemyModel = Content.Load<Model>("Models\\H8SHIPscaled");
strongEnemyModelTransforms = SetupEffectTransformDefaults(strongEnemyModel);
// load basic enemy bullet
basicEnemyWeaponBulletmodel = Content.Load<Model>("Models\\massiveorb");
basicEnemyWeaponbulletTransforms = SetupEffectTransformDefaults(basicEnemyWeaponBulletmodel);
// load strong enemy bullet
strongEnemyWeaponBulletmodel = Content.Load<Model>("Models\\massiveorb");
strongEnemyWeaponbulletTransforms = SetupEffectTransformDefaults(strongEnemyWeaponBulletmodel);
// Load layer1 and 2 content
bgLayer1.Initialize(Content, "bgLayer1", GraphicsDevice.Viewport.Width, -1);
bgLayer2.Initialize(Content, "bgLayer2", GraphicsDevice.Viewport.Width, -2);
// score Font
scoreFont = Content.Load<SpriteFont>("scoreFont");
// explosion texture
explosionTexture = Content.Load<Texture2D>("explosion");
//Create background texture
mainBackground = Content.Load<Texture2D>("sky-stars-background");
// load sound effects for explosions and crashes
CrashSounds[0] = Content.Load<SoundEffect>("sounds/explosion");
CrashSounds[1] = Content.Load<SoundEffect>("sounds/explosion1");
CrashSounds[2] = Content.Load<SoundEffect>("sounds/110115__ryansnook__small-explosion");
CrashSounds[3] = Content.Load<SoundEffect>("sounds/137040__mateusboga__explosion1");
CrashSounds[4] = Content.Load<SoundEffect>("sounds/explosion1");
// load sound effects for lasers/bullets
LaserSounds[0] = Content.Load<SoundEffect>("sounds/151022__bubaproducer__laser-shot-silenced");
LaserSounds[1] = Content.Load<SoundEffect>("sounds/42106__marcuslee__laser-wrath-4");
LaserSounds[2] = Content.Load<SoundEffect>("sounds/laserFire");
// background music
backgroundSong = Content.Load<Song>("Audio/DRIVE for the SEGA MASTER SYSTEM_GENESIS");
MediaPlayer.Play(backgroundSong);
MediaPlayer.IsRepeating = true;
}
/// <summary>
/// UnloadContent will be called once per game and is the place to unload
/// all content.
/// </summary>
protected override void UnloadContent()
{
// TODO: Unload any non ContentManager content here
}
/// <summary>
/// Allows the game to run logic such as updating the world,
/// checking for collisions, gathering input, and playing audio.
/// </summary>
/// <param name="gameTime">Provides a snapshot of timing values.</param>
protected override void Update(GameTime gameTime)
{
// Allows the game to exit
if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed || Keyboard.GetState().IsKeyDown(Keys.Escape))
this.Exit();
// counts the time since the start of the game
float timeDelta = (float)gameTime.ElapsedGameTime.TotalSeconds;
// spaceStation exit code
if (spaceStationHealth == 0)
{
Exit();
}
if (player.lives == 0)
{
Exit();
}
// if music is false
if (musicToggle == false)
{
// mute music
MediaPlayer.IsMuted = true;
}
// if music is true
else if (musicToggle == true)
{
// un-mute music
MediaPlayer.IsMuted = false;
}
// toggle audio
toggleAudio();
// player bullet timer update
playerBulletTimer(gameTime);
// basic enemies timer update
spawnBasicEnemiesTimer(gameTime);
//fast enemies timer update
spawnFastEnemiesTimer(gameTime);
// strong enemies timer update
spawnFastEnemiesTimer(gameTime);
// basic enemy bullet timer
spawnBasicEnemyBulletsTimer(gameTime);
// strong enemy bullet timer
spawnStrongEnemiesTimer(gameTime);
// Update the parallaxing background
bgLayer1.Update();
bgLayer2.Update();
// Clamps the player within the window (X coordinate)
player.playerPosition.X = MathHelper.Clamp(player.playerPosition.X, -2700.0f, 2950.0f - player.playerBox.Radius);
// Clamps the player within the window(Y coordinate)
player.playerPosition.Y = MathHelper.Clamp(player.playerPosition.Y, -1950.0f, 2000.0f - player.playerBox.Radius);
// update player
player.Update();
// update explosions
UpdateExplosions(gameTime);
// shoot bullet code
shootbullets();
// gamepad controller bullet code
gamePadShootBullets();
// shoot enemy bullets
spawnBasicEnemybullets();
// shoot enemy bullets
spawnStrongEnemybullets();
// bullet list update
for(int i = 0; i < GameConstants.NumBasicBullets; i++)
{
if(basicWeaponBulletList[i].isActive)
{
basicWeaponBulletList[i].Update(timeDelta);
}
}
// spawn basic enemies
spawnBasicEnemies();
// basic enemies update list
for (int i = 0; i < GameConstants.basicEnemyNumbers; i++)
{
if (basicEnemyList[i].isActive)
{
basicEnemyList[i].Update(timeDelta);
}
}
spawnFastEnemies();
// fast enemies update list
for (int i = 0; i < GameConstants.fastEnemyNumbers; i++)
{
if (fastEnemyList[i].isActive)
{
fastEnemyList[i].Update(timeDelta);
}
}
spawnStrongEnemies();
// fast enemies update list
for (int i = 0; i < GameConstants.strongEnemyNumbers; i++)
{
if (strongEnemyList[i].isActive)
{
strongEnemyList[i].Update(timeDelta);
}
}
// enemy bullets
for (int i = 0; i < GameConstants.NumBasicEnemyBullets; i++)
{
if (basicEnemyWeaponBulletList[i].isActive)
{
basicEnemyWeaponBulletList[i].Update(timeDelta);
}
}
// strong enemy bullets
for (int i = 0; i < GameConstants.NumBasicEnemyBullets; i++)
{
if (strongEnemyWeaponBulletList[i].isActive)
{
strongEnemyWeaponBulletList[i].Update(timeDelta);
}
}
// update player
player.Update();
// collision for basic enemies
for (int i = 0; i < basicEnemyList.Length; i++)
{
if (basicEnemyList[i].isActive)
{
// create bounding
BoundingSphere basicEnemyBounding = new BoundingSphere(basicEnemyList[i].basicEnemyposition,
basicEnemyModel.Meshes[0].BoundingSphere.Radius * GameConstants.basicEnemyBoundingSphereScale);
// if player passed left hand side of screen
if (basicEnemyList[i].basicEnemyposition.X < -3300 ||
basicEnemyList[i].basicEnemyposition.Z > GameConstants.PlayfieldSizeZ ||
basicEnemyList[i].basicEnemyposition.Z < -GameConstants.PlayfieldSizeZ)
{
// space station health decreases
spaceStationHealth--;
}
// for each player bullet
for (int K = 0; K < basicWeaponBulletList.Length; K++)
{
// if bullet is active
if (basicWeaponBulletList[K].isActive)
{
// create bounding for bullet
BoundingSphere basicWeaponBounding = new BoundingSphere(basicWeaponBulletList[K].basicWeaponBulletposition,
basicWeaponBulletModel.Meshes[0].BoundingSphere.Radius * GameConstants.basicWeaponBoundingSphereScale);
// is enemy intersects weapon bounding
if (basicEnemyBounding.Intersects(basicWeaponBounding))
{
// enemy health decreases
basicEnemyList[i].health--;
// if enemy health = 0
if (basicEnemyList[i].health == 0)
{
// play random sound effects
int crashIndex = random.Next(0, 4);
CrashSounds[crashIndex].Play();
//AddExplosion(new Vector2(basicEnemyList[i].basicEnemyposition.X,basicEnemyList[i].basicEnemyposition.Y));
}
// bullet is no longer active
basicWeaponBulletList[K].isActive = false;
hitCount++;
// increase score
score++;
break;
}
}
// if enemy intersects player
if (basicEnemyBounding.Intersects(player.playerBox))
{
//AddExplosion(new Vector2(basicEnemyList[i].basicEnemyposition.X,basicEnemyList[i].basicEnemyposition.Y));
// play random sound
int crashIndex = random.Next(0,4);
CrashSounds[crashIndex].Play();
// enemy is set to false
basicEnemyList[i].isActive = false;
// player health decreases
player.Health--;
hitCount++;
break;
}
}
}
}
for (int i = 0; i < basicEnemyWeaponBulletList.Length; i++)
{
if (basicEnemyWeaponBulletList[i].isActive)
{
BoundingSphere basicEnemyBulletBounding = new BoundingSphere(basicEnemyWeaponBulletList[i].basicEnemyWeaponBulletposition,
basicEnemyWeaponBulletmodel.Meshes[0].BoundingSphere.Radius * GameConstants.basicEnemyBoundingSphereScale);
if (basicEnemyBulletBounding.Intersects(player.playerBox))
{
basicEnemyWeaponBulletList[i].isActive = false;
player.Health--;
// random sound plays
int crashIndex = random.Next(0, 4);
CrashSounds[crashIndex].Play();
break;
}
}
}
// for each fast enemy
for (int i = 0; i < fastEnemyList.Length; i++)
{
// if enemy is active
if (fastEnemyList[i].isActive)
{
// create bounding
BoundingSphere fastEnemyBounding = new BoundingSphere(fastEnemyList[i].fastEnemyposition,
fastEnemyModel.Meshes[0].BoundingSphere.Radius * GameConstants.fastEnemyBoundingSphereScale);
// for each bullet
for (int K = 0; K < basicWeaponBulletList.Length; K++)
{
// if bullet is active
if (basicWeaponBulletList[K].isActive)
{
// create bounding
BoundingSphere basicWeaponBounding = new BoundingSphere(basicWeaponBulletList[K].basicWeaponBulletposition,
basicWeaponBulletModel.Meshes[0].BoundingSphere.Radius * GameConstants.basicWeaponBoundingSphereScale);
// if fast enemy gets hit by bullet
if (fastEnemyBounding.Intersects(basicWeaponBounding))
{
// health decreases
fastEnemyList[i].health--;
// bullet is destroyed
basicWeaponBulletList[K].isActive = false;
// random sound plays
int crashIndex = random.Next(0, 4);
CrashSounds[crashIndex].Play();
hitCount++;
// score decreases
score--;
break;
}
}
// if fast enemy hits player
if (fastEnemyBounding.Intersects(player.playerBox))
{
// health decreases
player.Health--;
// score decreases
score--;
// random sound plays
int crashIndex = random.Next(0, 4);
CrashSounds[crashIndex].Play();
// enemy is destroyed
fastEnemyList[i].isActive = false;
hitCount++;
break;
}
}
}
}
// strong enemy collision
for (int i = 0; i < strongEnemyList.Length; i++)
{
// if strong enemy is active
if (strongEnemyList[i].isActive)
{
// create bounding
BoundingSphere strongEnemyBounding = new BoundingSphere(strongEnemyList[i].strongEnemyposition,
strongEnemyModel.Meshes[0].BoundingSphere.Radius * GameConstants.strongEnemyBoundingSphereScale);
// strong enemy passed left of screen
if (strongEnemyList[i].strongEnemyposition.X < -3300 ||
strongEnemyList[i].strongEnemyposition.Z > GameConstants.PlayfieldSizeZ ||
strongEnemyList[i].strongEnemyposition.Z < -GameConstants.PlayfieldSizeZ)
{
// space station health decreases
spaceStationHealth--;
}
// create bullet bounding
for (int K = 0; K < basicWeaponBulletList.Length; K++)
{
if (basicWeaponBulletList[K].isActive)
{
BoundingSphere basicWeaponBounding = new BoundingSphere(basicWeaponBulletList[K].basicWeaponBulletposition,
basicWeaponBulletModel.Meshes[0].BoundingSphere.Radius * GameConstants.basicWeaponBoundingSphereScale);
if (strongEnemyBounding.Intersects(basicWeaponBounding))
{
strongEnemyList[i].health--;
basicWeaponBulletList[K].isActive = false;
int crashIndex = random.Next(0, 4);
CrashSounds[crashIndex].Play();
hitCount++;
score++;
break;
}
}
// if strong enemy hits player
if (strongEnemyBounding.Intersects(player.playerBox))
{
player.Health--;
int crashIndex = random.Next(0, 4);
CrashSounds[crashIndex].Play();
strongEnemyList[i].isActive = false;
hitCount++;
Debug.WriteLine("enemy hit");
break;
}
}
}
}
// update game
base.Update(gameTime);
}
// updates the explosions
private void UpdateExplosions(GameTime gameTime)
{
for (int i = explosions.Count - 1; i >= 0; i--)
{
explosions[i].Update(gameTime);
if (explosions[i].Active == false)
{
explosions.RemoveAt(i);
}
}
}
// timer for player bullets
public void playerBulletTimer(GameTime gameTime)
{
// set current time to count seconds
playerReloadTime.currentTime += (float)gameTime.ElapsedGameTime.TotalSeconds; //Time passed since last Update()
// reload counter
if (playerReloadTime.time > 0)
{
// if current time is more than count duration
if (playerReloadTime.currentTime >= playerReloadTime.countDuration)
{
// counter increases
playerReloadTime.counter++;
playerReloadTime.currentTime -= playerReloadTime.countDuration;
Debug.WriteLine("In first counter");
}
// if counter is over the spawn time
if (playerReloadTime.counter >= playerReloadTime.time)
{
// reset counter
playerReloadTime.counter = 0;
// reset timer
playerReloadTime.time = 0;
Debug.WriteLine("Reload reset");
}
}
}
// timer for spawning basic enemies
public void spawnBasicEnemiesTimer(GameTime gameTime)
{
// set timer for reload
enemySpawnTime.currentTime += (float)gameTime.ElapsedGameTime.TotalSeconds; //Time passed since last Update()
// reload counter
if (enemySpawnTime.time > 0)
{
if (enemySpawnTime.currentTime >= enemySpawnTime.countDuration)
{
enemySpawnTime.counter++;
enemySpawnTime.currentTime -= enemySpawnTime.countDuration;
Debug.WriteLine("In first enemy counter");
}
if (enemySpawnTime.counter >= enemySpawnTime.time)
{
enemySpawnTime.counter = 0;
enemySpawnTime.time = 0;
Debug.WriteLine("enemy spawned reset");
}
}
}
// spawn basic enemy bullets
public void spawnBasicEnemyBulletsTimer(GameTime gameTime)
{
// set timer for enemy bullets
basicEnemyBulletTimer.currentTime += (float)gameTime.ElapsedGameTime.TotalSeconds; //Time passed since last Update()
// reload counter
if (basicEnemyBulletTimer.time > 0)
{
if (basicEnemyBulletTimer.currentTime >= basicEnemyBulletTimer.countDuration)
{
basicEnemyBulletTimer.counter++;
basicEnemyBulletTimer.currentTime -= basicEnemyBulletTimer.countDuration;
Debug.WriteLine("In enemy bullet counter");
}
if (basicEnemyBulletTimer.counter >= basicEnemyBulletTimer.time)
{
basicEnemyBulletTimer.counter = 0;
basicEnemyBulletTimer.time = 0;
Debug.WriteLine("enemy bullet reset");
}
}
}
// spawn fast enemies
public void spawnFastEnemiesTimer(GameTime gameTime)
{
// set timer for fastenemy spawn
fastEnemySpawnTime.currentTime += (float)gameTime.ElapsedGameTime.TotalSeconds; //Time passed since last Update()
// reload counter
if (fastEnemySpawnTime.time > 0)
{
if (fastEnemySpawnTime.currentTime >= fastEnemySpawnTime.countDuration)
{
fastEnemySpawnTime.counter++;
fastEnemySpawnTime.currentTime -= fastEnemySpawnTime.countDuration;
Debug.WriteLine("In first enemy counter");
}
if (fastEnemySpawnTime.counter >= fastEnemySpawnTime.time)
{
fastEnemySpawnTime.counter = 0;
fastEnemySpawnTime.time = 0;
Debug.WriteLine("enemy spawned reset");
}
}
}
// spawn strong enemeis
public void spawnStrongEnemiesTimer(GameTime gameTime)
{
// set timer for strongenemy spawn
strongEnemySpawnTime.currentTime += (float)gameTime.ElapsedGameTime.TotalSeconds; //Time passed since last Update()
// reload counter
if (strongEnemySpawnTime.time > 0)
{
if (strongEnemySpawnTime.currentTime >= strongEnemySpawnTime.countDuration)
{
strongEnemySpawnTime.counter++;
strongEnemySpawnTime.currentTime -= strongEnemySpawnTime.countDuration;
Debug.WriteLine("In strong enemy counter");
}
if (strongEnemySpawnTime.counter >= strongEnemySpawnTime.time)
{
strongEnemySpawnTime.counter = 0;
strongEnemySpawnTime.time = 0;
Debug.WriteLine("enemy strong spawned reset");
}
}
}
// spawn strong enemies
public void spawnStrongEnemyBulletsTimer(GameTime gameTime)
{
// set timer for enemy bullets
strongEnemyBulletTimer.currentTime += (float)gameTime.ElapsedGameTime.TotalSeconds; //Time passed since last Update()
// reload counter
if (strongEnemyBulletTimer.time > 0)
{
if (strongEnemyBulletTimer.currentTime >= strongEnemyBulletTimer.countDuration)
{
strongEnemyBulletTimer.counter++;
strongEnemyBulletTimer.currentTime -= strongEnemyBulletTimer.countDuration;
Debug.WriteLine("In enemy bullet counter");
}
if (strongEnemyBulletTimer.counter >= strongEnemyBulletTimer.time)
{
strongEnemyBulletTimer.counter = 0;
strongEnemyBulletTimer.time = 0;
Debug.WriteLine("enemy bullet reset");
}
}
}
// draws player bullets
public void Drawbullets(GameTime gameTime)
{
// draws bullets
for (int i = 0; i < GameConstants.NumBasicBullets; i++)
{
if (basicWeaponBulletList[i].isActive)
{
Matrix laserTransform = Matrix.CreateTranslation(basicWeaponBulletList[i].basicWeaponBulletposition);
DrawModel(basicWeaponBulletModel, laserTransform, basicWeaponbulletTransforms);
}
}
}
// Draw basic Enemy Models
public void DrawBasicEnemies(GameTime gameTime)
{
// draws basic enemies
for (int i = 0; i < GameConstants.basicEnemyNumbers; i++)
{
if (basicEnemyList[i].isActive)
{
Matrix basicEnemyTransform = Matrix.CreateTranslation(basicEnemyList[i].basicEnemyposition);
DrawModel(basicEnemyModel, basicEnemyTransform, basicEnemyModelTransforms);
}
}
}
// Draw basic Enemy Bullets
public void DrawBasicEnemybullets(GameTime gameTime)
{
// draw basic enemy bullets
for (int i = 0; i < GameConstants.NumBasicEnemyBullets; i++)
{
if (basicEnemyWeaponBulletList[i].isActive)
{
Matrix enemyBulletTransform = Matrix.CreateTranslation(basicEnemyWeaponBulletList[i].basicEnemyWeaponBulletposition);
DrawModel(basicEnemyWeaponBulletmodel, enemyBulletTransform, basicEnemyWeaponbulletTransforms);
}
}
}
// Draw Fast Enemy Models
public void DrawFastEnemies(GameTime gameTime)
{
// draws fast enemies
for (int i = 0; i < GameConstants.fastEnemyNumbers; i++)
{
if (fastEnemyList[i].isActive)
{
Matrix fastEnemyTransform = Matrix.CreateRotationY(300.0f) * Matrix.CreateTranslation(fastEnemyList[i].fastEnemyposition);
DrawModel(fastEnemyModel, fastEnemyTransform, fastEnemyModelTransforms);
}
}
}
// Draw Strong Enemy Models
public void DrawStrongEnemies(GameTime gameTime)
{
// draws strong enemies
for (int i = 0; i < GameConstants.strongEnemyNumbers; i++)
{
if (strongEnemyList[i].isActive)
{
Matrix strongEnemyTransform = Matrix.CreateTranslation(strongEnemyList[i].strongEnemyposition);
DrawModel(strongEnemyModel, strongEnemyTransform, strongEnemyModelTransforms);
}
}
}
// Draw basic Enemy Bullets
public void DrawStrongEnemybullets(GameTime gameTime)
{
// draw basic enemy bullets
for (int i = 0; i < GameConstants.NumBasicEnemyBullets; i++)
{
if (strongEnemyWeaponBulletList[i].isActive)
{
Matrix enemyBulletTransform = Matrix.CreateTranslation(basicEnemyWeaponBulletList[i].basicEnemyWeaponBulletposition);
DrawModel(strongEnemyWeaponBulletmodel, enemyBulletTransform, strongEnemyWeaponbulletTransforms);
}
}
}
/// <summary>
/// This is called when the game should draw itself.
/// </summary>
/// <param name="gameTime">Provides a snapshot of timing values.</param>
protected override void Draw(GameTime gameTime)
{
GraphicsDevice.Clear(Color.CornflowerBlue);
// TODO: Add your drawing code here
// Begin Sprite drawing
spriteBatch.Begin();
// Draw Background
spriteBatch.Draw(mainBackground, Vector2.Zero, Color.White);
// Draw the moving background
bgLayer1.Draw(spriteBatch);
bgLayer2.Draw(spriteBatch);
for (int i = 0; i < explosions.Count; i++)
{
explosions[i].Draw(spriteBatch);
Debug.WriteLine("Explosion Drawn");
}
//End Sprite drawing
spriteBatch.End();
// stencil depth drawer
GraphicsDevice.DepthStencilState = new DepthStencilState() { DepthBufferEnable = true };
// draw player bullets
Drawbullets(gameTime);
// Draws the basic Enemies
DrawBasicEnemies(gameTime);
// draw basic enemy bullets
DrawBasicEnemybullets(gameTime);
//Draws fast enemies
DrawFastEnemies(gameTime);
// draws strong enemies
DrawStrongEnemies(gameTime);
// draw basic enemy bullets
DrawStrongEnemybullets(gameTime);
// draws player and transforms
Matrix modelTransform = Matrix.CreateRotationY(player.modelRotation) * Matrix.CreateTranslation(player.playerPosition);
DrawModel(player.playerModel, modelTransform, player.playerTransforms);
// Draws the text for the Score
writeText("Score:" + score.ToString() , new Vector2(50,10), Color.Yellow);
// Draws the text for the players health
writeText("Player Health/Lives:" + player.Health.ToString() + "/" + player.lives.ToString() , new Vector2(200, 10), Color.Yellow);
// Draws the text for the space stations health
writeText("Space Station Health:" + spaceStationHealth.ToString(), new Vector2(500, 10), Color.Yellow);
// draw
base.Draw(gameTime);
}
}
}
|
using System.Collections.Generic;
namespace SQLite
{
public class TestDatabase:AbstractDatabase
{
const string _DATABASE_NAME = "test";
const string _DATABASE_PATH = "/Datas/SQLiteData/";
SqlDatabase _database;
SqlField[] _tableSqlFields;
public TestDatabase(string tableName)
{
Initiate();
TableName = tableName;
}
private protected sealed override SqlDatabase InitiateSqlDatabase()
{
return new SqlDatabase(_DATABASE_NAME,InitiateSqlTable());
}
private protected sealed override List<SqlTable> InitiateSqlTable()
{
List<SqlTable> resultSqlTables = new List<SqlTable> {InitiateTableTest_t()};
return resultSqlTables;
}
void Initiate()
{
_database = InitiateSqlDatabase();
}
public override string GetTableName()
{
return TableName;
}
public override string GetDatabasePath()
{
return _DATABASE_PATH;
}
public override List<SqlField> GetAllFields()
{
return _database.SelectSqlTable(TableName).TableFields;
}
public override string GetDatabaseName()
{
return _DATABASE_NAME;
}
#region tableList
SqlTable InitiateTableTest_t()
{
string tableName = "test_t";
SqlField id=new SqlField("_id").SetType(SqlFieldType.Int);
SqlField name=new SqlField("_name").SetType(SqlFieldType.Text);
SqlField data=new SqlField("_data").SetType(SqlFieldType.Text);
SqlField floatField=new SqlField("_floatField").SetType(SqlFieldType.Float);
SqlField blobField=new SqlField("_blobField").SetType(SqlFieldType.Binary);
List<SqlField> result = new List<SqlField>
{
id,
name,
data,
floatField,
blobField
};
return new SqlTable(tableName,result);
}
#endregion
}
} |
using Atmos;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[RequireComponent(typeof(PipeConnections))]
public class BlockThruster : Block, Atmos.Atmospheric
{
[SerializeField]
private GameObject thrusterEfect;
[SerializeField]
private float internalTankSize = 1000;
private bool hasFuel {
get {
return gasMix.GetPressure() > 10;
}
} //TODO: Eventually this should be a fuel interface with properties like thrust force, color, isp, etc
private bool isActive;
private GasMix gasMix;
private PipeConnections connections;
void Atmospheric.DrawDebugGUI(Vector2 location) {
const float step = 20;
GUI.Label(new Rect(location, new Vector2(150, step)), "Vol: " + gasMix.volume);
location.y += step;
GUI.Label(new Rect(location, new Vector2(150, step)), "Temp: " + gasMix.temperature);
location.y += step;
GUI.Label(new Rect(location, new Vector2(150, step)), "Pres: " + gasMix.GetPressure());
foreach(GasCount gas in gasMix.GetCurrentGasses()) {
location.y += step;
GUI.Label(new Rect(location, new Vector2(150, step)), gas.gas.name + ": " + gas.mols);
}
}
void Atmospheric.Tick() {
// Fill a local tank with fuel, gasMix or buckets worth
List<GasMix> mixes = new List<GasMix>(connections.sockets.Length);
mixes.Add(gasMix);
foreach(ConnectionSocket socket in connections.sockets) {
PipeNetwork network = ship.pipes.GetConnectingNetwork(blockPos + socket.relativeLoc, socket.dir);
if(network != null) {
mixes.Add(network.GetGasMix());
}
}
GasMix.Mix(mixes);
if(isActive && hasFuel) {
gasMix.RemoveGas(Gas.Fuel, 1);
}
}
public override void OnPlace(ShipManager ship, Vector2I gridBlockPos) {
base.OnPlace(ship, gridBlockPos);
ship.atmo.AddAtmosphericObject(this);
}
public override void OnRemove(ShipManager ship, Vector2I blockPos) {
base.OnRemove(ship, blockPos);
ship.atmo.RemoveAtmosphericObject(this);
}
private void Awake() {
connections = GetComponent<PipeConnections>();
gasMix = new GasMix(internalTankSize);
}
private void Update() {
if(Input.GetButton("Jump")) {
this.isActive = true;
} else {
this.isActive = false;
}
if(isActive && hasFuel) {
thrusterEfect.SetActive(true);
} else {
thrusterEfect.SetActive(false);
}
}
}
|
using GaleService.Controllers.Validators;
using GaleService.DomainLayer.Managers.Enums;
using GaleService.DomainLayer.Managers.Exceptions;
using GaleService.DomainLayer.Managers.Models;
using GaleService.DomainLayer.Managers.Models.Request;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.Diagnostics.CodeAnalysis;
namespace ClassTests.Validators
{
[TestClass]
[ExcludeFromCodeCoverage]
public class GaleRequestValidatorTests
{
private const string ValidAccessToken = "Test";
private DateTime ValidAccessTokenExpirationDate = DateTime.Now;
private FitnessDevice ValidFitnessDeviceType = FitnessDevice.FitbitTracker;
private const string ValidFilter = "test";
private const int ValidPeriod = 1;
[TestMethod]
[TestCategory("Class Test")]
public void Validate_WhenAccessTokenIsNull_ShouldThrow()
{
// Arrange
var expectedExceptionMessage = "received a null access token";
string invalidAccessToken = null;
var invalidGaleRequest = new GaleRequest(invalidAccessToken, ValidAccessTokenExpirationDate);
try
{
// Act
GaleRequestValidator.Validate(invalidGaleRequest);
Assert.Fail($"Expected a {nameof(GaleInvalidRequestException)} to be thrown, but none was thrown.");
}
catch (GaleInvalidRequestException e)
{
// Assert
var actualExceptionMessage = e.Message;
StringAssert.Contains(actualExceptionMessage, expectedExceptionMessage);
}
}
[TestMethod]
[TestCategory("Class Test")]
public void Validate_WhenAccessTokenExpirationDateIsInvalid_ShouldThrow()
{
// Arrange
var expectedExceptionMessage = "received a bad access token expiration date";
var invalidAccessTokenExpirationDate = DateTime.MinValue;
var invalidGaleRequest = new GaleRequest(ValidAccessToken, invalidAccessTokenExpirationDate);
try
{
// Act
GaleRequestValidator.Validate(invalidGaleRequest);
Assert.Fail($"Expected a {nameof(GaleInvalidRequestException)} to be thrown, but none was thrown.");
}
catch (GaleInvalidRequestException e)
{
// Assert
var actualExceptionMessage = e.Message;
StringAssert.Contains(actualExceptionMessage, expectedExceptionMessage);
}
}
[TestMethod]
[TestCategory("Class Test")]
public void Validate_WhenFitnessDeviceTypeIsSetToNone_ShouldThrow()
{
// Arrange
var expectedExceptionMessage = "received an invalid fitness device";
var invalidFitnessDeviceType = FitnessDevice.None;
var invalidGaleRequest = new GaleFitnessDeviceStatsRequest(ValidAccessToken, ValidAccessTokenExpirationDate, invalidFitnessDeviceType, ValidFilter, ValidPeriod);
try
{
GaleRequestValidator.Validate(invalidGaleRequest);
Assert.Fail($"Expected a {nameof(GaleInvalidRequestException)} to be thrown, but none was thrown.");
}
catch (GaleInvalidRequestException e)
{
// Assert
var actualExceptionMessage = e.Message;
// Act
StringAssert.Contains(actualExceptionMessage, expectedExceptionMessage);
}
}
[TestMethod]
[TestCategory("Class Test")]
public void Validate_WhenFilterIsNull_ShouldThrow()
{
// Arrange
var expectedExceptionMessage = "received an invalid device filter";
string invalidFilter = null;
var invalidGaleRequest = new GaleFitnessDeviceStatsRequest(ValidAccessToken, ValidAccessTokenExpirationDate, ValidFitnessDeviceType, invalidFilter, ValidPeriod);
try
{
// Act
GaleRequestValidator.Validate(invalidGaleRequest);
Assert.Fail($"Expected a {nameof(GaleInvalidRequestException)} to be thrown, but none was thrown.");
}
catch (GaleInvalidRequestException e)
{
// Assert
var actualExceptionMessage = e.Message;
StringAssert.Contains(actualExceptionMessage, expectedExceptionMessage);
}
}
[TestMethod]
[TestCategory("Class Test")]
public void Validate_WhenPeriodIsNegativeOne_ShouldThrow()
{
// Arrange
var expectedExceptionMessage = "received an invalid period number";
var invalidPeriod = -1;
var invalidGaleRequest = new GaleFitnessDeviceStatsRequest(ValidAccessToken, ValidAccessTokenExpirationDate, ValidFitnessDeviceType, ValidFilter, invalidPeriod);
try
{
// Act
GaleRequestValidator.Validate(invalidGaleRequest);
Assert.Fail($"Expected a {nameof(GaleInvalidRequestException)} to be thrown, but none was thrown.");
}
catch (GaleInvalidRequestException e)
{
// Assert
var actualExceptionMessage = e.Message;
StringAssert.Contains(actualExceptionMessage, expectedExceptionMessage);
}
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Game3 : MonoBehaviour
{
public Light myLight;
public float time1;
// Intensity Variables
public bool changeIntensity = false;
public float intensitySpeed = 1.0f;
public float maxIntensity = 10.0f;
// Color variables
public bool changeColors = false;
public float colorSpeed = 0.2f;
public Color startColor;
public Color endColor;
public bool repeatColor = true;
public int score = 0;
bool count = true;
float startTime;
// Use this for initialization
void Start()
{
myLight = GetComponent<Light>();
startTime = Time.time;
}
// Update is called once per frame
void Update()
{
if (changeColors)
{
if (repeatColor)
{
float t = (Mathf.Sin(Time.time - startTime * colorSpeed));
myLight.color = Color.Lerp(startColor, endColor, t);
}
else
{
float t = Time.time - startTime * colorSpeed;
myLight.color = Color.Lerp(startColor, endColor, t);
}
}
//output part
if (myLight.color == Color.green && count == true)
{
time1 += Time.deltaTime;
if (Input.GetKeyDown(KeyCode.Mouse0))
{
//Debug.Log(myLight.color);
Debug.Log(time1);
score = score + 1;
count = false;
}
}
if (myLight.color != Color.green)
{
count = true;
}
}
} |
namespace IEEE754FormatOfFloat
{
using System;
using System.Threading;
class IEEE754FormatOfFloat
{
/// <summary>
/// Write a program that shows the internal binary representation of given 32-bit signed floating-point number
/// in IEEE 754 format (the C# type float).
/// Example: -27,25 -> sign = 1, exponent = 10000011, mantissa = 10110100000000000000000.
/// </summary>
public static void Main(string[] args)
{
Thread.CurrentThread.CurrentCulture = System.Globalization.CultureInfo.InvariantCulture;
float floatNumber = -27.25f;
string binaryNumber = ConvertFloatToBinary(floatNumber);
Console.WriteLine("Number: " + floatNumber);
Console.WriteLine("Binary number: " + binaryNumber);
Console.WriteLine("Sign: " + binaryNumber[0]);
Console.WriteLine("Exponent: " + binaryNumber.Substring(1, 8));
Console.WriteLine("Mantissa: " + binaryNumber.Substring(9));
Console.WriteLine();
floatNumber = 27.25f;
binaryNumber = ConvertFloatToBinary(floatNumber);
Console.WriteLine("Number: " + floatNumber);
Console.WriteLine("Binary number: " + binaryNumber);
Console.WriteLine("Sign: " + binaryNumber[0]);
Console.WriteLine("Exponent: " + binaryNumber.Substring(1, 8));
Console.WriteLine("Mantissa: " + binaryNumber.Substring(9));
}
public static string ConvertFloatToBinary(float floatNumber)
{
string result = "";
byte[] floatBytes = BitConverter.GetBytes(floatNumber);
for (int i = 3; i >= 0; --i)
{
result += GroupToBinary(GetLeftGroup(floatBytes[i]));
result += GroupToBinary(GetRightGroup(floatBytes[i]));
}
return result;
}
public static int GetLeftGroup(byte x)
{
return (x >> 4);
}
public static int GetRightGroup(byte x)
{
return (x & 15);
}
public static string GroupToBinary(int x)
{
string result = "";
for (int i = 3; i >= 0; --i)
{
result += (x >> i) & 1;
}
return result;
}
}
} |
namespace BlazorChatApp.Client.Data
{
public static class Messages
{
public static string RECEIVE = "ReceiveMessage";
public static string REGISTER = "Register";
public static string SEND = "SendMessage";
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using MessageBoardBackend.Models;
using Microsoft.EntityFrameworkCore;
namespace MessageBoardBackend.Controllers
{
/// <summary>
/// currently filled with mock data to pass into
/// angular cli uses ienumreble and returns json array of Models.message
/// </summary>
[Produces("application/json")]
[Route("api/Messages")]
public class MessagesController : Controller
{
//--------------------------------------db static ----------------------------------------
public static DbContextOptions<ApiContext> options = new DbContextOptions<ApiContext>();
public static ApiContext db = new ApiContext(Options);
public static DbContextOptions<ApiContext> Options { get => options; set => options = value; }
//------------------------------------------------------------------------------------------
public IEnumerable<Message> Get()
{
var q = db.Messages.ToList();
return q;
}
[HttpGet("{name}")]
public IEnumerable<Message> Get(string name)
{
return db.Messages.Where(m => m.Owner == name);
}
//post req
[HttpPost]
public Message Post([FromBody] Message message)
{
var msg = new Message { Owner = message.Owner, Text = message.Text };
db.Messages.AddAsync(msg);
db.SaveChangesAsync();
return message;
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace BankTwo_v2.Funcionarios
{
public interface IAutenticavel // Interface 'Autenticavel' que dita regra para as classes-filha implementar o método 'Autenticar'
{
bool Autenticar(string senha);
}
}
|
using Microsoft.EntityFrameworkCore;
using OpenGov.Models;
using System;
namespace OpenGovAlerts.Models
{
public class AlertsDbContext : DbContext
{
public AlertsDbContext(DbContextOptions options)
: base(options)
{ }
public DbSet<Document> Documents { get; set; }
public DbSet<Meeting> Meetings { get; set; }
public DbSet<Source> Sources { get; set; }
public DbSet<Observer> Observers { get; set; }
public DbSet<Search> Searches { get; set; }
public DbSet<ObserverSearch> ObserverSearches { get; set; }
public DbSet<SearchSource> SearchSources { get; set; }
public DbSet<SeenMeeting> SeenMeetings { get; set; }
public DbSet<Match> Matches { get; set; }
public async virtual void UpdateSchema()
{
await Database.MigrateAsync();
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<Source>()
.HasMany(s => s.Meetings)
.WithOne(m => m.Source);
modelBuilder.Entity<Meeting>()
.HasMany(m => m.Documents)
.WithOne(d => d.Meeting);
modelBuilder.Entity<Observer>()
.HasMany(o => o.CreatedSearches)
.WithOne(s => s.CreatedBy);
modelBuilder.Entity<Observer>()
.HasMany(o => o.SubscribedSearches)
.WithOne(s => s.Observer);
modelBuilder.Entity<Search>()
.HasMany(s => s.Subscribers)
.WithOne(s => s.Search);
modelBuilder.Entity<Observer>()
.Property(o => o.Emails)
.HasColumnName("Email")
.HasConversion(
e => string.Join(',', e),
e => e.Split(',', StringSplitOptions.RemoveEmptyEntries));
modelBuilder.Entity<ObserverSearch>()
.HasKey(s => new { s.ObserverId, s.SearchId });
modelBuilder.Entity<SearchSource>()
.HasKey(s => new { s.SearchId, s.SourceId });
modelBuilder.Entity<SeenMeeting>()
.HasKey(m => new { m.SearchId, m.MeetingId });
modelBuilder.Entity<Search>()
.HasMany(s => s.Sources)
.WithOne(s => s.Search);
modelBuilder.Entity<Search>()
.HasMany(s => s.SeenMeetings)
.WithOne(m => m.Search);
modelBuilder.Entity<Search>()
.HasMany(s => s.Matches)
.WithOne(m => m.Search);
modelBuilder.Entity<Search>()
.HasMany(s => s.Sources)
.WithOne(s => s.Search);
modelBuilder.Entity<Meeting>()
.HasMany(m => m.Matches)
.WithOne(m => m.Meeting);
modelBuilder.Entity<Meeting>()
.Property(m => m.Url)
.HasConversion(v => v.ToString(), v => new Uri(v));
modelBuilder.Entity<Meeting>()
.Ignore(m => m.DocumentsUrl);
modelBuilder.Entity<Document>()
.Property(d => d.Url)
.HasConversion(v => v.ToString(), v => new Uri(v));
}
}
} |
using System;
namespace Reto_Semana_06_02
{
class Program
{
static void Main(string[] args)
{
//https://youtu.be/MQcUhRfExjs
Random random = new Random();
int totalPuntos = 0, vidas = 3, turno = 1, dado = 0;
string inputUsuario = "";
Console.WriteLine("¡Bienvenido al juego!");
while (true)
{
//Mostrar estadísticas
Console.ForegroundColor = ConsoleColor.Cyan;
Console.WriteLine("|| Estadísticas ||");
Console.WriteLine("Vidas: " + vidas);
Console.WriteLine("Puntos: " + totalPuntos );
Console.WriteLine("Turno: " + turno + "\n\n");
Console.ForegroundColor = ConsoleColor.White;
//Preguntar por retirarse
Console.WriteLine("¿Desea retirarse? (s/n)");
inputUsuario = Console.ReadLine();
while (inputUsuario != "s" && inputUsuario != "n")
{
Console.WriteLine("Comando Desconocido");
inputUsuario = Console.ReadLine();
}
if (inputUsuario == "s") return;
/// TIRADA DEL DADO
//En cada 3 turnos tirar 2 dados
if (turno % 3 == 0)
{
int dado1 = random.Next(1, 7);
int dado2 = random.Next(1, 7);
Console.WriteLine("Has sacado un " + dado1 + " y un " + dado2 + "\n\n\n");
//Ganar una vida al sacar un par
if (dado1 == dado2)
{
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine("¡Has ganado una vida al sacar un par!");
vidas++;
}
}
//Tirada Normal
else
{
dado = random.Next(1, 7);
Console.WriteLine("Has sacado " + dado + "\n\n\n");
totalPuntos += dado;
}
//Perder una vida cada 2 turnos
if (turno % 2 == 0)
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("Has perdido 1 vida al pasar 2 turnos");
vidas--;
}
//Perder en caso de quedarse sin vidas
if (vidas == 0)
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("¡Te has quedado sin vidas y has perdido!");
return;
}
//Ganar al alcanzar los 100 puntos
if (totalPuntos >= 100)
{
Console.ForegroundColor = ConsoleColor.Yellow;
Console.WriteLine("¡Has ganado al alcanzar los 100 puntos!");
return;
}
Console.ForegroundColor = ConsoleColor.White;
turno++;
}
}
}
}
|
using Domain.Entities;
using Microsoft.AspNetCore.Http;
namespace Application.Common.Vm {
public class FormUserVm {
public User User { get; set; }
public IFormFile UserProfile { get; set; }
}
} |
using LuaInterface;
using SLua;
using System;
using UnityEngine.Events;
public class Lua_UnityEngine_Events_UnityEvent : LuaObject
{
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int constructor(IntPtr l)
{
int result;
try
{
UnityEvent o = new UnityEvent();
LuaObject.pushValue(l, true);
LuaObject.pushValue(l, o);
result = 2;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int AddListener(IntPtr l)
{
int result;
try
{
UnityEvent unityEvent = (UnityEvent)LuaObject.checkSelf(l);
UnityAction unityAction;
LuaDelegation.checkDelegate(l, 2, out unityAction);
unityEvent.AddListener(unityAction);
LuaObject.pushValue(l, true);
result = 1;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int RemoveListener(IntPtr l)
{
int result;
try
{
UnityEvent unityEvent = (UnityEvent)LuaObject.checkSelf(l);
UnityAction unityAction;
LuaDelegation.checkDelegate(l, 2, out unityAction);
unityEvent.RemoveListener(unityAction);
LuaObject.pushValue(l, true);
result = 1;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int Invoke(IntPtr l)
{
int result;
try
{
UnityEvent unityEvent = (UnityEvent)LuaObject.checkSelf(l);
unityEvent.Invoke();
LuaObject.pushValue(l, true);
result = 1;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
public static void reg(IntPtr l)
{
LuaObject.getTypeTable(l, "UnityEngine.Events.UnityEvent");
LuaObject.addMember(l, new LuaCSFunction(Lua_UnityEngine_Events_UnityEvent.AddListener));
LuaObject.addMember(l, new LuaCSFunction(Lua_UnityEngine_Events_UnityEvent.RemoveListener));
LuaObject.addMember(l, new LuaCSFunction(Lua_UnityEngine_Events_UnityEvent.Invoke));
LuaObject.createTypeMetatable(l, new LuaCSFunction(Lua_UnityEngine_Events_UnityEvent.constructor), typeof(UnityEvent), typeof(UnityEventBase));
}
}
|
using Hahn.ApplicatonProcess.December2020.Data.Entities;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.ValueGeneration;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Hahn.ApplicatonProcess.December2020.Data
{
public class AppDbContext : DbContext
{
public AppDbContext(DbContextOptions<AppDbContext> options) : base(options)
{
}
public DbSet<Applicant> Applicants { get; set; }
protected override void OnModelCreating(ModelBuilder builder)
{
// builder.Entity<Applicant>().Property(x => x.DateCreated).ValueGeneratedOnAdd().HasValueGenerator(new ValueGenerator(;
// builder.Entity<Applicant>().Property(x => x.FamilyName).HasDefaultValue()
// builder.Entity<Applicant>().HasIndex(x => x.EmailAddress).IsUnique();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace pushpop
{
class Program
{
static void Main(string[] args)
{
Stack<float> fnumber = new Stack<float>();
fnumber.Push(10.15f);
fnumber.Push(11.15f);
fnumber.Push(15.15f);
fnumber.Push(105.15f);
Console.WriteLine("\nBefore calling the pop method\n");
foreach (var fn in fnumber)
Console.WriteLine(fn);
fnumber.Pop();
Console.WriteLine("\nAfter calling the pop method\n");
foreach (var fn in fnumber)
Console.WriteLine(fn);
Queue<double> qnumbers = new Queue<double>();
qnumbers.Enqueue(10.98);
qnumbers.Enqueue(15.98);
qnumbers.Enqueue(16.98);
qnumbers.Enqueue(105.98);
Console.WriteLine("\nBefore calling the Deque method\n");
foreach (var qn in qnumbers)
Console.WriteLine(qn);
qnumbers.Dequeue();
Console.WriteLine("\nAfter calling the Deque method\n");
foreach (var qn in qnumbers)
Console.WriteLine(qn);
Console.ReadKey();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ControlValveMaintenance.Services;
using System.ComponentModel;
using System.Data;
using System.Windows.Data;
using ControlValveMaintenance.Models;
using ControlValveMaintenance.Models.Lookups;
using GalaSoft.MvvmLight.Messaging;
using System.Windows.Input;
using ControlValveMaintenance.Commands;
using Microsoft.Practices.Prism.Commands;
namespace ControlValveMaintenance.ViewModels
{
class PickControlValveViewModel : BaseViewModel
{
#region variables
// CLASS VARIABLES
private SiteMaintenance siteMaint;
private SiteMaintenanceService dataService;
private ICollectionView valveList;
private ICommand selectCommand;
private bool canApprove;
private bool canReview;
#endregion
#region Properties
// PROPERTIES
public ICollectionView ValveList
{
get
{
return valveList;
}
set
{
valveList = value;
OnPropertyChanged("ValveList");
CompletePage.RaiseCanExecuteChanged();
}
}
public SiteMaintenance SiteMaint
{
get
{
return siteMaint;
}
set
{
siteMaint = value;
OnPropertyChanged("SiteMaint");
CompletePage.RaiseCanExecuteChanged();
}
}
public ICommand SelectCommand {
get
{
return selectCommand;
}
set
{
selectCommand = value;
}
}
public bool? IsAirVac
{
get
{
if (StatusCodes.Instance.getID(SiteMaint.AirVacChkStatus) > 1)
{
return null;
}
return StatusCodes.Instance.getID( SiteMaint.AirVacChkStatus ) == 1 ? true : false;
}
set
{
SiteMaint.AirVacChkStatus = setHelper(value);
RaisePropertyChanged("IsAirVac");
RaisePropertyChanged("SaveOrComplete");
CompletePage.RaiseCanExecuteChanged();
}
}
public bool? IsRelief
{
get
{
if (StatusCodes.Instance.getID(SiteMaint.RelChkStatus) > 1)
{
return null;
}
return StatusCodes.Instance.getID(SiteMaint.RelChkStatus) == 1 ? true : false;
}
set
{
siteMaint.RelChkStatus = setHelper(value);
OnPropertyChanged("IsRelief");
OnPropertyChanged("SaveOrComplete");
CompletePage.RaiseCanExecuteChanged();
}
}
public bool? IsPressureGaugeChk
{
get
{
if (StatusCodes.Instance.getID(SiteMaint.PressureGuageChkStatus) > 1)
{
return null;
}
return StatusCodes.Instance.getID(SiteMaint.PressureGuageChkStatus) == 1 ? true : false;
}
set
{
siteMaint.PressureGuageChkStatus = setHelper(value);
OnPropertyChanged("IsPressureGaugeChk");
OnPropertyChanged("SaveOrComplete");
CompletePage.RaiseCanExecuteChanged();
}
}
public bool? IsTransChk
{
get
{
if (StatusCodes.Instance.getID(SiteMaint.TransChkStatus) > 1)
{
return null;
}
return StatusCodes.Instance.getID(SiteMaint.TransChkStatus) == 1 ? true : false;
}
set
{
siteMaint.TransChkStatus = setHelper(value);
OnPropertyChanged("IsTransChk");
OnPropertyChanged("SaveOrComplete");
CompletePage.RaiseCanExecuteChanged();
}
}
public bool? IsAlarmsChk
{
get
{
if (StatusCodes.Instance.getID(SiteMaint.AlarmsChkStatus) > 1)
{
return null;
}
return StatusCodes.Instance.getID(SiteMaint.AlarmsChkStatus) == 1 ? true : false;
}
set
{
siteMaint.AlarmsChkStatus = setHelper(value);
OnPropertyChanged("IsAlarmsChk");
OnPropertyChanged("SaveOrComplete");
CompletePage.RaiseCanExecuteChanged();
}
}
public bool? IsVltChk
{
get
{
if (StatusCodes.Instance.getID(SiteMaint.VaultClnStatus) > 1)
{
return null;
}
return StatusCodes.Instance.getID(SiteMaint.VaultClnStatus) == 1 ? true : false;
}
set
{
siteMaint.VaultClnStatus = setHelper(value);
OnPropertyChanged("IsVltChk");
OnPropertyChanged("SaveOrComplete");
CompletePage.RaiseCanExecuteChanged();
}
}
public bool? IsLightChk
{
get
{
if (StatusCodes.Instance.getID(SiteMaint.LightHeatChkStatus) > 1)
{
return null;
}
return StatusCodes.Instance.getID(SiteMaint.LightHeatChkStatus) == 1 ? true : false;
}
set
{
siteMaint.LightHeatChkStatus = setHelper(value);
OnPropertyChanged("IsLightChk");
OnPropertyChanged("SaveOrComplete");
CompletePage.RaiseCanExecuteChanged();
}
}
public bool? IsSumpChk
{
get
{
if (StatusCodes.Instance.getID(SiteMaint.SumpChkStatus) > 1)
{
return null;
}
return StatusCodes.Instance.getID(SiteMaint.SumpChkStatus) == 1 ? true : false;
}
set
{
siteMaint.SumpChkStatus = setHelper(value);
OnPropertyChanged("IsSumpChk");
OnPropertyChanged("SaveOrComplete");
CompletePage.RaiseCanExecuteChanged();
}
}
public bool? IsAccessHatchStatus
{
get
{
if (StatusCodes.Instance.getID(SiteMaint.AccessHatchStatus) > 1)
{
return null;
}
return StatusCodes.Instance.getID(SiteMaint.AccessHatchStatus) == 1 ? true : false;
}
set
{
siteMaint.AccessHatchStatus = setHelper(value);
OnPropertyChanged("IsAccessHatchStatus");
OnPropertyChanged("SaveOrComplete");
CompletePage.RaiseCanExecuteChanged();
}
}
public bool? IsLadderStatus
{
get
{
if (StatusCodes.Instance.getID(SiteMaint.LadderStatus) > 1)
{
return null;
}
return StatusCodes.Instance.getID(SiteMaint.LadderStatus) == 1 ? true : false;
}
set
{
siteMaint.LadderStatus = setHelper(value);
OnPropertyChanged("IsLadderStatus");
OnPropertyChanged("SaveOrComplete");
CompletePage.RaiseCanExecuteChanged();
}
}
public DateTime? CompletedDate
{
get
{
return SiteMaint.CompletedDate;
}
set
{
siteMaint.CompletedDate = value;
OnPropertyChanged("CompletedDate");
OnPropertyChanged("SaveOrComplete");
CompletePage.RaiseCanExecuteChanged();
}
}
public string CompletedBy
{
get
{
return SiteMaint.CompletedBy;
}
set
{
siteMaint.CompletedBy = value;
OnPropertyChanged("CompletedBy");
OnPropertyChanged("SaveOrComplete");
CompletePage.RaiseCanExecuteChanged();
}
}
public int SiteID
{
get
{
return siteMaint.SiteID;
}
set
{
}
}
public String FieldComments
{
get
{
return siteMaint.FieldComments;
}
set
{
siteMaint.FieldComments = value;
OnPropertyChanged("FieldComments");
CompletePage.RaiseCanExecuteChanged();
}
}
public String ApprovedBy
{
get
{
return siteMaint.ApprovedBy;
}
set
{
siteMaint.ApprovedBy = value;
OnPropertyChanged("ApprovedBy");
ApprovePage.RaiseCanExecuteChanged();
}
}
public DateTime? ApprovalDate
{
get
{
return SiteMaint.ApprovalDate;
}
set
{
siteMaint.ApprovalDate = value;
OnPropertyChanged("ApprovalDate");
ApprovePage.RaiseCanExecuteChanged();
}
}
public String ReviewedBy
{
get
{
return siteMaint.ReviewedBy;
}
set
{
siteMaint.ReviewedBy = value;
OnPropertyChanged("ReviewedBy");
ApprovePage.RaiseCanExecuteChanged();
}
}
public DateTime? ReviewedDate
{
get
{
return SiteMaint.ReviewedDate;
}
set
{
siteMaint.ReviewedDate = value;
OnPropertyChanged("ReviewedDate");
ApprovePage.RaiseCanExecuteChanged();
}
}
public String CanApprove
{
get
{
if (canApprove) return "Visible";
return "Hidden";
}
set
{
}
}
public String CanReview
{
get
{
if (canReview) return "Visible";
return "Hidden";
}
set
{
}
}
public DelegateCommand CompletePage
{
get;
private set;
}
public DelegateCommand CancelPage
{
get;
private set;
}
public DelegateCommand ApprovePage
{
get;
private set;
}
public DelegateCommand ReviewPage
{
get;
private set;
}
public string SaveOrComplete
{
get
{
if (canComplete()) return "Complete";
return "Save";
}
set
{
}
}
#endregion
/// <summary>
/// DEFAULT CONSTRUCTOR
/// </summary>
public PickControlValveViewModel()
{
// set private variables
canApprove = false;
canReview = false;
PageName = "Pick Control Valve";
// use data service to populate model
dataService = new SiteMaintenanceService();
// check to see if user can approve sites
checkUser();
this.SelectCommand = new RelayCommand(new Action<object>(setValveMaintenance));
CompletePage = new DelegateCommand(Execute, CanExecute);
CancelPage = new DelegateCommand(CancelExecute, CancelCanExecute);
}
/// <summary>
/// Update the model with the current SiteMaintID selected
/// </summary>
public override void syncModel()
{
updateModel(SiteMaintID);
}
/// <summary>
/// Find the SiteMaintenance and set the valveList
/// </summary>
/// <param name="id">
///
/// </param>
public override void updateModel(int id)
{
findSiteRecord(id);
setValveMaintList(id);
}
/// <summary>
/// Call data service to get site maintenance
/// </summary>
/// <param name="id">
/// The Site Maintenance Record ID
/// </param>
private void findSiteRecord(int id)
{
SiteMaint = dataService.getSiteMaintenance(id);
}
/// <summary>
/// Send a message to switch the data context to specified record
/// </summary>
/// <param name="obj">
/// the record to do valve maintenance
/// </param>
public void setValveMaintenance(object obj)
{
var page = new PageMessage() { Name = "Control Valve", data = obj, options = SiteMaint.MaintType };
Messenger.Default.Send<PageMessage>(page);
}
/// <summary>
/// If control valve view model completed date is wipe, wipe completed date in site maintenance
/// </summary>
public override void wipeCompleted()
{
siteMaint.CompletedDate= null;
siteMaint.CompletedBy = "";
siteMaint.ReviewedBy = "";
siteMaint.ReviewedDate = null;
siteMaint.ApprovedBy = "";
siteMaint.ApprovalDate = null;
dataService.approveSiteMaintenance(SiteMaint);
}
/// <summary>
/// If Completed Date is Empty, set it to current date
/// If User is empty, set it to the current user logged in
/// </summary>
public override void insertUser()
{
if (siteMaint.CompletedDate == null) siteMaint.CompletedDate = DateTime.Now;
if (String.IsNullOrEmpty(siteMaint.CompletedBy)) siteMaint.CompletedBy = Environment.UserName.ToString();
if (canReview)
{
if (siteMaint.ReviewedDate == null) siteMaint.ReviewedDate = DateTime.Now;
if (String.IsNullOrEmpty(siteMaint.ReviewedBy)) siteMaint.ReviewedBy = Environment.UserName.ToString();
}
if (canApprove)
{
if (siteMaint.ApprovalDate == null) siteMaint.ApprovalDate = DateTime.Now;
if (String.IsNullOrEmpty(siteMaint.ApprovedBy)) siteMaint.ApprovedBy = Environment.UserName.ToString();
}
}
/// <summary>
/// Allows completion of the form if, unless only save
/// </summary>
/// <returns>
/// true if required fields are completed
/// </returns>
private bool canComplete()
{
if (CompletedBy == null ||
CompletedBy == "" ||
CompletedDate == DateTime.MinValue ||
CompletedDate == null ||
IsAirVac == false ||
IsRelief == false ||
IsPressureGaugeChk == false ||
IsTransChk == false ||
IsAccessHatchStatus == false ||
IsLadderStatus == false ||
IsAlarmsChk == false ||
IsVltChk == false ||
IsLightChk == false ||
IsSumpChk == false
)
{
return false;
}
return isValveListComplete();
}
#region Delegate Commands
/// <summary>
/// If valve maintenances are not complete, return false
/// </summary>
/// <returns>
/// False if Valve maintenances are not completed
/// </returns>
private bool isValveListComplete()
{
foreach (ValveMaintenance vm in ValveList)
{
if (vm.CompletedDate == null)
{
return false;
}
}
return true;
}
/// <summary>
/// Complete the site maintenance form, or save if incomplete form
/// </summary>
public void Execute()
{
if (canApprove || canReview)
{
dataService.approveSiteMaintenance(SiteMaint);
}
else
{
if (canComplete())
{
dataService.updateSiteMaintenance(SiteMaint);
}
else
{
CompletedBy = null;
CompletedDate = null;
dataService.updateSiteMaintenance(SiteMaint);
}
}
var page = new PageMessage() { Name = "Back to Pick Site Valve" };
Messenger.Default.Send<PageMessage>(page);
}
/// <summary>
/// Always allow save or complete
/// </summary>
/// <returns>
/// true
/// </returns>
public bool CanExecute()
{
return true;
}
/// <summary>
/// Don't save any changes on page and revert back to Site pick list
/// </summary>
public void CancelExecute()
{
var page = new PageMessage() { Name = "Cancel Site Maintenance"};
Messenger.Default.Send<PageMessage>(page);
}
/// <summary>
/// Always allow backtrack by canceling page changes
/// </summary>
/// <returns>
/// true
/// </returns>
public bool CancelCanExecute()
{
return true;
}
#endregion
/// <summary>
/// Set the Valve List
/// </summary>
/// <param name="id">
/// the target list to set valvelist to
/// </param>
private void setValveMaintList(int id)
{
ValveList = new ListCollectionView(dataService.getValveMaintenances(id));
}
/// <summary>
/// Set the checkbox to the appropriate value
/// </summary>
/// <param name="val">
/// the boolean of the checkbox
/// </param>
/// <returns>
/// a string representation of the value
/// </returns>
private string setHelper( bool? val)
{
if (val == null)
{
return "255";
}
else if (val == true)
{
return "1";
}
return "0";
}
/// <summary>
/// Grab the credentials of the current user and set user to class variable
/// </summary>
private void checkUser()
{
User currentUser = new User() { Name = Environment.UserName.ToString() };
Users userList = dataService.getUsers();
foreach (var user in userList)
{
if (user.Name.ToLower() == (currentUser.Name).ToLower())
{
if (user.Task == "Approve SiteMaintenances") canApprove = true;
if (user.Task == "Review SiteMaintenances") canReview = true;
}
}
}
}
}
|
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using LogiCon.Areas.Master.Controllers;
using Master.Contract;
namespace LogiCon.Tests.Areas.Master
{
[TestClass]
public class BranchControllerTest
{
[TestMethod]
public void Save()
{
var branchController = new BranchController();
}
private Branch GetMockedBranch()
{
var branch = new Branch();
branch.BranchID = UTILITY.BRANCHID;
return branch;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
namespace TableOptimization
{
public struct Point
{
public double XCoordinate { get; set; }
public double YCoordinate { get; set; }
}
}
|
using System;
namespace JakContinueMapper
{
public static class GameMemory
{
public const int GOAL_MAX_SYMBOLS = 0x2000;
public const int BASIC_OFFSET = 4;
public const int SymbolTableOffset = (GOAL_MAX_SYMBOLS / 2) * 8 + 0;
public const int UsableSymbolCount = 8161;
}
[AttributeUsage(AttributeTargets.Class, AllowMultiple = true, Inherited = false)]
public class GameMemoryAttribute : Attribute
{
public string Name { get; private set; }
public GameRegion Region { get; private set; }
public int TargetPos { get; private set; }
public int SymbolTable { get; private set; }
public GameMemoryAttribute(string name, GameRegion region, int targetpos = 0, int s7 = 0)
{
Name = name;
Region = region;
TargetPos = targetpos;
SymbolTable = s7 - GameMemory.SymbolTableOffset;
}
}
}
|
#region Related components
using System;
using System.Linq;
using System.Dynamic;
using System.Diagnostics;
using System.Numerics;
using System.Threading;
using System.Threading.Tasks;
using System.Collections.Generic;
using System.Collections.Concurrent;
using System.Security.Cryptography;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using net.vieapps.Components.Security;
using net.vieapps.Components.Repository;
using net.vieapps.Components.Caching;
using net.vieapps.Components.Utility;
#endregion
namespace net.vieapps.Services.Users
{
public class ServiceComponent : ServiceBase
{
#region Properties
ConcurrentDictionary<string, Tuple<DateTime, string>> Sessions { get; } = new ConcurrentDictionary<string, Tuple<DateTime, string>>();
string ActivationKey => this.GetKey("Activation", "VIEApps-56BA2999-NGX-A2E4-Services-4B54-Activation-83EB-Key-693C250DC95D");
string AuthenticationKey => this.GetKey("Authentication", "VIEApps-65E47754-NGX-50C0-Services-4565-Authentication-BA55-Key-A8CC23879C5D");
BigInteger ECCKey => this.GetKey("ECC", "tRZMCCemDIshR6SBnltv/kZvamQfMuMyx+2DG+2Yuw+13xN4A7Kk+nmEM81kx6ISlaxGgJjr/xK9kWznIC3OWlF2yrdMKeeCPM8eVFIfkiGqIPnGPDJaWRbtGswNjMmfQhbQvQ9qa5306RLt9F94vrOQp2M9eojE3cSuTqNg4OTL+9Dddabgzl94F3gOJoPRxzHqyKWRUhQdP+hOsWSS2KTska2ddm/Zh/fGKXwY9lnnrLHY1wjSJqCS3OO7PCRfQtEWSJcvzzgm7bvJ18fOLuJ5CZVThS+XLNwZgkbcICepRCiVbsk6fmh0482BJesG55pVeyv7ZyKNW+RyMXNEyLn5VY/1lPLxz7lLS88Lvqo=").Base64ToBytes().Decrypt().ToUnsignedBigInteger();
string RSAKey => this.GetKey("RSA", "NihT0EJ2NLRhmGNbZ8A3jUdhZfO4jG4hfkwaHF1o00YoVx9S61TpmMiaZssOZB++UUyNsZZzxSfkh0i5O9Yr9us+/2zXhgR2zQVxOUrZnPpHpspyJzOegBpMMuTWF4WTl7st797BQ0AmUY1nEjfMTKVP+VSrrx0opTgi93MyvRGGa48vd7PosAM8uq+oMkhMZ/jTvasK6n3PKtb9XAm3hh4NFZBf7P2WuACXZ4Vbzd1MGtLHWfrYnWjGI9uhlo2QKueRLmHoqKM5pQFlB9M7/i2D/TXeWZSWNU+vW93xncUght3QtCwRJu7Kp8UGf8nnrFOshHgvMgsdDlvJt9ECN0/2uyUcWzB8cte5C9r6sP6ClUVSkKDvEOJVmuS2Isk72hbooPaAm7lS5NOzb2pHrxTKAZxaUyiZkFXH5rZxQ/5QjQ9PiAzm1AVdBE1tg1BzyGzY2z7RY/iQ5o22hhRSN3l49U4ftfXuL+LrGKnzxtVrQ15Vj9/pF7mz3lFy2ttTxJPccBiffi9LVtuUCo9BRgw7syn07gAqj1WXzuhPALwK6P6M1pPeFg6NEKLNWgRFE8GZ+dPhr2O0YCgDVuhJ+hDUxCDAEkZ0cQBiliHtjldJji1FnFMqg90QvFCuVCydq94Dnxdl9HSVMNC69i6H2GNfBuD9kTQ6gIOepc86YazDto8JljqEVOpkegusPENadLjpwOYCCslN1Y314B2g9vvZRwU3T+PcziBjym1ceagEEAObZ22Z/vhxBZ83Z2E1/RkbJqovIRKuHLCzU/4lBeTseJNlKPSACPuKAX08P4y5c+28WDrHv2+o7x9ISJe0SN1KmFMvv1xYtj/1NwOHQzfVjbpL46E0+Jr/IOOjh2CQhhUMm1GOEQAZ9n+b7a4diUPDG+BewAZvtd5gNX4zD0IKkJFwN+fBMWSHs0gs3jNz4RcYhH5IoHq27jrfM3cUlvBP9JpbZugNIh8ddZsUd4XQuCVZF+qlfRjY6lfEy4nXX48ianvdCqnBpkmRadG8qFLybkVS+s8RHcPwRkkzKQ4oGHdDeyiU8ZXnwvJ3IxDLoJV0xqKSRjhe9MxwdeN7VMSTNRAtQvqVvm6cL8KNbd2Hx1kPDEcqeUfVIeZ+zTIptO5GpjEMV+4gu338WG1RyEMAaiE536E+UR+0MqIe/Q==").Decrypt();
RSA _rsa = null;
RSA RSA
{
get
{
if (this._rsa == null)
{
this._rsa = CryptoService.CreateRSA(this.RSAKey);
if (this._rsa.KeySize != 2048)
{
this._rsa = RSA.Create();
this._rsa.KeySize = 2048;
}
}
return this._rsa;
}
}
#endregion
public override string ServiceName => "Users";
public override void Start(string[] args = null, bool initializeRepository = true, Func<IService, Task> nextAsync = null)
{
// initialize static properties
Utility.Cache = new Cache($"VIEApps-Services-{this.ServiceName}", Components.Utility.Logger.GetLoggerFactory());
Utility.ActivateHttpURI = this.GetHttpURI("Portals", "https://portals.vieapps.net");
while (Utility.ActivateHttpURI.EndsWith("/"))
Utility.ActivateHttpURI = Utility.ActivateHttpURI.Left(Utility.FilesHttpURI.Length - 1);
Utility.ActivateHttpURI += "home?prego=activate&mode={mode}&code={code}";
Utility.FilesHttpURI = this.GetHttpURI("Files", "https://fs.vieapps.net");
while (Utility.FilesHttpURI.EndsWith("/"))
Utility.FilesHttpURI = Utility.FilesHttpURI.Left(Utility.FilesHttpURI.Length - 1);
// start the service
base.Start(args, initializeRepository, async service =>
{
// register timers
this.RegisterTimers(args);
// last action
if (nextAsync != null)
try
{
await nextAsync(service).ConfigureAwait(false);
}
catch (Exception ex)
{
this.Logger.LogError("Error occurred while invoking the next action", ex);
}
});
}
public override async Task<JToken> ProcessRequestAsync(RequestInfo requestInfo, CancellationToken cancellationToken = default(CancellationToken))
{
var stopwatch = Stopwatch.StartNew();
this.WriteLogs(requestInfo, $"Begin request ({requestInfo.Verb} {requestInfo.GetURI()})");
using (var cts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, this.CancellationTokenSource.Token))
try
{
JToken json = null;
switch (requestInfo.ObjectName.ToLower())
{
case "session":
json = await this.ProcessSessionAsync(requestInfo, cts.Token).ConfigureAwait(false);
break;
case "otp":
json = await this.ProcessOTPAsync(requestInfo, cts.Token).ConfigureAwait(false);
break;
case "account":
json = await this.ProcessAccountAsync(requestInfo, cts.Token).ConfigureAwait(false);
break;
case "profile":
json = await this.ProcessProfileAsync(requestInfo, cts.Token).ConfigureAwait(false);
break;
case "activate":
json = await this.ProcessActivationAsync(requestInfo, cts.Token).ConfigureAwait(false);
break;
case "privileges":
json = requestInfo.Verb.IsEquals("GET")
? await this.GetPrivilegesAsync(requestInfo, cts.Token).ConfigureAwait(false)
: requestInfo.Verb.IsEquals("POST") || requestInfo.Verb.IsEquals("PUT")
? await this.SetPrivilegesAsync(requestInfo, cts.Token).ConfigureAwait(false)
: throw new MethodNotAllowedException(requestInfo.Verb);
break;
case "captcha":
if (!requestInfo.Verb.IsEquals("GET"))
throw new MethodNotAllowedException(requestInfo.Verb);
var captcha = CaptchaService.GenerateCode();
json = new JObject
{
{ "Code", captcha },
{ "Uri", $"{Utility.CaptchaURI}{captcha.Url64Encode()}/{(requestInfo.GetQueryParameter("register") ?? UtilityService.NewUUID.Encrypt(this.EncryptionKey, true)).Substring(UtilityService.GetRandomNumber(13, 43), 13).Reverse()}.jpg" }
};
break;
default:
throw new InvalidRequestException($"The request is invalid ({requestInfo.Verb} {requestInfo.GetURI()})");
}
stopwatch.Stop();
this.WriteLogs(requestInfo, $"Success response - Execution times: {stopwatch.GetElapsedTimes()}");
if (this.IsDebugResultsEnabled)
this.WriteLogs(requestInfo,
$"- Request: {requestInfo.ToJson().ToString(this.IsDebugLogEnabled ? Formatting.Indented : Formatting.None)}" + "\r\n" +
$"- Response: {json?.ToString(this.IsDebugLogEnabled ? Formatting.Indented : Formatting.None)}"
);
return json;
}
catch (Exception ex)
{
throw this.GetRuntimeException(requestInfo, ex, stopwatch);
}
}
#region Get instructions
async Task<Tuple<string, string, string, string, Tuple<string, int, bool, string, string>>> GetInstructionsOfRelatedServiceAsync(RequestInfo requestInfo, string mode = "reset", CancellationToken cancellationToken = default(CancellationToken))
{
var data = (await this.CallServiceAsync(new RequestInfo(requestInfo.Session, requestInfo.Query["related-service"], "Instruction", "GET")
{
Query = new Dictionary<string, string>(requestInfo.Query ?? new Dictionary<string, string>(), StringComparer.OrdinalIgnoreCase)
{
["object-identity"] = "account"
},
Header = requestInfo.Header,
Extra = new Dictionary<string, string>(requestInfo.Extra ?? new Dictionary<string, string>(), StringComparer.OrdinalIgnoreCase)
{
["mode"] = mode
},
CorrelationID = requestInfo.CorrelationID
}, cancellationToken).ConfigureAwait(false)).ToExpandoObject();
var subject = data.Get<string>("Subject");
var body = data.Get<string>("Body");
var signature = data.Get<string>("Signature");
var sender = data.Get<string>("Sender");
var smtpServer = data.Get<string>("SmtpServer");
var smtpServerPort = data.Get("SmtpServerPort", 25);
var smtpServerEnableSsl = data.Get<bool>("SmtpServerEnableSsl");
var smtpUser = data.Get<string>("SmtpUser");
var smtpUserPassword = data.Get<string>("SmtpUserPassword");
return new Tuple<string, string, string, string, Tuple<string, int, bool, string, string>>(subject, body, signature, sender, new Tuple<string, int, bool, string, string>(smtpServer, smtpServerPort, smtpServerEnableSsl, smtpUser, smtpUserPassword));
}
async Task<Tuple<string, string, string, string, Tuple<string, int, bool, string, string>>> GetActivateInstructionsAsync(RequestInfo requestInfo, string mode = "reset", CancellationToken cancellationToken = default(CancellationToken))
{
string subject = "", body = "", signature = "", sender = "";
string smtpServer = "", smtpUser = "", smtpUserPassword = "";
var smtpServerPort = 25;
var smtpServerEnableSsl = false;
if (requestInfo.Query.ContainsKey("related-service"))
try
{
var data = await this.GetInstructionsOfRelatedServiceAsync(requestInfo, mode, cancellationToken).ConfigureAwait(false);
subject = data.Item1;
body = data.Item2;
signature = data.Item3;
sender = data.Item4;
smtpServer = data.Item5.Item1;
smtpServerPort = data.Item5.Item2;
smtpServerEnableSsl = data.Item5.Item3;
smtpUser = data.Item5.Item4;
smtpUserPassword = data.Item5.Item5;
}
catch { }
if (string.IsNullOrWhiteSpace(subject))
switch (mode)
{
case "account":
subject = "[{Host}] Kích hoạt tài khoản đăng nhập";
break;
case "invite":
subject = "[{Host}] Lời mời tham gia hệ thống";
break;
case "reset":
subject = "[{Host}] Kích hoạt mật khẩu đăng nhập mới";
break;
}
if (string.IsNullOrWhiteSpace(body))
switch (mode)
{
case "account":
body = @"
Xin chào <b>{Name}</b>
<br/><br/>
Chào mừng bạn đã tham gia vào hệ thống cùng chúng tôi.
<br/><br/>
Tài khoản thành viên của bạn đã được khởi tạo với các thông tin sau:
<blockquote>
Email đăng nhập: <b>{Email}</b>
<br/>
Mật khẩu đăng nhập: <b>{Password}</b>
</blockquote>
<br/>
Để hoàn tất quá trình đăng ký, bạn vui lòng kích hoạt tài khoản đã đăng ký bằng cách mở liên kết dưới:
<br/><br/>
<span style='display:inline-block;padding:15px;border-radius:5px;background-color:#eee;font-weight:bold'>
<a href='{Uri}' style='color:red'>Kích hoạt tài khoản</a>
</span>
<br/><br/>
<br/>
<i>Thông tin thêm:</i>
<ul>
<li>
Hoạt động này được thực hiện lúc <b>{Time}</b> tại <b>{Location}</b>
</li>
<li>
Mã kích hoạt chỉ có giá trị trong vòng 01 tháng kể từ thời điểm nhận được email này.
<br/>
Sau thời gian đó, để gia nhập hệ thống bạn cần thực hiện lại hoạt động đăng ký thành viên.
</li>
<li>
Nếu không phải bạn thực hiện hoạt động này, bạn cũng không phải bận tâm
vì hệ thống sẽ tự động loại bỏ các thông tin không sử dụng sau thời gian đăng ký 01 tháng.
</li>
</ul>
<br/><br/>
{Signature}".Replace("\t", "");
break;
case "invite":
body = @"
Xin chào <b>{Name}</b>
<br/><br/>
Chào mừng bạn đến với hệ thống qua lời mời của <b>{Inviter}</b> ({InviterEmail}).
<br/><br/>
Tài khoản thành viên của bạn sẽ được khởi tạo với các thông tin sau:
<blockquote>
Email đăng nhập: <b>{Email}</b>
<br/>
Mật khẩu đăng nhập: <b>{Password}</b>
</blockquote>
<br/>
Để hoàn tất quá trình và trở thành thành viên của hệ thống, bạn vui lòng khởi tạo & kích hoạt tài khoản bằng cách mở liên kết dưới:
<br/><br/>
<span style='display:inline-block;padding:15px;border-radius:5px;background-color:#eee;font-weight:bold'>
<a href='{Uri}' style='color:red'>Khởi tạo & Kích hoạt tài khoản</a>
</span>
<br/><br/>
<br/>
<i>Thông tin thêm:</i>
<ul>
<li>
Hoạt động này được thực hiện lúc <b>{Time}</b> với thiết bị <b>{AppPlatform}</b> tại <b>{Location}</b>
</li>
<li>
Mã khởi tạo & kích hoạt chỉ có giá trị trong vòng 01 tháng kể từ thời điểm nhận được email này.
<br/>
Sau thời gian đó, để gia nhập hệ thống bạn cần thực hiện hoạt động đăng ký thành viên.
</li>
<li>
Nếu bạn không muốn tham gia vào hệ thống, bạn cũng không phải bận tâm vì hệ thống sẽ chỉ khởi tạo tài khoản khi bạn thực hiện hoạt động này.
</li>
</ul>
<br/><br/>
{Signature}".Replace("\t", "");
break;
case "reset":
body = @"
Xin chào <b>{Name}</b>
<br/><br/>
Tài khoản đăng nhập của bạn đã được yêu cầu đặt lại thông tin đăng nhập như sau:
<blockquote>
Email đăng nhập: <b>{Email}</b>
<br/>
Mật khẩu đăng nhập (mới): <b>{Password}</b>
</blockquote>
<br/>
Để hoàn tất quá trình thay đổi mật khẩu mới, bạn vui lòng kích hoạt bằng cách mở liên kết dưới:
<br/><br/>
<span style='display:inline-block;padding:15px;border-radius:5px;background-color:#eee;font-weight:bold'>
<a href='{Uri}' style='color:red'>Kích hoạt mật khẩu đăng nhập mới</a>
</span>
<br/><br/>
<br/>
<i>Thông tin thêm:</i>
<ul>
<li>
Hoạt động này được thực hiện lúc <b>{Time}</b> với thiết bị <b>{AppPlatform}</b> tại <b>{Location}</b>
</li>
<li>
Mã kích hoạt chỉ có giá trị trong vòng 01 ngày kể từ thời điểm nhận được email này.
</li>
<li>
Nếu không phải bạn thực hiện hoạt động này, bạn nên kiểm tra lại thông tin đăng nhập cũng như email liên quan
vì có thể một điểm nào đó trong hệ thống thông tin bị rò rỉ (và có thể gây hại cho bạn).
<br/>
Khi bạn chưa kích hoạt thì mật khẩu đăng nhập mới là chưa có tác dụng.
</li>
</ul>
<br/><br/>
{Signature}".Replace("\t", "");
break;
}
return new Tuple<string, string, string, string, Tuple<string, int, bool, string, string>>(subject, body, signature, sender, new Tuple<string, int, bool, string, string>(smtpServer, smtpServerPort, smtpServerEnableSsl, smtpUser, smtpUserPassword));
}
async Task<Tuple<string, string, string, string, Tuple<string, int, bool, string, string>>> GetUpdateInstructionsAsync(RequestInfo requestInfo, string mode = "password", CancellationToken cancellationToken = default(CancellationToken))
{
string subject = "", body = "", signature = "", sender = "";
string smtpServer = "", smtpUser = "", smtpUserPassword = "";
var smtpServerPort = 25;
var smtpServerEnableSsl = false;
if (requestInfo.Query.ContainsKey("related-service"))
try
{
var data = await this.GetInstructionsOfRelatedServiceAsync(requestInfo, mode, cancellationToken).ConfigureAwait(false);
subject = data.Item1;
body = data.Item2;
signature = data.Item3;
sender = data.Item4;
smtpServer = data.Item5.Item1;
smtpServerPort = data.Item5.Item2;
smtpServerEnableSsl = data.Item5.Item3;
smtpUser = data.Item5.Item4;
smtpUserPassword = data.Item5.Item5;
}
catch { }
if (string.IsNullOrWhiteSpace(subject))
switch (mode)
{
case "password":
subject = "[{Host}] Thông báo thông tin đăng nhập tài khoản thay đổi (mật khẩu)";
break;
case "email":
subject = "[{Host}] Thông báo thông tin đăng nhập tài khoản thay đổi (email)";
break;
}
if (string.IsNullOrWhiteSpace(body))
switch (mode)
{
case "password":
body = @"
Xin chào <b>{Name}</b>
<br/><br/>
Tài khoản đăng nhập của bạn đã được cật nhật thông tin đăng nhập như sau:
<blockquote>
Email đăng nhập: <b>{Email}</b>
<br/>
Mật khẩu đăng nhập (mới): <b>{Password}</b>
</blockquote>
<br/>
<i>Thông tin thêm:</i>
<ul>
<li>
Hoạt động này được thực hiện lúc <b>{Time}</b> với thiết bị <b>{AppPlatform}</b> tại <b>{Location}</b>
</li>
<li>
Nếu không phải bạn thực hiện hoạt động này, bạn nên kiểm tra lại thông tin đăng nhập cũng như email liên quan
vì có thể một điểm nào đó trong hệ thống thông tin bị rò rỉ (và có thể gây hại cho bạn).
</li>
</ul>
<br/><br/>
{Signature}".Replace("\t", "");
break;
case "email":
body = @"
Xin chào <b>{Name}</b>
<br/><br/>
Tài khoản đăng nhập của bạn đã được cật nhật thông tin đăng nhập như sau:
<blockquote>
Email đăng nhập (mới): <b>{Email}</b>
<br/>
Email đăng nhập (cũ): <b>{OldEmail}</b>
</blockquote>
<br/>
<i>Thông tin thêm:</i>
<ul>
<li>
Hoạt động này được thực hiện lúc <b>{Time}</b> với thiết bị <b>{AppPlatform}</b> tại <b>{Location}</b>
</li>
<li>
Nếu không phải bạn thực hiện hoạt động này, bạn nên kiểm tra lại thông tin đăng nhập cũng như email liên quan
vì có thể một điểm nào đó trong hệ thống thông tin bị rò rỉ (và có thể gây hại cho bạn).
</li>
</ul>
<br/><br/>
{Signature}".Replace("\t", "");
break;
}
return new Tuple<string, string, string, string, Tuple<string, int, bool, string, string>>(subject, body, signature, sender, new Tuple<string, int, bool, string, string>(smtpServer, smtpServerPort, smtpServerEnableSsl, smtpUser, smtpUserPassword));
}
#endregion
#region Call related services
IService GetRelatedService(RequestInfo requestInfo)
{
try
{
return Router.GetService(requestInfo?.GetQueryParameter("related-service"));
}
catch
{
return null;
}
}
async Task<JToken> CallRelatedServiceAsync(RequestInfo requestInfo, User user, string objectName, string verb = "GET", string objectIdentity = null, Dictionary<string, string> extra = null, CancellationToken cancellationToken = default(CancellationToken))
{
var correlationID = requestInfo.CorrelationID ?? UtilityService.NewUUID;
try
{
var request = new RequestInfo(
new Services.Session(requestInfo.Session)
{
User = user ?? requestInfo.Session.User ?? User.GetDefault(requestInfo.Session.SessionID)
},
requestInfo.GetQueryParameter("related-service") ?? "",
objectName ?? "",
verb ?? "GET",
new Dictionary<string, string>(requestInfo.Query ?? new Dictionary<string, string>(), StringComparer.OrdinalIgnoreCase),
new Dictionary<string, string>(requestInfo.Header ?? new Dictionary<string, string>(), StringComparer.OrdinalIgnoreCase),
requestInfo.Body ?? "",
new Dictionary<string, string>(requestInfo.Extra ?? new Dictionary<string, string>(), StringComparer.OrdinalIgnoreCase),
correlationID
);
if (!string.IsNullOrWhiteSpace(objectIdentity))
request.Query["object-identity"] = objectIdentity;
extra?.ForEach(kvp => request.Extra[kvp.Key] = kvp.Value);
return await this.CallServiceAsync(request, cancellationToken).ConfigureAwait(false);
}
catch (Exception ex)
{
if (this.IsDebugLogEnabled)
await this.WriteLogsAsync(correlationID, $"Error occurred while calling the related service => {ex.Message}", ex).ConfigureAwait(false);
return new JObject();
}
}
#endregion
protected override Privileges Privileges => new Privileges();
Task<JToken> ProcessSessionAsync(RequestInfo requestInfo, CancellationToken cancellationToken)
{
switch (requestInfo.Verb)
{
// check exists
case "EXIST":
return this.CheckSessionExistsAsync(requestInfo, cancellationToken);
// get a session
case "GET":
return this.GetSessionAsync(requestInfo, cancellationToken);
// register a session
case "POST":
return this.RegisterSessionAsync(requestInfo, cancellationToken);
// log a session in
case "PUT":
return this.LogSessionInAsync(requestInfo, cancellationToken);
// log a session out
case "DELETE":
return this.LogSessionOutAsync(requestInfo, cancellationToken);
// unknown
default:
return Task.FromException<JToken>(new MethodNotAllowedException(requestInfo.Verb));
}
}
#region Check exists of a session
async Task<JToken> CheckSessionExistsAsync(RequestInfo requestInfo, CancellationToken cancellationToken)
{
if (string.IsNullOrWhiteSpace(requestInfo.Session?.SessionID))
return new JObject
{
{ "ID", requestInfo.Session?.SessionID },
{ "Existed", false }
};
else if (this.Sessions.ContainsKey(requestInfo.Session.SessionID))
return new JObject
{
{ "ID", requestInfo.Session.SessionID },
{ "Existed", true }
};
var session = await Utility.Cache.GetAsync<Session>($"Session#{requestInfo.Session.SessionID}", cancellationToken).ConfigureAwait(false);
if (session == null && !requestInfo.Session.User.ID.Equals("") && !requestInfo.Session.User.IsSystemAccount)
session = await Session.GetAsync<Session>(requestInfo.Session.SessionID, cancellationToken).ConfigureAwait(false);
return new JObject
{
{ "ID", requestInfo.Session.SessionID },
{ "Existed", session != null }
};
}
#endregion
#region Get a session
async Task<JToken> GetSessionAsync(RequestInfo requestInfo, CancellationToken cancellationToken)
{
// verify
if (requestInfo.Extra == null || !requestInfo.Extra.ContainsKey("Signature") || !requestInfo.Extra["Signature"].Equals(requestInfo.Header["x-app-token"].GetHMACSHA256(this.ValidationKey)))
throw new InformationInvalidException("The signature is not found or invalid");
// get information
var session = requestInfo.Session.User.ID.Equals("") || requestInfo.Session.User.IsSystemAccount
? await Utility.Cache.FetchAsync<Session>(requestInfo.Session.SessionID).ConfigureAwait(false)
: await Session.GetAsync<Session>(requestInfo.Session.SessionID, cancellationToken).ConfigureAwait(false);
return session?.ToJson();
}
#endregion
#region Register a session
async Task<JToken> RegisterSessionAsync(RequestInfo requestInfo, CancellationToken cancellationToken)
{
// prepare
if (string.IsNullOrWhiteSpace(requestInfo.Session.SessionID))
throw new InvalidRequestException();
// verify
if (requestInfo.Extra == null || !requestInfo.Extra.ContainsKey("Signature") || !requestInfo.Extra["Signature"].Equals(requestInfo.Body.GetHMACSHA256(this.ValidationKey)))
throw new InformationInvalidException("The signature is not found or invalid");
var request = requestInfo.GetBodyExpando();
if (request == null)
throw new InformationRequiredException();
// register a session of vistor/system account
if (requestInfo.Session.User.ID.Equals("") || requestInfo.Session.User.IsSystemAccount)
{
// update cache of session
var session = request.Copy<Session>();
await Utility.Cache.SetAsync(session, cancellationToken).ConfigureAwait(false);
// response
return session.ToJson();
}
// register a session of authenticated account
else
{
var session = await Session.GetAsync<Session>(requestInfo.Session.SessionID, cancellationToken, false).ConfigureAwait(false);
if (session == null)
{
session = request.Copy<Session>();
await Session.CreateAsync(session, cancellationToken).ConfigureAwait(false);
}
else
{
if (!requestInfo.Session.SessionID.IsEquals(request.Get<string>("ID")) || !requestInfo.Session.User.ID.IsEquals(request.Get<string>("UserID")))
throw new InvalidSessionException();
session.CopyFrom(request);
await Session.UpdateAsync(session, true, cancellationToken).ConfigureAwait(false);
}
// make sure the cache has updated && remove duplicated sessions
await Task.WhenAll(
Utility.Cache.SetAsync(session, cancellationToken),
Session.DeleteManyAsync(Filters<Session>.And(
Filters<Session>.Equals("DeviceID", session.DeviceID),
Filters<Session>.NotEquals("ID", session.ID)
), null, cancellationToken)
).ConfigureAwait(false);
// update account information
var account = await Account.GetAsync<Account>(session.UserID, cancellationToken).ConfigureAwait(false);
account.LastAccess = DateTime.Now;
await account.GetSessionsAsync(cancellationToken).ConfigureAwait(false);
await Account.UpdateAsync(account, true, cancellationToken).ConfigureAwait(false);
// response
return session.ToJson();
}
}
#endregion
#region Log a session in
async Task<JToken> LogSessionInAsync(RequestInfo requestInfo, CancellationToken cancellationToken)
{
// verify
if (requestInfo.Extra == null || !requestInfo.Extra.ContainsKey("Signature") || !requestInfo.Extra["Signature"].Equals(requestInfo.Body.GetHMACSHA256(this.ValidationKey)))
throw new InformationInvalidException("The signature is not found or invalid");
// prepare
var request = requestInfo.GetBodyExpando();
var type = request.Get("Type", "BuiltIn").ToEnum<AccountType>();
var email = request.Get("Email", "").Decrypt(this.EncryptionKey).Trim().ToLower();
var password = request.Get("Password", "").Decrypt(this.EncryptionKey);
Account account = null;
// Windows account
if (type.Equals(AccountType.Windows))
{
var username = email.Left(email.PositionOf("@"));
username = username.PositionOf(@"\") > 0
? username.Right(username.Length - username.PositionOf(@"\") - 1).Trim()
: username.Trim();
var domain = email.Right(email.Length - email.PositionOf("@") - 1).Trim();
var body = new JObject
{
{ "Domain", domain.Encrypt(this.EncryptionKey) },
{ "Username", username.Encrypt(this.EncryptionKey) },
{ "Password", password.Encrypt(this.EncryptionKey) }
}.ToString(Formatting.None);
await this.CallServiceAsync(new RequestInfo(requestInfo.Session, "WindowsAD", "Account", "POST")
{
Header = requestInfo.Header,
Body = body,
Extra = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase)
{
{ "Signature", body.GetHMACSHA256(this.ValidationKey) }
}
}, cancellationToken).ConfigureAwait(false);
// state to create information of account/profile
var needToCreateAccount = true;
if (requestInfo.Extra != null && requestInfo.Extra.ContainsKey("x-no-account"))
needToCreateAccount = false;
// create information of account/profile
if (needToCreateAccount)
{
account = await Account.GetByIdentityAsync(email, AccountType.Windows, cancellationToken).ConfigureAwait(false);
if (account == null)
{
account = new Account
{
ID = UtilityService.NewUUID,
Type = AccountType.Windows,
AccessIdentity = email
};
await Account.CreateAsync(account, cancellationToken).ConfigureAwait(false);
var profile = new Profile
{
ID = account.ID,
Name = request.Get("Name", username),
Email = email
};
await Profile.CreateAsync(profile, cancellationToken).ConfigureAwait(false);
}
}
// no need to create account, then response with success state
else
return new JObject();
}
// OAuth account
else if (type.Equals(AccountType.OAuth))
{
}
// BuiltIn account
else
{
account = await Account.GetByIdentityAsync(email, AccountType.BuiltIn, cancellationToken).ConfigureAwait(false);
if (account == null || !Account.GeneratePassword(account.ID, password).Equals(account.AccessKey))
throw new WrongAccountException();
}
// prepare results
var results = account.GetAccountJson();
// two-factors authentication is required
if (account.TwoFactorsAuthentication.Required)
{
results["Require2FA"] = true;
results["Providers"] = account.TwoFactorsAuthentication.GetProvidersJson(this.AuthenticationKey);
}
// clear cached of current session when 2FA is not required
else
await Utility.Cache.RemoveAsync<Session>(requestInfo.Session.SessionID, cancellationToken).ConfigureAwait(false);
// response
return results;
}
#endregion
#region Log a session out
async Task<JToken> LogSessionOutAsync(RequestInfo requestInfo, CancellationToken cancellationToken)
{
// verify
if (requestInfo.Extra == null || !requestInfo.Extra.ContainsKey("Signature") || !requestInfo.Extra["Signature"].Equals(requestInfo.Header["x-app-token"].GetHMACSHA256(this.ValidationKey)))
throw new InformationInvalidException("The signature is not found or invalid");
// remove session
await Session.DeleteAsync<Session>(requestInfo.Session.SessionID, requestInfo.Session.User.ID, cancellationToken).ConfigureAwait(false);
// update account
var account = await Account.GetAsync<Account>(requestInfo.Session.User.ID, cancellationToken).ConfigureAwait(false);
if (account != null)
{
if (account.Sessions == null)
await account.GetSessionsAsync(cancellationToken).ConfigureAwait(false);
account.Sessions = account.Sessions.Where(s => !s.ID.Equals(requestInfo.Session.SessionID)).ToList();
account.LastAccess = DateTime.Now;
await Account.UpdateAsync(account, true, cancellationToken).ConfigureAwait(false);
}
// response
return new JObject();
}
#endregion
Task<JToken> ProcessOTPAsync(RequestInfo requestInfo, CancellationToken cancellationToken)
{
switch (requestInfo.Verb)
{
// validate
case "POST":
return this.ValidateOTPAsync(requestInfo, cancellationToken);
// provisioning
case "GET":
return this.GetProvisioningOTPAsync(requestInfo, cancellationToken);
// update
case "PUT":
return this.UpdateOTPAsync(requestInfo, cancellationToken);
// delete
case "DELETE":
return this.DeleteOTPAsync(requestInfo, cancellationToken);
// unknown
default:
return Task.FromException<JToken>(new MethodNotAllowedException(requestInfo.Verb));
}
}
#region Validate an OTP
async Task<JToken> ValidateOTPAsync(RequestInfo requestInfo, CancellationToken cancellationToken)
{
// prepare
var body = requestInfo.GetBodyExpando();
var id = body.Get("ID", "");
var otp = body.Get("OTP", "");
var info = body.Get("Info", "");
if (string.IsNullOrWhiteSpace(id) || string.IsNullOrWhiteSpace(otp) || string.IsNullOrWhiteSpace(info))
throw new InformationRequiredException();
try
{
id = id.Decrypt(this.EncryptionKey);
otp = otp.Decrypt(this.EncryptionKey);
info = info.Decrypt(this.EncryptionKey);
}
catch (Exception ex)
{
throw new InformationInvalidException(ex);
}
var account = await Account.GetAsync<Account>(id, cancellationToken);
if (account == null)
throw new InformationNotFoundException();
var type = TwoFactorsAuthenticationType.App;
var stamp = "";
try
{
var data = info.Decrypt(this.AuthenticationKey, true).ToArray('|');
type = data[0].ToEnum<TwoFactorsAuthenticationType>();
var time = Convert.ToInt64(data[2]);
if (account.TwoFactorsAuthentication.Settings.Where(s => s.Type.Equals(type) && s.Stamp.Equals(data[1]) && s.Time.Equals(time)).Count() > 0)
stamp = data[1] + (!type.Equals(TwoFactorsAuthenticationType.Phone) ? $"|{time}" : "");
else
throw new InformationInvalidException();
}
catch (InformationInvalidException)
{
throw;
}
catch (Exception ex)
{
throw new InformationInvalidException(ex);
}
// validate
await this.CallServiceAsync(new RequestInfo(requestInfo.Session, "AuthenticatorOTP", "Time-Based-OTP", "GET")
{
Extra = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase)
{
{ "Type", type.ToString() },
{ "ID", account.ID.Encrypt(this.EncryptionKey) },
{ "Stamp", stamp.Encrypt(this.EncryptionKey) },
{ "Password", otp.Encrypt(this.EncryptionKey) }
}
}, cancellationToken).ConfigureAwait(false);
// update when success
await Task.WhenAll(
Utility.Cache.SetAsync(account, cancellationToken),
Utility.Cache.RemoveAsync<Session>(requestInfo.Session.SessionID, cancellationToken)
).ConfigureAwait(false);
return account.GetAccountJson();
}
#endregion
#region Get an OTP for provisioning
async Task<JToken> GetProvisioningOTPAsync(RequestInfo requestInfo, CancellationToken cancellationToken)
{
// check
var account = await Account.GetAsync<Account>(requestInfo.Session.User.ID, cancellationToken).ConfigureAwait(false);
if (account == null)
throw new InformationNotFoundException();
var body = requestInfo.GetRequestExpando();
if (!body.Get("Type", "").TryToEnum(out TwoFactorsAuthenticationType type))
type = TwoFactorsAuthenticationType.App;
var stamp = type.Equals(TwoFactorsAuthenticationType.App) ? UtilityService.NewUUID : body.Get("Number", "");
if (string.IsNullOrWhiteSpace(stamp))
throw new InformationRequiredException();
// get provisioning info
stamp += "|" + DateTime.Now.ToUnixTimestamp().ToString();
var json = await this.CallServiceAsync(new RequestInfo(requestInfo.Session, "AuthenticatorOTP", "Time-Based-OTP", "GET")
{
Extra = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase)
{
{ "Type", type.ToString() },
{ "ID", account.ID.Encrypt(this.EncryptionKey) },
{ "Stamp", stamp.Encrypt(this.EncryptionKey) },
{ "Account", account.AccessIdentity.Encrypt(this.EncryptionKey) },
{ "Issuer", body.Get("Issuer", "").Encrypt(this.EncryptionKey) },
{ "Setup", "" }
}
}, cancellationToken).ConfigureAwait(false);
// response
json["Provisioning"] = new JObject
{
{ "Type", type.ToString() },
{ "Account", account.AccessIdentity },
{ "ID", account.ID },
{ "Stamp", stamp }
}.ToString(Formatting.None).Encrypt(this.AuthenticationKey);
return json;
}
#endregion
#region Update an OTP
async Task<JToken> UpdateOTPAsync(RequestInfo requestInfo, CancellationToken cancellationToken)
{
// prepare
var account = await Account.GetAsync<Account>(requestInfo.Session.User.ID, cancellationToken);
if (account == null)
throw new InformationNotFoundException();
try
{
var password = requestInfo.Extra != null && requestInfo.Extra.ContainsKey("x-password")
? requestInfo.Extra["x-password"].Decrypt(this.EncryptionKey)
: null;
if (string.IsNullOrWhiteSpace(password) || !Account.GeneratePassword(account.ID, password).Equals(account.AccessKey))
throw new WrongAccountException();
}
catch (WrongAccountException)
{
throw;
}
catch (Exception ex)
{
throw new WrongAccountException(ex);
}
var body = requestInfo.GetBodyExpando();
var json = JObject.Parse(body.Get("Provisioning", "").Decrypt(this.AuthenticationKey));
if (!account.ID.IsEquals(json.Get<string>("ID")) || !account.AccessIdentity.IsEquals(json.Get<string>("Account")))
throw new InformationInvalidException();
// validate with OTPs service
if (!Enum.TryParse(json.Get<string>("Type"), out TwoFactorsAuthenticationType type))
type = TwoFactorsAuthenticationType.App;
var stamp = json.Get<string>("Stamp");
json = await this.CallServiceAsync(new RequestInfo(requestInfo.Session, "AuthenticatorOTP", "Time-Based-OTP", "GET")
{
Extra = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase)
{
{ "Type", type.ToString() },
{ "ID", account.ID.Encrypt(this.EncryptionKey) },
{ "Stamp", stamp.Encrypt(this.EncryptionKey) },
{ "Password", body.Get("OTP", "").Encrypt(this.EncryptionKey) }
}
}, cancellationToken).ConfigureAwait(false) as JObject;
// update settings
account.TwoFactorsAuthentication.Required = true;
account.TwoFactorsAuthentication.Settings.Add(new TwoFactorsAuthenticationSetting
{
Type = type,
Stamp = stamp.ToArray('|').First(),
Time = Convert.ToInt64(stamp.ToArray('|').Last())
});
// get all sessions
if (account.Sessions == null)
await account.GetSessionsAsync(cancellationToken).ConfigureAwait(false);
// revoke all sessions that are not verified with two-factors authentication
var sessions = account.Sessions.Where(s => !s.ID.Equals(requestInfo.Session.SessionID) && !s.Verified).ToList();
var messages = sessions.Select(s => new BaseMessage
{
Type = "Session#Revoke",
Data = new JObject
{
{ "SessionID", s.ID }
}
}).ToList();
// update current session
var session = account.Sessions.First(s => s.ID.Equals(requestInfo.Session.SessionID));
var needUpdate = false;
if (!session.Verified)
{
needUpdate = session.Verified = true;
messages.Add(new BaseMessage
{
Type = "Session#Update",
Data = new JObject
{
{ "SessionID", session.ID },
{ "User", account.GetAccountJson() },
{ "Verified", session.Verified }
}
});
}
// update account
if (sessions.Count > 0)
account.Sessions = account.Sessions.Except(sessions).ToList();
json = account.GetAccountJson(true, this.AuthenticationKey);
// run all tasks
await Task.WhenAll(
Account.UpdateAsync(account, true, cancellationToken),
needUpdate ? Session.UpdateAsync(session, true, cancellationToken) : Task.CompletedTask,
sessions.Count > 0 ? Session.DeleteManyAsync(Filters<Session>.Or(sessions.Select(s => Filters<Session>.Equals("ID", s.ID))), null, cancellationToken) : Task.CompletedTask,
sessions.Count > 0 ? sessions.ForEachAsync((s, token) => Utility.Cache.RemoveAsync(s, token), cancellationToken) : Task.CompletedTask,
messages.Count > 0 ? this.SendInterCommunicateMessagesAsync("APIGateway", messages, cancellationToken) : Task.CompletedTask
).ConfigureAwait(false);
// response
return json;
}
#endregion
#region Delete an OTP
async Task<JToken> DeleteOTPAsync(RequestInfo requestInfo, CancellationToken cancellationToken)
{
// prepare
var account = await Account.GetAsync<Account>(requestInfo.Session.User.ID, cancellationToken);
if (account == null)
throw new InformationNotFoundException();
try
{
var password = requestInfo.Extra != null && requestInfo.Extra.ContainsKey("x-password")
? requestInfo.Extra["x-password"].Decrypt(this.EncryptionKey)
: null;
if (string.IsNullOrWhiteSpace(password) || !Account.GeneratePassword(account.ID, password).Equals(account.AccessKey))
throw new WrongAccountException();
}
catch (WrongAccountException)
{
throw;
}
catch (Exception ex)
{
throw new WrongAccountException(ex);
}
var info = (requestInfo.Query.ContainsKey("Info") ? requestInfo.Query["Info"].Decrypt(this.AuthenticationKey, true) : "").ToArray('|');
var type = info[0].ToEnum<TwoFactorsAuthenticationType>();
var stamp = info[1];
var time = Convert.ToInt64(info[2]);
// update settings
account.TwoFactorsAuthentication.Settings = account.TwoFactorsAuthentication.Settings.Where(s => !s.Type.Equals(type) && !s.Stamp.Equals(stamp) && !s.Time.Equals(time)).ToList();
account.TwoFactorsAuthentication.Required = account.TwoFactorsAuthentication.Settings.Count > 0;
// prepare to update
var json = account.GetAccountJson(true, this.AuthenticationKey);
if (account.Sessions == null)
await account.GetSessionsAsync(cancellationToken).ConfigureAwait(false);
if (!account.TwoFactorsAuthentication.Required)
account.Sessions.ForEach(s => s.Verified = false);
// run all tasks
await Task.WhenAll(
Account.UpdateAsync(account, true, cancellationToken),
account.TwoFactorsAuthentication.Required ? Task.CompletedTask : account.Sessions.ForEachAsync((session, token) => Session.UpdateAsync(session, true, token), cancellationToken),
account.TwoFactorsAuthentication.Required ? Task.CompletedTask : this.SendInterCommunicateMessagesAsync("APIGateway", account.Sessions.Select(session => new BaseMessage
{
Type = "Session#Update",
Data = new JObject
{
{ "SessionID", session.ID },
{ "Verification", false }
}
}).ToList(), cancellationToken)
).ConfigureAwait(false);
// response
return json;
}
#endregion
Task<JToken> ProcessAccountAsync(RequestInfo requestInfo, CancellationToken cancellationToken)
{
switch (requestInfo.Verb)
{
// get an account
case "GET":
return this.GetAccountAsync(requestInfo, cancellationToken);
// create or invite to register an account
case "POST":
return this.CreateAccountAsync(requestInfo, cancellationToken);
// update an account
case "PUT":
var identity = requestInfo.GetObjectIdentity();
if ("reset".IsEquals(identity))
return this.ResetPasswordAsync(requestInfo, cancellationToken);
else if ("password".IsEquals(identity))
return this.UpdatePasswordAsync(requestInfo, cancellationToken);
else if ("email".IsEquals(identity))
return this.UpdateEmailAsync(requestInfo, cancellationToken);
else
return this.SetPrivilegesAsync(requestInfo, cancellationToken);
// get sessions of an account
case "HEAD":
return this.GetAccountSessionsAsync(requestInfo, cancellationToken);
// unknown
default:
return Task.FromException<JToken>(new MethodNotAllowedException(requestInfo.Verb));
}
}
#region Get an account
async Task<JToken> GetAccountAsync(RequestInfo requestInfo, CancellationToken cancellationToken)
{
// check to see the user in the request is system administrator or not
if (requestInfo.Extra != null && requestInfo.Extra.ContainsKey("IsSystemAdministrator"))
return new JObject
{
{ "ID", requestInfo.Session.User.ID },
{ "IsSystemAdministrator", requestInfo.Session.User.IsSystemAdministrator }
};
// check permission
if (!this.IsAuthenticated(requestInfo))
throw new AccessDeniedException();
// get account information
var account = await Account.GetAsync<Account>(requestInfo.GetObjectIdentity() ?? requestInfo.Session.User.ID, cancellationToken).ConfigureAwait(false);
if (account == null)
throw new InformationNotFoundException();
// response
return account.GetAccountJson(requestInfo.Query.ContainsKey("x-status"), this.AuthenticationKey);
}
#endregion
#region Create an account
async Task<JToken> CreateAccountAsync(RequestInfo requestInfo, CancellationToken cancellationToken)
{
// convert
if (requestInfo.Extra != null && requestInfo.Extra.ContainsKey("x-convert"))
{
if (!requestInfo.Session.User.IsSystemAdministrator)
throw new AccessDeniedException();
var requestBody = requestInfo.GetBodyExpando();
var account = requestBody.Copy<Account>();
account.AccessKey = requestBody.Get<string>("AccessKey") ?? Account.GeneratePassword(account.AccessIdentity);
await Account.CreateAsync(account, cancellationToken).ConfigureAwait(false);
return account.ToJson();
}
// register
else
{
// prepare
var requestBody = requestInfo.GetBodyExpando();
var id = UtilityService.GetUUID();
var json = new JObject
{
{ "Message", "Please check email and follow the instructions" }
};
var name = requestBody.Get<string>("Name");
var email = requestInfo.Extra != null && requestInfo.Extra.ContainsKey("Email")
? requestInfo.Extra["Email"].Decrypt(this.EncryptionKey).Trim().ToLower()
: null;
var password = requestInfo.Extra != null && requestInfo.Extra.ContainsKey("Password")
? requestInfo.Extra["Password"].Decrypt(this.EncryptionKey)
: null;
if (string.IsNullOrWhiteSpace(password))
password = Account.GeneratePassword(email);
// check existing account
if (await Account.GetByIdentityAsync(email, AccountType.BuiltIn, cancellationToken).ConfigureAwait(false) != null)
throw new InformationExistedException("The email address (" + email + ") has been used for another account");
// related: privileges, service, extra info
var privileges = requestInfo.Extra != null && requestInfo.Extra.ContainsKey("Privileges")
? JArray.Parse(requestInfo.Extra["Privileges"].Decrypt(this.EncryptionKey)).ToList<Privilege>()
: null;
var relatedService = requestInfo.GetQueryParameter("related-service");
var relatedInfo = !string.IsNullOrWhiteSpace(relatedService) && requestInfo.Extra != null && requestInfo.Extra.ContainsKey("RelatedInfo")
? requestInfo.Extra["RelatedInfo"].Decrypt(this.EncryptionKey).ToExpandoObject()
: null;
// permissions of privileges & related info
if (privileges != null || relatedInfo != null)
{
var gotRights = await this.IsSystemAdministratorAsync(requestInfo).ConfigureAwait(false);
if (!gotRights && !string.IsNullOrWhiteSpace(relatedService))
{
var relatedSvc = this.GetRelatedService(requestInfo);
gotRights = relatedSvc != null && await relatedSvc.CanManageAsync(requestInfo.Session.User, requestInfo.ObjectName, null, null, null, cancellationToken).ConfigureAwait(false);
}
if (!gotRights)
{
privileges = null;
relatedInfo = null;
}
}
// create new account & profile
var isCreateNew = requestInfo.Extra != null && requestInfo.Extra.ContainsKey("x-create");
if (isCreateNew)
{
// create account
var account = new Account
{
ID = id,
Status = requestBody.Get("Status", "Registered").ToEnum<AccountStatus>(),
Type = requestBody.Get("Type", "BuiltIn").ToEnum<AccountType>(),
AccessIdentity = email,
AccessKey = password,
AccessPrivileges = privileges ?? new List<Privilege>()
};
await Account.CreateAsync(account, cancellationToken).ConfigureAwait(false);
json = account.GetAccountJson();
// create profile
var profile = requestBody.Copy<Profile>();
profile.ID = id;
profile.Name = name;
profile.Email = email;
await Task.WhenAll(
Profile.CreateAsync(profile, cancellationToken),
string.IsNullOrWhiteSpace(relatedService)
? Task.CompletedTask
: this.CallRelatedServiceAsync(requestInfo, json.Copy<User>(), "profile", "POST", null, relatedInfo?.ToDictionary(kvp => kvp.Key, kvp => kvp.Value as string), cancellationToken)
).ConfigureAwait(false);
}
// send activation email
var mode = requestInfo.Extra != null && requestInfo.Extra.ContainsKey("x-invite")
? "invite"
: "account";
var codeData = new JObject
{
{ "ID", id },
{ "Name", name },
{ "Email", email },
{ "Password", password },
{ "Time", DateTime.Now },
{ "Mode", isCreateNew ? "Status" : "Create" }
};
if (privileges != null)
codeData["Privileges"] = privileges.ToJsonArray();
if (!string.IsNullOrWhiteSpace(relatedService) && relatedInfo != null)
{
codeData["RelatedService"] = relatedService;
codeData["RelatedUser"] = requestInfo.Session.User.ID;
codeData["RelatedInfo"] = relatedInfo.ToJson();
}
var code = codeData.ToString(Formatting.None).Encrypt(this.ActivationKey).ToBase64Url(true);
var uri = requestInfo.GetQueryParameter("uri")?.Url64Decode() ?? Utility.ActivateHttpURI;
uri = uri.Replace(StringComparison.OrdinalIgnoreCase, "{mode}", "account");
uri = uri.Replace(StringComparison.OrdinalIgnoreCase, "{code}", code);
// prepare activation email
string inviter = "", inviterEmail = "";
if (mode.Equals("invite"))
{
var profile = await Profile.GetAsync<Profile>(requestInfo.Session.User.ID, cancellationToken).ConfigureAwait(false);
inviter = profile.Name;
inviterEmail = profile.Email;
}
var instructions = await this.GetActivateInstructionsAsync(requestInfo, mode, cancellationToken).ConfigureAwait(false);
var data = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase)
{
{ "Host", requestInfo.GetQueryParameter("host") ?? "unknown" },
{ "Email", email },
{ "Password", password },
{ "Name", name },
{ "Time", DateTime.Now.ToString("hh:mm tt @ dd/MM/yyyy") },
{ "AppPlatform", requestInfo.Session.AppName + " @ " + requestInfo.Session.AppPlatform },
{ "Location", await requestInfo.GetLocationAsync().ConfigureAwait(false) },
{ "IP", requestInfo.Session.IP },
{ "Uri", uri },
{ "Code", code },
{ "Inviter", inviter },
{ "InviterEmail", inviterEmail },
{ "Signature", instructions.Item3 }
};
// send an email
var from = instructions.Item4;
var to = name + " <" + email + ">";
var subject = instructions.Item1;
var body = instructions.Item2;
data.ForEach(info =>
{
subject = subject.Replace(StringComparison.OrdinalIgnoreCase, "{" + info.Key + "}", info.Value);
body = body.Replace(StringComparison.OrdinalIgnoreCase, "{" + info.Key + "}", info.Value);
});
var smtpServer = instructions.Item5.Item1;
var smtpServerPort = instructions.Item5.Item2;
var smtpServerEnableSsl = instructions.Item5.Item3;
var smtpServerUsername = instructions.Item5.Item4;
var smtpServerPassword = instructions.Item5.Item5;
await this.SendEmailAsync(from, to, subject, body, smtpServer, smtpServerPort, smtpServerEnableSsl, smtpServerUsername, smtpServerPassword, cancellationToken).ConfigureAwait(false);
// result
return json;
}
}
#endregion
#region Get the privilege objects of an account
async Task<JToken> GetPrivilegesAsync(RequestInfo requestInfo, CancellationToken cancellationToken)
{
var gotRights = requestInfo.Session.User.IsSystemAdministrator;
var relatedService = gotRights ? null : this.GetRelatedService(requestInfo);
if (!gotRights && relatedService != null)
{
var serviceName = requestInfo.GetQueryParameter("related-service");
var objectName = requestInfo.GetQueryParameter("related-object");
var systemID = requestInfo.GetQueryParameter("related-system");
var definitionID = requestInfo.GetQueryParameter("related-definition");
var objectID = requestInfo.GetQueryParameter("related-object-identity");
if (await relatedService.CanManageAsync(requestInfo.Session.User, objectName, systemID, definitionID, objectID, cancellationToken).ConfigureAwait(false))
return await this.CallServiceAsync(new RequestInfo(requestInfo.Session, serviceName, "Privileges", "GET")
{
Header = requestInfo.Header,
Query = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase)
{
{ "x-object-name", objectName },
{ "x-system-id", systemID },
{ "x-definition-id", definitionID },
{ "x-object-id", objectID }
},
CorrelationID = requestInfo.CorrelationID
}, cancellationToken).ConfigureAwait(false);
}
return gotRights
? new JObject()
: throw new AccessDeniedException();
}
#endregion
#region Update the privileges of an account
async Task<JToken> SetPrivilegesAsync(RequestInfo requestInfo, CancellationToken cancellationToken)
{
// prepare
var serviceName = requestInfo.GetQueryParameter("related-service");
var objectName = requestInfo.GetQueryParameter("related-object");
var systemID = requestInfo.GetQueryParameter("related-system");
var definitionID = requestInfo.GetQueryParameter("related-definition");
var objectID = requestInfo.GetQueryParameter("related-object-identity");
var isSystemAdministrator = requestInfo.Session.User.IsSystemAdministrator;
// check permission => only system administrator or manager of the specified service can do
var gotRights = isSystemAdministrator;
var relatedService = gotRights ? null : this.GetRelatedService(requestInfo);
if (!gotRights && relatedService != null)
gotRights = await relatedService.CanManageAsync(requestInfo.Session.User, objectName, systemID, definitionID, objectID, cancellationToken).ConfigureAwait(false);
if (!gotRights)
throw new AccessDeniedException();
// get account
var account = await Account.GetAsync<Account>(requestInfo.GetObjectIdentity(), cancellationToken).ConfigureAwait(false);
if (account == null)
throw new InformationNotFoundException();
// roles of a system
if (!string.IsNullOrWhiteSpace(systemID) && requestInfo.Extra != null && requestInfo.Extra.ContainsKey("Roles"))
try
{
account.AccessRoles[systemID] = JArray.Parse(requestInfo.Extra["Roles"].Decrypt(this.EncryptionKey)).ToList<string>();
}
catch (Exception ex)
{
this.Logger.LogError("Error while processing roles", ex);
}
// privileges of a service
if (requestInfo.Extra != null && requestInfo.Extra.ContainsKey("Privileges"))
try
{
var allPrivileges = requestInfo.Extra["Privileges"].Decrypt(this.EncryptionKey).ToJson().ToExpandoObject();
if (isSystemAdministrator)
{
(allPrivileges as IDictionary<string, object>).Keys.ForEach(svcName =>
{
var svcPrivileges = allPrivileges.Get<List<Privilege>>(svcName).Where(p => p.ServiceName.IsEquals(svcName)).ToList();
if (svcPrivileges.Count == 1 && svcPrivileges[0].ObjectName.Equals("") && svcPrivileges[0].Role.Equals(PrivilegeRole.Viewer.ToString()))
svcPrivileges = new List<Privilege>();
account.AccessPrivileges = account.AccessPrivileges.Where(p => !p.ServiceName.IsEquals(svcName)).Concat(svcPrivileges).ToList();
});
}
else if (!string.IsNullOrWhiteSpace(serviceName))
{
var svcPrivileges = allPrivileges.Get<List<Privilege>>(serviceName).Where(p => p.ServiceName.IsEquals(serviceName)).ToList();
if (svcPrivileges.Count == 1 && svcPrivileges[0].ObjectName.Equals("") && svcPrivileges[0].Role.Equals(PrivilegeRole.Viewer.ToString()))
svcPrivileges = new List<Privilege>();
account.AccessPrivileges = account.AccessPrivileges.Where(p => !p.ServiceName.IsEquals(serviceName)).Concat(svcPrivileges).ToList();
}
account.AccessPrivileges = account.AccessPrivileges.OrderBy(p => p.ServiceName).ThenBy(p => p.ObjectName).ToList();
}
catch (Exception ex)
{
this.Logger.LogError("Error while processing privileges", ex);
}
// sessions
var json = account.GetAccountJson(account.TwoFactorsAuthentication.Required, this.AuthenticationKey);
var user = json.FromJson<User>();
if (account.Sessions == null)
await account.GetSessionsAsync(cancellationToken).ConfigureAwait(false);
account.Sessions.Where(session => session.ExpiredAt > DateTime.Now).ForEach(session =>
{
try
{
session.RenewedAt = DateTime.Now;
session.ExpiredAt = DateTime.Now.AddDays(60);
session.AccessToken = user.GetAccessToken(this.ECCKey);
}
catch (Exception ex)
{
this.Logger.LogError("Error while preparing session when update privileges", ex);
}
});
// update database
await Task.WhenAll(
Account.UpdateAsync(account, requestInfo.Session.User.ID, cancellationToken),
Task.WhenAll(account.Sessions.Select(session => Session.UpdateAsync(session, true, cancellationToken)))
).ConfigureAwait(false);
// send update messages to API Gateway to update with clients
await this.SendInterCommunicateMessagesAsync("APIGateway", account.Sessions.Select(session => new BaseMessage
{
Type = "Session#Update",
Data = new JObject
{
{ "SessionID", session.ID },
{ "User", json },
{ "Verification", session.Verified }
}
}).ToList(), cancellationToken).ConfigureAwait(false);
// response
return json;
}
#endregion
#region Renew password of an account
async Task<JToken> ResetPasswordAsync(RequestInfo requestInfo, CancellationToken cancellationToken)
{
// get account
var email = requestInfo.Extra["Email"].Decrypt(this.EncryptionKey);
var account = await Account.GetByIdentityAsync(email, AccountType.BuiltIn, cancellationToken).ConfigureAwait(false);
if (account == null)
return new JObject
{
{ "Message", "Please check your email and follow the instruction to activate" }
};
// prepare
var password = Account.GeneratePassword(email);
var code = new JObject
{
{ "ID", account.ID },
{ "Password", password },
{ "Time", DateTime.Now }
}.ToString(Formatting.None).Encrypt(this.ActivationKey).ToBase64Url(true);
var uri = requestInfo.Query.ContainsKey("uri")
? requestInfo.Query["uri"].Url64Decode()
: Utility.ActivateHttpURI;
uri = uri.Replace(StringComparison.OrdinalIgnoreCase, "{mode}", "password");
uri = uri.Replace(StringComparison.OrdinalIgnoreCase, "{code}", code);
// prepare activation email
var instructions = await this.GetActivateInstructionsAsync(requestInfo, "reset", cancellationToken).ConfigureAwait(false);
var data = new Dictionary<string, string>
{
{ "Host", requestInfo.GetQueryParameter("host") ?? "unknown" },
{ "Email", account.AccessIdentity },
{ "Password", password },
{ "Name", account.Profile.Name },
{ "Time", DateTime.Now.ToString("hh:mm tt @ dd/MM/yyyy") },
{ "AppPlatform", requestInfo.Session.AppName + " @ " + requestInfo.Session.AppPlatform },
{ "Location", await requestInfo.GetLocationAsync().ConfigureAwait(false) },
{ "IP", requestInfo.Session.IP },
{ "Uri", uri },
{ "Code", code },
{ "Signature", instructions.Item3 }
};
// send an email
var subject = instructions.Item1;
var body = instructions.Item2;
data.ForEach(info =>
{
subject = subject.Replace(StringComparison.OrdinalIgnoreCase, "{" + info.Key + "}", info.Value);
body = body.Replace(StringComparison.OrdinalIgnoreCase, "{" + info.Key + "}", info.Value);
});
var smtp = instructions.Item5;
await this.SendEmailAsync(instructions.Item4, account.Profile.Name + " <" + account.AccessIdentity + ">", subject, body, smtp.Item1, smtp.Item2, smtp.Item3, smtp.Item4, smtp.Item5, cancellationToken).ConfigureAwait(false);
// response
return new JObject
{
{ "Message", "Please check your email and follow the instruction to activate" }
};
}
#endregion
#region Update password of an account
async Task<JToken> UpdatePasswordAsync(RequestInfo requestInfo, CancellationToken cancellationToken)
{
// get account and check
var oldPassword = requestInfo.Extra["OldPassword"].Decrypt(this.EncryptionKey);
var account = await Account.GetAsync<Account>(requestInfo.Session.User.ID, cancellationToken).ConfigureAwait(false);
if (account == null || !Account.GeneratePassword(account.ID, oldPassword).Equals(account.AccessKey))
throw new WrongAccountException();
// update
var password = requestInfo.Extra["Password"].Decrypt(this.EncryptionKey);
account.AccessKey = Account.GeneratePassword(account.ID, password);
account.LastAccess = DateTime.Now;
await Account.UpdateAsync(account, true, cancellationToken);
// send alert email
var instructions = await this.GetUpdateInstructionsAsync(requestInfo, "password", cancellationToken).ConfigureAwait(false);
var data = new Dictionary<string, string>
{
{ "Host", requestInfo.GetQueryParameter("host") ?? "unknown" },
{ "Email", account.AccessIdentity },
{ "Password", password },
{ "Name", account.Profile.Name },
{ "Time", DateTime.Now.ToString("hh:mm tt @ dd/MM/yyyy") },
{ "AppPlatform", requestInfo.Session.AppName + " @ " + requestInfo.Session.AppPlatform },
{ "Location", await requestInfo.GetLocationAsync().ConfigureAwait(false) },
{ "IP", requestInfo.Session.IP },
{ "Signature", instructions.Item3 }
};
// send an email
var subject = instructions.Item1;
var body = instructions.Item2;
data.ForEach(info =>
{
subject = subject.Replace(StringComparison.OrdinalIgnoreCase, "{" + info.Key + "}", info.Value);
body = body.Replace(StringComparison.OrdinalIgnoreCase, "{" + info.Key + "}", info.Value);
});
var smtp = instructions.Item5;
await this.SendEmailAsync(instructions.Item4, account.Profile.Name + " <" + account.AccessIdentity + ">", subject, body, smtp.Item1, smtp.Item2, smtp.Item3, smtp.Item4, smtp.Item5, cancellationToken).ConfigureAwait(false);
// response
return account.Profile.ToJson();
}
#endregion
#region Update email of an account
async Task<JToken> UpdateEmailAsync(RequestInfo requestInfo, CancellationToken cancellationToken)
{
// get account and check
var oldPassword = requestInfo.Extra["OldPassword"].Decrypt(this.EncryptionKey);
var account = await Account.GetAsync<Account>(requestInfo.Session.User.ID, cancellationToken).ConfigureAwait(false);
if (account == null || !Account.GeneratePassword(account.ID, oldPassword).Equals(account.AccessKey))
throw new WrongAccountException();
// check existing
var email = requestInfo.Extra["Email"].Decrypt(this.EncryptionKey);
var otherAccount = await Account.GetByIdentityAsync(email, AccountType.BuiltIn, cancellationToken).ConfigureAwait(false);
if (otherAccount != null)
throw new InformationExistedException("The email '" + email + "' is used by other account");
// update
var oldEmail = account.AccessIdentity;
account.AccessIdentity = email.Trim().ToLower();
account.LastAccess = DateTime.Now;
account.Profile.Email = email.Trim().ToLower();
account.Profile.LastUpdated = DateTime.Now;
await Task.WhenAll(
Account.UpdateAsync(account, requestInfo.Session.User.ID, cancellationToken),
Profile.UpdateAsync(account.Profile, requestInfo.Session.User.ID, cancellationToken)
).ConfigureAwait(false);
// send alert email
var instructions = await this.GetUpdateInstructionsAsync(requestInfo, "email", cancellationToken).ConfigureAwait(false);
var data = new Dictionary<string, string>
{
{ "Host", requestInfo.GetQueryParameter("host") ?? "unknown" },
{ "Email", account.AccessIdentity },
{ "OldEmail", oldEmail },
{ "Name", account.Profile.Name },
{ "Time", DateTime.Now.ToString("hh:mm tt @ dd/MM/yyyy") },
{ "AppPlatform", requestInfo.Session.AppName + " @ " + requestInfo.Session.AppPlatform },
{ "Location", await requestInfo.GetLocationAsync().ConfigureAwait(false) },
{ "IP", requestInfo.Session.IP },
{ "Signature", instructions.Item3 }
};
// send an email
var subject = instructions.Item1;
var body = instructions.Item2;
data.ForEach(info =>
{
subject = subject.Replace(StringComparison.OrdinalIgnoreCase, "{" + info.Key + "}", info.Value);
body = body.Replace(StringComparison.OrdinalIgnoreCase, "{" + info.Key + "}", info.Value);
});
var smtp = instructions.Item5;
await this.SendEmailAsync(instructions.Item4, account.Profile.Name + " <" + account.AccessIdentity + ">", subject, body, smtp.Item1, smtp.Item2, smtp.Item3, smtp.Item4, smtp.Item5, cancellationToken).ConfigureAwait(false);
// response
return account.Profile.ToJson();
}
#endregion
#region Get the sessions of an account
async Task<JToken> GetAccountSessionsAsync(RequestInfo requestInfo, CancellationToken cancellationToken)
{
var userID = requestInfo.GetObjectIdentity() ?? requestInfo.Session.User.ID;
var account = !userID.Equals("") && !requestInfo.Session.User.IsSystemAccount
? await Account.GetAsync<Account>(userID, cancellationToken).ConfigureAwait(false)
: null;
if (account != null && account.Sessions == null)
await account.GetSessionsAsync(cancellationToken).ConfigureAwait(false);
return new JObject
{
{ "ID", userID },
{
"Sessions",
account != null
? account.Sessions.ToJArray(session => new JObject
{
{ "SessionID", session.ID },
{ "DeviceID", session.DeviceID },
{ "AppInfo", session.AppInfo },
{ "IsOnline", session.Online }
})
: new JArray()
}
};
}
#endregion
Task<JToken> ProcessProfileAsync(RequestInfo requestInfo, CancellationToken cancellationToken)
{
switch (requestInfo.Verb)
{
case "GET":
var identity = requestInfo.GetObjectIdentity();
// search
if ("search".IsEquals(identity))
return this.SearchProfilesAsync(requestInfo, cancellationToken);
// fetch
else if ("fetch".IsEquals(identity))
return this.FetchProfilesAsync(requestInfo, cancellationToken);
// get details of a profile
else
return this.GetProfileAsync(requestInfo, cancellationToken);
// create a profile
case "POST":
return this.CreateProfileAsync(requestInfo, cancellationToken);
// update a profile
case "PUT":
return this.UpdateProfileAsync(requestInfo, cancellationToken);
// unknown
default:
return Task.FromException<JToken>(new MethodNotAllowedException(requestInfo.Verb));
}
}
#region Search profiles
async Task<JToken> SearchProfilesAsync(RequestInfo requestInfo, CancellationToken cancellationToken)
{
// check permissions
if (!this.IsAuthenticated(requestInfo))
throw new AccessDeniedException();
// prepare
var request = requestInfo.GetRequestExpando();
var query = request.Get<string>("FilterBy.Query");
var filter = request.Get<ExpandoObject>("FilterBy", null)?.ToFilterBy<Profile>();
var sort = request.Get<ExpandoObject>("SortBy", null)?.ToSortBy<Profile>();
if (sort == null && string.IsNullOrWhiteSpace(query))
sort = Sorts<Profile>.Ascending("Name");
var pagination = request.Has("Pagination")
? request.Get<ExpandoObject>("Pagination").GetPagination()
: new Tuple<long, int, int, int>(-1, 0, 20, 1);
var pageNumber = pagination.Item4;
// check cache
var cacheKey = string.IsNullOrWhiteSpace(query)
? this.GetCacheKey(filter, sort)
: "";
var json = !cacheKey.Equals("")
? await Utility.Cache.GetAsync<string>($"{cacheKey }{pageNumber}:json").ConfigureAwait(false)
: "";
if (!string.IsNullOrWhiteSpace(json))
return JObject.Parse(json);
// prepare pagination
var totalRecords = pagination.Item1 > -1
? pagination.Item1
: -1;
if (totalRecords < 0)
totalRecords = string.IsNullOrWhiteSpace(query)
? await Profile.CountAsync(filter, $"{cacheKey}total", cancellationToken).ConfigureAwait(false)
: await Profile.CountAsync(query, filter, cancellationToken).ConfigureAwait(false);
var pageSize = pagination.Item3;
var totalPages = (new Tuple<long, int>(totalRecords, pageSize)).GetTotalPages();
if (totalPages > 0 && pageNumber > totalPages)
pageNumber = totalPages;
// search
var objects = totalRecords > 0
? string.IsNullOrWhiteSpace(query)
? await Profile.FindAsync(filter, sort, pageSize, pageNumber, $"{cacheKey}{pageNumber}", cancellationToken).ConfigureAwait(false)
: await Profile.SearchAsync(query, filter, pageSize, pageNumber, cancellationToken).ConfigureAwait(false)
: new List<Profile>();
// build result
var profiles = new JArray();
await objects.ForEachAsync(async (profile, token) =>
{
profiles.Add(profile.GetProfileJson(await this.GetProfileRelatedJsonAsync(requestInfo, token).ConfigureAwait(false) as JObject, !requestInfo.Session.User.IsSystemAdministrator));
}, cancellationToken, true, false).ConfigureAwait(false);
pagination = new Tuple<long, int, int, int>(totalRecords, totalPages, pageSize, pageNumber);
var result = new JObject
{
{ "FilterBy", (filter ?? new FilterBys<Profile>()).ToClientJson(query) },
{ "SortBy", sort?.ToClientJson() },
{ "Pagination", pagination?.GetPagination() },
{ "Objects", profiles }
};
// update cache
if (!cacheKey.Equals(""))
{
json = result.ToString(this.IsDebugLogEnabled ? Formatting.Indented : Formatting.None);
await Utility.Cache.SetAsync($"{cacheKey }{pageNumber}:json", json, Utility.Cache.ExpirationTime / 2).ConfigureAwait(false);
}
// return the result
return result;
}
#endregion
#region Fetch profiles
async Task<JToken> FetchProfilesAsync(RequestInfo requestInfo, CancellationToken cancellationToken)
{
// prepare
if (!this.IsAuthenticated(requestInfo))
throw new AccessDeniedException();
else if (!await this.IsAuthorizedAsync(requestInfo, "profile", Components.Security.Action.View, cancellationToken).ConfigureAwait(false))
throw new AccessDeniedException();
// fetch
var request = requestInfo.GetRequestExpando();
var filter = Filters<Profile>.Or(request.Get("IDs", new List<string>()).Select(id => Filters<Profile>.Equals("ID", id)));
var objects = await Profile.FindAsync(filter, null, 0, 1, null, cancellationToken);
// build result
var profiles = new JArray();
await objects.ForEachAsync(async (profile, token) =>
{
profiles.Add(profile.GetProfileJson(await this.GetProfileRelatedJsonAsync(requestInfo, token).ConfigureAwait(false) as JObject, !requestInfo.Session.User.IsSystemAdministrator));
}, cancellationToken, true, false).ConfigureAwait(false);
// return
return new JObject
{
{ "Objects", profiles }
};
}
#endregion
#region Create a profile
async Task<JToken> CreateProfileAsync(RequestInfo requestInfo, CancellationToken cancellationToken)
{
if (requestInfo.Extra != null && requestInfo.Extra.ContainsKey("x-convert"))
{
if (!requestInfo.Session.User.IsSystemAdministrator)
throw new AccessDeniedException();
var profile = requestInfo.GetBodyJson().Copy<Profile>();
await Profile.CreateAsync(profile, cancellationToken).ConfigureAwait(false);
return profile.GetProfileJson(null, false);
}
throw new InvalidRequestException();
}
#endregion
#region Get a profile
Task<JToken> GetProfileRelatedJsonAsync(RequestInfo requestInfo, CancellationToken cancellationToken)
=> this.CallRelatedServiceAsync(requestInfo, null, "Profile", "GET", requestInfo.Session.User.ID, null, cancellationToken);
async Task<JToken> GetProfileAsync(RequestInfo requestInfo, CancellationToken cancellationToken)
{
// get information
var id = requestInfo.GetObjectIdentity() ?? requestInfo.Session.User.ID;
var profile = await Profile.GetAsync<Profile>(id, cancellationToken).ConfigureAwait(false);
if (profile == null)
throw new InformationNotFoundException();
// prepare
var serviceName = requestInfo.GetQueryParameter("related-service");
var objectName = requestInfo.GetQueryParameter("related-object");
var systemID = requestInfo.GetQueryParameter("related-system");
var definitionID = requestInfo.GetQueryParameter("related-definition");
var objectID = requestInfo.GetQueryParameter("related-object-identity");
// check permissions
var doNormalize = false;
var gotRights = this.IsAuthenticated(requestInfo) && requestInfo.Session.User.ID.IsEquals(id);
if (!gotRights)
{
gotRights = requestInfo.Session.User.IsSystemAdministrator || await this.IsAuthorizedAsync(requestInfo, "profile", Components.Security.Action.View, cancellationToken).ConfigureAwait(false);
doNormalize = !requestInfo.Session.User.IsSystemAdministrator;
}
var relatedService = gotRights ? null : this.GetRelatedService(requestInfo);
if (!gotRights && relatedService != null)
{
gotRights = await relatedService.CanManageAsync(requestInfo.Session.User, objectName, systemID, definitionID, objectID, cancellationToken).ConfigureAwait(false);
doNormalize = false;
}
if (!gotRights)
throw new AccessDeniedException();
// response
return profile.GetProfileJson(await this.GetProfileRelatedJsonAsync(requestInfo, cancellationToken).ConfigureAwait(false) as JObject, doNormalize);
}
#endregion
#region Update a profile
async Task<JToken> UpdateProfileAsync(RequestInfo requestInfo, CancellationToken cancellationToken)
{
// check permissions
var id = requestInfo.GetObjectIdentity() ?? requestInfo.Session.User.ID;
var gotRights = requestInfo.Session.User.IsSystemAdministrator || (this.IsAuthenticated(requestInfo) && requestInfo.Session.User.ID.IsEquals(id));
if (!gotRights)
gotRights = await this.IsAuthorizedAsync(requestInfo, "profile", Components.Security.Action.Update, cancellationToken).ConfigureAwait(false);
if (!gotRights)
throw new AccessDeniedException();
// get information
var profile = await Profile.GetAsync<Profile>(id, cancellationToken).ConfigureAwait(false);
var account = await Account.GetAsync<Account>(id, cancellationToken).ConfigureAwait(false);
if (profile == null || account == null)
throw new InformationNotFoundException();
// prepare
profile.CopyFrom(requestInfo.GetBodyJson(), "ID,Title,LastUpdated".ToHashSet(), accountprofile =>
{
profile.Title = null;
profile.LastUpdated = DateTime.Now;
profile.Avatar = string.IsNullOrWhiteSpace(profile.Avatar)
? string.Empty
: profile.Avatar.IsStartsWith(Utility.AvatarURI)
? profile.Avatar.Replace(Utility.FilesHttpURI, "~~")
: profile.Avatar;
if (account.Type.Equals(AccountType.BuiltIn) && !profile.Email.Equals(account.AccessIdentity))
profile.Email = account.AccessIdentity;
if (string.IsNullOrWhiteSpace(profile.Alias))
profile.Alias = "";
});
// update
await Task.WhenAll(
Profile.UpdateAsync(profile, requestInfo.Session.User.ID, cancellationToken),
requestInfo.Query.ContainsKey("related-service")
? this.CallRelatedServiceAsync(requestInfo, null, "Profile", "PUT", profile.ID, null, cancellationToken)
: Task.CompletedTask
).ConfigureAwait(false);
// send update message
var json = profile.GetProfileJson(await this.GetProfileRelatedJsonAsync(requestInfo, cancellationToken).ConfigureAwait(false) as JObject, false);
await this.SendUpdateMessageAsync(new UpdateMessage
{
Type = "Users#Profile#Update",
DeviceID = "*",
ExcludedDeviceID = requestInfo.Session.DeviceID,
Data = json
}, cancellationToken).ConfigureAwait(false);
// response
return json;
}
#endregion
async Task<JToken> ProcessActivationAsync(RequestInfo requestInfo, CancellationToken cancellationToken)
{
if (!requestInfo.Verb.IsEquals("GET"))
throw new MethodNotAllowedException(requestInfo.Verb);
#region prepare
var mode = requestInfo.Query.ContainsKey("mode")
? requestInfo.Query["mode"]
: null;
if (string.IsNullOrWhiteSpace(mode))
throw new InvalidActivateInformationException();
var code = requestInfo.Query.ContainsKey("code")
? requestInfo.Query["code"]
: null;
if (string.IsNullOrWhiteSpace(code))
throw new InvalidActivateInformationException();
try
{
code = code.ToBase64(false, true).Decrypt(this.ActivationKey);
}
catch (Exception ex)
{
throw new InvalidActivateInformationException(ex);
}
ExpandoObject info = null;
try
{
info = code.ToExpandoObject();
}
catch (Exception ex)
{
throw new InvalidActivateInformationException(ex);
}
// check time
if (!info.Has("Time"))
throw new InvalidActivateInformationException();
var time = info.Get<DateTime>("Time");
if (mode.IsEquals("account") && (DateTime.Now - time).TotalDays > 30)
throw new ActivateInformationExpiredException();
else if ((DateTime.Now - time).TotalHours > 24)
throw new ActivateInformationExpiredException();
#endregion
// activate account
if (mode.IsEquals("account"))
return await this.ActivateAccountAsync(requestInfo, info, cancellationToken).ConfigureAwait(false);
// activate password
else if (mode.IsEquals("password"))
return await this.ActivatePasswordAsync(requestInfo, info, cancellationToken).ConfigureAwait(false);
// unknown
throw new InvalidRequestException();
}
#region Activate new account
async Task<JToken> ActivateAccountAsync(RequestInfo requestInfo, ExpandoObject info, CancellationToken cancellationToken)
{
// prepare
var mode = info.Get<string>("Mode");
var id = info.Get<string>("ID");
var name = info.Get<string>("Name");
var email = info.Get<string>("Email");
var privileges = info.Get<List<Privilege>>("Privileges");
var relatedService = info.Get<string>("RelatedService");
var relatedUser = info.Get<string>("RelatedUser");
var relatedInfo = info.Get<ExpandoObject>("RelatedInfo");
// activate
if (mode.IsEquals("Status"))
{
// check
var account = await Account.GetAsync<Account>(id, cancellationToken).ConfigureAwait(false);
if (account == null && !string.IsNullOrWhiteSpace(email))
account = await Account.GetByIdentityAsync(email, AccountType.BuiltIn, cancellationToken).ConfigureAwait(false);
if (account == null)
throw new InformationNotFoundException();
// update status
if (account.Status.Equals(AccountStatus.Registered))
{
account.Status = AccountStatus.Activated;
account.LastAccess = DateTime.Now;
await Account.UpdateAsync(account, true, cancellationToken).ConfigureAwait(false);
}
// update related information
if (!string.IsNullOrWhiteSpace(relatedService) && !string.IsNullOrWhiteSpace(relatedUser))
try
{
// prepare
var relatedAccount = await Account.GetAsync<Account>(relatedUser, cancellationToken).ConfigureAwait(false);
var relatedSession = new Services.Session(requestInfo.Session)
{
User = relatedAccount.GetAccountJson().Copy<User>()
};
// update privileges
try
{
account.AccessPrivileges = account.AccessPrivileges.Where(p => !p.ServiceName.IsEquals(relatedService))
.Concat(JArray.Parse(requestInfo.Extra["Privileges"].Decrypt(this.EncryptionKey)).ToList<Privilege>().Where(p => p.ServiceName.IsEquals(relatedService)))
.ToList();
await Account.UpdateAsync(account, true, cancellationToken).ConfigureAwait(false);
}
catch { }
// update related information
if (relatedInfo != null)
await this.CallServiceAsync(new RequestInfo(relatedSession, relatedService, "activate", "GET")
{
Query = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase)
{
{ "object-identity", account.ID }
},
Extra = relatedInfo.ToDictionary(kvp => kvp.Key, kvp => kvp.Value as string),
CorrelationID = requestInfo.CorrelationID
}, cancellationToken).ConfigureAwait(false);
}
catch { }
// response
return account.GetAccountJson();
}
// create new account
else
{
// create account
var account = new Account
{
ID = id,
Status = AccountStatus.Activated,
Type = info.Get("Type", "BuiltIn").ToEnum<AccountType>(),
Joined = info.Get<DateTime>("Time"),
AccessIdentity = email,
AccessKey = Account.GeneratePassword(id, info.Get<string>("Password")),
AccessPrivileges = privileges ?? new List<Privilege>()
};
await Account.CreateAsync(account, cancellationToken).ConfigureAwait(false);
// prepare response
var json = account.GetAccountJson();
// create profile
var profile = new Profile
{
ID = id,
Name = name,
Email = email
};
await Profile.CreateAsync(profile, cancellationToken).ConfigureAwait(false);
// update information of related service
if (!string.IsNullOrWhiteSpace(relatedService) && !string.IsNullOrWhiteSpace(relatedUser) && relatedInfo != null)
try
{
var relatedAccount = await Account.GetAsync<Account>(relatedUser, cancellationToken).ConfigureAwait(false);
var relatedSession = new Services.Session(requestInfo.Session)
{
User = relatedAccount.GetAccountJson().Copy<User>()
};
await this.CallServiceAsync(new RequestInfo(relatedSession, relatedService, "activate", "GET")
{
Query = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase)
{
{ "object-identity", account.ID }
},
Extra = relatedInfo.ToDictionary(kvp => kvp.Key, kvp => kvp.Value as string),
CorrelationID = requestInfo.CorrelationID
}, cancellationToken).ConfigureAwait(false);
}
catch { }
// return
return json;
}
}
#endregion
#region Activate new password
async Task<JToken> ActivatePasswordAsync(RequestInfo requestInfo, ExpandoObject info, CancellationToken cancellationToken)
{
// prepare
var id = info.Get<string>("ID");
var password = info.Get<string>("Password");
// load account
var account = await Account.GetAsync<Account>(id, cancellationToken).ConfigureAwait(false);
if (account == null)
throw new InvalidActivateInformationException();
// update new password
account.AccessKey = Account.GeneratePassword(account.ID, password);
account.LastAccess = DateTime.Now;
account.Sessions = null;
await Account.UpdateAsync(account, true, cancellationToken).ConfigureAwait(false);
// response
return account.GetAccountJson();
}
#endregion
protected override async Task ProcessInterCommunicateMessageAsync(CommunicateMessage message, CancellationToken cancellationToken = default(CancellationToken))
{
// prepare
var correlationID = UtilityService.NewUUID;
var request = message.Data?.ToExpandoObject();
if (request == null)
return;
// state of a session
if (message.Type.IsEquals("Session#State"))
try
{
var sessionID = request.Get<string>("SessionID");
var userID = request.Get<string>("UserID");
var key = $"Session#{sessionID}";
if (request.Get<bool>("IsOnline"))
{
var session = string.IsNullOrWhiteSpace(userID)
? await Utility.Cache.GetAsync<Session>(key, cancellationToken).ConfigureAwait(false)
: await Session.GetAsync<Session>(sessionID, cancellationToken).ConfigureAwait(false);
if (session != null)
{
if (this.Sessions.TryGetValue(sessionID, out Tuple<DateTime, string> info))
this.Sessions.TryUpdate(sessionID, new Tuple<DateTime, string>(DateTime.Now, userID), info);
else
this.Sessions.TryAdd(sessionID, new Tuple<DateTime, string>(DateTime.Now, userID));
if (string.IsNullOrWhiteSpace(userID))
await Utility.Cache.SetAsync(key, session, 0, cancellationToken).ConfigureAwait(false);
else if (info == null || (DateTime.Now - info.Item1).TotalMinutes > 14)
{
var account = await Account.GetAsync<Account>(userID, cancellationToken).ConfigureAwait(false);
if (account != null)
{
account.LastAccess = DateTime.Now;
await Account.UpdateAsync(account, true, cancellationToken).ConfigureAwait(false);
}
}
}
}
else if (this.Sessions.TryRemove(sessionID, out Tuple<DateTime, string> info))
{
if (string.IsNullOrWhiteSpace(info.Item2))
await Utility.Cache.RemoveAsync(key, cancellationToken).ConfigureAwait(false);
else
{
var session = await Session.GetAsync<Session>(sessionID, cancellationToken).ConfigureAwait(false);
if (session != null)
{
session.Online = false;
await Session.UpdateAsync(session, true, cancellationToken).ConfigureAwait(false);
}
var account = string.IsNullOrWhiteSpace(info.Item2) ? null : await Account.GetAsync<Account>(info.Item2, cancellationToken).ConfigureAwait(false);
if (account != null)
{
account.LastAccess = DateTime.Now;
await Account.UpdateAsync(account, true, cancellationToken).ConfigureAwait(false);
}
}
}
if (this.IsDebugResultsEnabled)
await this.WriteLogsAsync(correlationID, $"Update online state of a session successful - Online sessions: {this.Sessions.Count:#,##0}", null, this.ServiceName, "Communicates").ConfigureAwait(false);
}
catch (Exception ex)
{
await this.WriteLogsAsync(correlationID, $"Error occurred while updating session state => {ex.Message}", ex, this.ServiceName, "Communicates", LogLevel.Error).ConfigureAwait(false); ;
}
// status of sessions
else if (message.Type.IsEquals("Session#Status"))
{
var numberOfVisitorSessions = this.Sessions.Count(kvp => string.IsNullOrWhiteSpace(kvp.Value.Item2));
await this.SendUpdateMessageAsync(new UpdateMessage
{
Type = "Users#Session#Status",
DeviceID = "*",
Data = new JObject
{
{ "TotalSessions", this.Sessions.Count },
{ "VisitorSessions", numberOfVisitorSessions },
{ "UserSessions", this.Sessions.Count - numberOfVisitorSessions }
}
}, cancellationToken).ConfigureAwait(false);
}
// unknown
else if (this.IsDebugResultsEnabled)
await this.WriteLogsAsync(correlationID, $"Got an inter-communicate message => {message.ToJson().ToString(this.IsDebugLogEnabled ? Formatting.Indented : Formatting.None)})", null, this.ServiceName, "Communicates", LogLevel.Warning).ConfigureAwait(false);
}
#region Timers for working with background workers & schedulers
void RegisterTimers(string[] args = null)
{
// clean expired sessions (13 hours)
this.StartTimer(async () =>
{
var userID = UtilityService.GetAppSetting("Users:SystemAccountID", "VIEAppsNGX-MMXVII-System-Account");
var sessions = await Session.FindAsync(Filters<Session>.LessThan("ExpiredAt", DateTime.Now), null, 0, 1, null, this.CancellationTokenSource.Token).ConfigureAwait(false);
await sessions.ForEachAsync((session, token) => Session.DeleteAsync<Session>(session.ID, userID, token), this.CancellationTokenSource.Token, true, false).ConfigureAwait(false);
}, 13 * 60 * 60);
// refresh sessions (10 minutes)
this.StartTimer(async () =>
{
var userTimepoint = DateTime.Now.AddMinutes(-15);
var visitorTimepoint = DateTime.Now.AddMinutes(-10);
await this.Sessions.Select(kvp => new { SessionID = kvp.Key, LastActivity = kvp.Value.Item1, UserID = kvp.Value.Item2 })
.ToList()
.ForEachAsync(async (info, token) =>
{
// remove offline session
if (info.LastActivity < (string.IsNullOrWhiteSpace(info.UserID) ? visitorTimepoint : userTimepoint))
await this.SendInterCommunicateMessageAsync(new CommunicateMessage("Users")
{
Type = "Session#State",
Data = new JObject
{
{ "SessionID", info.SessionID },
{ "UserID", info.UserID },
{ "IsOnline", false }
}
}, token).ConfigureAwait(false);
// refresh anonymous session
else if (string.IsNullOrWhiteSpace(info.UserID))
{
var key = $"Session#{info.SessionID}";
var session = await Utility.Cache.GetAsync<Session>(key, token).ConfigureAwait(false);
if (session != null)
await Utility.Cache.SetAsync(key, session, 0, token).ConfigureAwait(false);
else
this.Sessions.TryRemove(info.SessionID, out Tuple<DateTime, string> sessioninfo);
}
}, this.CancellationTokenSource.Token)
.ConfigureAwait(false);
}, 10 * 60);
}
#endregion
}
} |
using System.Collections.Generic;
using Hayalpc.Library.Common.Results;
using Microsoft.AspNetCore.Mvc;
using Hayalpc.Fatura.Data.Models;
using Hayalpc.Fatura.Panel.Internal.Services.Interfaces;
using DevExtreme.AspNet.Data;
namespace Hayalpc.Fatura.Panel.Internal.Controllers
{
[Route("api/[controller]/[action]")]
[ApiController]
public class BulletinController : ControllerBase
{
private readonly IUserBulletinService service;
public BulletinController(IUserBulletinService service)
{
this.service = service;
}
[HttpGet("{id}")]
public IDataResult<UserBulletin> Get(long Id)
{
service.Read(Id);
return service.Get(Id);
}
[HttpGet("{id}")]
public IResult Read(long Id)
{
return service.Read(Id);
}
[HttpGet]
public IResult ReadAll()
{
return service.ReadAll();
}
[HttpPost]
public IDataResult<UserBulletin> Add(UserBulletin model)
{
return service.Add(model);
}
[HttpPut]
public IDataResult<UserBulletin> Update(UserBulletin model)
{
return service.Update(model);
}
[HttpPost]
public IDataResult<IEnumerable<UserBulletin>> Search(DataSourceLoadOptionsBase req)
{
return service.Search(req);
}
}
}
|
using System;
using System.Linq.Expressions;
using Bindable.Linq.Interfaces;
using Bindable.Linq.Operators;
namespace Bindable.Linq
{
public static partial class BindableEnumerable
{
/// <summary>
/// Checks a condition on a specified source.
/// </summary>
/// <typeparam name="TSource">The type of the source.</typeparam>
/// <param name="source">The source.</param>
/// <returns></returns>
public static ISwitchDeclaration<TSource> Switch<TSource>(this IBindable<TSource> source)
{
return new EmptySwitchDefinition<TSource>(source, source.Dispatcher);
}
#region Result type not known yet
/// <summary>
/// Adds a case to the current switch statement.
/// </summary>
/// <typeparam name="TSource">The type of the source.</typeparam>
/// <typeparam name="TResult">The type of the result.</typeparam>
/// <param name="switchDeclaration">The switch declaration.</param>
/// <param name="condition">The condition.</param>
/// <param name="result">The result.</param>
/// <returns>The switch statement.</returns>
public static ISwitch<TSource, TResult> Case<TSource, TResult>(this ISwitchDeclaration<TSource> switchDeclaration, TSource condition, TResult result)
{
return switchDeclaration.Case(c => AreEqual(c, condition), result);
}
/// <summary>
/// Adds a case to the current switch statement.
/// </summary>
/// <typeparam name="TSource">The type of the source.</typeparam>
/// <typeparam name="TResult">The type of the result.</typeparam>
/// <param name="switchDeclaration">The switch declaration.</param>
/// <param name="condition">The condition.</param>
/// <param name="result">The result.</param>
/// <returns>The switch statement.</returns>
public static ISwitch<TSource, TResult> Case<TSource, TResult>(this ISwitchDeclaration<TSource> switchDeclaration, TSource condition, Expression<Func<TSource, TResult>> result)
{
return switchDeclaration.Case(c => AreEqual(c, condition), result);
}
/// <summary>
/// Adds a case to the current switch statement.
/// </summary>
/// <typeparam name="TSource">The type of the source.</typeparam>
/// <typeparam name="TResult">The type of the result.</typeparam>
/// <param name="switchDeclaration">The switch declaration.</param>
/// <param name="condition">The condition.</param>
/// <param name="result">The result.</param>
/// <returns>The switch statement.</returns>
public static ISwitch<TSource, TResult> Case<TSource, TResult>(this ISwitchDeclaration<TSource> switchDeclaration, Expression<Func<TSource, bool>> condition, TResult result)
{
return switchDeclaration.Case(condition, i => result);
}
/// <summary>
/// Adds a case to the current switch statement.
/// </summary>
/// <typeparam name="TSource">The type of the source.</typeparam>
/// <typeparam name="TResult">The type of the result.</typeparam>
/// <param name="switchDeclaration">The switch declaration.</param>
/// <param name="condition">The condition.</param>
/// <param name="result">The result.</param>
/// <returns>The switch statement.</returns>
public static ISwitch<TSource, TResult> Case<TSource, TResult>(this ISwitchDeclaration<TSource> switchDeclaration, Expression<Func<TSource, bool>> condition, Expression<Func<TSource, TResult>> result)
{
return switchDeclaration.CreateForResultType<TResult>().Case(condition, result);
}
/// <summary>
/// Sets the default case for the current switch statement.
/// </summary>
/// <typeparam name="TSource">The type of the source.</typeparam>
/// <typeparam name="TResult">The type of the result.</typeparam>
/// <param name="switchDeclaration">The switch declaration.</param>
/// <param name="result">The result.</param>
/// <returns>The switch statement.</returns>
public static ISwitch<TSource, TResult> Default<TSource, TResult>(this ISwitchDeclaration<TSource> switchDeclaration, TResult result)
{
return switchDeclaration.Default(r => result);
}
/// <summary>
/// Sets the default case for the current switch statement.
/// </summary>
/// <typeparam name="TSource">The type of the source.</typeparam>
/// <typeparam name="TResult">The type of the result.</typeparam>
/// <param name="switchDeclaration">The switch declaration.</param>
/// <param name="result">The result.</param>
/// <returns>The switch statement.</returns>
public static ISwitch<TSource, TResult> Default<TSource, TResult>(this ISwitchDeclaration<TSource> switchDeclaration, Expression<Func<TSource, TResult>> result)
{
return switchDeclaration.CreateForResultType<TResult>().Default(result);
}
#endregion
#region Result type known
/// <summary>
/// Adds a case to the current switch statement.
/// </summary>
/// <typeparam name="TSource">The type of the source.</typeparam>
/// <typeparam name="TResult">The type of the result.</typeparam>
/// <param name="currentSwitch">The current switch.</param>
/// <param name="condition">The condition.</param>
/// <param name="result">The result.</param>
/// <returns>The switch statement.</returns>
public static ISwitch<TSource, TResult> Case<TSource, TResult>(this ISwitch<TSource, TResult> currentSwitch, TSource condition, TResult result)
{
return currentSwitch.Case(c => AreEqual(c, condition), result);
}
/// <summary>
/// Adds a case to the current switch statement.
/// </summary>
/// <typeparam name="TSource">The type of the source.</typeparam>
/// <typeparam name="TResult">The type of the result.</typeparam>
/// <param name="currentSwitch">The current switch.</param>
/// <param name="condition">The condition.</param>
/// <param name="result">The result.</param>
/// <returns>The switch statement.</returns>
public static ISwitch<TSource, TResult> Case<TSource, TResult>(this ISwitch<TSource, TResult> currentSwitch, TSource condition, Expression<Func<TSource, TResult>> result)
{
return currentSwitch.Case(c => AreEqual(c, condition), result);
}
/// <summary>
/// Adds a case to the current switch statement.
/// </summary>
/// <typeparam name="TSource">The type of the source.</typeparam>
/// <typeparam name="TResult">The type of the result.</typeparam>
/// <param name="currentSwitch">The current switch.</param>
/// <param name="condition">The condition.</param>
/// <param name="result">The result.</param>
/// <returns>The switch statement.</returns>
public static ISwitch<TSource, TResult> Case<TSource, TResult>(this ISwitch<TSource, TResult> currentSwitch, Expression<Func<TSource, bool>> condition, TResult result)
{
return currentSwitch.Case(condition, i => result);
}
/// <summary>
/// Adds a case to the current switch statement.
/// </summary>
/// <typeparam name="TSource">The type of the source.</typeparam>
/// <typeparam name="TResult">The type of the result.</typeparam>
/// <param name="currentSwitch">The current switch.</param>
/// <param name="condition">The condition.</param>
/// <param name="result">The result.</param>
/// <returns>The switch statement.</returns>
public static ISwitch<TSource, TResult> Case<TSource, TResult>(this ISwitch<TSource, TResult> currentSwitch, Expression<Func<TSource, bool>> condition, Expression<Func<TSource, TResult>> result)
{
return currentSwitch.AddCase(new SwitchCase<TSource, TResult>(condition, result));
}
/// <summary>
/// Sets the default case for the current switch statement.
/// </summary>
/// <typeparam name="TSource">The type of the source.</typeparam>
/// <typeparam name="TResult">The type of the result.</typeparam>
/// <param name="currentSwitch">The current switch.</param>
/// <param name="result">The result.</param>
/// <returns>The switch statement.</returns>
public static ISwitch<TSource, TResult> Default<TSource, TResult>(this ISwitch<TSource, TResult> currentSwitch, TResult result)
{
return currentSwitch.Default(i => result);
}
/// <summary>
/// Sets the default case for the current switch statement.
/// </summary>
/// <typeparam name="TSource">The type of the source.</typeparam>
/// <typeparam name="TResult">The type of the result.</typeparam>
/// <param name="currentSwitch">The current switch.</param>
/// <param name="result">The result.</param>
/// <returns>The switch statement.</returns>
public static ISwitch<TSource, TResult> Default<TSource, TResult>(this ISwitch<TSource, TResult> currentSwitch, Expression<Func<TSource, TResult>> result)
{
return currentSwitch.AddCase(new SwitchDefault<TSource, TResult>(result));
}
#endregion
/// <summary>
/// Ends the switch.
/// </summary>
/// <typeparam name="TSource">The type of the source.</typeparam>
/// <typeparam name="TResult">The type of the result.</typeparam>
/// <param name="currentSwitch">The current switch.</param>
/// <returns></returns>
public static IBindable<TResult> EndSwitch<TSource, TResult>(this ISwitch<TSource, TResult> currentSwitch)
{
return currentSwitch as IBindable<TResult>;
}
private static bool AreEqual(object lhs, object rhs)
{
return lhs == null ? rhs == null :
rhs == null ? false : lhs.Equals(rhs);
}
}
}
|
/*
Copyright (c) 2010, Direct Project
All rights reserved.
Authors:
Umesh Madan umeshma@microsoft.com
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
Neither the name of The Direct Project (directproject.org) nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Net.Mail;
using Health.Direct.Common.Extensions;
namespace Health.Direct.Config.Store
{
/// <summary>
/// Used to manage configured addresses
/// </summary>
public class AddressManager : IEnumerable<Address>
{
readonly ConfigStore m_store;
internal AddressManager(ConfigStore store)
{
m_store = store;
}
internal ConfigStore Store
{
get
{
return m_store;
}
}
/// <summary>
/// Add a new email address
/// </summary>
/// <remarks>
/// - Gets the domain of the address and ensures that it exists
/// - Then tries to create an entry in the Address table
/// - The address is created with EntityStatus.New
/// - To use the address, you must enable it
/// </remarks>
/// <param name="mailAddress">Mail address object</param>
public void Add(MailAddress mailAddress)
{
this.Add(mailAddress, EntityStatus.New, "SMTP");
}
/// <summary>
/// Add a new email address
/// </summary>
/// <remarks>
/// - Gets the domain of the address and ensures that it exists
/// - Then tries to create an entry in the Address table
/// - The address is created in the given state
/// </remarks>
/// <param name="mailAddress">Mail address object</param>
/// <param name="status">entity status</param>
/// <param name="addressType"></param>
public void Add(MailAddress mailAddress, EntityStatus status, string addressType)
{
if (mailAddress == null)
{
throw new ArgumentNullException("mailAddress");
}
using(ConfigDatabase db = this.Store.CreateContext())
{
this.Add(db, mailAddress, status, addressType);
db.SubmitChanges();
}
}
/// <summary>
/// Add a new email address within the given database context
/// The operation is performed within any transactions in the context
/// </summary>
/// <remarks>
/// - Gets the domain of the address and ensures that it exists
/// - Then tries to create an entry in the Address table
/// - The address is created in the given state
/// </remarks>
/// <param name="db">db context</param>
/// <param name="mailAddress">Mail address object</param>
/// <param name="status">entity status</param>
/// <param name="addressType"></param>
public void Add(ConfigDatabase db, MailAddress mailAddress, EntityStatus status, string addressType)
{
if (db == null)
{
throw new ArgumentNullException("db");
}
if (mailAddress == null)
{
throw new ArgumentNullException("mailAddress");
}
Domain domain = this.Store.Domains.Get(db, mailAddress.Host);
if (domain == null)
{
throw new ConfigStoreException(ConfigStoreError.InvalidDomain);
}
Address address = new Address(domain.ID, mailAddress) {Type = addressType, Status = status};
this.Add(db, address);
}
/// <summary>
/// Add an address to the store
/// </summary>
/// <param name="address">address object</param>
public Address Add(Address address)
{
using (ConfigDatabase db = this.Store.CreateContext())
{
this.Add(db, address);
db.SubmitChanges();
return address;
}
}
/// <summary>
/// Add a set of addresses to the store in a single transaction
/// </summary>
/// <param name="addresses">address set</param>
public void Add(IEnumerable<Address> addresses)
{
if (addresses == null)
{
throw new ArgumentNullException("addresses");
}
using (ConfigDatabase db = this.Store.CreateContext())
{
foreach(Address address in addresses)
{
this.Add(db, address);
}
db.SubmitChanges();
}
}
/// <summary>
/// Add an address to the database using the given database context
/// The address will be added within the context's currently active transaction
/// </summary>
/// <param name="db">database context to use</param>
/// <param name="address">address object</param>
public void Add(ConfigDatabase db, Address address)
{
if (db == null)
{
throw new ArgumentNullException("db");
}
if (address == null)
{
throw new ConfigStoreException(ConfigStoreError.InvalidAddress);
}
if (!address.IsValidMailAddress())
{
throw new ConfigStoreException(ConfigStoreError.InvalidAddress);
}
db.Addresses.InsertOnSubmit(address);
}
public void Update(Address address)
{
using (ConfigDatabase db = this.Store.CreateContext())
{
this.Update(db, address);
db.SubmitChanges();
}
}
public void Update(IEnumerable<Address> addresses)
{
if (addresses == null)
{
throw new ArgumentNullException("addresses");
}
using (ConfigDatabase db = this.Store.CreateContext())
{
foreach(Address address in addresses)
{
this.Update(db, address);
}
db.SubmitChanges();
}
}
void Update(ConfigDatabase db, Address address)
{
if (db == null)
{
throw new ArgumentNullException("db");
}
if (address == null)
{
throw new ConfigStoreException(ConfigStoreError.InvalidAddress);
}
if (!address.IsValidMailAddress())
{
throw new ConfigStoreException(ConfigStoreError.InvalidAddress);
}
Address update = new Address();
update.CopyFixed(address);
db.Addresses.Attach(update);
update.ApplyChanges(address);
}
public int Count(long domainID)
{
using (ConfigDatabase db = this.Store.CreateReadContext())
{
return db.Addresses.GetCount(domainID);
}
}
public Address[] GetAllForDomain(string domainName
, int maxResults)
{
using (ConfigDatabase db = this.Store.CreateReadContext())
{
return this.GetAllForDomain(db
, domainName
, maxResults).ToArray();
}
}
public IEnumerable<Address> GetAllForDomain(ConfigDatabase db
, string domainName
, int maxResults)
{
if (db == null)
{
throw new ArgumentNullException("db");
}
return db.Addresses.ExecGetByDomainName(domainName, maxResults);
}
public Address Get(string emailAddress)
{
using(ConfigDatabase db = this.Store.CreateReadContext())
{
return this.Get(db, emailAddress);
}
}
public Address Get(ConfigDatabase db, string emailAddress)
{
if (db == null)
{
throw new ArgumentNullException("db");
}
return db.Addresses.Get(emailAddress);
}
public Address[] Get(string[] emailAddresses)
{
return this.Get(emailAddresses, false, null);
}
public Address[] Get(string[] emailAddresses, bool domainSearchEnabled)
{
return this.Get(emailAddresses, domainSearchEnabled, null);
}
public IEnumerable<Address> Get(ConfigDatabase db, string[] emailAddresses)
{
return this.Get(db, emailAddresses, null);
}
public Address[] Get(string[] emailAddresses, EntityStatus? status)
{
return Get(emailAddresses, false, status);
}
public Address[] Get(string[] emailAddresses, bool domainSearchEnabled, EntityStatus? status)
{
using (ConfigDatabase db = this.Store.CreateReadContext())
{
Address[] addresses = this.Get(db, emailAddresses, status).ToArray();
if (domainSearchEnabled)
{
List<Address> addressList = new List<Address>();
foreach (var emailAddress in emailAddresses)
{
string enclosureEmailAddress = emailAddress;
Address existingAddress = addresses.SingleOrDefault(a => a.EmailAddress.Equals(enclosureEmailAddress, StringComparison.OrdinalIgnoreCase));
if (existingAddress != null)
{
addressList.Add(existingAddress);
continue;
}
AutoMapDomains(enclosureEmailAddress, addressList, status);
}
return addressList.ToArray();
}
return addresses;
}
}
private void AutoMapDomains(string enclosureEmailAddress, List<Address> addressList, EntityStatus? status)
{
MailAddress mailAddress = new MailAddress(enclosureEmailAddress);
Domain domain = Store.Domains.Get(mailAddress.Host);
if (domain == null ||
(status.HasValue && domain.Status != status)
) return;
var address = new Address(domain.ID, mailAddress);
address.Type = "SMTP";
address.Status = domain.Status;
addressList.Add(address);
}
public IEnumerable<Address> Get(ConfigDatabase db, string[] emailAddresses, EntityStatus? status)
{
if (db == null)
{
throw new ArgumentNullException("db");
}
this.VerifyEmailAddresses(emailAddresses);
if (status == null)
{
return db.Addresses.Get(emailAddresses);
}
return db.Addresses.Get(emailAddresses, status.Value);
}
public Address[] Get(string lastAddressID, int maxResults)
{
using (ConfigDatabase db = this.Store.CreateReadContext())
{
return this.Get(db, lastAddressID, maxResults).ToArray();
}
}
public IEnumerable<Address> Get(ConfigDatabase db, string lastAddressID, int maxResults)
{
if (db == null)
{
throw new ArgumentNullException("db");
}
return db.Addresses.ExecGet(lastAddressID, maxResults);
}
public Address[] Get(long domainID, string lastAddressID, int maxResults)
{
using (ConfigDatabase db = this.Store.CreateReadContext())
{
return this.Get(db, domainID, lastAddressID, maxResults).ToArray();
}
}
public IEnumerable<Address> Get(ConfigDatabase db, long domainID, string lastAddressID, int maxResults)
{
if (db == null)
{
throw new ArgumentNullException("db");
}
return db.Addresses.ExecGet(domainID, lastAddressID, maxResults);
}
public Address[] Get(long[] addressIDs)
{
return this.Get(addressIDs, null);
}
public IEnumerable<Address> Get(ConfigDatabase db, long[] addressIDs)
{
return this.Get(db, addressIDs, null);
}
public Address[] Get(long[] addressIDs, EntityStatus? status)
{
using (ConfigDatabase db = this.Store.CreateReadContext())
{
return this.Get(db, addressIDs, status).ToArray();
}
}
public IEnumerable<Address> Get(ConfigDatabase db, long[] addressIDs, EntityStatus? status)
{
if (db == null)
{
throw new ArgumentNullException("db");
}
if (status == null)
{
return db.Addresses.Get(addressIDs);
}
return db.Addresses.Get(addressIDs, status.Value);
}
public Address Get(long addressID)
{
using(ConfigDatabase db = this.Store.CreateReadContext())
{
return this.Get(db, addressID);
}
}
public Address Get(ConfigDatabase db, long addressID)
{
if (db == null)
{
throw new ArgumentNullException("db");
}
return db.Addresses.Get(addressID);
}
public void Remove(string emailAddress)
{
using(ConfigDatabase db = this.Store.CreateContext())
{
this.Remove(db, emailAddress);
}
}
public void Remove(ConfigDatabase db, string emailAddress)
{
if (string.IsNullOrEmpty(emailAddress))
{
throw new ConfigStoreException(ConfigStoreError.InvalidEmailAddress);
}
db.Addresses.ExecDelete(emailAddress);
}
public void Remove(IEnumerable<string> emailAddresses)
{
using (ConfigDatabase db = this.Store.CreateContext())
{
foreach(string emailAddress in emailAddresses)
{
this.Remove(db, emailAddress);
}
}
}
public void RemoveDomain(long domainID)
{
using (ConfigDatabase db = this.Store.CreateContext())
{
this.RemoveDomain(db, domainID);
}
}
public void RemoveDomain(ConfigDatabase db, long domainID)
{
db.Addresses.ExecDeleteDomain(domainID);
}
public void SetStatus(long domainID, EntityStatus status)
{
using (ConfigDatabase db = this.Store.CreateContext())
{
db.Addresses.ExecSetStatus(domainID, status);
}
}
void VerifyEmailAddresses(string[] emailAddresses)
{
if (emailAddresses.IsNullOrEmpty())
{
throw new ConfigStoreException(ConfigStoreError.InvalidEmailAddress);
}
for (int i = 0; i < emailAddresses.Length; ++i)
{
if (string.IsNullOrEmpty(emailAddresses[i]))
{
throw new ConfigStoreException(ConfigStoreError.InvalidEmailAddress);
}
}
}
public IEnumerator<Address> GetEnumerator()
{
using (ConfigDatabase db = this.Store.CreateContext())
{
foreach (Address address in db.Addresses)
{
yield return address;
}
}
}
#region IEnumerable Members
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return this.GetEnumerator();
}
#endregion
}
} |
using OrderProject.Context;
using OrderProject.Models;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using System.Text;
namespace OrderProject.Repository
{
class OrderRepository
{
private OrderContext _context;
public OrderRepository(OrderContext context)
{
_context = context;
}
public void Add(Order item)
{
using (OrderContext db = new OrderContext())
{
db.Add(item);
db.SaveChanges();
}
}
//Get all the records
public IEnumerable<Order> GetAll()
{
return _context.Orders;
}
//Get by ID
public Order GetById(object id)
{
return _context.Orders.Find(id);
}
//delete Students by id
//public void delete(int id)
//{
// var obj = _context.Students.Find(id);
// _context.Students.Remove(obj);
// _context.SaveChanges();
//}
public void update(Order item)
{
var obj = _context.Orders.Find(item.Orderid);
obj.DDate = item.DDate;
_context.SaveChanges();
}
}
}
|
namespace Standard
{
using System;
using System.Runtime.InteropServices;
[ComImport, Guid("71e806fb-8dee-46fc-bf8c-7748a8a1ae13"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
internal interface IObjectWithProgId
{
void SetProgID([MarshalAs(UnmanagedType.LPWStr)] string pszProgID);
[return: MarshalAs(UnmanagedType.LPWStr)]
string GetProgID();
}
}
|
using System;
using System.Collections.Generic;
public class Program
{
public static void Main()
{
var input = Console.ReadLine().Split();
var minWord = input[0].Length > input[1].Length ? input[1] : input[0];
var maxWord = input[0].Length > input[1].Length ? input[0] : input[1];
var usedCharactersDictionary = new Dictionary<char, char>();
var canExchange = true;
for (int i = 0; i < minWord.Length; i++)
{
var minWordChar = minWord[i];
var maxWordChar = maxWord[i];
if (!usedCharactersDictionary.ContainsKey(minWordChar))
{
if (!usedCharactersDictionary.ContainsValue(maxWordChar))
{
usedCharactersDictionary[minWordChar] = maxWordChar;
}
else
{
canExchange = false;
break;
}
}
else
{
if (usedCharactersDictionary[minWordChar] != maxWordChar)
{
canExchange = false;
break;
}
}
}
if (minWord.Length != maxWord.Length && canExchange)
{
var remainingChars = maxWord.Substring(minWord.Length);
foreach (var remainingChar in remainingChars)
{
if (!usedCharactersDictionary.ContainsKey(remainingChar) && !usedCharactersDictionary.ContainsValue(remainingChar))
{
canExchange = false;
break;
}
}
}
Console.WriteLine(canExchange.ToString().ToLower());
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ModelMVPDataBasePart.IModels
{
public interface IMainIModel
{
object GetMainView(IMainFormData DBOperational);
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using CommonTypes;
using CommonTypes.NameRegistry;
using CommonTypes.Transactions;
using ServerLib;
using ServerLib.Storage;
using ServerLib.Transactions;
namespace Server
{
internal class Server : MarshalByRefObject, IServer, IPartitipantProxy
{
private const int HeartbeatTime = 10000;
private readonly Dictionary<int, bool> _faultDetection;
private readonly int _parent;
private readonly IParticipant _participant;
private readonly int _serverId;
private bool _isFrozen;
private bool _isSplitLocked;
private int _serverCount;
private Timer _timerReference;
private bool _timerRunning;
private int _version;
public Server(ServerInit serverInit)
{
_serverId = serverInit.Uuid;
_serverCount = serverInit.ServerCount;
_participant = new Participant(_serverId, new KeyValueStorage());
_version = serverInit.Version;
_isSplitLocked = false;
StartHearthBeat();
_parent = serverInit.Parent;
_faultDetection = serverInit.FaultDetection;
}
public void DumpState()
{
_participant.DumpState();
}
public bool Status()
{
Console.WriteLine("########## STATE DUMP ##########");
Console.WriteLine("[Server: {0}] Version: {1} | OK: {2}", _serverId, _version, !_isFrozen);
_participant.DumpState();
Console.WriteLine("################################");
return !_isFrozen;
}
public bool Fail()
{
Environment.Exit(0);
return true;
}
public bool Freeze()
{
StopHearthBeat();
return _isFrozen = true;
}
public bool Recover()
{
lock (this)
{
_isFrozen = false;
StartHearthBeat();
Monitor.PulseAll(this);
}
return true;
}
public int ReadValue(int version, int txid, int key)
{
WaitIfFrozen();
WaitIfSplitLocked();
if (_version > version)
{
throw new WrongVersionException();
}
if (!ConsistentHashCalculator.IsMyPadInt(_serverCount, key, _serverId) &&
CheckServer(ConsistentHashCalculator.GetServerIdForPadInt(_serverCount, key)))
{
throw new WrongVersionException();
}
int value = _participant.ReadValue(txid, key);
try
{
GetReplica().ReadThrough(version, txid, key);
}
catch
{
}
return value;
}
public void ReadThrough(int version, int txid, int key)
{
WaitIfFrozen();
WaitIfSplitLocked();
_participant.ReadValue(txid, key);
}
public void WriteValue(int version, int txid, int key, int value)
{
WaitIfFrozen();
WaitIfSplitLocked();
if (_version > version)
{
throw new WrongVersionException();
}
if (!ConsistentHashCalculator.IsMyPadInt(_serverCount, key, _serverId) &&
CheckServer(ConsistentHashCalculator.GetServerIdForPadInt(_serverCount, key)))
{
return;
}
_participant.WriteValue(txid, key, value);
try
{
GetReplica().WriteThrough(version, txid, key, value);
}
catch
{
}
}
public void WriteThrough(int version, int txid, int key, int value)
{
WaitIfFrozen();
WaitIfSplitLocked();
_participant.WriteValue(txid, key, value);
}
public void PrepareTransaction(int txid)
{
WaitIfFrozen();
WaitIfSplitLocked();
_participant.PrepareTransaction(txid);
}
public void CommitTransaction(int txid)
{
WaitIfFrozen();
WaitIfSplitLocked();
_participant.CommitTransaction(txid);
}
public void AbortTransaction(int txid)
{
WaitIfFrozen();
WaitIfSplitLocked();
_participant.AbortTransaction(txid);
}
public ParticipantStatus OnChild(int uid, int version, int serverCount)
{
WaitIfFrozen();
if (_faultDetection.Count > 0 && _faultDetection.Keys.Max() < uid)
{
foreach (int fd in _faultDetection.Keys)
{
if (uid != fd)
{
var server = (IServer) Activator.GetObject(typeof (IServer), Config.GetServerUrl(fd));
server.RemoveFaultDetection(_serverId);
var master = (IMainServer) Activator.GetObject(typeof (IMainServer), Config.RemoteMainserverUrl);
master.RemoveFaultDetection(fd, _serverId);
}
}
}
else if (_faultDetection.Count == 0 && _parent != -1)
{
var server = (IServer) Activator.GetObject(typeof (IServer), Config.GetServerUrl(_parent));
server.RemoveFaultDetection(_serverId);
var master = (IMainServer) Activator.GetObject(typeof (IMainServer), Config.RemoteMainserverUrl);
master.RemoveFaultDetection(_parent, _serverId);
}
_faultDetection[uid] = true;
_serverCount = serverCount;
_version = version;
return _participant.GetStatus();
}
public void OnFaultDetectionDeath(int deadId)
{
WaitIfFrozen();
if (_faultDetection.ContainsKey(deadId))
{
_faultDetection[deadId] = false;
}
}
public void OnFaultDetectionReborn(int deadId)
{
WaitIfFrozen();
if (_faultDetection.ContainsKey(deadId))
{
_faultDetection[deadId] = true;
}
}
public void StartSplitLock()
{
_isSplitLocked = true;
}
public void EndSplitLock()
{
lock (this)
{
_isSplitLocked = false;
Monitor.PulseAll(this);
}
}
public bool AreYouAlive()
{
WaitIfFrozen();
Console.WriteLine("[Server:{0}] I'm Alive" + DateTime.Now, _serverId);
return true;
}
public void RemoveFaultDetection(int uid)
{
if (_faultDetection.ContainsKey(uid))
{
_faultDetection.Remove(uid);
var mainServer = (IMainServer) Activator.GetObject(typeof (IMainServer), Config.RemoteMainserverUrl);
mainServer.RemoveFaultDetection(_serverId, uid);
}
}
public void SetStatus(ParticipantStatus storage)
{
_participant.SetStatus(storage);
}
private void WaitIfFrozen()
{
lock (this)
{
if (_isFrozen)
{
Monitor.Wait(this);
}
}
}
private void WaitIfSplitLocked()
{
lock (this)
{
if (_isSplitLocked)
{
Monitor.Wait(this);
}
}
}
private IServer GetReplica()
{
if (_faultDetection.Count > 0)
{
int backup = _faultDetection.Keys.Max();
if (_faultDetection[backup])
{
return (IServer) Activator.GetObject(typeof (IServer), Config.GetServerUrl(backup));
}
}
throw new NoReplicationAvailableException();
}
private void TimerTask(Object server)
{
if (!_timerRunning)
{
Console.WriteLine("Killing ping service ... " + DateTime.Now);
_timerReference.Dispose();
return;
}
if (_faultDetection.Count > 0)
{
foreach (var faultDetection in _faultDetection.ToList())
{
if (!faultDetection.Value)
{
continue;
}
CheckServer(faultDetection.Key);
}
}
else
{
Console.WriteLine("Nobody to ping ... " + DateTime.Now, _parent);
}
}
private bool CheckServer(int serverUid)
{
try
{
Console.WriteLine("Sending ping to server:{0} ... " + DateTime.Now, serverUid);
var backupServer = (IServer) Activator.GetObject(typeof (IServer), Config.GetServerUrl(serverUid));
backupServer.AreYouAlive();
}
catch
{
Console.WriteLine("Ping to server:{0} failed ... " + DateTime.Now, serverUid);
var mainServer = (IMainServer) Activator.GetObject(typeof (IMainServer), Config.RemoteMainserverUrl);
OnFaultDetectionDeath(serverUid);
mainServer.ReportDead(_serverId, serverUid);
return false;
}
return true;
}
private void StartHearthBeat()
{
_timerRunning = true;
_timerReference = new Timer(TimerTask, this, HeartbeatTime, HeartbeatTime);
}
private void StopHearthBeat()
{
_timerRunning = false;
}
}
} |
using System;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Application.Interfaces;
using AutoMapper;
using Domain;
using MediatR;
using Microsoft.AspNetCore.Hosting;
using Microsoft.EntityFrameworkCore;
using Persistence;
namespace Application.User
{
public class CurrentUser
{
public class Query : IRequest<UserResource> { }
public class Handler : IRequestHandler<Query, UserResource>
{
private readonly IUserAccessor _userAccessor;
private readonly DataContext _context;
private readonly IMapper _mapper;
private readonly IHostingEnvironment _hostingEnvironment;
private readonly IJwtGenerator _jwtGenerator;
public Handler(DataContext context, IUserAccessor userAccessor, IMapper mapper, IHostingEnvironment hostingEnvironment, IJwtGenerator jwtGenerator)
{
_jwtGenerator = jwtGenerator;
_userAccessor = userAccessor;
_context = context;
_mapper = mapper;
_hostingEnvironment = hostingEnvironment;
}
public async Task<UserResource> Handle(Query request, CancellationToken cancellationToken)
{
var env = _hostingEnvironment.EnvironmentName;
var root = env == "Development" ? _hostingEnvironment.ContentRootPath + "\\images" : _hostingEnvironment.WebRootPath;
var user = await _context.Users.SingleOrDefaultAsync(x => x.UserName == _userAccessor.GetCurrentUsername());
var ret = _mapper.Map<AppUser, UserResource>(user);
ret.Token = _jwtGenerator.CreateToken(new AppUser { UserName = user.UserName });
string path = $"{root}\\profile.png";
byte[] b = System.IO.File.ReadAllBytes(path);
ret.Photo = "data:image/png;base64," + (user.Photo == null ? Convert.ToBase64String(b) : Convert.ToBase64String(user.Photo));
return ret;
}
}
}
} |
using Logs.Data.Contracts;
using Logs.Models;
using Moq;
using NUnit.Framework;
namespace Logs.Services.Tests.UserServiceTests
{
[TestFixture]
public class ChangeProfilePictureTests
{
[TestCase("d547a40d-c45f-4c43-99de-0bfe9199ff95", "https://picturethismaths.files.wordpress.com/2016/03/fig6bigforblog.png?w=419&h=364")]
public void TestEditUser_ShouldCallRepositoryGetById(string userId,
string imageUrl)
{
// Arrange
var mockedRepository = new Mock<IRepository<User>>();
var mockedUnitOfWork = new Mock<IUnitOfWork>();
var service = new UserService(mockedRepository.Object, mockedUnitOfWork.Object);
// Act
service.ChangeProfilePicture(userId, imageUrl);
// Assert
mockedRepository.Verify(r => r.GetById(userId), Times.Once);
}
[TestCase("d547a40d-c45f-4c43-99de-0bfe9199ff95", "https://picturethismaths.files.wordpress.com/2016/03/fig6bigforblog.png?w=419&h=364")]
public void TestEditUser_RepositoryReturnsNull_ShouldNotCallUnitOfWorkCommit(string userId,
string imageUrl)
{
// Arrange
var mockedRepository = new Mock<IRepository<User>>();
var mockedUnitOfWork = new Mock<IUnitOfWork>();
var service = new UserService(mockedRepository.Object, mockedUnitOfWork.Object);
// Act
service.ChangeProfilePicture(userId, imageUrl);
// Assert
mockedUnitOfWork.Verify(u => u.Commit(), Times.Never);
}
[TestCase("d547a40d-c45f-4c43-99de-0bfe9199ff95", "https://picturethismaths.files.wordpress.com/2016/03/fig6bigforblog.png?w=419&h=364")]
public void TestEditUser_RepositoryReturnsUser_ShouldSetUserDescriptionCorrectly(string userId,
string imageUrl)
{
// Arrange
var user = new User();
var mockedRepository = new Mock<IRepository<User>>();
mockedRepository.Setup(r => r.GetById(It.IsAny<object>())).Returns(user);
var mockedUnitOfWork = new Mock<IUnitOfWork>();
var service = new UserService(mockedRepository.Object, mockedUnitOfWork.Object);
// Act
service.ChangeProfilePicture(userId, imageUrl);
// Assert
Assert.AreEqual(imageUrl, user.ProfileImageUrl);
}
[TestCase("d547a40d-c45f-4c43-99de-0bfe9199ff95", "https://picturethismaths.files.wordpress.com/2016/03/fig6bigforblog.png?w=419&h=364")]
public void TestEditUser_RepositoryReturnsUser_ShouldCallRepositoryUpdateCorrectly(string userId,
string imageUrl)
{
// Arrange
var user = new User();
var mockedRepository = new Mock<IRepository<User>>();
mockedRepository.Setup(r => r.GetById(It.IsAny<object>())).Returns(user);
var mockedUnitOfWork = new Mock<IUnitOfWork>();
var service = new UserService(mockedRepository.Object, mockedUnitOfWork.Object);
// Act
service.ChangeProfilePicture(userId, imageUrl);
// Assert
mockedRepository.Verify(r => r.Update(user), Times.Once);
}
[TestCase("d547a40d-c45f-4c43-99de-0bfe9199ff95", "https://picturethismaths.files.wordpress.com/2016/03/fig6bigforblog.png?w=419&h=364")]
public void TestEditUser_RepositoryReturnsUser_ShouldCallUnitOfWorkCommit(string userId,
string imageUrl)
{
// Arrange
var user = new User();
var mockedRepository = new Mock<IRepository<User>>();
mockedRepository.Setup(r => r.GetById(It.IsAny<object>())).Returns(user);
var mockedUnitOfWork = new Mock<IUnitOfWork>();
var service = new UserService(mockedRepository.Object, mockedUnitOfWork.Object);
// Act
service.ChangeProfilePicture(userId, imageUrl);
// Assert
mockedUnitOfWork.Verify(u => u.Commit(), Times.Once);
}
}
}
|
using System.Text;
using System;
using System.Collections.Generic;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json;
using System.Net.Http;
using System.Drawing;
using System.Collections.ObjectModel;
using System.Xml;
using System.ComponentModel;
using System.Reflection;
namespace LinnworksAPI
{
public class PurchaseOrderHeader
{
public Guid pkPurchaseID;
public Guid fkSupplierId;
public Guid fkLocationId;
public String ExternalInvoiceNumber;
public PurchaseOrderStatus Status;
public String Currency;
public String SupplierReferenceNumber;
public Boolean Locked;
public Int32 LineCount;
public Int32 DeliveredLinesCount;
public DateTime DateOfPurchase;
public DateTime DateOfDelivery;
public DateTime QuotedDeliveryDate;
public Decimal PostagePaid;
public Decimal TotalCost;
public Decimal taxPaid;
public Decimal ShippingTaxRate;
public Decimal ConversionRate;
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DIDemo
{
internal interface IUserBiz
{
//检查用户名和密码是否匹配
public bool CheckLogin(string userName, string password);
}
}
|
//using LiteDB;
//namespace TreeStore.LiteDb
//{
// public sealed class LiteRepositoryAdapater
// {
// public LiteRepositoryAdapater(LiteRepository liteDb)
// {
// this.LiteRepository = liteDb;
// this.Entities = this.LiteRepository.Database.GetCollection("entities");
// this.Tags = this.LiteRepository.Database.GetCollection("tags");
// this.Categories = this.LiteRepository.Database.GetCollection("categories");
// }
// public LiteRepository LiteRepository { get; }
// public LiteCollection<BsonDocument> Entities { get; }
// public LiteCollection<BsonDocument> Tags { get; }
// public LiteCollection<BsonDocument> Categories { get; }
// }
//} |
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace CaseConverter
{
class Program
{
static void Main(string[] args)
{
//Get all excel files from current folder
List<string> files = Utility.GetExcelFiles();
//Create a new folder 'Output', if exist, skip
string folderName = "Output";
string outputFolder = Path.Combine(Application.StartupPath, folderName);
if (!Directory.Exists(outputFolder))
{
Directory.CreateDirectory(outputFolder);
}
//Open each one by one, select * from sheet1 where type <> 'C' and action <> 'wait'
DataTable outputData = new DataTable();
files.ForEach(f =>
{
Utility.AddLog(string.Format("Open {0}", f));
//f is the full filepath and name
//read file to DataTable
DataTable inputMetadata = Utility.ReadInputFile(f);
//Translate into human language, store in outputData
outputData = Utility.TranslateIntoHumanLanguage(inputMetadata);
//Create new excel and insert the data
Utility.CreateOutputFiles(outputData, outputFolder);
Utility.AddLog(string.Format("Complete {0}", f));
});
}
}
}
|
namespace Bridge.RealWorld
{
/// <summary>
/// The remote control.
/// </summary>
class RemoteControl
{
/// <summary>
/// The device.
/// </summary>
protected IDevice device;
/// <summary>
/// Initializes a new instance of the <see cref="RemoteControl"/> class.
/// </summary>
/// <param name="device">The device.</param>
public RemoteControl(IDevice device)
{
this.device = device;
}
/// <summary>
/// Toggles the power.
/// </summary>
public void TogglePower()
{
if (device.IsEnabled)
{
device.Disable();
}
else
{
device.Enable();
}
}
/// <summary>
/// Volumes down.
/// </summary>
public void VolumeDown()
{
this.device.SetVolume(device.GetVolume() - 10);
}
/// <summary>
/// Volumes up.
/// </summary>
public void VolumeUp()
{
this.device.SetVolume(device.GetVolume() + 10);
}
/// <summary>
/// Channels down.
/// </summary>
public void ChannelDown()
{
this.device.SetChannel(this.device.GetChannel() - 1);
}
/// <summary>
/// Channels up.
/// </summary>
public void ChannelUp()
{
this.device.SetChannel(this.device.GetChannel() + 1);
}
}
} |
using System.Diagnostics;
using TinyIoC;
namespace Kit
{
public partial class Tools
{
public static bool IsInited => currentInstance != null;
public static void Set(AbstractTools Instance)
{
currentInstance = Instance;
}
private static AbstractTools currentInstance;
public static AbstractTools Instance
{
get
{
if (currentInstance == null)
{
return null;
}
//throw new ArgumentException("Please Init Plugin.Xamarin.Tools before using it");
return currentInstance;
}
set => currentInstance = value;
}
public static TinyIoCContainer Container => TinyIoC.TinyIoCContainer.Current;
private static bool? _Debugging = null;
public static bool Debugging => _Debugging ?? Debugger.IsAttached;
public static bool SetDebugging(bool? debugging = null)
{
Tools._Debugging = debugging;
return Debugging;
}
protected static void BaseInit()
{
if (Tools.Instance.RuntimePlatform != Enums.RuntimePlatform.WPF)
{
DirectoryInfo TempDirectory = new DirectoryInfo(Instance.TemporalPath);
if (!TempDirectory.Exists)
{
TempDirectory.Create();
}
}
}
}
} |
using Microsoft.VisualStudio.TestTools.UnitTesting;
using otus_architecture_lab_8;
namespace UnitTestProject1
{
[TestClass]
public class UnitTest1
{
#region Nested classes
class LoggerMock : ILogger
{
public void Dispose() {}
public void Log(string message)
{
LastMessage = message;
}
public string LastMessage = null;
}
#endregion
#region Tests
[TestMethod]
public void FileParserXmlTest()
{
LoggerMock logger = new LoggerMock();
SimpleServiceLocator.Instance.RegisterService<ILogger>(logger);
FileParserXml p = new FileParserXml();
p.Handle("test.xml");
Assert.IsTrue(logger.LastMessage.Contains("FileParserXml parce"));
p.Handle("test.obj");
Assert.IsTrue(logger.LastMessage.Contains("Can't parce file"));
SimpleServiceLocator.Instance.Dispose();
}
[TestMethod]
public void FileParserTxtTest()
{
LoggerMock logger = new LoggerMock();
SimpleServiceLocator.Instance.RegisterService<ILogger>(logger);
FileParserTxt p = new FileParserTxt();
p.Handle("test.txt");
Assert.IsTrue(logger.LastMessage.Contains("FileParserTxt parce"));
p.Handle("test.obj");
Assert.IsTrue(logger.LastMessage.Contains("Can't parce file"));
SimpleServiceLocator.Instance.Dispose();
}
[TestMethod]
public void FileParserCsvTest()
{
LoggerMock logger = new LoggerMock();
SimpleServiceLocator.Instance.RegisterService<ILogger>(logger);
FileParserCsv p = new FileParserCsv();
p.Handle("test.csv");
Assert.IsTrue(logger.LastMessage.Contains("FileParserCsv parce"));
p.Handle("test.obj");
Assert.IsTrue(logger.LastMessage.Contains("Can't parce file"));
SimpleServiceLocator.Instance.Dispose();
}
[TestMethod]
public void FileParserJsonTest()
{
LoggerMock logger = new LoggerMock();
SimpleServiceLocator.Instance.RegisterService<ILogger>(logger);
FileParserJson p = new FileParserJson();
p.Handle("test.json");
Assert.IsTrue(logger.LastMessage.Contains("FileParserJson parce"));
p.Handle("test.obj");
Assert.IsTrue(logger.LastMessage.Contains("Can't parce file"));
SimpleServiceLocator.Instance.Dispose();
}
#endregion
}
}
|
#if NET40
using System;
using System.Collections.Generic;
using System.Reflection;
using static yocto.Preconditions;
namespace yocto
{
internal class TypeInfo
{
private readonly Type _type;
public TypeInfo(Type type)
{
CheckIsNotNull(nameof(type), type);
_type = type;
}
public string Name
{
get
{
return _type.Name;
}
}
public Type AsType()
{
return _type;
}
public IEnumerable<ConstructorInfo> DeclaredConstructors()
{
return _type.GetConstructors();
}
}
}
#endif |
using System;
using System.Diagnostics;
using System.IO;
using System.IO.Pipelines;
using System.Threading;
using System.Threading.Tasks;
namespace Koek
{
/// <summary>
/// Allows us to observe when Complete() is called.
/// </summary>
public sealed class InterceptingPipeReader : PipeReader
{
public Task ReaderCompleted => _readerCompleted.Task;
private readonly TaskCompletionSource<bool> _readerCompleted = new();
public InterceptingPipeReader(PipeReader reader)
{
_reader = reader;
}
private readonly PipeReader _reader;
public override void Complete(Exception? exception = null)
{
_reader.Complete(exception);
_readerCompleted.SetResult(true);
}
public override async ValueTask CompleteAsync(Exception? exception = null)
{
await _reader.CompleteAsync(exception);
_readerCompleted.SetResult(true);
}
[DebuggerStepThrough]
public override void AdvanceTo(SequencePosition consumed) => _reader.AdvanceTo(consumed);
[DebuggerStepThrough]
public override void AdvanceTo(SequencePosition consumed, SequencePosition examined) => _reader.AdvanceTo(consumed, examined);
[DebuggerStepThrough]
public override void CancelPendingRead() => _reader.CancelPendingRead();
[DebuggerStepThrough]
public override ValueTask<ReadResult> ReadAsync(CancellationToken cancellationToken = default) => _reader.ReadAsync(cancellationToken);
[DebuggerStepThrough]
public override bool TryRead(out ReadResult result) => _reader.TryRead(out result);
[DebuggerStepThrough]
public override Stream AsStream(bool leaveOpen = false) => _reader.AsStream(leaveOpen);
[DebuggerStepThrough]
public override Task CopyToAsync(PipeWriter destination, CancellationToken cancellationToken = default) => _reader.CopyToAsync(destination, cancellationToken);
[DebuggerStepThrough]
public override Task CopyToAsync(Stream destination, CancellationToken cancellationToken = default) => _reader.CopyToAsync(destination, cancellationToken);
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.Audio;
public class GlowneMenu : MonoBehaviour {
public void Graj(int numerPoziomu)
{
if(numerPoziomu == 1)
{
#pragma warning disable CS0618 // Type or member is obsolete
Application.LoadLevel("SpaceX");
#pragma warning restore CS0618 // Type or member is obsolete
}
else if(numerPoziomu == 2)
{
#pragma warning disable CS0618 // Type or member is obsolete
Application.LoadLevel("Ksiezyc");
#pragma warning restore CS0618 // Type or member is obsolete
}
else if (numerPoziomu == 3)
{
#pragma warning disable CS0618 // Type or member is obsolete
Application.LoadLevel("Awaria");
#pragma warning restore CS0618 // Type or member is obsolete
}
else if (numerPoziomu == 4)
{
#pragma warning disable CS0618 // Type or member is obsolete
Application.LoadLevel("SpaceX Demo");
#pragma warning restore CS0618 // Type or member is obsolete
}
}
public void QuitGame()
{
Debug.Log("wyjscie");
Application.Quit();
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ReturnVolume : MonoBehaviour
{
// Start is called before the first frame update
void Start()
{
AuidoScript.instance.Set_Volume("Marcha", 0.1f);
AuidoScript.instance.Set_Volume("Colecionables", 0f);
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace L2CapstoneProject
{
interface IBeamformer
{
void Connect();
void Disconnect();
}
interface ISequencedBeamformer : IBeamformer
{
void LoadSequence(string sequenceName);
void LoadSequence(string sequenceName, List<PhaseAmplitudeOffset> offsets);
void InitiateSequence(string sequenceName);
void AbortSequence();
}
interface ISteppedBeamformer : IBeamformer
{
void LoadOffset(PhaseAmplitudeOffset offset);
}
}
|
using System.ComponentModel;
using System.Runtime.CompilerServices;
using Bililive_dm.Annotations;
namespace Bililive_dm
{
public class SessionItem : INotifyPropertyChanged
{
private string _item;
private decimal _num;
private string _userName;
public string UserName
{
get => _userName;
set
{
if (value == _userName) return;
_userName = value;
OnPropertyChanged();
}
}
public string Item
{
get => _item;
set
{
if (value == _item) return;
_item = value;
OnPropertyChanged();
}
}
public decimal num
{
get => _num;
set
{
if (value == _num) return;
_num = value;
OnPropertyChanged();
}
}
public event PropertyChangedEventHandler PropertyChanged;
[NotifyPropertyChangedInvocator]
protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
} |
namespace AcceptanceTests.ServiceLocator
{
internal sealed class ServiceLocatorForTest
{
}
}
|
using BlazorIdentity.Server.Data;
using BlazorIdentity.Server.Models;
using BlazorIdentity.Server.Services;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Identity.UI.Services;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using OpenIddict.Abstractions;
using OpenIddict.Core;
using OpenIddict.EntityFrameworkCore.Models;
using System;
using System.Threading;
using System.Threading.Tasks;
using static OpenIddict.Abstractions.OpenIddictConstants;
namespace BlazorIdentity.Server
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
// For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<AppDbContext>(options =>
{
// Configure the context to use SQLite.
options.UseSqlite(Configuration.GetConnectionString("AppDbContextConnection"));
// Register the entity sets needed by OpenIddict.
// Note: use the generic overload if you need
// to replace the default OpenIddict entities.
options.UseOpenIddict();
});
services.AddIdentity<ApplicationUser, IdentityRole>(options =>
{
options.Password.RequireNonAlphanumeric = false;
options.Password.RequireUppercase = false;
// Add more password requirements ...
})
.AddEntityFrameworkStores<AppDbContext>()
.AddDefaultTokenProviders();
// Configure Identity to use the same JWT claims as OpenIddict instead
// of the legacy WS-Federation claims it uses by default (ClaimTypes),
// which saves you from doing the mapping in your authorization controller.
services.Configure<IdentityOptions>(options =>
{
options.ClaimsIdentity.UserNameClaimType = Claims.Name;
options.ClaimsIdentity.UserIdClaimType = Claims.Subject;
options.ClaimsIdentity.RoleClaimType = Claims.Role;
});
services.AddOpenIddict()
// Register the OpenIddict core components.
.AddCore(options =>
{
// Configure OpenIddict to use the Entity Framework Core stores and models.
// Note: call ReplaceDefaultEntities() to replace the default OpenIddict entities.
options.UseEntityFrameworkCore()
.UseDbContext<AppDbContext>();
})
// Register the OpenIddict server components.
.AddServer(options =>
{
// Enable the authorization, logout, token and userinfo endpoints.
options.SetAuthorizationEndpointUris("/connect/authorize")
.SetLogoutEndpointUris("/connect/logout")
.SetTokenEndpointUris("/connect/token")
.SetUserinfoEndpointUris("/connect/userinfo");
// Mark the "email", "profile" and "roles" scopes as supported scopes.
options.RegisterScopes(Scopes.Email, Scopes.Profile, Scopes.Roles);
// Note: the sample uses the code and refresh token flows but you can enable
// the other flows if you need to support implicit, password or client credentials.
options.AllowAuthorizationCodeFlow()
.AllowRefreshTokenFlow();
// Register the signing and encryption credentials.
options.AddDevelopmentEncryptionCertificate()
.AddDevelopmentSigningCertificate();
// Register the ASP.NET Core host and configure the ASP.NET Core-specific options.
options.UseAspNetCore()
.EnableAuthorizationEndpointPassthrough()
.EnableLogoutEndpointPassthrough()
.EnableStatusCodePagesIntegration()
.EnableTokenEndpointPassthrough();
})
// Register the OpenIddict validation components.
.AddValidation(options =>
{
// Import the configuration from the local OpenIddict server instance.
options.UseLocalServer();
// Register the ASP.NET Core host.
options.UseAspNetCore();
});
services.AddControllersWithViews();
services.AddRazorPages();
services.AddServerSideBlazor();
services.AddSingleton<IEmailSender, EmailSender>();
services.AddSingleton<WeatherForecastService>();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseDatabaseErrorPage();
//app.UseWebAssemblyDebugging(); // Enable for Blazor WASM
}
else
{
app.UseExceptionHandler("/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseHttpsRedirection();
//app.UseBlazorFrameworkFiles(); // Enable for Blazor WASM
app.UseStaticFiles();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapRazorPages();
endpoints.MapControllers();
endpoints.MapBlazorHub(); // Enable For Blazor Server only
endpoints.MapFallbackToPage("/_Host"); // Enable For Blazor Server only
//endpoints.MapFallbackToFile("index.html"); // Enable for Blazor WASM
});
InitializeAsync(app.ApplicationServices, CancellationToken.None).GetAwaiter().GetResult();
}
async Task InitializeAsync(IServiceProvider services, CancellationToken cancellationToken)
{
// Create a new service scope to ensure the database context is correctly disposed when this methods returns.
using var scope = services.GetRequiredService<IServiceScopeFactory>().CreateScope();
var manager = scope.ServiceProvider.GetRequiredService<OpenIddictApplicationManager<OpenIddictEntityFrameworkCoreApplication>>();
// Dev / Test Client
if (await manager.FindByClientIdAsync("BBB84B82-F440-4222-8C32-E0E030496828") is null)
{
await manager.CreateAsync(new OpenIddictApplicationDescriptor
{
ClientId = "BBB84B82-F440-4222-8C32-E0E030496828",
ConsentType = ConsentTypes.Explicit,
DisplayName = "Blazor client application",
Type = ClientTypes.Public,
PostLogoutRedirectUris =
{
new Uri("https://localhost:5001/authentication/logout-callback")
},
RedirectUris =
{
new Uri("https://localhost:5001/authentication/login-callback")
},
Permissions =
{
Permissions.Endpoints.Authorization,
Permissions.Endpoints.Logout,
Permissions.Endpoints.Token,
Permissions.GrantTypes.AuthorizationCode,
Permissions.GrantTypes.RefreshToken,
Permissions.Scopes.Email,
Permissions.Scopes.Profile,
Permissions.Scopes.Roles
},
Requirements =
{
Requirements.Features.ProofKeyForCodeExchange
}
});
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using BusinessAPI.BO;
using BusinessAPI.DL;
using System.Data.Entity;
using System.Data.EntityModel;
using System.Data.Entity.Infrastructure;
namespace BusinessAPI.BL
{
public class Employeedetails
{
TestDBEntities Context = new TestDBEntities();
public List<Employee> GetEmpDetails()
{
return Context.t_employee.Select(k => new Employee()
{
EmpID = k.EmpiD,
EmpName = k.EmpName,
Designation = k.Designation,
Salary = k.Salary
}).ToList();
}
}
}
|
using System.Windows.Controls;
namespace TableTopCrucible.Domain.Library.WPF.Views
{
/// <summary>
/// Interaction logic for FileDefinition.xaml
/// </summary>
public partial class FileList : UserControl
{
public FileList()
{
InitializeComponent();
}
}
}
|
using Microsoft.AspNet.Identity;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using TachyHealth.Models;
namespace TachyHealth.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
bool val1 = (System.Web.HttpContext.Current.User != null) && System.Web.HttpContext.Current.User.Identity.IsAuthenticated;
RegisterViewModel R = new RegisterViewModel();
if (val1)
{
try
{
AccountController Ac = new AccountController();
var signedUser = (User.Identity.GetUserId());
var SU = Ac._Context.Users.SingleOrDefault(c => c.Id.Equals(signedUser));
R.FullName = SU.UserName;
R.MobileNumber = SU.PhoneNumber;
R.Email = SU.Email;
}
catch (NullReferenceException ex)
{
return View(R);
}
}
return View(R);
}
public ActionResult About()
{
ViewBag.Message = "Your application description page.";
return View();
}
public ActionResult Contact()
{
ViewBag.Message = "Your contact page.";
return View();
}
}
} |
using UnityEngine;
using System.Collections;
public class PostImpressionist : MonoBehaviour {
public bool played = false;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
}
void OnMouseOver(){
if(played == false){
audio.Play();
played = true;
}
}
}
|
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
namespace CoreEngine.UI
{
[AddComponentMenu("Core.UI/Vertex Effects/ShearUI")]
#if UNITY_5_2 || UNITY_5_3_OR_NEWER
public class ShearUI : BaseMeshEffect
#else
public class ShearUI : BaseVertexEffect
#endif
{
public Vector2 m_Shear = Vector2.zero;
public
#if !UNITY_5_2 && !UNITY_5_3_OR_NEWER
override
#endif
void ModifyVertices (List<UIVertex> verts)
{
var shearMatrix = Matrix4x4.identity;
shearMatrix[0,1] = m_Shear.x;
shearMatrix[1,0] = m_Shear.y;
for (int i = 0; i < verts.Count; ++i )
{
var vert = verts[i];
vert.position = shearMatrix.MultiplyPoint( vert.position );
verts[i] = vert;
}
}
#if UNITY_5_2 || UNITY_5_3_OR_NEWER
public override void ModifyMesh(VertexHelper vh)
{
if ( !IsActive() )
return;
var list = new List<UIVertex>();
vh.GetUIVertexStream( list );
ModifyVertices( list );
vh.Clear();
vh.AddUIVertexTriangleStream( list );
}
#endif
}
} |
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Networking;
using UnityEngine.SceneManagement;
#if UNITY_EDITOR
using UnityEditor;
#endif
namespace HT.Framework
{
/// <summary>
/// 默认的资源管理器助手
/// </summary>
public sealed class DefaultResourceHelper : IResourceHelper
{
/// <summary>
/// 资源管理器
/// </summary>
public InternalModuleBase Module { get; set; }
/// <summary>
/// 当前的资源加载模式
/// </summary>
public ResourceLoadMode LoadMode { get; private set; }
/// <summary>
/// 是否是编辑器模式
/// </summary>
public bool IsEditorMode { get; private set; }
/// <summary>
/// AssetBundle资源加载根路径
/// </summary>
public string AssetBundleRootPath { get; private set; }
/// <summary>
/// 所有AssetBundle资源包清单的名称
/// </summary>
public string AssetBundleManifestName { get; private set; }
/// <summary>
/// 缓存的所有AssetBundle包【AB包名称、AB包】
/// </summary>
public Dictionary<string, AssetBundle> AssetBundles { get; private set; } = new Dictionary<string, AssetBundle>();
/// <summary>
/// 所有AssetBundle资源包清单
/// </summary>
public AssetBundleManifest AssetBundleManifest { get; private set; }
/// <summary>
/// 所有AssetBundle的Hash128值【AB包名称、Hash128值】
/// </summary>
public Dictionary<string, Hash128> AssetBundleHashs { get; private set; } = new Dictionary<string, Hash128>();
/// <summary>
/// 单线下载中
/// </summary>
private bool _isLoading = false;
/// <summary>
/// 单线下载等待
/// </summary>
private WaitUntil _loadWait;
/// <summary>
/// 初始化助手
/// </summary>
public void OnInitialization()
{
}
/// <summary>
/// 助手准备工作
/// </summary>
public void OnPreparatory()
{
}
/// <summary>
/// 刷新助手
/// </summary>
public void OnRefresh()
{
}
/// <summary>
/// 终结助手
/// </summary>
public void OnTermination()
{
UnLoadAllAsset(true);
ClearMemory();
}
/// <summary>
/// 暂停助手
/// </summary>
public void OnPause()
{
}
/// <summary>
/// 恢复助手
/// </summary>
public void OnUnPause()
{
}
/// <summary>
/// 设置加载器
/// </summary>
/// <param name="loadMode">加载模式</param>
/// <param name="isEditorMode">是否是编辑器模式</param>
/// <param name="manifestName">AB包清单名称</param>
public void SetLoader(ResourceLoadMode loadMode, bool isEditorMode, string manifestName)
{
LoadMode = loadMode;
IsEditorMode = isEditorMode;
AssetBundleRootPath = Application.persistentDataPath + "/";
AssetBundleManifestName = manifestName;
_loadWait = new WaitUntil(() => { return !_isLoading; });
}
/// <summary>
/// 设置AssetBundle资源根路径(仅当使用AssetBundle加载时有效)
/// </summary>
/// <param name="path">AssetBundle资源根路径</param>
public void SetAssetBundlePath(string path)
{
AssetBundleRootPath = path;
}
/// <summary>
/// 通过名称获取指定的AssetBundle
/// </summary>
/// <param name="assetBundleName">名称</param>
/// <returns>AssetBundle</returns>
public AssetBundle GetAssetBundle(string assetBundleName)
{
if (AssetBundles.ContainsKey(assetBundleName))
{
return AssetBundles[assetBundleName];
}
else
{
return null;
}
}
/// <summary>
/// 加载资源(异步)
/// </summary>
/// <typeparam name="T">资源类型</typeparam>
/// <param name="info">资源信息标记</param>
/// <param name="loadingAction">加载中事件</param>
/// <param name="loadDoneAction">加载完成事件</param>
/// <param name="isPrefab">是否是加载预制体</param>
/// <param name="parent">预制体加载完成后的父级</param>
/// <param name="isUI">是否是加载UI</param>
/// <returns>加载协程迭代器</returns>
public IEnumerator LoadAssetAsync<T>(ResourceInfoBase info, HTFAction<float> loadingAction, HTFAction<T> loadDoneAction, bool isPrefab, Transform parent, bool isUI) where T : UnityEngine.Object
{
DateTime beginTime = DateTime.Now;
if (_isLoading)
{
yield return _loadWait;
}
_isLoading = true;
yield return LoadDependenciesAssetBundleAsync(info.AssetBundleName);
DateTime waitTime = DateTime.Now;
UnityEngine.Object asset = null;
if (LoadMode == ResourceLoadMode.Resource)
{
ResourceRequest request = Resources.LoadAsync<T>(info.ResourcePath);
while (!request.isDone)
{
loadingAction?.Invoke(request.progress);
yield return null;
}
asset = request.asset;
if (asset)
{
if (isPrefab)
{
asset = ClonePrefab(asset as GameObject, parent, isUI);
}
}
else
{
throw new HTFrameworkException(HTFrameworkModule.Resource, "加载资源失败:Resources文件夹中不存在资源 " + info.ResourcePath + "!");
}
}
else
{
#if UNITY_EDITOR
if (IsEditorMode)
{
loadingAction?.Invoke(1);
yield return null;
asset = AssetDatabase.LoadAssetAtPath<T>(info.AssetPath);
if (asset)
{
if (isPrefab)
{
asset = ClonePrefab(asset as GameObject, parent, isUI);
}
}
else
{
throw new HTFrameworkException(HTFrameworkModule.Resource, "加载资源失败:路径中不存在资源 " + info.AssetPath + "!");
}
}
else
{
yield return LoadAssetBundleAsync(info.AssetBundleName, loadingAction);
if (AssetBundles.ContainsKey(info.AssetBundleName))
{
asset = AssetBundles[info.AssetBundleName].LoadAsset<T>(info.AssetPath);
if (asset)
{
if (isPrefab)
{
asset = ClonePrefab(asset as GameObject, parent, isUI);
}
}
else
{
throw new HTFrameworkException(HTFrameworkModule.Resource, "加载资源失败:AB包 " + info.AssetBundleName + " 中不存在资源 " + info.AssetPath + " !");
}
}
}
#else
yield return LoadAssetBundleAsync(info.AssetBundleName, loadingAction);
if (AssetBundles.ContainsKey(info.AssetBundleName))
{
asset = AssetBundles[info.AssetBundleName].LoadAsset<T>(info.AssetPath);
if (asset)
{
if (isPrefab)
{
asset = ClonePrefab(asset as GameObject, parent, isUI);
}
}
else
{
throw new HTFrameworkException(HTFrameworkModule.Resource, "加载资源失败:AB包 " + info.AssetBundleName + " 中不存在资源 " + info.AssetPath + " !");
}
}
#endif
}
DateTime endTime = DateTime.Now;
Log.Info(string.Format("异步加载资源{0}[{1}模式]:\r\n{2}\r\n等待耗时:{3}秒 加载耗时:{4}秒"
, asset ? "成功" : "失败"
, LoadMode.ToString()
, LoadMode == ResourceLoadMode.Resource ? info.GetResourceFullPath() : info.GetAssetBundleFullPath(AssetBundleRootPath)
, (waitTime - beginTime).TotalSeconds
, (endTime - waitTime).TotalSeconds));
if (asset)
{
DataSetInfo dataSet = info as DataSetInfo;
if (dataSet != null && dataSet.Data != null)
{
asset.Cast<DataSetBase>().Fill(dataSet.Data);
}
loadDoneAction?.Invoke(asset as T);
}
asset = null;
_isLoading = false;
}
/// <summary>
/// 加载场景(异步)
/// </summary>
/// <param name="info">资源信息标记</param>
/// <param name="loadingAction">加载中事件</param>
/// <param name="loadDoneAction">加载完成事件</param>
/// <returns>加载协程迭代器</returns>
public IEnumerator LoadSceneAsync(SceneInfo info, HTFAction<float> loadingAction, HTFAction loadDoneAction)
{
DateTime beginTime = DateTime.Now;
if (_isLoading)
{
yield return _loadWait;
}
_isLoading = true;
yield return LoadDependenciesAssetBundleAsync(info.AssetBundleName);
DateTime waitTime = DateTime.Now;
if (LoadMode == ResourceLoadMode.Resource)
{
throw new HTFrameworkException(HTFrameworkModule.Resource, "加载场景失败:场景加载不允许使用Resource模式!");
}
else
{
#if UNITY_EDITOR
if (IsEditorMode)
{
throw new HTFrameworkException(HTFrameworkModule.Resource, "加载场景失败:场景加载不允许使用编辑器模式!");
}
else
{
yield return LoadAssetBundleAsync(info.AssetBundleName, loadingAction);
yield return SceneManager.LoadSceneAsync(info.AssetPath, LoadSceneMode.Additive);
}
#else
yield return LoadAssetBundleAsync(info.AssetBundleName, loadingAction);
yield return SceneManager.LoadSceneAsync(info.AssetPath, LoadSceneMode.Additive);
#endif
}
DateTime endTime = DateTime.Now;
Log.Info(string.Format("异步加载场景完成[{0}模式]:{1}\r\n等待耗时:{2}秒 加载耗时:{3}秒"
, LoadMode.ToString()
, info.AssetPath
, (waitTime - beginTime).TotalSeconds
, (endTime - waitTime).TotalSeconds));
loadDoneAction?.Invoke();
_isLoading = false;
}
/// <summary>
/// 卸载资源(卸载AssetBundle)
/// </summary>
/// <param name="assetBundleName">AB包名称</param>
/// <param name="unloadAllLoadedObjects">是否同时卸载所有实体对象</param>
public void UnLoadAsset(string assetBundleName, bool unloadAllLoadedObjects = false)
{
if (LoadMode == ResourceLoadMode.Resource)
{
Resources.UnloadUnusedAssets();
}
else
{
if (AssetBundles.ContainsKey(assetBundleName))
{
AssetBundles[assetBundleName].Unload(unloadAllLoadedObjects);
AssetBundles.Remove(assetBundleName);
}
if (AssetBundleHashs.ContainsKey(assetBundleName))
{
AssetBundleHashs.Remove(assetBundleName);
}
}
}
/// <summary>
/// 卸载所有资源(卸载AssetBundle)
/// </summary>
/// <param name="unloadAllLoadedObjects">是否同时卸载所有实体对象</param>
public void UnLoadAllAsset(bool unloadAllLoadedObjects = false)
{
if (LoadMode == ResourceLoadMode.Resource)
{
Resources.UnloadUnusedAssets();
}
else
{
foreach (var assetBundle in AssetBundles)
{
assetBundle.Value.Unload(unloadAllLoadedObjects);
}
AssetBundles.Clear();
AssetBundleHashs.Clear();
AssetBundle.UnloadAllAssetBundles(unloadAllLoadedObjects);
}
}
/// <summary>
/// 清理内存,释放空闲内存
/// </summary>
public void ClearMemory()
{
Resources.UnloadUnusedAssets();
GC.Collect();
}
/// <summary>
/// 克隆预制体
/// </summary>
/// <param name="prefabTem">预制体模板</param>
/// <param name="parent">克隆后的父级</param>
/// <param name="isUI">是否是UI</param>
/// <returns>克隆后的预制体</returns>
private GameObject ClonePrefab(GameObject prefabTem, Transform parent, bool isUI)
{
GameObject prefab = UnityEngine.Object.Instantiate(prefabTem) as GameObject;
if (parent)
{
prefab.transform.SetParent(parent);
}
if (isUI)
{
prefab.rectTransform().anchoredPosition3D = prefabTem.rectTransform().anchoredPosition3D;
prefab.rectTransform().sizeDelta = prefabTem.rectTransform().sizeDelta;
prefab.rectTransform().anchorMin = prefabTem.rectTransform().anchorMin;
prefab.rectTransform().anchorMax = prefabTem.rectTransform().anchorMax;
prefab.transform.localRotation = Quaternion.identity;
prefab.transform.localScale = Vector3.one;
}
else
{
prefab.transform.localPosition = prefabTem.transform.localPosition;
prefab.transform.localRotation = Quaternion.identity;
prefab.transform.localScale = Vector3.one;
}
prefab.SetActive(false);
return prefab;
}
/// <summary>
/// 异步加载依赖AB包
/// </summary>
/// <param name="assetBundleName">AB包名称</param>
/// <returns>协程迭代器</returns>
private IEnumerator LoadDependenciesAssetBundleAsync(string assetBundleName)
{
if (LoadMode == ResourceLoadMode.AssetBundle)
{
#if UNITY_EDITOR
if (!IsEditorMode)
{
yield return LoadAssetBundleManifestAsync();
if (AssetBundleManifest != null)
{
string[] dependencies = AssetBundleManifest.GetAllDependencies(assetBundleName);
foreach (string item in dependencies)
{
if (AssetBundles.ContainsKey(item))
{
continue;
}
yield return LoadAssetBundleAsync(item);
}
}
}
#else
yield return LoadAssetBundleManifestAsync();
if (AssetBundleManifest != null)
{
string[] dependencies = AssetBundleManifest.GetAllDependencies(assetBundleName);
foreach (string item in dependencies)
{
if (AssetBundles.ContainsKey(item))
{
continue;
}
yield return LoadAssetBundleAsync(item);
}
}
#endif
}
yield return null;
}
/// <summary>
/// 异步加载AB包清单
/// </summary>
/// <returns>协程迭代器</returns>
private IEnumerator LoadAssetBundleManifestAsync()
{
if (string.IsNullOrEmpty(AssetBundleManifestName))
{
throw new HTFrameworkException(HTFrameworkModule.Resource, "请设置资源管理模块的 Manifest Name 属性,为所有AB包提供依赖清单!");
}
else
{
if (AssetBundleManifest == null)
{
yield return LoadAssetBundleAsync(AssetBundleManifestName, true);
if (AssetBundles.ContainsKey(AssetBundleManifestName))
{
AssetBundleManifest = AssetBundles[AssetBundleManifestName].LoadAsset<AssetBundleManifest>("AssetBundleManifest");
UnLoadAsset(AssetBundleManifestName);
}
}
}
yield return null;
}
/// <summary>
/// 异步加载AB包
/// </summary>
/// <param name="assetBundleName">AB包名称</param>
/// <param name="isManifest">是否是加载清单</param>
/// <returns>协程迭代器</returns>
private IEnumerator LoadAssetBundleAsync(string assetBundleName, bool isManifest = false)
{
if (!AssetBundles.ContainsKey(assetBundleName))
{
using (UnityWebRequest request = isManifest
? UnityWebRequestAssetBundle.GetAssetBundle(AssetBundleRootPath + assetBundleName)
: UnityWebRequestAssetBundle.GetAssetBundle(AssetBundleRootPath + assetBundleName, GetAssetBundleHash(assetBundleName)))
{
yield return request.SendWebRequest();
if (!request.isNetworkError && !request.isHttpError)
{
AssetBundle bundle = DownloadHandlerAssetBundle.GetContent(request);
if (bundle)
{
AssetBundles.Add(assetBundleName, bundle);
}
else
{
throw new HTFrameworkException(HTFrameworkModule.Resource, "请求:" + request.url + " 未下载到AB包!");
}
}
else
{
throw new HTFrameworkException(HTFrameworkModule.Resource, "请求:" + request.url + " 遇到网络错误:" + request.error + "!");
}
}
}
yield return null;
}
/// <summary>
/// 异步加载AB包(提供进度回调)
/// </summary>
/// <param name="assetBundleName">AB包名称</param>
/// <param name="loadingAction">加载中事件</param>
/// <param name="isManifest">是否是加载清单</param>
/// <returns>协程迭代器</returns>
private IEnumerator LoadAssetBundleAsync(string assetBundleName, HTFAction<float> loadingAction, bool isManifest = false)
{
if (!AssetBundles.ContainsKey(assetBundleName))
{
using (UnityWebRequest request = isManifest
? UnityWebRequestAssetBundle.GetAssetBundle(AssetBundleRootPath + assetBundleName)
: UnityWebRequestAssetBundle.GetAssetBundle(AssetBundleRootPath + assetBundleName, GetAssetBundleHash(assetBundleName)))
{
request.SendWebRequest();
while (!request.isDone)
{
loadingAction?.Invoke(request.downloadProgress);
yield return null;
}
if (!request.isNetworkError && !request.isHttpError)
{
AssetBundle bundle = DownloadHandlerAssetBundle.GetContent(request);
if (bundle)
{
AssetBundles.Add(assetBundleName, bundle);
}
else
{
throw new HTFrameworkException(HTFrameworkModule.Resource, "请求:" + request.url + " 未下载到AB包!");
}
}
else
{
throw new HTFrameworkException(HTFrameworkModule.Resource, "请求:" + request.url + " 遇到网络错误:" + request.error + "!");
}
}
}
yield return null;
}
/// <summary>
/// 获取AB包的hash值
/// </summary>
/// <param name="assetBundleName">AB包名称</param>
/// <returns>hash值</returns>
private Hash128 GetAssetBundleHash(string assetBundleName)
{
if (AssetBundleHashs.ContainsKey(assetBundleName))
{
return AssetBundleHashs[assetBundleName];
}
else
{
Hash128 hash = AssetBundleManifest.GetAssetBundleHash(assetBundleName);
AssetBundleHashs.Add(assetBundleName, hash);
return hash;
}
}
}
} |
using System.Linq;
using Psub.DataAccess.Abstract;
using Psub.DataService.HandlerPerQuery.SectionProcess.Entities;
using Psub.Domain.Entities;
using UESPDataManager.DataService.HandlerPerQuery.Abstract;
namespace Psub.DataService.HandlerPerQuery.SectionProcess.Handlers
{
public class SectionEditGetHandler : IQueryHandler<SectionEditGetQuery, SectionEditGetViewModel>
{
private readonly IRepository<MainSection> _mainSectionRepository;
private readonly IRepository<Section> _sectionRepository;
public SectionEditGetHandler(IRepository<MainSection> mainSectionRepository,
IRepository<Section> sectionRepository)
{
_mainSectionRepository = mainSectionRepository;
_sectionRepository = sectionRepository;
}
public SectionEditGetViewModel Handle(SectionEditGetQuery catalog)
{
var section = _sectionRepository.Get(catalog.Id);
return new SectionEditGetViewModel
{
Id = section.Id,
Name = section.Name,
MainSectionId = section.MainSection.Id,
MainSections = _mainSectionRepository.Query().Select(m => new MainSectionItem
{
Id = m.Id,
Name = m.Name
}).ToList()
};
}
}
}
|
namespace Services.Logger
{
public interface ILoggerManager
{
void LogInfo (string message);
void LogWarn (string message);
void LogDebug (string message);
void LogError (string message);
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using SincolPDV.BLL;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web.Security;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
namespace Projeto.Operacoes
{
public partial class saida : System.Web.UI.Page
{
Saida Saida = new Saida();
Ferramentas.Uteis ut = new Ferramentas.Uteis();
DataRow Linha;
string parcelas_faltantes;
protected void Page_Load(object sender, EventArgs e)
{
txtDataVencimento.Text = DateTime.Now.ToShortDateString();
if (IsPostBack == false)
{
PreencherCampos();
ADD_Forma_pagamento();
}
}
private void PreencherCampos()
{
txtDataVenda.Text = DateTime.Now.ToShortDateString();
}
private void ADD_Forma_pagamento()
{
DataTable tbDados;
DataColumn Coluna;
DataColumn Coluna2;
DataColumn Coluna3;
DataColumn Coluna4;
Session["contador"] = 0;
tbDados = new DataTable();
Coluna = new DataColumn();
Coluna.DataType = System.Type.GetType("System.String");
Coluna.ColumnName = "ID";
tbDados.Columns.Add(Coluna);
Coluna = new DataColumn();
Coluna.DataType = System.Type.GetType("System.String");
Coluna2 = new DataColumn();
Coluna2.DataType = System.Type.GetType("System.String");
Coluna3 = new DataColumn();
Coluna3.DataType = System.Type.GetType("System.String");
Coluna4 = new DataColumn();
Coluna4.DataType = System.Type.GetType("System.String");
Coluna.ColumnName = "Modo de Pagamento";
Coluna2.ColumnName = "Vencimento";
Coluna3.ColumnName = "Parcelas";
Coluna4.ColumnName = "Valor";
tbDados.Columns.Add(Coluna);
tbDados.Columns.Add(Coluna2);
tbDados.Columns.Add(Coluna3);
tbDados.Columns.Add(Coluna4);
Session["TabelaDados"] = tbDados;
GridView2.DataSource = tbDados;
GridView2.DataBind();
}
protected void btnIncluir_Click(object sender, EventArgs e)
{
double Valor3 = Convert.ToDouble(txtValor3.Text);
double Valor2 = Convert.ToDouble(txtValor2.Text);
int parcela = Convert.ToInt32(listQuantidadeParcelas2.SelectedValue);
string parcelas = listQuantidadeParcelas2.SelectedValue;
//Cauculando os valores dos TextBox
if (listModoPagamento2.SelectedValue == "A Vista" && (Valor3 > 0) && (Valor2 > 0) )
{
double resultado = (Valor3 - Valor2);
if (resultado >= 0){
txtValor3.Text = Convert.ToString(resultado);
parcelas_faltantes = parcelas;
incluir_parcelas();
}
}
else if (listModoPagamento2.SelectedValue == "Parcelado" && Valor3 > 0 )
{
double resultado = (Valor3 / parcela);
double resultado2 = (Valor3 - (resultado * parcela));
txtValor3.Text = Convert.ToString(resultado2);
for (int i = 1; i <= parcela; i++)
{
parcelas_faltantes = Convert.ToString(i) + "/" + parcela;
int data = ((i) * 30);
txtDataVencimento.Text = System.DateTime.Now.AddDays(data).ToString("dd/MM/yyyy");
incluir_parcelas();
}
}
}
protected void incluir_parcelas()
{
DataTable tbDadosSession = new DataTable();
tbDadosSession = (DataTable)Session["TabelaDados"];
string modoPagamento = listModoPagamento2.SelectedValue;
string vencimento = txtDataVencimento.Text;
string parcelas = parcelas_faltantes;
string valor2 = txtValor2.Text;
Linha = tbDadosSession.NewRow();
Linha["ID"] = Convert.ToInt32(Session["contador"]) + 1;
Linha["Modo de Pagamento"] = modoPagamento;
Linha["vencimento"] = vencimento;
Linha["Parcelas"] = parcelas;
Linha["Valor"] = valor2;
tbDadosSession.Rows.Add(Linha);
Session["TabelaDados"] = tbDadosSession;
GridView2.DataSource = tbDadosSession;
GridView2.DataBind();
Session["contador"] = tbDadosSession.Rows.Count;
}
protected void ClienteGridView_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
DataTable tbDadosSession = new DataTable();
tbDadosSession = (DataTable)Session["TabelaDados"];
double Valor2 = Convert.ToDouble(txtValor2.Text);
double Valor3 = Convert.ToDouble(txtValor3.Text);
string valor_retorno = tbDadosSession.Rows[e.RowIndex][4].ToString();
double valor_retorno2 = Convert.ToDouble(valor_retorno);
valor_retorno2 = (valor_retorno2 + Valor3);
txtValor3.Text = Convert.ToString(valor_retorno2);
tbDadosSession.Rows[e.RowIndex].Delete();
Session["TabelaDados"] = tbDadosSession;
GridView2.DataSource = tbDadosSession;
GridView2.DataBind();
}
}
} |
using MarsRoverAPI.Model;
namespace MarsRoverAPI.Responses
{
public class SendMessageToMarsSurfaceResponse : ApiResponse<MarsSurfaceInfo>
{
}
}
|
// Copyright 2021 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using NtApiDotNet.Win32.SafeHandles;
using NtApiDotNet.Win32.Security.Native;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
namespace NtApiDotNet.Win32.Security.Sam
{
/// <summary>
/// Class to represent a SAM group.
/// </summary>
public class SamGroup : SamObject
{
#region Private Members
private static IReadOnlyList<SamGroupMember> ConvertMembers(SafeSamMemoryBuffer rids, SafeSamMemoryBuffer attrs, int count)
{
using (SafeBuffer a = rids, b = attrs)
{
rids.Initialize<uint>((uint)count);
attrs.Initialize<uint>((uint)count);
uint[] rid_array = rids.ReadArray<uint>(0, count);
uint[] attr_array = attrs.ReadArray<uint>(0, count);
return rid_array.Select((r, i) => new SamGroupMember(r, attr_array[i])).ToList().AsReadOnly();
}
}
#endregion
#region Internal Members
internal SamGroup(SafeSamHandle handle, SamGroupAccessRights granted_access, string server_name, string group_name, Sid sid)
: base(handle, granted_access, SamUtils.SAM_GROUP_NT_TYPE_NAME, group_name, server_name)
{
Sid = sid;
Name = group_name;
}
#endregion
#region Public Methods
/// <summary>
/// Get members of the group.
/// </summary>
/// <param name="throw_on_error">True to throw on error.</param>
/// <returns>The list of group members.</returns>
public NtResult<IReadOnlyList<SamGroupMember>> GetMembers(bool throw_on_error)
{
return SecurityNativeMethods.SamGetMembersInGroup(Handle, out SafeSamMemoryBuffer rids,
out SafeSamMemoryBuffer attrs, out int count).CreateResult(throw_on_error, () => ConvertMembers(rids, attrs, count));
}
/// <summary>
/// Get members of the group.
/// </summary>
/// <returns>The list of group members.</returns>
public IReadOnlyList<SamGroupMember> GetMembers()
{
return GetMembers(true).Result;
}
/// <summary>
/// Query group attribute flags.
/// </summary>
/// <param name="throw_on_error">True to throw on error.</param>
/// <returns>The group attribute flags.</returns>
public NtResult<GroupAttributes> QueryGroupAttributes(bool throw_on_error)
{
return SecurityNativeMethods.SamQueryInformationGroup(Handle,
GROUP_INFORMATION_CLASS.GroupAttributeInformation, out SafeSamMemoryBuffer buffer).CreateResult(throw_on_error, () =>
{
using (buffer)
{
buffer.Initialize<GROUP_ATTRIBUTE_INFORMATION>(1);
return buffer.Read<GROUP_ATTRIBUTE_INFORMATION>(0).Attributes;
}
});
}
/// <summary>
/// Set the group attribute flags.
/// </summary>
/// <param name="attributes">The attributes to set.</param>
/// <param name="throw_on_error">True to throw on error.</param>
/// <returns>The NT status code.</returns>
public NtStatus SetGroupAttributes(GroupAttributes attributes, bool throw_on_error)
{
using (var buffer = new GROUP_ATTRIBUTE_INFORMATION() { Attributes = attributes }.ToBuffer())
{
return SecurityNativeMethods.SamSetInformationGroup(Handle,
GROUP_INFORMATION_CLASS.GroupAttributeInformation, buffer).ToNtException(throw_on_error);
}
}
/// <summary>
/// Delete the group object.
/// </summary>
/// <param name="throw_on_error">True to throw on error.</param>
/// <returns>The NT status code.</returns>
public NtStatus Delete(bool throw_on_error)
{
return SecurityNativeMethods.SamDeleteGroup(Handle).ToNtException(throw_on_error);
}
/// <summary>
/// Delete the group object.
/// </summary>
public void Delete()
{
Delete(true);
}
#endregion
#region Public Properties
/// <summary>
/// The group name.
/// </summary>
public string Name { get; }
/// <summary>
/// The SID of the group.
/// </summary>
public Sid Sid { get; }
/// <summary>
/// Get or set the group attribute flags.
/// </summary>
public GroupAttributes Attributes
{
get => QueryGroupAttributes(true).Result;
set => SetGroupAttributes(value, true);
}
#endregion
}
}
|
using System.Collections.Generic;
using System.IO;
using System.Security.Cryptography;
using System.Text;
namespace ClouDeveloper.Hash.SHA256
{
public static partial class SHA256HashExtensions
{
public static string ComputeSHA256(
this Stream inputStream,
bool isUpperCase = true)
{
return HashExtensions.ComputeHash<SHA256Managed>(inputStream, isUpperCase);
}
public static string ComputeSHA256(
this byte[] buffer,
int offset,
int count,
bool isUpperCase = true)
{
return HashExtensions.ComputeHash<SHA256Managed>(buffer, offset, count, isUpperCase);
}
public static string ComputeSHA256(
this byte[] buffer,
bool isUpperCase = true)
{
return HashExtensions.ComputeHash<SHA256Managed>(buffer, isUpperCase);
}
public static string ComputeSHA256(
this IEnumerable<byte> buffer,
int offset,
int count,
bool isUpperCase = true)
{
return HashExtensions.ComputeHash<SHA256Managed>(buffer, offset, count, isUpperCase);
}
public static string ComputeSHA256(
this IEnumerable<byte> buffer,
bool isUpperCase = true)
{
return HashExtensions.ComputeHash<SHA256Managed>(buffer, isUpperCase);
}
public static string ComputeSHA256(
this char[] text,
int index,
int count,
Encoding targetEncoding = default(Encoding),
bool isUpperCase = true)
{
return HashExtensions.ComputeHash<SHA256Managed>(text, index, count, targetEncoding, isUpperCase);
}
public static string ComputeSHA256(
this char[] text,
Encoding targetEncoding = default(Encoding),
bool isUpperCase = true)
{
return HashExtensions.ComputeHash<SHA256Managed>(text, targetEncoding, isUpperCase);
}
public static string ComputeSHA256(
this IEnumerable<char> text,
int index,
int count,
Encoding targetEncoding = default(Encoding),
bool isUpperCase = true)
{
return HashExtensions.ComputeHash<SHA256Managed>(text, index, count, targetEncoding, isUpperCase);
}
public static string ComputeSHA256(
this IEnumerable<char> text,
Encoding targetEncoding = default(Encoding),
bool isUpperCase = true)
{
return HashExtensions.ComputeHash<SHA256Managed>(text, targetEncoding, isUpperCase);
}
public static string ComputeSHA256(
this string text,
int index,
int count,
Encoding targetEncoding = default(Encoding),
bool isUpperCase = true)
{
return HashExtensions.ComputeHash<SHA256Managed>(text, index, count, targetEncoding, isUpperCase);
}
public static string ComputeSHA256(
this string text,
Encoding targetEncoding = default(Encoding),
bool isUpperCase = true)
{
return HashExtensions.ComputeHash<SHA256Managed>(text, targetEncoding, isUpperCase);
}
public static string ComputeSHA256(
this StringBuilder text,
int index,
int count,
Encoding targetEncoding = default(Encoding),
bool isUpperCase = true)
{
return HashExtensions.ComputeHash<SHA256Managed>(text, index, count, targetEncoding, isUpperCase);
}
public static string ComputeSHA256(
this StringBuilder text,
Encoding targetEncoding = default(Encoding),
bool isUpperCase = true)
{
return HashExtensions.ComputeHash<SHA256Managed>(text, targetEncoding, isUpperCase);
}
public static string ComputeSHA256(
this TextReader reader,
Encoding targetEncoding = default(Encoding),
bool isUpperCase = true)
{
return HashExtensions.ComputeHash<SHA256Managed>(reader, targetEncoding, isUpperCase);
}
}
}
|
// Copyright (C) 2020 Kazuhiro Fujieda <fujieda@users.osdn.me>
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using KancolleSniffer.Model;
using KancolleSniffer.Net;
using KancolleSniffer.Util;
using KancolleSniffer.View;
namespace KancolleSniffer.Notification
{
public class Notifier : IUpdateContext, Sniffer.IRepeatingTimerController
{
private readonly Scheduler _scheduler;
private readonly Method _method;
private class Method
{
public Action FlashWindow;
public Action<string, string> ShowToaster;
public Action<string, int> PlaySound;
}
public UpdateContext Context { get; set; }
private TimeStep Step => Context.GetStep();
private NotificationConfig Notifications => Context.Config.Notifications;
public Notifier(Action flashWindow, Action<string, string> showToaster, Action<string, int> playSound)
{
_method = new Method
{
FlashWindow = flashWindow,
ShowToaster = showToaster,
PlaySound = playSound,
};
_scheduler = new Scheduler(Alarm);
}
public void Stop(string key)
{
_scheduler.StopRepeat(key,
(key == "入渠終了" || key == "遠征終了") &&
(Context.Config.Notifications[key].Flags & NotificationType.Cont) != 0);
}
public void Stop(string key, int fleet) => _scheduler.StopRepeat(key, fleet);
public void Suspend(string exception = null) => _scheduler.SuspendRepeat(exception);
public void Resume() => _scheduler.ResumeRepeat();
public void StopAllRepeat() => _scheduler.StopAllRepeat();
public void StopRepeatingTimer(IEnumerable<string> names)
{
foreach (var name in names)
_scheduler.StopRepeat(name);
}
public void NotifyShipItemCount()
{
var ship = Context.Sniffer.ShipCounter;
if (ship.Alarm)
{
var message = $"残り{ship.Rest:D}隻";
_scheduler.Enqueue("艦娘数超過", message);
ship.Alarm = false;
}
var item = Context.Sniffer.ItemCounter;
if (item.Alarm)
{
var message = $"残り{item.Rest:D}個";
_scheduler.Enqueue("装備数超過", message);
item.Alarm = false;
}
_scheduler.Flush();
}
public void NotifyDamagedShip()
{
_scheduler.StopRepeat("大破警告");
if (!Context.Sniffer.BadlyDamagedShips.Any())
return;
SetNotification("大破警告", string.Join(" ", Context.Sniffer.BadlyDamagedShips));
_scheduler.Flush();
}
public void NotifyTimers()
{
for (var i = 0; i < Context.Sniffer.Missions.Length; i++)
{
var entry = Context.Sniffer.Missions[i];
if (entry.Name == "前衛支援任務" || entry.Name == "艦隊決戦支援任務")
continue;
CheckAlarm("遠征終了", entry.Timer, i + 1, entry.Name);
}
for (var i = 0; i < Context.Sniffer.NDock.Length; i++)
{
var entry = Context.Sniffer.NDock[i];
CheckAlarm("入渠終了", entry.Timer, i, entry.Name);
}
for (var i = 0; i < Context.Sniffer.KDock.Length; i++)
{
var timer = Context.Sniffer.KDock[i];
CheckAlarm("建造完了", timer, i, "");
}
NotifyCondTimers();
NotifyAkashiTimer();
_scheduler.Flush();
}
private void CheckAlarm(string key, AlarmTimer timer, int fleet, string subject)
{
if (timer.CheckAlarm(Step))
{
SetNotification(key, fleet, subject);
return;
}
var pre = TimeSpan.FromSeconds(Notifications[key].PreliminaryPeriod);
if (pre == TimeSpan.Zero)
return;
if (timer.CheckAlarm(Step + pre))
SetPreNotification(key, fleet, subject);
}
private void NotifyCondTimers()
{
var notice = Context.Sniffer.GetConditionNotice(Step);
var pre = TimeSpan.FromSeconds(Notifications["疲労回復"].PreliminaryPeriod);
var preNotice = pre == TimeSpan.Zero
? new int[ShipInfo.FleetCount]
: Context.Sniffer.GetConditionNotice(Step + pre);
var conditions = Context.Config.NotifyConditions;
for (var i = 0; i < ShipInfo.FleetCount; i++)
{
if (conditions.Contains(notice[i]))
{
SetNotification("疲労回復" + notice[i], i, "cond" + notice[i]);
}
else if (conditions.Contains(preNotice[i]))
{
SetPreNotification("疲労回復" + preNotice[i], i, "cond" + notice[i]);
}
}
}
private void NotifyAkashiTimer()
{
var akashi = Context.Sniffer.AkashiTimer;
var msgs = akashi.GetNotice(Step);
if (msgs.Length == 0)
{
_scheduler.StopRepeat("泊地修理");
return;
}
if (!akashi.CheckRepairing(Context.GetStep().Now) && !(akashi.CheckPresetRepairing() && Context.Config.UsePresetAkashi))
{
_scheduler.StopRepeat("泊地修理");
return;
}
var skipPreliminary = false;
if (msgs[0].Proceeded == "20分経過しました。")
{
SetNotification("泊地修理20分経過", msgs[0].Proceeded);
msgs[0].Proceeded = "";
skipPreliminary = true;
// 修理完了がいるかもしれないので続ける
}
for (var i = 0; i < ShipInfo.FleetCount; i++)
{
if (msgs[i].Proceeded != "")
SetNotification("泊地修理進行", i, msgs[i].Proceeded);
if (msgs[i].Completed != "")
SetNotification("泊地修理完了", i, msgs[i].Completed);
}
var pre = TimeSpan.FromSeconds(Notifications["泊地修理20分経過"].PreliminaryPeriod);
if (skipPreliminary || pre == TimeSpan.Zero)
return;
if ((msgs = akashi.GetNotice(Step + pre))[0].Proceeded == "20分経過しました。")
SetPreNotification("泊地修理20分経過", 0, msgs[0].Proceeded);
}
public void NotifyQuestComplete()
{
Context.Sniffer.GetQuestNotifications(out var notify, out var stop);
foreach (var questName in notify)
SetNotification("任務達成", 0, questName);
foreach (var questName in stop)
_scheduler.StopRepeat("任務達成", questName);
_scheduler.Flush();
}
private void SetNotification(string key, string subject)
{
SetNotification(key, 0, subject);
}
private void SetNotification(string key, int fleet, string subject)
{
var spec = Spec(key);
_scheduler.Enqueue(key, fleet, subject,
(spec.Flags & Context.Config.NotificationFlags & NotificationType.Repeat) == 0
? 0
: spec.RepeatInterval);
}
private void SetPreNotification(string key, int fleet, string subject)
{
if ((Spec(key).Flags & NotificationType.Preliminary) != 0)
_scheduler.Enqueue(key, fleet, subject, 0, true);
}
private NotificationSpec Spec(string key)
{
return Notifications[_scheduler.KeyToName(key)];
}
private void Alarm(string balloonTitle, string balloonMessage, string name)
{
if (Check(name, NotificationType.FlashWindow))
_method.FlashWindow();
if (Check(name, NotificationType.ShowBaloonTip))
_method.ShowToaster(balloonTitle, balloonMessage);
if (Check(name, NotificationType.PlaySound))
_method.PlaySound(Context.Config.Sounds[name], Context.Config.Sounds.Volume);
if (Context.Config.Pushbullet.On && CheckPush(name))
{
Task.Run(() =>
{
PushNotification.PushToPushbullet(Context.Config.Pushbullet.Token, balloonTitle,
balloonMessage);
});
}
if (Context.Config.Pushover.On && CheckPush(name))
{
Task.Run(() =>
{
PushNotification.PushToPushover(Context.Config.Pushover.ApiKey, Context.Config.Pushover.UserKey,
balloonTitle, balloonMessage);
});
}
}
private bool Check(string name, NotificationType type)
{
return (Flags(name) & type) != 0;
}
private NotificationType Flags(string name)
{
return Context.Config.NotificationFlags & Notifications[name].Flags;
}
private bool CheckPush(string name)
{
return (Notifications[name].Flags & NotificationType.Push) != 0;
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace HZGZDL.YZFJKGZXFXY.Common {
public class DataConvert {
static public int ADCReadData(byte[] data) {
return 2;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace Project_1
{
public partial class Confirmation : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
Dictionary<string, string> newTicket = new Dictionary<string, string>();
if (!IsPostBack)
{
if (Session.Count > 0)
{
int ticketNum = (int)Session["ticketNum"];
newTicket = (Dictionary<string, string>)Session["ticket" + ticketNum];
lblThankYou.Text = "Thank you for your ticket submission, " +
newTicket["firstName"].ToString() + " " +
newTicket["lastName"].ToString();
lblIssueSubmitted.Text = newTicket["issue"].ToString();
if (newTicket["priority"].ToString() == "Low")
{
lblPriority.Text = "Low Priority";
imgPriority.ImageUrl = "~/imgs/Button-Blank-Green-icon.png";
}
else if (newTicket["priority"].ToString() == "Medium")
{
lblPriority.Text = "Medium Priority";
imgPriority.ImageUrl = "~/imgs/Button-Blank-Yellow-icon.png";
}
else if (newTicket["priority"].ToString() == "High")
{
lblPriority.Text = "High Priority";
imgPriority.ImageUrl = "~/imgs/Button-Blank-Red-icon.png";
}
}
}
else
{
Response.Redirect("NewTicket.aspx");
}
}
}
} |
using System;
using Xamarin.Forms;
using Xamarin.Forms.Platform.iOS;
using App1.Renderers;
using App1.iOS.Renderers;
[assembly: ExportRenderer(typeof(CustomFrame), typeof(CustomFrameRenderer))]
namespace App1.iOS.Renderers
{
public class CustomFrameRenderer : FrameRenderer
{
protected override void OnElementChanged(ElementChangedEventArgs<Frame> e)
{
base.OnElementChanged(e);
Layer.CornerRadius = (nfloat)10.0;
}
}
} |
using Darek_kancelaria.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Darek_kancelaria.Repository
{
interface IPrice : IRepository<Price>
{
int? GetAllCasePrice(int id);
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Revature_Project1.Data;
using Revature_Project1.Models;
namespace Revature_Project1.Controllers
{
public class LoanController : Controller
{
private readonly MSSQLContext _db;
public LoanController(MSSQLContext db)
{
_db = db;
}
public ActionResult Pay(int? id)
{
if (id == null)
{
return NotFound();
}
LoanAccount la = _db.LoanAccounts.Find(id);
if (la == null)
{
return NotFound();
}
return View(la);
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Pay(string accountID, string Debit, string paymentvalue)
{
try
{
double balance = double.Parse(Debit) - double.Parse(paymentvalue);
int accid = int.Parse(accountID);
LoanAccount la = _db.LoanAccounts.Find(accid) as LoanAccount;
la.Debit = balance;
Transaction ta = new Transaction()
{
id = 0,
accountID = int.Parse(accountID),
transactionMessage = "Deposit of " + paymentvalue
};
_db.Transactions.Add(ta);
_db.Entry(la).State = EntityState.Modified;
_db.SaveChanges();
ViewBag.Confirm = $"Your payment of {paymentvalue} was completed for account {accountID}";
return View("Confirmed");
}
catch
{
return RedirectToAction("Index");
}
}
public ActionResult Delete(int? id)
{
if (id == null)
{
return NotFound();
}
PersonalCheckingAccount personalCheckingAccount = _db.CheckingAccounts.Find(id);
if (personalCheckingAccount == null)
{
return NotFound();
}
return View(personalCheckingAccount);
}
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public ActionResult DeleteConfirmed(int id)
{
PersonalCheckingAccount personalCheckingAccount = _db.CheckingAccounts.Find(id);
_db.CheckingAccounts.Remove(personalCheckingAccount);
_db.SaveChanges();
return RedirectToAction("Index");
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
_db.Dispose();
}
base.Dispose(disposing);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using UdemyWebAPIClass.Models;
namespace UdemyWebAPIClass.Controllers
{
[RoutePrefix("api/Contacts")]
public class ContactsController : ApiController
{
Contacts[] contacts = new Contacts[]
{
new Contacts() {Id=0,FirstName="Peter",LastName="Smith" },
new Contacts() {Id=1,FirstName="Bruce",LastName="Parker" },
new Contacts() {Id=2,FirstName="Wayne",LastName="Jones" },
new Contacts() {Id=3,FirstName="Jake",LastName="Banner" },
};
// GET: api/Contacts
[Route("")]
public IEnumerable<Contacts> Get()
{
return contacts;
}
// GET: api/Contacts/5
[Route("{id:int}")]
public IHttpActionResult Get(int id)
{
Contacts contact = contacts.FirstOrDefault<Contacts>(c => c.Id == id);
if (contact == null)
return NotFound();
return Ok(contact);
}
[HttpGet]
[Route("{name}")]
public IEnumerable<Contacts> FindContactByName(string name)
{
Contacts[] contactArray = contacts
.Where<Contacts>(c => c.FirstName.Contains(name)).ToArray<Contacts>();
return contactArray;
}
// POST: api/Contacts
[Route("")]
public IEnumerable<Contacts> Post([FromBody]Contacts newContact)
{
List<Contacts> contactList = contacts.ToList<Contacts>();
newContact.Id = contactList.Count;
contactList.Add(newContact);
contacts = contactList.ToArray();
return contacts;
}
// PUT: api/Contacts/5
[Route("{id:int}")]
public IEnumerable<Contacts> Put(int id, [FromBody]Contacts updateContact)
{
Contacts contact = contacts.FirstOrDefault<Contacts>(c => c.Id == id);
if(contact != null)
{
contact.FirstName = updateContact.FirstName;
contact.LastName = updateContact.LastName;
}
return contacts;
}
// DELETE: api/Contacts/5
[Route("{id:int}")]
public IEnumerable<Contacts> Delete(int id)
{
contacts = contacts.Where<Contacts>(c => c.Id != id).ToArray<Contacts>();
return contacts;
}
}
}
|
using System.Collections.Generic;
using MongoDB.Driver;
using MongoDB.Driver.Builders;
using Braspag.Domain.DTO;
namespace Braspag.Domain.Filters
{
public static class AdquirentesFilters
{
public static IMongoQuery[] CriarSpecification(this AdquirentesDto filtro)
{
List<IMongoQuery> criterio = new List<IMongoQuery>();
if (!string.IsNullOrEmpty(filtro.adquirentes))
{
criterio.Add(Query<AdquirentesDto>.EQ(x => x.adquirentes, filtro.adquirentes));
}
return criterio.ToArray();
}
}
}
|
using One.Common;
using One.Converter;
using One.Model;
using One.UC;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Net.Http;
using Windows.ApplicationModel.DataTransfer;
using Windows.Storage;
using Windows.Storage.Streams;
using Windows.UI;
using Windows.UI.Notifications;
using Windows.UI.ViewManagement;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Media.Imaging;
using Windows.UI.Xaml.Navigation;
// https://go.microsoft.com/fwlink/?LinkId=234238 上介绍了“空白页”项模板
namespace One.Pages
{
/// <summary>
/// 可用于自身或导航至 Frame 内部的空白页。
/// </summary>
public sealed partial class IndexPage : Page
{
private ObservableCollection<PhotoAlbum_Datum> _photoMonthList = null;
bool isAwait = true;
private PhotoAlbum_Datum photoAlbum_Datum = new PhotoAlbum_Datum();
double listPagelastPosition = 0;
bool listPageBackTopButtonIn = false;
bool listPageBackTopButtonOut = false;
public IndexPage()
{
this.InitializeComponent();
Window.Current.SetTitleBar(TitleBarBlankBlock);
}
protected override void OnNavigatedTo(NavigationEventArgs e)
{
base.OnNavigatedTo(e);
_photoMonthList = e.Parameter as ObservableCollection<PhotoAlbum_Datum>;
}
/// <summary>
/// 点击首页item 进入每个item的详细页面
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private async void ItemListview_ItemClick(object sender, ItemClickEventArgs e)
{
photoAlbum_Datum = (PhotoAlbum_Datum)e.ClickedItem;
//获取图片的主要颜色,算法不是自己写的。因为计算主要颜色需要点时间,所以放在开头
var rass = RandomAccessStreamReference.CreateFromUri(new Uri(photoAlbum_Datum.HpImgUrl));
IRandomAccessStream inputStream = await rass.OpenReadAsync();
WriteableBitmap wb = new WriteableBitmap(5000, 5000);
wb.SetSource(inputStream);
ContentContainer.Background = new SolidColorBrush(MyColorHelper.GetMajorColor(wb));
//页面中其它数据的绑定
BitmapImage bitmapImage = new BitmapImage(new Uri(photoAlbum_Datum.HpImgUrl));
DetailsImage.Source = bitmapImage;
VolumeText.Text = photoAlbum_Datum.HpTitle;
WordsText.Text = photoAlbum_Datum.HpContent + " by " + photoAlbum_Datum.ImageAuthors;
LikesCountTextBlock.Text = photoAlbum_Datum.Praisenum.ToString();
//等待主要颜色获取成功后,就可以打开
ItemDetailsPannel.Visibility = Visibility.Visible;
JudeCurrentWidth();
}
/// <summary>
/// 点击保存图片
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ImageDownloadButton_Click(object sender, RoutedEventArgs e)
{
X();
}
public async void X()
{
string imageName = photoAlbum_Datum.HpcontentId+".jpg";
string imageUri = photoAlbum_Datum.HpImgUrl;
DownloadImageManager downloadImageManager = new DownloadImageManager();
await downloadImageManager.SaveImage(imageName, imageUri);
}
private void OpenSharePage(object sender, RoutedEventArgs e)
{
SharePage.Visibility = Visibility.Visible;
}
/// <summary>
/// 点击分享面版旁边的阴影 退出分享界面
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void CloseSharePage(object sender, Windows.UI.Xaml.Input.PointerRoutedEventArgs e)
{
SharePage.Visibility = Visibility.Collapsed;
}
/// <summary>
/// 点击复制连接按钮
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void CopyShare_link(object sender, RoutedEventArgs e)
{
string shareLinkString = photoAlbum_Datum.ShareList.Weibo.link;
DataPackage dataPackage = new DataPackage();
dataPackage.SetText(shareLinkString);
Clipboard.SetContent(dataPackage);
//当用户设置为不提示的时候 就不提示233
if ((bool)AppSettings.GetSetting("Toast"))
{
//ToastNotification toast = ToastHelper.ShowAToast("已经复制", shareLinkString);
//ToastNotificationManager.CreateToastNotifier().Show(toast);
PopupNotice popupNotice = new PopupNotice("已经复制到剪贴板");
popupNotice.ShowAPopup();
}
}
/// <summary>
/// 分享到微博
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ShareToWeibo(object sender, RoutedEventArgs e)
{
}
/// <summary>
/// 调用系统的分享
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ShareMore(object sender, RoutedEventArgs e)
{
DataTransferManager dataTransferManager = DataTransferManager.GetForCurrentView();
dataTransferManager.DataRequested += IndexPage_DataRequested;
DataTransferManager.ShowShareUI();
}
void IndexPage_DataRequested(DataTransferManager sender, DataRequestedEventArgs args)
{
string shareLinkString = photoAlbum_Datum.ShareList.Weibo.link;
DataPackage dataPackage = new DataPackage();
dataPackage.SetWebLink(new Uri(shareLinkString));
dataPackage.SetBitmap(RandomAccessStreamReference.CreateFromUri((new Uri(photoAlbum_Datum.HpImgUrl))));
dataPackage.Properties.Title = photoAlbum_Datum.HpTitle;
dataPackage.Properties.Description = "ONE for Windows10";
DataRequest request = args.Request;
request.Data = dataPackage;
}
/// <summary>
/// 滚动条滚动事件
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ItemListContainerScrollViewer_ViewChanged(object sender, ScrollViewerViewChangedEventArgs e)
{
ScrollViewer scrollViewer = sender as ScrollViewer;
if ((scrollViewer.VerticalOffset > scrollViewer.ViewportHeight) && listPageBackTopButtonIn == false && scrollViewer.VerticalOffset - listPagelastPosition >= 10) //
{
listPageBackTopButtonIn = true;
ListPageBackTopButtonIn.Begin();
listPageBackTopButtonOut = false;
}
else if (scrollViewer.VerticalOffset < scrollViewer.ViewportHeight && listPageBackTopButtonOut == false && scrollViewer.VerticalOffset - listPagelastPosition <= -10) //当滚动条滚动到 呈现的高度的位置时隐藏
{
listPageBackTopButtonOut = true;
ListPageBackTopButtonOut.Begin();
listPageBackTopButtonIn = false;
}
//判断滑倒底部 更新数据
if (scrollViewer.ScrollableHeight == scrollViewer.VerticalOffset && isAwait == true)
{
PreData();
}
listPagelastPosition = scrollViewer.VerticalOffset;
}
private async void PreData()
{
var time = _photoMonthList[_photoMonthList.Count - 1].HpMakettime;
DateTime dt = DateTime.Parse(time);
dt = dt.AddMonths(-1);
PhotoAlbum_GettingStarted data1 = new PhotoAlbum_GettingStarted();
isAwait = !isAwait;
data1 = await PhotoAlbumManager.GetPhotolistByLastMonth(dt.ToString("yyyy-MM-dd"));
isAwait = !isAwait;
data1.Data.ForEach(p => _photoMonthList.Add(p));
}
/// <summary>
/// 暂时每张照片的额info
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ShowImageInfo(object sender, RoutedEventArgs e)
{
ImageInfoPageMask.Visibility = Visibility.Visible;
ImageInfoPage.Visibility = Visibility.Visible;
ImageIinfo_Image.Source = new BitmapImage(new Uri(photoAlbum_Datum.HpImgUrl));
ImageIinfo_Author.Text = photoAlbum_Datum.HpAuthor + "&" + photoAlbum_Datum.ImageAuthors + "作品";
ImageIinfo_Time.Text = photoAlbum_Datum.HpMakettime;
ImageIinfo_Uri.Text = photoAlbum_Datum.WebUrl;
}
private void ImageInfoPage_PointerPressed(object sender, Windows.UI.Xaml.Input.PointerRoutedEventArgs e)
{
ImageInfoPageMask.Visibility = Visibility.Collapsed;
ImageInfoPage.Visibility = Visibility.Collapsed;
}
private void ListPageBackTopButton_Click(object sender, RoutedEventArgs e)
{
//放回顶部
ItemListContainerScrollViewer.ChangeView(null, 0, null);
}
private void CloseDetialPage(object sender, RoutedEventArgs e)
{
TitleBarHelper.ShowOrHideHamburgerButton(true);
TitleBarBackButton.Visibility = Visibility.Collapsed;
ItemDetailsPannel.Visibility = Visibility.Collapsed;
}
private void JudeCurrentWidth()
{
var width = Window.Current.Bounds.Width;
if (width <= 1000 && ItemDetailsPannel.Visibility == Visibility.Visible)
{
TitleBarHelper.ShowOrHideHamburgerButton(false);
TitleBarBackButton.Visibility = Visibility.Visible;
}
else
{
TitleBarHelper.ShowOrHideHamburgerButton(true);
TitleBarBackButton.Visibility = Visibility.Collapsed;
}
}
private void Grid_SizeChanged(object sender, SizeChangedEventArgs e)
{
JudeCurrentWidth();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Android.Graphics.Drawables;
using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Xamarin.Forms;
using Xamarin.Forms.Platform.Android;
using RenderTest.Renderers;
using RenderTest.Droid.Renderers;
[assembly: ExportRenderer(typeof(RoundCornersButton), typeof(RoundCornersButtonRenderer))]
namespace RenderTest.Droid.Renderers
{
public class RoundCornersButtonRenderer : ButtonRenderer
{
protected override void OnElementChanged(ElementChangedEventArgs<Xamarin.Forms.Button> e)
{
base.OnElementChanged(e);
if (e.NewElement != null)
{
//Subscribe to the events and stuff
}
else if (e.OldElement != null)
{
//Unsubscribe from events
}
if (Control != null)
{
GradientDrawable gradientDrawable = new GradientDrawable();
gradientDrawable.SetShape(ShapeType.Rectangle);
gradientDrawable.SetColor(Element.BackgroundColor.ToAndroid());
gradientDrawable.SetStroke(4, Element.BorderColor.ToAndroid());
gradientDrawable.SetCornerRadius(38.0f);
Control.SetBackground(gradientDrawable);
}
}
}
} |
using System;
using UIKit;
using Foundation;
using CoreGraphics;
using System.Collections.Generic;
using System.Linq;
using Xamarin.Forms.Platform.iOS;
using App2.ShowPopup;
namespace App2.iOS.ShowPopup
{
public static class ViewExtensions
{
public static IEnumerable<T> Flatten<T>(this IEnumerable<T> source, Func<T, IEnumerable<T>> childrenSelector)
{
foreach (var item in source)
{
yield return item;
foreach (var child in childrenSelector(item).Flatten(childrenSelector))
{
yield return child;
}
}
}
public static T FirstOrDefaultFromMany<T>(this IEnumerable<T> source, Func<T, IEnumerable<T>> childrenSelector, Predicate<T> condition)
{
while (true)
{
// return default if no items
var enumerable = source as T[] ?? source.ToArray();
if (source == null || !enumerable.Any()) return default(T);
// return result if found and stop traversing hierarchy
var attempt = enumerable.FirstOrDefault(t => condition(t));
if (!Equals(attempt, default(T))) return attempt;
// recursively call this function on lower levels of the
// hierarchy until a match is found or the hierarchy is exhausted
source = enumerable.SelectMany(childrenSelector);
}
}
}
public abstract class OverlayView : UIView
{
protected internal readonly float NavigationBarHeightPortrait = 45;
protected internal readonly float NavigationBarHeightOther = 33;
protected internal readonly float TabBarHeight = 49;
protected internal readonly float NotPortraitHeightOffset = 10;
private bool _registeredForObserver;
private readonly XOverLayControl _viewDetails;
protected OverlayView(IntPtr h) : base(h)
{
}
protected OverlayView()
{
}
private void RegisterForObserver()
{
var notificationCenter = NSNotificationCenter.DefaultCenter;
notificationCenter.AddObserver(UIApplication.DidChangeStatusBarOrientationNotification, DeviceOrientationDidChange);
UIDevice.CurrentDevice.BeginGeneratingDeviceOrientationNotifications();
_registeredForObserver = true;
}
protected OverlayView(XOverLayControl details, bool xibView = false)
{
// configurable bits
_viewDetails = details;
//this.BackgroundColor = UIColor.Black;
if (_viewDetails.HasNavigationBar == false)
{
// check NavigationBar
_viewDetails.HasNavigationBar =
UIApplication.SharedApplication.KeyWindow.Subviews.FirstOrDefaultFromMany(item => item.Subviews,
x => x is UINavigationBar) != null;
NavigationBarHeightOther = 0;
NavigationBarHeightPortrait = 0;
}
if (xibView == false)
{
SetViewProperties(this);
}
RegisterForObserver();
}
protected internal void SetViewProperties(UIView view)
{
BackgroundColor = _viewDetails.BackgroundColor != Xamarin.Forms.Color.Default ? _viewDetails.BackgroundColor.ToUIColor() : UIColor.White;
Alpha = 1; //(nfloat)this.ViewDetails.Alpha;
}
private void DeviceOrientationDidChange(NSNotification notification)
{
DoLayout();
}
internal abstract void DoLayout();
/// <summary>
/// Fades out the control and then removes it from the super view
/// </summary>
protected internal void Hide()
{
if (_viewDetails != null && _viewDetails.AnimateClosing)
{
Animate(
0.5, // duration
() => { Alpha = 0; },
RemoveFromSuperview
);
}
else
{
RemoveFromSuperview();
}
if (_registeredForObserver)
{
var notificationCenter = NSNotificationCenter.DefaultCenter;
notificationCenter.RemoveObserver(this, UIDevice.OrientationDidChangeNotification, UIApplication.SharedApplication);
UIDevice.CurrentDevice.EndGeneratingDeviceOrientationNotifications();
notificationCenter.RemoveObserver(this, UIApplication.DidBecomeActiveNotification, UIApplication.SharedApplication);
}
Dispose();
}
/// <summary>
/// Gets the height of the status bar.
/// </summary>
/// <value>The height of the status bar.</value>
protected internal nfloat StatusBarHeight
{
get
{
var statusHidden = UIApplication.SharedApplication.StatusBarHidden;
nfloat statusHeight = 0;
if (statusHidden == false)
{
statusHeight = UIApplication.SharedApplication.StatusBarFrame.Height;
}
return statusHeight;
}
}
protected internal void SetFrame()
{
Frame = GetFrame();
}
protected internal CGRect GetFrame()
{
var bounds = UIScreen.MainScreen.ApplicationFrame;
//Show overlay full Screen
var frame = new CGRect(0, StatusBarHeight, bounds.Width, bounds.Height);
return frame;
}
}
} |
using Library.DataAccess.Interface;
using Library.Services;
using Moq;
using NUnit.Framework;
using System;
using System.Collections.Generic;
using System.Text;
namespace Library.UnitTests
{
[TestFixture]
public class AuthorServiceTests
{
[TestCase(null)]
[TestCase("")]
[TestCase(" ")]
public void Create_AuthorNameNullOrSpace_Fails(string badName)
{
//Arrange
//Mock repository and create physical service to test
Mock<IAuthorRepository> fakeRepository = new Mock<IAuthorRepository>();
AuthorService authorService = new AuthorService(fakeRepository.Object);
//Act
authorService.Create(badName);
//Assert
Assert.ThrowsAsync<ArgumentException>(() => authorService.Create(badName));
}
}
}
|
using UnityEngine;
using System.Collections;
public class HunterComponent : MonoBehaviour
{
public Hunter hunterComponent;
}
|
using System;
using System.Collections.Generic;
using System.Linq;
namespace aoc2019
{
public class Day02
{
public int Solve(string input, Action<List<int>> modify = null)
{
var codes = input.Split(',').Select(int.Parse).ToList();
modify?.Invoke(codes);
var pos = 0;
while (true)
{
var intCode = codes[pos];
if (intCode == 1)
{
var term1 = codes[codes[pos + 1]];
var term2 = codes[codes[pos + 2]];
var outPos = codes[pos + 3];
codes[outPos] = term1 + term2;
}
else if (intCode == 2)
{
var term1 = codes[codes[pos + 1]];
var term2 = codes[codes[pos + 2]];
var outPos = codes[pos + 3];
codes[outPos] = term1 * term2;
}
else if (intCode == 99)
{
break;
}
pos += 4;
}
return codes[0];
}
}
} |
using System;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Windows.Forms;
namespace Vpit.Coursework
{
public partial class RowForm : Form
{
private const int rowHeight = 26;
public DataTable Table { get; set; }
public DataRow Row { get; set; }
protected bool isEditing;
private RowForm()
{
InitializeComponent();
}
public RowForm(DataRow row) : this()
{
Row = row;
Table = Row.Table;
isEditing = true;
}
public RowForm(DataTable table) : this()
{
Table = table;
Row = Table.NewRow();
isEditing = false;
}
private void RowForm_Load(object sender, EventArgs e)
{
var x = 12;
var y = 15;
foreach (var column in Table.Columns.Cast<DataColumn>().Select(c => c.ColumnName))
{
if (column == "Id")
{
continue;
}
Height += rowHeight;
Controls.Add(new Label
{
AutoSize = true,
Location = new Point(x, y),
Name = "label" + column,
Size = new Size(35, 13),
Text = column
});
Controls.Add(new TextBox
{
Location = new Point(x + 100, y - 3),
Name = "textBox" + column,
Size = new Size(160, 20),
Text = isEditing ? Row[column].ToString() : ""
});
y += rowHeight;
}
}
private void saveButton_Click(object sender, EventArgs e)
{
foreach (DataColumn column in Table.Columns)
{
if (column.ColumnName == "Id")
{
continue;
}
var textBox = (TextBox)Controls["textBox" + column.ColumnName];
Row[column] = textBox.Text;
}
}
}
}
|
using Nancy;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using InternetOfGreens.Domain;
namespace InternetOfGreens
{
public class PlantModule : NancyModule
{
public PlantModule(IPlantService svc)
: base("/plants")
{
Get["/"] = x =>
{
return Response.AsJson<object>(svc.GetAll());
};
}
}
}
|
namespace PicoShelter_DesktopApp.Infrastructure
{
public enum ExceptionType
{
UNTYPED,
MODEL_NOT_VALID,
USERNAME_ALREADY_REGISTERED,
EMAIL_ALREADY_REGISTERED,
CREDENTIALS_INCORRECT,
USER_NOT_FOUND,
ALBUM_NOT_FOUND,
YOU_NOT_OWNER_OF_IMAGE,
ADMIN_KICK_DISALLOWED,
USERCODE_ALREADY_TAKED,
INTERNAL_FILE_ERROR,
INPUT_IMAGE_INVALID,
ALBUM_ACCESS_FORBIDDEN,
UNREGISTERED_QUALITY_FORBIDDEN,
UNREGISTERED_DELETEIN_FORBIDDEN,
UNREGISTERED_ISPUBLICPROP_FORBIDDEN,
UNREGISTERED_JOINTOALBUM_FORBIDDEN,
CURRENT_EMAIL_WAS_ALREADY_CHANGED,
CONFIRMATIONTYPE_UNSUPPORTED,
USER_ALREADY_INVITED,
USER_ALREADY_JOINED
}
}
|
using System;
using System.Linq;
using System.Web.Mvc;
using ArteVida.Dominio.Contexto;
using ArteVida.Dominio.Repositorio;
using ArteVida.Dominio.Entidades;
using AutoMapper;
using AutoMapper.QueryableExtensions;
using Kendo.Mvc.Extensions;
using Kendo.Mvc.UI;
using ArteVida.GestorWeb.ViewModels;
namespace ArteVida.GestorWeb.Controllers
{
public class TabelaAuxiliarController : Controller
{
private DbContexto _contexto;
private RepositorioTabelaAuxiliar _repositorio;
public TabelaAuxiliarController()
{
_contexto = new DbContexto();
_repositorio = new RepositorioTabelaAuxiliar(_contexto);
// ViewData["Funcionarios"] = _repositorioFuncionario.ObterTodos().Select(c => new { Id = c.PessoaId, Nome = c.Nome }).OrderBy(x=>x.Nome);
}
public ActionResult Index()
{
return View();
}
public ActionResult RamoAtividades()
{
var model = new JanelaViewModel { Titulo = "Cadastro de Ramo de Atividades", Relatorio = "", Tela = "_GridRamoAtividades" };
return View(model);
}
public ActionResult Nacionalidades()
{
var model = new JanelaViewModel { Titulo = "Cadastro de Nacionalidade", Relatorio = "", Tela = "_GridNacionalidades" };
return View(model);
}
public ActionResult Cargos()
{
return View();
}
public ActionResult Acomodacoes()
{
return View();
}
public ActionResult Associacoes()
{
return View();
}
public ActionResult TipoPlanoSaude()
{
return View();
}
public ActionResult Ler([DataSourceRequest] DataSourceRequest request)
{
return Json(PegarTabelaAuxiliares().ToDataSourceResult(request));
}
public ActionResult LerRamoAtividade([DataSourceRequest] DataSourceRequest request)
{
return Json(PegarTabelaAuxiliares("Ramo de Atividade").ToDataSourceResult(request));
}
public ActionResult LerNacionalidade([DataSourceRequest] DataSourceRequest request)
{
return Json(PegarTabelaAuxiliares("Nacionalidade").ToDataSourceResult(request));
}
public ActionResult LerCargos([DataSourceRequest] DataSourceRequest request)
{
return Json(PegarTabelaAuxiliares("Cargo").ToDataSourceResult(request));
}
//LerAcomodacoes
public ActionResult LerAcomodacoes([DataSourceRequest] DataSourceRequest request)
{
return Json(PegarTabelaAuxiliares("Acomodações").ToDataSourceResult(request));
}
public ActionResult LerTipoPlano([DataSourceRequest] DataSourceRequest request)
{
return Json(PegarTabelaAuxiliares("Tipo de Plano").ToDataSourceResult(request));
}
public ActionResult LerAssociacoes([DataSourceRequest] DataSourceRequest request)
{
return Json(PegarTabelaAuxiliares("Tipo de Associação").ToDataSourceResult(request));
}
private IQueryable<TabelaAuxiliarViewModel> PegarTabelaAuxiliares(string tipo = "Todos")
{
if (tipo != "Todos")
{
//var dados = _repositorio.ObterTodos().Where(x => x.Tipo == tipo);
//return ListarDados(dados);
return _repositorio.ObterTodos().Where(x => x.Tipo == tipo).ProjectTo<TabelaAuxiliarViewModel>();
}
else
{
//var dados = _repositorio.ObterTodos();
//return ListarDados(dados);
return _repositorio.ObterTodos().ProjectTo<TabelaAuxiliarViewModel>();
}
}
//private static IQueryable<TabelaAuxiliarViewModel> ListarDados(IQueryable<TabelaAuxiliar> dados)
//{
// return dados.Select(t => new TabelaAuxiliarViewModel()
// {
// Id = t.Id,
// Nome = t.Nome,
// Tipo = t.Tipo
// });
//}
public ActionResult Incluir([DataSourceRequest] DataSourceRequest request, TabelaAuxiliarViewModel item)
{
if (ModelState.IsValid)
{
try
{
TabelaAuxiliar dados = Mapper.Map<TabelaAuxiliar>(item);
_repositorio.Inserir(dados);
_contexto.SaveChanges();
item.Id = dados.Id;
}
catch (Exception erro)
{
if (erro.InnerException.InnerException.Message.Contains("IdxNome"))
{
ModelState.AddModelError("", "O nome já foi incluído.");
}
_contexto.Rollback();
return Json(ModelState.ToDataSourceResult());
}
}
return Json(new[] { item }.ToDataSourceResult(request));
}
public ActionResult Atualizar([DataSourceRequest] DataSourceRequest request, TabelaAuxiliarViewModel item)
{
if (ModelState.IsValid)
{
try
{
TabelaAuxiliar dados = Mapper.Map<TabelaAuxiliar>(item);
dados = _repositorio.Atualizar(dados);
_contexto.Commit();
}
catch (Exception erro)
{
ModelState.AddModelError("", erro.Message);
_contexto.Rollback();
}
}
return Json(ModelState.ToDataSourceResult());
}
public ActionResult Excluir([DataSourceRequest] DataSourceRequest request, TabelaAuxiliarViewModel item)
{
try
{
_contexto.TabelasAuxiliares.Remove(_contexto.TabelasAuxiliares.Find(item.Id));
_contexto.SaveChanges();
ModelState.IsValidField("true");
}
catch (Exception erro)
{
ModelState.IsValidField("false");
ModelState.AddModelError("", erro.Message);
_contexto.Rollback();
}
return Json(ModelState.ToDataSourceResult());
}
}
} |
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
namespace Cw1
{
public class Program
{
public static async Task Main(string[] args)
{
if (args.Length == 0)
throw new ArgumentNullException();
var httpClient = new HttpClient();
try
{
var response = await httpClient.GetAsync(args[0]);
if (response.IsSuccessStatusCode)
{
var tmp = await response.Content.ReadAsStringAsync();
var reg = new Regex("[a-z]+[a-z0-9]*@[a-z0-9]+\\.[a-z]+", RegexOptions.IgnoreCase);
var matches = reg.Matches(tmp);
if (matches.Count == 0)
throw new Exception("Nie znaleziono adresów email");
HashSet<string> set = new HashSet<string>();
foreach (var match in matches)
set.Add(match.ToString());
foreach(var st in set)
Console.WriteLine(st);
}
httpClient.Dispose();
}
catch(InvalidOperationException argex) {
throw new ArgumentException();
}
catch(HttpRequestException ex)
{
throw new Exception("Bład w czasie pobierania strony");
}
catch(Exception e)
{
Console.WriteLine(e.Message);
}
}
}
}
|
using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
public partial class DeliveryReport : System.Web.UI.Page
{
ClientsReport obj_Class = new ClientsReport();
ProjectBased Obj_Class3 = new ProjectBased();
DataSet ds;
DataTable dt_ProjectNo = new DataTable();
DataSet ds_WBSNo = new DataSet();
string obj_Authenticated;
PlaceHolder maPlaceHolder;
UserControl obj_Tabs;
UserControl obj_LoginCtrl;
UserControl obj_WelcomCtrl;
UserControl obj_Navi;
UserControl obj_Navihome;
protected void Page_Load(object sender, EventArgs e)
{
//lbl_msg.Visible = false;
if (Session["UserID"] != string.Empty && Convert.ToInt32(Session["UserID"].ToString()) > 0)
{
if (!IsPostBack)
{
ChkAuthentication();
LoadDeliveryDetails();
Load_ProjectNo();
}
}
else
{
Response.Redirect("Index.html");
}
}
public void Load_ProjectNo()
{
dt_ProjectNo = obj_Class.BizConnect_Get_ThermaxProjectNO(Convert.ToInt32(Session["ClientID"].ToString()));
ddl_ProjectNo.DataSource = dt_ProjectNo;
ddl_ProjectNo.DataTextField = "ProjectNo";
ddl_ProjectNo.DataValueField = "ProjectID";
ddl_ProjectNo.DataBind();
ddl_ProjectNo.Items.Insert(0, "--Select--");
}
public void LoadDeliveryDetails()
{
try
{
ds = obj_Class.Bizconnect_DeliveryReport(Convert.ToInt32(Session["ClientID"].ToString()), Convert.ToInt32(Session["ClientAdrID"].ToString()));
if (ds.Tables[0].Rows.Count > 0)
{
Gridwindow.DataSource = ds;
Gridwindow.DataBind();
}
}
catch (Exception ex)
{
lbl_msg.Text = "Data Not Avaliable !";
}
}
public void ChkAuthentication()
{
obj_LoginCtrl = null;
obj_WelcomCtrl = null;
obj_Navi = null;
obj_Navihome = null;
if (Session["Authenticated"] == null)
{
Session["Authenticated"] = "0";
}
else
{
obj_Authenticated = Session["Authenticated"].ToString();
}
maPlaceHolder = (PlaceHolder)Master.FindControl("P1");
if (maPlaceHolder != null)
{
obj_Tabs = (UserControl)maPlaceHolder.FindControl("loginheader1");
if (obj_Tabs != null)
{
obj_LoginCtrl = (UserControl)obj_Tabs.FindControl("login1");
obj_WelcomCtrl = (UserControl)obj_Tabs.FindControl("welcome1");
// obj_Navi = (UserControl)obj_Tabs.FindControl("Navii");
//obj_Navihome = (UserControl)obj_Tabs.FindControl("Navihome1");
if (obj_LoginCtrl != null & obj_WelcomCtrl != null)
{
if (obj_Authenticated == "1")
{
SetVisualON();
}
else
{
SetVisualOFF();
}
}
}
else
{
}
}
else
{
}
}
public void SetVisualON()
{
obj_LoginCtrl.Visible = false;
obj_WelcomCtrl.Visible = true;
//obj_Navi.Visible = true;
//obj_Navihome.Visible = true;
}
public void SetVisualOFF()
{
obj_LoginCtrl.Visible = true;
obj_WelcomCtrl.Visible = false;
// obj_Navi.Visible = true;
//obj_Navihome.Visible = false;
}
protected void link_preview_Click(object sender, EventArgs e)
{
LinkButton b = (LinkButton)sender;
GridViewRow row = (GridViewRow)b.NamingContainer;
if (row != null)
{
Label imgid = (Label)Gridwindow.Rows[row.RowIndex].FindControl("lblplanID");
Session["ImageID"] = imgid.Text;
OpenFourViewWindow();
}
}
public void OpenFourViewWindow()
{
ClientScript.RegisterStartupScript(this.GetType(), "OpenWin", "<script>window.open('TruckFourView.aspx?imgID=" + Session["ImageID"].ToString() + "', 'mynewwin', 'width=600,height=500,scrollbars=yes,toolbar=1')</script>");
}
protected void ddl_ProjectNo_SelectedIndexChanged(object sender, EventArgs e)
{
ds_WBSNo = Obj_Class3.Bizconnect_ThermaxCnote_LoadWBSNoBasedOnProject(ddl_ProjectNo.SelectedItem.Text);
ddl_Wbsno.Items.Clear();
ddl_Wbsno.DataSource = ds_WBSNo;
ddl_Wbsno.DataTextField = "WBSNo";
ddl_Wbsno.DataValueField = "WBSNo";
ddl_Wbsno.DataBind();
ddl_Wbsno.Items.Insert(0, "--Select--");
}
protected void btn_Search_Click(object sender, EventArgs e)
{
dt_ProjectNo.Clear();
dt_ProjectNo = obj_Class.Bizconnect_Search_DeliveryReportByProjectNoAndWbSNo(Convert.ToInt32(Session["ClientID"].ToString()), Convert.ToInt32(Session["ClientAdrID"].ToString()),ddl_ProjectNo .SelectedItem .Text ,ddl_Wbsno.SelectedItem .Text);
Gridwindow.DataSource = dt_ProjectNo;
Gridwindow.DataBind();
}
protected void link_preview1_Click(object sender, EventArgs e)
{
}
protected void link_Unloading_Click(object sender, EventArgs e)
{
LinkButton b = (LinkButton)sender;
GridViewRow row = (GridViewRow)b.NamingContainer;
if (row != null)
{
Label imgid = (Label)Gridwindow.Rows[row.RowIndex].FindControl("lbl_UnloadConfirmNo");
Session["UnImgID"] = imgid.Text;
OpenUnloadImageWindow();
}
}
public void OpenUnloadImageWindow()
{
ClientScript.RegisterStartupScript(this.GetType(), "OpenWin", "<script>window.open('UnloadingTruckFrontImage.aspx?ImgID=" + Session["UnImgID"].ToString() + "', 'mynewwin', 'width=600,height=500,scrollbars=yes,toolbar=1')</script>");
}
protected void Gridwindow_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
Gridwindow.PageIndex = e.NewPageIndex;
LoadDeliveryDetails();
}
}
|
using System.Collections.Generic;
namespace MusicCatalogue.ConsoleClient
{
public interface IServiceProcessor<T> where T : class
{
IEnumerable<T> GetAll();
T GetByID(int id);
void Add(T entry);
void Modify(int id, T entry);
T Delete(int id);
}
}
|
using Entities.Models;
namespace Entities.ViewModels
{
public class CommentViewModel
{
public int ZoneId { get; set; }
public Comment comment { get; set; }
}
}
|
namespace ns11
{
using System;
using System.Runtime.InteropServices;
[StructLayout(LayoutKind.Sequential)]
internal struct Struct11
{
public const uint uint_0 = 0x800;
public const int int_0 = 11;
public const int int_1 = 6;
private const int int_2 = 5;
private const int int_3 = 2;
private static readonly uint[] uint_1;
private uint uint_2;
static Struct11()
{
uint_1 = new uint[0x200];
for (int i = 8; i >= 0; i--)
{
uint num2 = ((uint) 1) << (9 - i);
for (uint j = ((uint) 1) << ((9 - i) - 1); j < num2; j++)
{
uint_1[j] = ((uint) (i << 6)) + (((num2 - j) << 6) >> ((9 - i) - 1));
}
}
}
public void method_0()
{
this.uint_2 = 0x400;
}
public void method_1(uint uint_3)
{
if (uint_3 == 0)
{
this.uint_2 += (uint) ((0x800 - this.uint_2) >> 5);
}
else
{
this.uint_2 -= this.uint_2 >> 5;
}
}
public void method_2(Class61 class61_0, uint uint_3)
{
uint num = (class61_0.uint_2 >> 11) * this.uint_2;
if (uint_3 == 0)
{
class61_0.uint_2 = num;
this.uint_2 += (uint) ((0x800 - this.uint_2) >> 5);
}
else
{
class61_0.ulong_0 += num;
class61_0.uint_2 -= num;
this.uint_2 -= this.uint_2 >> 5;
}
if (class61_0.uint_2 < 0x1000000)
{
class61_0.uint_2 = class61_0.uint_2 << 8;
class61_0.method_7();
}
}
public uint method_3(uint uint_3)
{
return uint_1[(int) ((IntPtr) ((((this.uint_2 - uint_3) ^ -uint_3) & 0x7ffL) >> 2))];
}
public uint method_4()
{
return uint_1[this.uint_2 >> 2];
}
public uint method_5()
{
return uint_1[(int) ((0x800 - this.uint_2) >> 2)];
}
}
}
|
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 _1._1
{
public partial class FormSprite : Form
{
Graph graph;
Sprite sprite;
public FormSprite()
{
InitializeComponent();
graph = new Graph(picture.Width, picture.Height);//высоту и ширину берем прямо из элемента picturebox1 окна программы.
sprite = new Sprite();
picture.Image = graph.bmp;
currLine.x1 = -1;
}
MyLine currLine;
int currColor=0;
private void picture_MouseDown(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
currLine.x1 = e.X;
currLine.y1 = e.Y;
currLine.x2 = e.X;
currLine.y2 = e.Y;
return;
}
}
private void picture_MouseMove(object sender, MouseEventArgs e)
{
if (e.Button == System.Windows.Forms.MouseButtons.Left)
{
currLine.color = 0;
graph.Draw(currLine);
currLine.x2 = e.X;
currLine.y2 = e.Y;
currLine.color = currColor;
graph.Draw(currLine);
RefreshBitmap();
}
}
private void picture_MouseUp(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
currLine.color = currColor;
sprite.AddLine(currLine);
RefreshBitmap();
}
}
private void RefreshBitmap()
{
graph.Draw(sprite);
picture.Image = graph.bmp;
}
private void button6_Click(object sender, EventArgs e)
{
}
private void button_color_click(object sender, EventArgs e)
{
currColor=Convert.ToInt16(((Button)sender).Tag); //Узнаем, какая кнопка нажата, и получаем цифру из поля Tag нажатой кнопки. В этом поле решили хранить номер цвета.
} //Смотрим на объект "sender" как на кнопку, потому что это кнопка и есть.
private void button_clear_click(object sender, EventArgs e)
{
graph.Clear();
sprite.Clear();
RefreshBitmap();
}
private void ButtonUndo_Click(object sender, EventArgs e)
{
graph.Clear();
sprite.Undo();
RefreshBitmap();
}
private void ButtonSave_Click(object sender, EventArgs e)
{
if (save.ShowDialog () == System.Windows.Forms.DialogResult.OK)
sprite.Save(save.FileName);
}
private void ButtonLoad_Click(object sender, EventArgs e)
{
if (open.ShowDialog() != System.Windows.Forms.DialogResult.OK)
return;
sprite = Sprite.Load(open.FileName); //("sprite.xml")
graph.Clear();
RefreshBitmap();
}
//// 2 ////
//public partial class FormSprite : Form
//{
// Graph graph;
// Sprite sprite;
// public FormSprite()
// {
// InitializeComponent();
// graph = new Graph(picture.Width, picture.Height);//высоту и ширину берем прямо из элемента picturebox1 окна программы.
// sprite = new Sprite();
// picture.Image = graph.bmp;
// currLine.x1 = -1;
// }
// MyLine currLine;
// private void picture_MouseClick(object sender, MouseEventArgs e)
// {
// if (e.Button == MouseButtons.Right)
// {
// }
// }
// private void picture_MouseMove(object sender, MouseEventArgs e)
// {
// if (e.Button == System.Windows.Forms.MouseButtons.Left)
// {
// currLine.x2 = e.X;
// currLine.y2 = e.Y;
// currLine.color = 1;
// graph.Draw(currLine);
// picture.Image = graph.bmp;
// }
// }
// private void picture_MouseDown(object sender, MouseEventArgs e)
// {
// if (e.Button == MouseButtons.Left)
// {
// currLine.x1 = e.X;
// currLine.y1 = e.Y;
// currLine.x2 = e.X;
// currLine.y2 = e.Y;
// return;
// }
// }
///// 1 /////
//public partial class FormSprite : Form
//{
// Graph graph;
// Sprite sprite;
// public FormSprite()
// {
// InitializeComponent();
// graph = new Graph(picture.Width, picture.Height);//высоту и ширину берем прямо из элемента picturebox1 окна программы.
// sprite = new Sprite();
// picture.Image = graph.bmp;
// lastX = -1;
// }
// int lastX;
// int lastY;
// private void picture_MouseClick(object sender, MouseEventArgs e)
// {
// if(e.Button == MouseButtons.Left)
// {
// if (lastX != -1)
// {
// sprite.AddLine(1, lastX, lastY, e.X, e.Y);
// graph.Draw(sprite);
// picture.Image = graph.bmp;
// }
// lastX = e.X;
// lastY = e.Y;
// return;
// }
// if (e.Button == MouseButtons.Right)
// {
// if (lastX == -1)
// return;
// sprite.AddLine(1, lastX, lastY, e.X, e.Y);
// graph.Draw(sprite);
// picture.Image = graph.bmp;
// lastX = -1;
// }
// }
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Configuration;
namespace SEGU_ACCESO
{
public class clsSEGU_NEGO
{
string sDE_CADENA = ConfigurationManager.ConnectionStrings["SEGURIDAD_JC"].ToString();
}
}
|
using UnityEngine;
using System.Collections;
public class Enemy : MonoBehaviour
{
//Variable Declarations
public int mDifficulty;
protected int mPlayerDamage; // amount of damage the Enemy may do to the player based on the difficulty setting.
protected float mMoveSpeed; // general speed that the Enemy may move based on the difficulty setting.
private float mMoveSpeedX; // X component of mMoveSpeed
private float mMoveSpeedY; // Y component of mMoveSpeed
private Vector2 mMinWalkPoint; //variables to determine if the Player has stepped outside of the Enemy's boundary.
private Vector3 mMaxWalkPoint;
private Rigidbody2D mMyRigidBody;
//variables for the walk() function
private bool mIsWalking;
private float mWalkTime = 0.5f;
private float mWalkCounter;
private float mWaitTime = 0.1f;
private float mWaitCounter;
private int mWalkDirection;
public Collider2D mWalkZone; //variable to define the boundary that the Enemies may be active in
private bool mHasWalkZone;
private Transform mTarget;
//** End Variable Declarations ** //
void Start()
{
initiate ();
}
//initiate function: allows subclasses to start the same way.
protected virtual void initiate()
{
if (mDifficulty>0)
{
mMoveSpeed = mDifficulty;
mPlayerDamage = mDifficulty * 5;
}
mMyRigidBody = GetComponent<Rigidbody2D> ();
mTarget = GameObject.FindWithTag("Player").transform;
if (mTarget)
{
FindObjectOfType<ZG_AudioManager>().playDynamicSound("ememyPursuit1");
}
mWaitCounter = mWaitTime;
mWalkCounter = mWalkTime;
chooseDirection();
if (mWalkZone != null)
{
mMinWalkPoint = mWalkZone.bounds.min;
mMaxWalkPoint = mWalkZone.bounds.max;
mHasWalkZone = true;
}
}
void Update()
{
updateEnemy ();
}
//function that allows subclasses to update the same as the superclass
protected virtual void updateEnemy()
{
if (mTarget)
{
attackPlayer ();
//lose interest in the Player if the Player leaves the Enemy's boundary
if ((mTarget.position.y > mMaxWalkPoint.y) ||
(mTarget.position.x > mMaxWalkPoint.x) || (mTarget.position.y < mMinWalkPoint.y) ||
(mTarget.position.x < mMinWalkPoint.x))
{
mTarget = null;
}
} else
{
// wander around aimlessly until a target (the Player) is acquired.
walk ();
mTarget = GameObject.FindWithTag("Player").transform;
if (mTarget)
{
FindObjectOfType<ZG_AudioManager>().playDynamicSound("ememyPursuit1");
}
//prevent enemy from acquiring an interest in the Player if the Player is outside the Enemy's boundary
if ((mTarget.position.y > mMaxWalkPoint.y) ||
(mTarget.position.x > mMaxWalkPoint.x) || (mTarget.position.y < mMinWalkPoint.y) ||
(mTarget.position.x < mMinWalkPoint.x))
{
mTarget = null;
}
}
}
//defines how the enemies wander around when there is no Player to chase
private void walk()
{
if (mIsWalking)
{
mWalkCounter -= Time.deltaTime;
switch (mWalkDirection)
{
case 0:
mMyRigidBody.velocity = new Vector2 (0, mMoveSpeed);
mMyRigidBody.rotation = 180;
if (mHasWalkZone && transform.position.y > mMaxWalkPoint.y)
{
mMyRigidBody.velocity = new Vector2 (0, -mMoveSpeed);
mIsWalking = false;
mWaitCounter = mWaitTime;
}
break;
case 1:
mMyRigidBody.velocity = new Vector2 (mMoveSpeed, 0);
mMyRigidBody.rotation = 90;
if (mHasWalkZone && transform.position.x > mMaxWalkPoint.x)
{
mMyRigidBody.velocity = new Vector2 (-mMoveSpeed, 0);
mIsWalking = false;
mWaitCounter = mWaitTime;
}
break;
case 2:
mMyRigidBody.velocity = new Vector2 (0, -mMoveSpeed);
mMyRigidBody.rotation = 0;
if (mHasWalkZone && transform.position.y < mMinWalkPoint.y)
{
mMyRigidBody.velocity = new Vector2 (0, mMoveSpeed);
mIsWalking = false;
mWaitCounter = mWaitTime;
}
break;
case 3:
mMyRigidBody.velocity = new Vector2 (-mMoveSpeed, 0);
mMyRigidBody.rotation = 270;
if (mHasWalkZone && transform.position.x < mMinWalkPoint.x)
{
mMyRigidBody.velocity = new Vector2 (mMoveSpeed, 0);
mIsWalking = false;
mWaitCounter = mWaitTime;
}
break;
}
if (mWalkCounter < 0)
{
mIsWalking = false;
mWaitCounter = mWaitTime;
}
}
else
{
mWaitCounter -= Time.deltaTime;
mMyRigidBody.velocity = Vector2.zero;
if (mWaitCounter < 0)
{
chooseDirection ();
}
}
}
//simple function to choose a random direction to move in the walk() function
public void chooseDirection()
{
mWalkDirection = Random.Range (0, 4);
mIsWalking = true;
mWalkCounter = mWalkTime;
}
//function to chase the Player
public void attackPlayer ()
{
//if the Enemy has a defined boundary, lose interest in the Player if the Player leaves that boundary.
if (mHasWalkZone)
{
if ((transform.position.y > mMaxWalkPoint.y) ||
(transform.position.x > mMaxWalkPoint.x) || (transform.position.y < mMinWalkPoint.y) ||
(transform.position.x < mMinWalkPoint.x))
{
mTarget = null;
return;
}
}
//code to determine the Enemy's direction of movement relative to the Player's position
if (mTarget.position.x < mMyRigidBody.position.x)
{
mMoveSpeedX = -mMoveSpeed;
} else if (mTarget.position.x > mMyRigidBody.position.x)
{
mMoveSpeedX = mMoveSpeed;
} else
{
mMoveSpeedX = 0;
}
if (mTarget.position.y < mMyRigidBody.position.y)
{
mMoveSpeedY = -mMoveSpeed;
} else if (mTarget.position.y > mMyRigidBody.position.y)
{
mMoveSpeedY = mMoveSpeed;
} else
{
mMoveSpeedY = 0;
}
//set the velocity based on the speed values for X and Y that were just determined.
mMyRigidBody.velocity = new Vector2 (mMoveSpeedX, mMoveSpeedY);
//REUSED CODE - user filipst on StackOverflow
//rotate the Enemy to face the Player
Vector3 dir = mTarget.position - mMyRigidBody.transform.position;
float angle = Mathf.Atan2(dir.y,dir.x) * Mathf.Rad2Deg + 90;
mMyRigidBody.transform.rotation = Quaternion.AngleAxis(angle, Vector3.forward);
//END REUSED CODE
}
//sets the boundary that the Enemies can be active in. If nothing is set, the enemies may wander anywhere.
public void setRoom(Collider2D r)
{
mWalkZone = r;
}
//Upon colliding the Player, respond by dealing damage to the Player and dying
//This functions as a very basic fighting mechanic
private void OnTriggerEnter2D(Collider2D collision)
{
uint damage = (uint)(int)mPlayerDamage;
if (collision.tag == "Player")
{
LH_Health playerHP = collision.gameObject.GetComponent<LH_Health> ();
FindObjectOfType<ZG_AudioManager>().playDynamicSound("enemyTakeDamage1");
playerHP.doDamage (damage);
Destroy (gameObject);
}
}
}
|
using System;
using System.Collections.Generic;
namespace WebsiteBanHang.Models
{
public class OrdersImportGoods
{
public OrdersImportGoods()
{
OrderImportGoodsDetails = new HashSet<OrderImportGoodsDetails>();
}
public int OrderId { get; set; }
public int? SupplierId { get; set; }
public DateTime OrderDate { get; set; }
public Guid? UserId { get; set; }
public decimal? TotalPrice { get; set; }
public UserInfo User { get; set; }
public Suppliers Supplier { get; set; }
public ICollection<OrderImportGoodsDetails> OrderImportGoodsDetails { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using com.gseo.browser.uri;
using System.Configuration;
using System.Diagnostics;
using System.Net;
namespace com.gseo.persistent.remote
{
/// <summary>
/// 調用遠端HistoryService,達成輸出歷史記綠
/// </summary>
public class HistoryExporter
{
private Uri _BASE_ADDRESS;
private string _JSON_STRING = "application/json";
private HttpClient _client;
public HistoryExporter()
{
string webApiServer = "http://192.168.100.85:8090/";
try
{
webApiServer = ConfigurationManager.AppSettings["PCGuardWebAPIServer"];
}
catch (Exception)
{
}
_BASE_ADDRESS = new Uri(webApiServer);
if (_client == null)
{
_client = new HttpClient();
_client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue(_JSON_STRING));
_client.BaseAddress = _BASE_ADDRESS;
}
}
/// <summary>
/// 新增一筆瀏覽歷史記綠
/// </summary>
/// <param name="his"></param>
/// <param name="empNo"></param>
/// <param name="deptNo"></param>
/// <returns>success表示成功,否則是[失敗訊息]</returns>
public string Export(URL his, string empNo, string deptNo)
{
if (his == null)
return "";
//準備json
string json = JsonConvert.SerializeObject(new
{
url = his.URI,
title = his.Title,
browser_type = his.BrowserType.ToString(),
last_visit_time = his.VisitedTime.ToFileTimeUtc(),
emp_no = empNo,
dept_no = deptNo
});
//呼叫WebAPI
return Post("api/PCGuardWebLib/PCGuardWebLib/HistoryService/Add", json);
}
/// <summary>
/// 遠端服務是否存活著
/// </summary>
/// <returns>true:是 / false:否</returns>
public bool IsAvailable()
{
string result = Post("api/PCGuardWebLib/PCGuardWebLib/HistoryService/Test", null);
if (result != null && result.Equals("true"))
return true;
return false;
}
/// <summary>
/// 送出Post請求
/// </summary>
/// <param name="uri">URI資源</param>
/// <param name="json">送出參數</param>
/// <returns>Post請求的回應, return null表示發生錯誤</returns>
private string Post(string uri, string json)
{
StringContent sc = null;
if(json != null && !json.Equals(""))
sc = new StringContent(json, Encoding.UTF8, _JSON_STRING);
try
{
HttpResponseMessage response = _client.PostAsync(uri, sc).Result;
if (response == null || response.StatusCode != HttpStatusCode.OK)
return null;
string responseBody = response.Content.ReadAsStringAsync().Result;
if (responseBody == null)
return null;
string result = JsonConvert.DeserializeObject<string>(responseBody);
return result;
}
catch (InvalidOperationException ex)
{
Debug.WriteLine(ex.ToString());
}
catch (AggregateException ex)
{
Debug.WriteLine(ex.ToString());
}
return null;
}
}
}
|
using System.Collections.Generic;
using System.Linq;
namespace MZcms.CommonModel
{
public class Privileges
{
public Privileges()
{
Privilege = new List<GroupActionItem>();
}
public List<GroupActionItem> Privilege { get; set; }
}
public class GroupActionItem
{
public GroupActionItem()
{
Items = new List<ActionItem>();
}
public string GroupName { set; get; }
public List<ActionItem> Items { get; set; }
}
public class ActionItem
{
public ActionItem()
{
Controllers = new List<Controllers>();
}
public string Name { get; set; }
public string Url { get; set; }
public List<Controllers> Controllers { set; get; }
public int PrivilegeId { get; set; }
public MZcms.CommonModel.AdminCatalogType Type { get; set; }
/// <summary>
/// 链接打开方式,blank,parent,self,top
/// </summary>
public string LinkTarget { get; set; }
}
public class Controllers
{
public Controllers()
{
ActionNames = new List<string>();
}
public string ControllerName { set; get; }
public List<string> ActionNames { set; get; }
}
}
|
using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Collections.Generic;
using System.Xml.Linq;
using System.Linq;
using System.Windows.Resources;
using Tff.Panzer.Models.Army;
using Tff.Panzer.Models.VictoryCondition;
namespace Tff.Panzer.Factories.VictoryCondition
{
public class ObjectiveTypeFactory
{
public List<ObjectiveType> ObjectiveTypes { get; private set; }
public ObjectiveTypeFactory()
{
ObjectiveTypes = new List<ObjectiveType>();
Uri uri = new Uri(Constants.ObjectiveTypeDataPath, UriKind.Relative);
XElement applicationXml;
StreamResourceInfo xmlStream = Application.GetResourceStream(uri);
applicationXml = XElement.Load(xmlStream.Stream);
var data = from t in applicationXml.Descendants("ObjectiveType")
select t;
ObjectiveType objectiveType = null;
foreach (var d in data)
{
objectiveType = new ObjectiveType();
objectiveType.ObjectiveTypeId = (Int32)d.Element("ObjectiveTypeId");
objectiveType.ObjectiveTypeDescription = (String)d.Element("ObjectiveTypeDescription");
ObjectiveTypes.Add(objectiveType);
}
}
public ObjectiveType GetObjectiveType(int objectiveTypeId)
{
ObjectiveType objectiveType = (from mt in this.ObjectiveTypes
where mt.ObjectiveTypeId == objectiveTypeId
select mt).First();
return objectiveType;
}
}
}
|
#r "Newtonsoft.Json"
using System.Net;
using System.Text;
using System.Net.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Primitives;
using Newtonsoft.Json;
public static string AAD_TENANTID = Environment.GetEnvironmentVariable("AAD_TENANTID");
public static string ENVIRONMENT_NAME = Environment.GetEnvironmentVariable("ENVIRONMENT_NAME");
public static string CLIENT_ID = Environment.GetEnvironmentVariable("CLIENT_ID");
public static string CLIENT_SECRET = Environment.GetEnvironmentVariable("CLIENT_SECRET");
public static string ADMIN_USERNAME = Environment.GetEnvironmentVariable("ADMIN_USERNAME");
public static string ADMIN_PASSWORD = Environment.GetEnvironmentVariable("ADMIN_PASSWORD");
public static string AUTHCODE_URI = Environment.GetEnvironmentVariable("AUTHCODE_URI");
public static string EVENT_URI = Environment.GetEnvironmentVariable("EVENT_URI");
public static async Task<IActionResult> Run(HttpRequest req, ILogger log)
{
HttpClient client = new HttpClient();
switch(req.Method)
{
case "GET":
{
log.LogInformation("C# HTTP trigger function processed a GET request.");
string AuthCode = "";
string State = "";
AuthCode = req.Query["code"];
State = req.Query["state"];
if(AuthCode != null && State != null)
{
string resp = "";
try{
resp = await PostAuthCodeToBCAsync(JsonConvert.SerializeObject(new { code = AuthCode ,state = State}),log);
log.LogInformation(resp);
dynamic respData = JsonConvert.DeserializeObject(resp);
string responseStringMessage = "";
switch(respData?.value.ToString())
{
case "OK":
responseStringMessage = "Authorization successfully passed. Please refresh the Square Settings page in Business Central. You can close this tab.";
break;
case "FAILED":
responseStringMessage = "Authorization failed. Failed to retrieve access token. You can close this tab.";
break;
}
return new OkObjectResult(responseStringMessage);
}
catch(Exception ex)
{
return new BadRequestObjectResult(ex.Message + ": " + resp);
}
}
else
{
return new BadRequestObjectResult("Authorization denied. You chose to deny access to the app.");
}
break;
}
case "POST" :
{
log.LogInformation("C# HTTP trigger function processed a POST request.");
try{
string documentContents = "{\"key1\":\"value\"}";
string requestBody = await new StreamReader(req.Body).ReadToEndAsync();
string resp = await PostEventToBCAsync(JsonConvert.SerializeObject(new { inputJson = requestBody}), log);
log.LogInformation(resp);
return new OkObjectResult(resp);
}
catch(Exception ex)
{
return new BadRequestObjectResult(ex.Message);
}
break;
}
default:
{
return new BadRequestObjectResult($"HTTPMethod {req.Method} is not supported!");
}
}
}
public static async Task<string> PostEventToBCAsync(string jsonBody, ILogger log)
{
HttpClient client = new HttpClient();
client.DefaultRequestHeaders.Add("Authorization", $"Bearer {await GetBearerTokenAsync()}");
var data = new StringContent(jsonBody, Encoding.UTF8, "application/json");
string postUri = $"https://api.businesscentral.dynamics.com/v2.0/{AAD_TENANTID}/{ENVIRONMENT_NAME}/{EVENT_URI}";
log.LogInformation(postUri);
log.LogInformation(jsonBody);
var response = await client.PostAsync(postUri, data);
var responseString = await response.Content.ReadAsStringAsync();
return responseString;
}
public static async Task<string> PostAuthCodeToBCAsync(string jsonBody, ILogger log)
{
HttpClient client = new HttpClient();
client.DefaultRequestHeaders.Add("Authorization", $"Bearer {await GetBearerTokenAsync()}");
var data = new StringContent(jsonBody, Encoding.UTF8, "application/json");
string postUri = $"https://api.businesscentral.dynamics.com/v2.0/{AAD_TENANTID}/{ENVIRONMENT_NAME}/{AUTHCODE_URI}";
log.LogInformation(postUri);
log.LogInformation(data.ReadAsStringAsync().Result);
var response = await client.PostAsync(postUri, data);
var responseString = await response.Content.ReadAsStringAsync();
return responseString;
}
public static async Task<string> GetBearerTokenAsync()
{
HttpClient client = new HttpClient();
client.DefaultRequestHeaders.Add("Authorization", $"Basic {EncodeTo64(CLIENT_ID + ":" + CLIENT_SECRET)}");
var grantValues = new Dictionary<string, string>
{
{ "grant_type", "password" },
{ "username", ADMIN_USERNAME },
{ "password", ADMIN_PASSWORD },
{ "resource", "https://api.businesscentral.dynamics.com/" }
};
var grantContent = new FormUrlEncodedContent(grantValues);
var response = await client.PostAsync($"https://login.windows.net/{AAD_TENANTID}/oauth2/token", grantContent);
var responseString = await response.Content.ReadAsStringAsync();
dynamic TokenData = JsonConvert.DeserializeObject(responseString);
return TokenData != null ? TokenData?.access_token : "";
}
public static string EncodeTo64(string toEncode)
{
byte[] toEncodeAsBytes = System.Text.ASCIIEncoding.ASCII.GetBytes(toEncode);
string returnValue = System.Convert.ToBase64String(toEncodeAsBytes);
return returnValue;
}
|
using System.Collections.Generic;
using System.Linq;
namespace LSystemsPlants.Core.L_Systems
{
public class Rule
{
public Rule(Symbol left, IEnumerable<Symbol> right)
{
Predecessor = left;
Successor = right.ToArray();
}
public Symbol Predecessor { get; private set; }
public Symbol[] Successor { get; private set; }
}
}
|
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Linq;
using System.Threading.Tasks;
using dk.via.ftc.businesslayer.Models;
using Newtonsoft.Json;
using System.IO;
using System.Text;
using System.Threading;
using dk.via.ftc.businesslayer.Models.DTO;
using dk.via.ftc.businesslayer.Persistence;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.DependencyInjection;
namespace dk.via.businesslayer.Data.Services
{
public class ProductService : IProductService
{
private string uri = "https://localhost:44332/db";
private string uri2 = "https://localhost:44332/db/Strains";
private readonly HttpClient client = new HttpClient();
private StrainContext sc;
public ProductService(IServiceProvider serviceProvider)
{
sc = serviceProvider.GetRequiredService<StrainContext>();
}
public IList<Product> Products { get; set; }
public async Task AddProductAsync(Product product)
{
//string productAsJson = JsonSerializer.Serialize(product);
//HttpContent content = new StringContent(productJson.Encoding.UTF8, "application/json");
//HttpResponseMessage response = await client.PutAsync(uri + "/Products", content);
//Console.WriteLine(response.ToString());
}
public async Task<Strain> GetStrainByIDAsync(int id)
{
Task<string> stringAsync = client.GetStringAsync(uri2 + "/Strain/" + id);
string message = await stringAsync;
Strain strain = System.Text.Json.JsonSerializer.Deserialize<Strain>(message);
return strain;
}
public async Task <ProductStrain> GetProductAsyncByStrain(int strain_id)
{
Task<string> stringAsync = client.GetStringAsync(uri + "/Product/"+strain_id);
string message = await stringAsync;
Product product= System.Text.Json.JsonSerializer.Deserialize<Product>(message);
Strain strain = await GetStrainByIDAsync(strain_id);
ProductStrain ps = new ProductStrain();
ftc.businesslayer.Models.DTO.Effects ef = new ftc.businesslayer.Models.DTO.Effects();
ef.medical = strain.Effects.First().Medical.ToList();
ef.negative = strain.Effects.First().Negative.ToList();
ef.positive = strain.Effects.First().Positive.ToList();
ps.effects = ef;
ps.flavors.Add("DisabledDueToRestrictions");
ps.ProductId = product.ProductId;
ps.id = strain.StrainId;
ps.StrainId = strain.StrainId;
ps.race = strain.Race;
ps.strainname = strain.StrainName;
ps.GrowType = product.GrowType;
ps.Orderlines = product.Orderlines;
ps.Unit = product.Unit;
ps.Vendor = product.Vendor;
ps.AvailableInventory = product.AvailableInventory;
ps.IsAvailable = product.IsAvailable;
ps.ProductName = product.ProductName;
ps.ReservedInventory = product.ReservedInventory;
ps.ThcContent = product.ThcContent;
ps.VendorId = product.VendorId;
return ps;
}
public async Task<IList<ProductStrain>> GetProductsAllProductsAsync()
{
Task<string> stringAsync = client.GetStringAsync(uri + "/Product/Products/All");
string message = await stringAsync;
IList<Product> results = JsonConvert.DeserializeObject < IList<Product>>(message);
IList<ProductStrain> pss = new List<ProductStrain>();
foreach (Product product in results)
{
StrainAPIObj strain = sc.GetStrainById(product.StrainId);
ProductStrain ps = new ProductStrain();
ps.effects = strain.effects;
ps.flavors = strain.flavors;
ps.ProductId = product.ProductId;
ps.id = strain.id;
ps.StrainId = strain.id;
ps.race = strain.race;
ps.strainname = strain.strainname;
ps.GrowType = product.GrowType;
ps.Orderlines = product.Orderlines;
ps.Unit = product.Unit;
ps.Vendor = product.Vendor;
ps.AvailableInventory = product.AvailableInventory;
ps.IsAvailable = product.IsAvailable;
ps.ProductName = product.ProductName;
ps.ReservedInventory = product.ReservedInventory;
ps.ThcContent = product.ThcContent;
ps.VendorId = product.VendorId;
pss.Add(ps);
}
return pss;
}
}
} |
using System.Text;
using System;
using System.Collections.Generic;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json;
using System.Net.Http;
using System.Drawing;
using System.Collections.ObjectModel;
using System.Xml;
using System.ComponentModel;
using System.Reflection;
namespace LinnworksAPI
{
public class Add_PurchaseOrderItemParameter
{
public Guid pkPurchaseId;
public Guid fkStockItemId;
public Int32 Qty;
public Int32 PackQuantity;
public Int32 PackSize;
public Decimal Cost;
public Decimal TaxRate;
}
} |
// -----------------------------------------------------------------------
// <copyright file="IOptimizerFactory.cs" company="Microsoft Corporation">
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root
// for license information.
// </copyright>
// -----------------------------------------------------------------------
namespace Mlos.Core
{
/// <summary>
/// Optimizer factory interface.
/// </summary>
public interface IOptimizerFactory
{
/// <summary>
/// A factory to create SimpleBayesianOptimizers.
/// </summary>
/// <typeparam name="TOptimizationProblem">Optimization problem type.</typeparam>
/// <param name="optimizationProblem">Instance of optimization problem. </param>
/// <returns>Instance of optimizer proxy.</returns>
public IOptimizerProxy CreateRemoteOptimizer<TOptimizationProblem>(TOptimizationProblem optimizationProblem)
where TOptimizationProblem : IOptimizationProblem;
}
}
|
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Sunny.DB;
using Sunny.Lib;
namespace MOAcceptanceFilegenerator
{
public static class DataAccessHelper
{
static DataAccessHelper()
{
SqlContext _sql = new SqlContext(ConfigurationManager.ConnectionStrings["MoBillingAppDb"].ToString());
SqlRepository.Context = _sql;
}
public static string[] GetAllMoName()
{
List<string> moNameList = new List<string>();
string sqlString = "select distinct [mo_id] from [MobileBilling_Dev].[dbo].[MoConfigurations]";
DataSet ds = SqlRepository.Context.ExecuteDataSet(sqlString, null);
if (ds != null && ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
{
foreach (DataRow row in ds.Tables[0].Rows)
{
moNameList.Add(row[0].ToString());
}
}
return moNameList.ToArray();
}
public static List<MOAcceptanceFileRecord> GetAcceptanceRecords(int maxCount, string moName, string filters)
{
List<MOAcceptanceFileRecord> moAcceptanceFileRecords = new List<MOAcceptanceFileRecord>();
string sqlString = string.Format(ConfigurationHelper.GetAppSettingsConfigrationByName("GetMoAcceptanceRecordsSqlStringFormat"), maxCount, moName);
if (!string.IsNullOrEmpty(filters))
{
sqlString = string.Format(sqlString, maxCount, filters);
}
DataSet ds = SqlRepository.Context.ExecuteDataSet(sqlString, null);
if (ds != null && ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
{
foreach (DataRow row in ds.Tables[0].Rows)
{
MOAcceptanceFileRecord acceptanceFileRecord = Sunny.Lib.ConvertHelper.GetEntityFromSPResult<MOAcceptanceFileRecord>(row);
if (acceptanceFileRecord != null)
{
moAcceptanceFileRecords.Add(acceptanceFileRecord);
}
}
}
return moAcceptanceFileRecords;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Drawing;
using PhotoFrame.Domain.Model;
namespace PhotoFrame.Domain.UseCase
{
public class SearchFolder
{
private readonly IPhotoRepository _photoRepository;
private readonly IPhotoFileService _photoFileService;
public SearchFolder(IPhotoRepository photoRepository, IPhotoFileService photoFileService)
{
_photoRepository = photoRepository;
_photoFileService = photoFileService;
}
/// <summary>
/// 指定したディレクトリ直下のフォトのリストを返す
/// </summary>
/// <param name="folderPath"></param>
/// <returns></returns>
public IEnumerable<Photo> Execute(string folderPath)
{
var files = _photoFileService.FindAllPhotoFilesFromDirectory(folderPath);
var photosInFolder = new List<Photo>();
if (files == null)
{
return null;
}
var photos = _photoRepository.Find(allPhoto => allPhoto);
foreach (var file in files)
{
var searchedPhoto = photos.SingleOrDefault(photo => photo.File.FilePath == file.FilePath);
if (searchedPhoto != null)
{
photosInFolder.Add(searchedPhoto);
}
else
{
var photo = Photo.CreateFromFile(file, GetDateTime(file.FilePath));
photosInFolder.Add(photo);
_photoRepository.Store(photo);
}
}
return photosInFolder;
}
/// <summary>
/// 非同期処理
/// </summary>
/// <param name="directoryName"></param>
/// <returns></returns>
public async Task<IEnumerable<Photo>> ExecuteAsync(string folderPath)
{
var files = _photoFileService.FindAllPhotoFilesFromDirectory(folderPath);
var photosInFolder = new List<Photo>();
if (files == null)
{
return null;
}
var photos = _photoRepository.Find(allPhoto => allPhoto);
var photosInDirectory = await Task.Run(() =>
{
var photosList = new List<Photo>();
foreach (var file in files)
{
var searchedPhoto = photos.SingleOrDefault(photo => photo.File.FilePath == file.FilePath);
if (searchedPhoto != null)
{
photosInFolder.Add(searchedPhoto);
}
else
{
var photo = Photo.CreateFromFile(file, GetDateTime(file.FilePath));
photosInFolder.Add(photo);
_photoRepository.Store(photo);
}
}
return photosList;
});
return photosInDirectory;
}
/// <summary>
/// 撮影日取得
/// </summary>
/// <param name="filePath"></param>
/// <returns></returns>
private DateTime GetDateTime(string filePath)
{
//読み込む
System.IO.FileStream stream = System.IO.File.OpenRead(filePath);
Image bmp = Image.FromStream(stream, false, false);
//var bmp = new System.Drawing.Bitmap(filePath);
//Exif情報を列挙する
var exifItem = bmp.PropertyItems.SingleOrDefault(item => item.Id == 0x9003 && item.Type == 2);
if(exifItem != null)
{
//文字列に変換する
var val = Encoding.ASCII.GetString(exifItem.Value);
val = val.Trim(new char[] {'\0'});
//DateTimeに変換
var date = DateTime.ParseExact(val, "yyyy:MM:dd HH:mm:ss", null);
return date;
}
else
{
// 作成日時を取得する
var date = System.IO.File.GetCreationTime(filePath);
return date;
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Tanki
{
class ServerManageEngine:ServerEngineAbs
{
public ServerManageEngine(IRoom inRoom) : base(inRoom)
{
this.ProcessMessage = ProcessMessage;
this.ProcessMessages = null;
}
public override ProcessMessageHandler ProcessMessage { get; protected set; }
public override ProcessMessagesHandler ProcessMessages { get; protected set; }
private void ProcessMessageHandler(IPackage msg)
{
// нужно реализовать обработку управляющих сообщений клиет-сервер
}
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Emgu.CV.Structure;
namespace LearnEmguCV
{
public partial class Smoothing : Form
{
public Smoothing()
{
InitializeComponent();
}
private void _buttonBrowse_Click(object sender, EventArgs e)
{
OpenFileDialog ofd = new OpenFileDialog();
if (ofd.ShowDialog() == DialogResult.OK)
{
_textBoxImageURL.Text = ofd.FileName;
}
}
private void _buttonOK_Click(object sender, EventArgs e)
{
Task.Factory.StartNew(() =>
{
try
{
Emgu.CV.Image<Bgr, Byte> original = new Emgu.CV.Image<Bgr, byte>(_textBoxImageURL.Text);
Emgu.CV.Image<Bgr, Byte> gaussian = original.SmoothGaussian(51);
Emgu.CV.Image<Bgr, Byte> bilatral = original.SmoothBilatral(51, 51, 51);
Emgu.CV.Image<Bgr, Byte> blur = original.SmoothBlur(50,50);
Emgu.CV.Image<Bgr, Byte> median = original.SmoothMedian(7);
pictureBox1.Image = (Image)original.ToBitmap();
pictureBox2.Image = (Image)gaussian.ToBitmap();
pictureBox3.Image = (Image)bilatral.ToBitmap();
pictureBox4.Image = (Image)blur.ToBitmap();
pictureBox5.Image = (Image)median.ToBitmap();
}
catch (Exception ex)
{
MessageBox.Show("Could not load Image.\n" + ex.Message);
}
});
}
}
}
|
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Windows.Forms;
using SelfCheckout.Model;
using SelfCheckout.Repository;
namespace SelfCheckout.Kiosk.Controller
{
public class ItemManager
{
private readonly IRepository _repository;
public ItemManager(IRepository repository)
{
_repository = repository;
}
public IEnumerable<Item> ImportInventroyList()
{
_repository.DeleteAll<Item>();
var invList = GetInventoryList().ToList();
for (int i = 1; i < invList.Count; i= i+2)
{
_repository.Create(new Item(invList[i-1].Trim(), Convert.ToDecimal(invList[i])));
}
return _repository.GetAll<Item>();
}
private IEnumerable<string> GetInventoryList()
{
OpenFileDialog dialog = new OpenFileDialog();
dialog.Filter = "Text Files (.txt)|*.txt|All Files (*.*)|*.*";
dialog.FilterIndex = 1;
if (dialog.ShowDialog() != DialogResult.OK)
return Enumerable.Empty<string>();
string cartContents;
using (Stream stream = dialog.OpenFile())
using (StreamReader reader = new StreamReader(stream))
{
cartContents = reader.ReadToEnd();
}
return cartContents.Split(',');
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.